From 8ca00026cf8adf6bc7ef294815bd303de534e793 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Mon, 2 Nov 2026 23:00:38 +0900 Subject: [PATCH 1/3] feat: expose public Haskell APIs through C and Python --- .github/workflows/docs.yml | 11 +- .github/workflows/prepare-release.yml | 97 + .github/workflows/publish-python.yml | 117 +- .github/workflows/python-wheels.yml | 34 +- .github/workflows/validate.yml | 2 + MANIFEST.in | 5 +- .../python/_hmath_native/_algebra_base.py | 99 + .../python/_hmath_native/_autodiff_value.py | 71 + bindings/python/_hmath_native/_buffer_base.py | 236 + bindings/python/_hmath_native/_bytes.py | 69 + .../python/_hmath_native/_callback_error.py | 38 + bindings/python/_hmath_native/_compat.py | 13 + .../python/_hmath_native/_expression_base.py | 1276 + .../_hmath_native/_expression_catalog.py | 4 + .../python/_hmath_native/_expression_error.py | 67 + .../python/_hmath_native/_foundation_base.py | 179 + .../python/_hmath_native/_geometry_base.py | 51 + bindings/python/_hmath_native/_graph_base.py | 100 + bindings/python/_hmath_native/_image_base.py | 82 + .../python/_hmath_native/_interchange_base.py | 394 + .../_hmath_native/_interchange_error.py | 60 + bindings/python/_hmath_native/_linear_base.py | 356 + bindings/python/_hmath_native/_math_error.py | 154 + bindings/python/_hmath_native/_matrix_base.py | 225 + .../python/_hmath_native/_matrix_value.py | 135 + bindings/python/_hmath_native/_neural_base.py | 953 + .../python/_hmath_native/_neural_catalog.py | 4 + bindings/python/_hmath_native/_neural_core.py | 92 + .../python/_hmath_native/_neural_metrics.py | 30 + .../python/_hmath_native/_neural_precision.py | 52 + bindings/python/_hmath_native/_numeric.py | 278 + .../python/_hmath_native/_numeric_modules.py | 37 + .../python/_hmath_native/_numeric_objects.py | 112 + .../_hmath_native/_numeric_types_runtime.py | 361 + .../python/_hmath_native/_numerical_base.py | 175 + .../python/_hmath_native/_optimization_all.py | 1096 + .../_hmath_native/_optimization_catalog.py | 1284 + .../python/_hmath_native/_polynomial_base.py | 194 + .../python/_hmath_native/_rotations_base.py | 58 + .../_hmath_native/_scalar_extras_base.py | 74 + .../python/_hmath_native/_spectral_base.py | 44 + .../python/_hmath_native/_stochastic_base.py | 108 + .../python/_hmath_native/_tensor_catalog.py | 4 + bindings/python/_hmath_native/_tensor_core.py | 1039 + .../python/_hmath_native/_tensor_object.py | 114 + .../python/_hmath_native/_timeseries_base.py | 24 + bindings/python/_hmath_native/_units_base.py | 139 + bindings/python/_hmath_native/_value.py | 424 + bindings/python/_hmath_native/algebra.py | 512 + bindings/python/_hmath_native/algebra_api.py | 318 + .../python/_hmath_native/algorithm_values.py | 164 + bindings/python/_hmath_native/algorithms.py | 286 + bindings/python/_hmath_native/api_algebra.py | 15 + bindings/python/_hmath_native/autodiff.py | 1125 + bindings/python/_hmath_native/backend.py | 599 + bindings/python/_hmath_native/basic.py | 83 + .../python/_hmath_native/buffer_values.py | 148 + bindings/python/_hmath_native/calculus.py | 292 + .../python/_hmath_native/combinatorics.py | 258 + .../_hmath_native/combinatorics_values.py | 132 + bindings/python/_hmath_native/complex.py | 146 + .../python/_hmath_native/complex_extras.py | 134 + bindings/python/_hmath_native/constants.py | 159 + .../_hmath_native/convergence_values.py | 305 + .../python/_hmath_native/data_structures.py | 706 + .../python/_hmath_native/datastructure.py | 18 + .../python/_hmath_native/decomposition.py | 445 + .../python/_hmath_native/deeplearning_core.py | 160 + .../_hmath_native/deeplearning_layers.py | 116 + .../_hmath_native/deeplearning_metrics.py | 34 + .../_hmath_native/deeplearning_precision.py | 34 + bindings/python/_hmath_native/discrete.py | 54 + .../python/_hmath_native/discrete_values.py | 541 + bindings/python/_hmath_native/errors.py | 114 + bindings/python/_hmath_native/execution.py | 196 + bindings/python/_hmath_native/expression.py | 230 + bindings/python/_hmath_native/fourier.py | 118 + .../python/_hmath_native/fourier_values.py | 261 + bindings/python/_hmath_native/geometry.py | 1158 + .../_hmath_native/geometry_primitives.py | 34 + bindings/python/_hmath_native/graph.py | 595 + bindings/python/_hmath_native/graph_core.py | 17 + bindings/python/_hmath_native/image.py | 570 + bindings/python/_hmath_native/image_color.py | 31 + bindings/python/_hmath_native/interchange.py | 469 + .../python/_hmath_native/interpolation.py | 20 + .../_hmath_native/interpolation_values.py | 345 + bindings/python/_hmath_native/iterative.py | 508 + bindings/python/_hmath_native/lapack.py | 597 + bindings/python/_hmath_native/linear.py | 204 + .../python/_hmath_native/machinelearning.py | 1296 + bindings/python/_hmath_native/matrix.py | 461 + .../python/_hmath_native/matrix_advanced.py | 377 + bindings/python/_hmath_native/numbertheory.py | 486 + .../_hmath_native/numbertheory_extras.py | 37 + bindings/python/_hmath_native/numeric.py | 115 + .../python/_hmath_native/numeric_types.py | 927 + bindings/python/_hmath_native/ode.py | 300 + bindings/python/_hmath_native/optimization.py | 139 + .../_hmath_native/optimization_common.py | 73 + bindings/python/_hmath_native/pde.py | 239 + bindings/python/_hmath_native/polynomial.py | 349 + bindings/python/_hmath_native/probability.py | 90 + .../_hmath_native/probability_values.py | 690 + bindings/python/_hmath_native/quaternion.py | 119 + bindings/python/_hmath_native/random.py | 62 + .../python/_hmath_native/random_values.py | 438 + bindings/python/_hmath_native/root.py | 275 + bindings/python/_hmath_native/rotation.py | 141 + bindings/python/_hmath_native/scalar.py | 975 + bindings/python/_hmath_native/shape_values.py | 180 + bindings/python/_hmath_native/signal.py | 342 + .../python/_hmath_native/signal_values.py | 355 + bindings/python/_hmath_native/sparse.py | 595 + .../python/_hmath_native/sparse_spectral.py | 424 + bindings/python/_hmath_native/special.py | 921 + .../python/_hmath_native/special_extras.py | 25 + bindings/python/_hmath_native/statistics.py | 69 + .../_hmath_native/statistics_advanced.py | 622 + .../python/_hmath_native/statistics_values.py | 412 + bindings/python/_hmath_native/symbolic.py | 324 + bindings/python/_hmath_native/tensor.py | 30 + bindings/python/_hmath_native/timeseries.py | 634 + .../python/_hmath_native/timeseries_core.py | 115 + .../_hmath_native/timeseries_diagnostics.py | 45 + bindings/python/_hmath_native/trigonometry.py | 654 + .../_hmath_native/trigonometry_extras.py | 122 + bindings/python/_hmath_native/units.py | 54 + bindings/python/_hmath_native/units_values.py | 508 + bindings/python/_hmath_native/vector.py | 394 + bindings/python/hmath.py | 166 +- bindings/schema/algebra-functions.json | 1496 + bindings/schema/algebra-objects.json | 877 + bindings/schema/autodiff-objects.json | 533 + bindings/schema/buffer-objects.json | 255 + bindings/schema/buffer-symbols.txt | 28 + bindings/schema/deeplearning-objects.json | 1295 + bindings/schema/deeplearning.json | 2351 ++ bindings/schema/errors-objects.json | 226 + bindings/schema/execution-api.json | 11 + bindings/schema/expression-objects.json | 2135 ++ bindings/schema/expression.json | 2955 ++ bindings/schema/foundation-functions.json | 3416 +++ bindings/schema/foundation-objects.json | 1510 + bindings/schema/geometry-functions.json | 645 + bindings/schema/geometry-objects.json | 1395 + bindings/schema/geometry-symbols.txt | 129 + bindings/schema/graph-functions.json | 540 + bindings/schema/graph-objects.json | 1105 + bindings/schema/image-objects.json | 915 + bindings/schema/image-symbols.txt | 82 + bindings/schema/interchange-functions.json | 440 + bindings/schema/interchange-objects.json | 957 + bindings/schema/linear-functions.json | 8468 ++++++ bindings/schema/linear-objects.json | 2845 ++ .../schema/machinelearning-functions.json | 959 + bindings/schema/machinelearning-objects.json | 1945 ++ bindings/schema/machinelearning-symbols.txt | 158 + bindings/schema/matrix-functions.json | 1002 + bindings/schema/matrix-objects.json | 662 + bindings/schema/matrix-value-objects.json | 443 + .../numeric-object-specializations.json | 203 + bindings/schema/numeric-object-symbols.txt | 33 + bindings/schema/numeric-symbols.txt | 921 + bindings/schema/numeric-types-objects.json | 1225 + bindings/schema/numeric-types-symbols.txt | 111 + bindings/schema/numeric.json | 8278 ++++++ bindings/schema/numerical-functions.json | 930 + bindings/schema/numerical-objects.json | 2005 ++ bindings/schema/objects.json | 167 + bindings/schema/optimization-all-objects.json | 1095 + bindings/schema/optimization.json | 1777 ++ bindings/schema/polynomial-objects.json | 541 + bindings/schema/polynomial-operations.json | 410 + bindings/schema/public-api.json | 23413 ++++++++++++++++ bindings/schema/rotation-objects.json | 525 + bindings/schema/rotation-symbols.txt | 49 + bindings/schema/scalar-extras-objects.json | 505 + bindings/schema/scalar-extras-symbols.txt | 50 + bindings/schema/shape-objects.json | 220 + bindings/schema/spectral-functions.json | 780 + bindings/schema/spectral-generic-objects.json | 26 + bindings/schema/spectral-objects.json | 1735 ++ bindings/schema/stochastic-functions.json | 4042 +++ bindings/schema/stochastic-objects.json | 1532 + bindings/schema/tensor-image-objects.json | 46 + bindings/schema/tensor-objects.json | 1035 + bindings/schema/tensor.json | 1821 ++ bindings/schema/timeseries-functions.json | 510 + bindings/schema/timeseries-objects.json | 1025 + bindings/schema/units-values-objects.json | 809 + cbits/algebra.c | 771 + cbits/autodiff_bindings.c | 819 + cbits/backend.c | 29 + cbits/buffer.c | 231 + cbits/bytes.c | 22 + cbits/deeplearning.c | 1190 + cbits/error_wire.c | 219 + cbits/execution.c | 227 + cbits/expression.c | 923 + cbits/foundation.c | 1733 ++ cbits/geometry.c | 1037 + cbits/graph_bindings.c | 1595 ++ cbits/image.c | 676 + cbits/interchange.c | 404 + cbits/linear.c | 1656 ++ cbits/machinelearning.c | 1269 + cbits/matrix_bindings.c | 1468 + cbits/matrix_internal.h | 11 + cbits/matrix_value.c | 181 + cbits/native.c | 74 +- cbits/native_internal.h | 1 + cbits/numeric_generated.c | 20760 ++++++++++++++ cbits/numeric_internal.h | 20 + cbits/numeric_objects.c | 269 + cbits/numeric_types.c | 1030 + cbits/numerical.c | 1670 ++ cbits/optimization.c | 125 + cbits/optimization_all.c | 667 + cbits/polynomial.c | 323 + cbits/rotations.c | 396 + cbits/runtime.c | 2 +- cbits/scalar_extras.c | 405 + cbits/shape.c | 182 + cbits/spectral.c | 1410 + cbits/stochastic.c | 878 + cbits/tensor_bindings.c | 1021 + cbits/timeseries.c | 1024 + cbits/units.c | 652 + cbits/value.c | 231 + cbits/value_internal.h | 18 + docs/getting-started/choose-an-operation.md | 24 +- docs/guides/releasing.md | 63 + docs/reference/algebra-values.md | 406 + docs/reference/autodiff-bindings.md | 320 + docs/reference/buffer-bindings.md | 365 + docs/reference/c.md | 9 +- docs/reference/deeplearning-bindings.md | 614 + docs/reference/errors.md | 110 + docs/reference/execution.md | 143 + docs/reference/expression-bindings.md | 438 + docs/reference/foundation.md | 808 + docs/reference/geometry-bindings.md | 1778 ++ docs/reference/graph-bindings.md | 2133 ++ docs/reference/image-bindings.md | 1156 + docs/reference/interchange-bindings.md | 1494 + docs/reference/linear-bindings.md | 2704 ++ docs/reference/machinelearning-bindings.md | 2194 ++ docs/reference/matrix-bindings.md | 1077 + docs/reference/matrix-values.md | 65 + docs/reference/numeric-bindings.md | 10804 +++++++ docs/reference/numeric-objects.md | 284 + docs/reference/numeric-type-functions.md | 108 + docs/reference/numeric-types.md | 153 + docs/reference/numerical-solvers.md | 2970 ++ docs/reference/optimization-bindings.md | 460 + docs/reference/polynomial.md | 547 + docs/reference/python.md | 39 +- docs/reference/rotations.md | 126 + docs/reference/scalar-extras.md | 582 + docs/reference/shapes.md | 83 + docs/reference/spectral-bindings.md | 2485 ++ docs/reference/stochastic.md | 876 + docs/reference/tensor-bindings.md | 687 + docs/reference/timeseries-bindings.md | 1628 ++ docs/reference/units-values.md | 792 + docs/reference/values.md | 148 + hmath.cabal | 359 +- include/hmath.h | 8 +- include/hmath_algebra.h | 283 + include/hmath_autodiff.h | 279 + include/hmath_backend.h | 7 + include/hmath_buffer.h | 89 + include/hmath_bytes.h | 19 + include/hmath_callback.h | 20 + include/hmath_deeplearning.h | 954 + include/hmath_error.h | 50 + include/hmath_execution.h | 67 + include/hmath_expression.h | 600 + include/hmath_expression_error.h | 36 + include/hmath_foundation.h | 656 + include/hmath_geometry.h | 310 + include/hmath_graph.h | 655 + include/hmath_image.h | 195 + include/hmath_interchange.h | 217 + include/hmath_interchange_error.h | 26 + include/hmath_linear.h | 606 + include/hmath_machinelearning.h | 381 + include/hmath_matrix.h | 236 + include/hmath_matrix_value.h | 53 + include/hmath_numeric.h | 6228 ++++ include/hmath_numeric_objects.h | 92 + include/hmath_numeric_types.h | 149 + include/hmath_numerical.h | 414 + include/hmath_optimization.h | 58 + include/hmath_optimization_all.h | 467 + include/hmath_polynomial.h | 78 + include/hmath_rotations.h | 75 + include/hmath_scalar_extras.h | 122 + include/hmath_shape.h | 71 + include/hmath_spectral.h | 358 + include/hmath_stochastic.h | 312 + include/hmath_tensor_bindings.h | 785 + include/hmath_timeseries.h | 239 + include/hmath_units.h | 96 + include/hmath_value.h | 84 + meson.build | 261 +- mkdocs.yml | 33 + src/HMath/FFI/AlgebraAll.hs | 248 + src/HMath/FFI/AlgebraCodec.hs | 191 + src/HMath/FFI/Autodiff.hs | 462 + src/HMath/FFI/AutodiffChecked.hs | 81 + src/HMath/FFI/AutodiffValue.hs | 64 + src/HMath/FFI/Boundary.hs | 53 + src/HMath/FFI/Buffer.hs | 47 + src/HMath/FFI/Buffer/Codec.hs | 188 + src/HMath/FFI/Bytes.hs | 37 + src/HMath/FFI/Coefficient.hs | 233 + src/HMath/FFI/DeepLearning.hs | 261 + src/HMath/FFI/Execution.hs | 65 + src/HMath/FFI/Expression.hs | 430 + src/HMath/FFI/Foundation.hs | 728 + src/HMath/FFI/FoundationCodec.hs | 239 + src/HMath/FFI/Geometry.hs | 807 + src/HMath/FFI/Graph.hs | 428 + src/HMath/FFI/GraphCodec.hs | 126 + src/HMath/FFI/Image.hs | 393 + src/HMath/FFI/InterchangeAll.hs | 229 + src/HMath/FFI/InterchangeCodec.hs | 125 + src/HMath/FFI/InterchangeElement.hs | 92 + src/HMath/FFI/InterchangeError.hs | 48 + src/HMath/FFI/LinearAll.hs | 1126 + src/HMath/FFI/LinearCodec.hs | 516 + src/HMath/FFI/MachineLearning.hs | 385 + src/HMath/FFI/MachineLearning/Codec.hs | 98 + src/HMath/FFI/MachineLearning/Types.hs | 87 + src/HMath/FFI/MathError.hs | 163 + src/HMath/FFI/Matrix.hs | 848 + src/HMath/FFI/MatrixValue.hs | 233 + src/HMath/FFI/Numeric.hs | 17818 ++++++++++++ src/HMath/FFI/NumericObjects.hs | 135 + src/HMath/FFI/NumericTypes.hs | 959 + src/HMath/FFI/NumericTypes/Core.hs | 575 + src/HMath/FFI/NumericalAll.hs | 274 + src/HMath/FFI/NumericalCodec.hs | 139 + src/HMath/FFI/OptimizationAll.hs | 311 + src/HMath/FFI/Optimizer.hs | 46 + src/HMath/FFI/Ordering.hs | 344 + src/HMath/FFI/Polynomial.hs | 207 + src/HMath/FFI/RandomCodec.hs | 16 + src/HMath/FFI/Rotations.hs | 386 + src/HMath/FFI/ScalarExtras.hs | 196 + src/HMath/FFI/ShapeAll.hs | 38 + src/HMath/FFI/ShapeCodec.hs | 123 + src/HMath/FFI/SpectralAll.hs | 286 + src/HMath/FFI/Stochastic.hs | 864 + src/HMath/FFI/TensorAll.hs | 216 + src/HMath/FFI/TensorCodec.hs | 187 + src/HMath/FFI/TimeSeries.hs | 466 + src/HMath/FFI/Units.hs | 243 + src/HMath/FFI/Value.hs | 223 + test/abi-symbols.txt | 4 + test/native/autodiff_bindings.py | 379 + test/native/autodiff_checked_contracts.c | 72 + test/native/autodiff_checked_contracts.cpp | 3 + test/native/autodiff_contracts.c | 167 + test/native/buffer_contracts.c | 98 + test/native/buffer_contracts.cpp | 3 + test/native/callback_errors.py | 123 + test/native/deeplearning_bindings.py | 191 + test/native/deeplearning_contracts.c | 43 + test/native/deeplearning_contracts.cpp | 3 + test/native/dlpack_numpy.py | 18 +- test/native/execution_blas_spy.c | 73 + test/native/execution_smoke.c | 19 + test/native/expanded_bindings.py | 102 + test/native/expression_bindings.py | 355 + test/native/expression_contracts.c | 115 + test/native/foundation_bindings.py | 268 + test/native/foundation_contracts.c | 205 + test/native/foundation_contracts.cpp | 3 + test/native/geometry.c | 62 + test/native/header_c99.c | 35 + test/native/image.c | 70 + test/native/interchange_bindings.py | 309 + test/native/interchange_contracts.c | 282 + test/native/interchange_contracts.cpp | 3 + test/native/kernel_storage.c | 127 + test/native/linear_bindings.py | 115 + test/native/linear_contracts.c | 83 + test/native/machinelearning.c | 103 + test/native/matrix_contracts.c | 72 + test/native/numeric_contracts.c | 85 + test/native/numeric_contracts.cpp | 3 + test/native/numeric_objects_contracts.c | 272 + test/native/numeric_objects_contracts.cpp | 3 + test/native/numeric_types.c | 77 + test/native/numeric_variants.c | 65 + test/native/numerical_bindings.py | 123 + test/native/optimization_bindings.py | 255 + test/native/optimization_contracts.c | 134 + test/native/polynomial_bindings.py | 113 + test/native/polynomial_contracts.c | 99 + test/native/rotations.c | 40 + test/native/scalar_extras.c | 54 + test/native/spectral_bindings.py | 86 + test/native/spectral_contracts.c | 46 + test/native/stochastic_bindings.py | 146 + test/native/stochastic_contracts.c | 73 + test/native/structural_matrix_contracts.c | 46 + test/native/structured_contracts.c | 75 + test/native/tensor_bindings.py | 351 + test/native/tensor_contracts.c | 90 + test/native/tensor_contracts.cpp | 3 + test/native/units_bindings.py | 92 + test/native/value_bindings.py | 127 + test/release_candidate.py | 542 + test/release_publishing.py | 145 + tools/build_c_sdk.py | 162 + tools/build_docs.py | 15 + tools/build_python_wheel.sh | 7 + tools/check_abi.py | 20 + tools/check_algebra_equivalence.py | 458 + tools/check_api_docs.py | 9 + tools/check_autodiff_coefficients.py | 224 + tools/check_autodiff_equivalence.py | 233 + tools/check_binding_coverage.py | 264 + tools/check_buffer_equivalence.py | 574 + tools/check_c_sdk.py | 120 + tools/check_deeplearning_equivalence.py | 633 + tools/check_execution.py | 221 + tools/check_expression_equivalence.py | 641 + tools/check_foundation_equivalence.py | 572 + tools/check_geometry_equivalence.py | 513 + tools/check_graph_equivalence.py | 337 + tools/check_image_equivalence.py | 460 + tools/check_install.py | 21 + .../check_interchange_bindings_equivalence.py | 805 + tools/check_linear_equivalence.py | 660 + tools/check_machinelearning_equivalence.py | 617 + tools/check_matrix_equivalence.py | 277 + tools/check_matrix_value_equivalence.py | 171 + tools/check_numeric_equality.py | 384 + tools/check_numeric_equivalence.py | 493 + tools/check_numeric_objects_equivalence.py | 542 + tools/check_numeric_types_equivalence.py | 730 + tools/check_numerical_equivalence.py | 770 + tools/check_optimization_equivalence.py | 462 + tools/check_polynomial_equivalence.py | 403 + tools/check_python_wheel.py | 4 +- tools/check_release_remote.py | 101 + tools/check_rotation_equivalence.py | 295 + tools/check_scalar_extras.py | 371 + tools/check_shape_equivalence.py | 223 + tools/check_spectral_equivalence.py | 430 + tools/check_stochastic_equivalence.py | 475 + tools/check_structural_matrix_equivalence.py | 222 + tools/check_tensor_equivalence.py | 485 + tools/check_timeseries_equivalence.py | 289 + tools/check_units_equivalence.py | 280 + tools/generate_algebra_bindings.py | 638 + tools/generate_buffer_bindings.py | 273 + tools/generate_deeplearning_bindings.py | 802 + tools/generate_expression_bindings.py | 747 + tools/generate_foundation_bindings.py | 888 + tools/generate_geometry_bindings.py | 494 + tools/generate_graph_bindings.py | 395 + tools/generate_image_bindings.py | 679 + tools/generate_interchange_bindings.py | 334 + tools/generate_linear_bindings.py | 1362 + tools/generate_machinelearning_bindings.py | 465 + tools/generate_matrix_bindings.py | 693 + tools/generate_matrix_value_bindings.py | 354 + tools/generate_numeric_bindings.py | 803 + tools/generate_numeric_objects.py | 136 + tools/generate_numeric_types.py | 819 + tools/generate_numerical_bindings.py | 359 + tools/generate_optimization_bindings.py | 60 + tools/generate_polynomial_bindings.py | 326 + tools/generate_rotation_bindings.py | 401 + tools/generate_scalar_extras.py | 517 + tools/generate_shape_bindings.py | 304 + tools/generate_spectral_bindings.py | 189 + tools/generate_stochastic_bindings.py | 714 + tools/generate_tensor_bindings.py | 406 + tools/generate_timeseries_bindings.py | 226 + tools/generate_units_bindings.py | 449 + tools/numeric_specializations.py | 149 + tools/publish_github_release.py | 159 + tools/release_manifest.py | 55 + tools/release_version.py | 29 + tools/select_release_candidate.py | 201 + tools/verify_release_candidate.py | 367 + 493 files changed, 302705 insertions(+), 113 deletions(-) create mode 100644 .github/workflows/prepare-release.yml create mode 100644 bindings/python/_hmath_native/_algebra_base.py create mode 100644 bindings/python/_hmath_native/_autodiff_value.py create mode 100644 bindings/python/_hmath_native/_buffer_base.py create mode 100644 bindings/python/_hmath_native/_bytes.py create mode 100644 bindings/python/_hmath_native/_callback_error.py create mode 100644 bindings/python/_hmath_native/_compat.py create mode 100644 bindings/python/_hmath_native/_expression_base.py create mode 100644 bindings/python/_hmath_native/_expression_catalog.py create mode 100644 bindings/python/_hmath_native/_expression_error.py create mode 100644 bindings/python/_hmath_native/_foundation_base.py create mode 100644 bindings/python/_hmath_native/_geometry_base.py create mode 100644 bindings/python/_hmath_native/_graph_base.py create mode 100644 bindings/python/_hmath_native/_image_base.py create mode 100644 bindings/python/_hmath_native/_interchange_base.py create mode 100644 bindings/python/_hmath_native/_interchange_error.py create mode 100644 bindings/python/_hmath_native/_linear_base.py create mode 100644 bindings/python/_hmath_native/_math_error.py create mode 100644 bindings/python/_hmath_native/_matrix_base.py create mode 100644 bindings/python/_hmath_native/_matrix_value.py create mode 100644 bindings/python/_hmath_native/_neural_base.py create mode 100644 bindings/python/_hmath_native/_neural_catalog.py create mode 100644 bindings/python/_hmath_native/_neural_core.py create mode 100644 bindings/python/_hmath_native/_neural_metrics.py create mode 100644 bindings/python/_hmath_native/_neural_precision.py create mode 100644 bindings/python/_hmath_native/_numeric.py create mode 100644 bindings/python/_hmath_native/_numeric_modules.py create mode 100644 bindings/python/_hmath_native/_numeric_objects.py create mode 100644 bindings/python/_hmath_native/_numeric_types_runtime.py create mode 100644 bindings/python/_hmath_native/_numerical_base.py create mode 100644 bindings/python/_hmath_native/_optimization_all.py create mode 100644 bindings/python/_hmath_native/_optimization_catalog.py create mode 100644 bindings/python/_hmath_native/_polynomial_base.py create mode 100644 bindings/python/_hmath_native/_rotations_base.py create mode 100644 bindings/python/_hmath_native/_scalar_extras_base.py create mode 100644 bindings/python/_hmath_native/_spectral_base.py create mode 100644 bindings/python/_hmath_native/_stochastic_base.py create mode 100644 bindings/python/_hmath_native/_tensor_catalog.py create mode 100644 bindings/python/_hmath_native/_tensor_core.py create mode 100644 bindings/python/_hmath_native/_tensor_object.py create mode 100644 bindings/python/_hmath_native/_timeseries_base.py create mode 100644 bindings/python/_hmath_native/_units_base.py create mode 100644 bindings/python/_hmath_native/_value.py create mode 100644 bindings/python/_hmath_native/algebra.py create mode 100644 bindings/python/_hmath_native/algebra_api.py create mode 100644 bindings/python/_hmath_native/algorithm_values.py create mode 100644 bindings/python/_hmath_native/algorithms.py create mode 100644 bindings/python/_hmath_native/api_algebra.py create mode 100644 bindings/python/_hmath_native/autodiff.py create mode 100644 bindings/python/_hmath_native/backend.py create mode 100644 bindings/python/_hmath_native/basic.py create mode 100644 bindings/python/_hmath_native/buffer_values.py create mode 100644 bindings/python/_hmath_native/calculus.py create mode 100644 bindings/python/_hmath_native/combinatorics.py create mode 100644 bindings/python/_hmath_native/combinatorics_values.py create mode 100644 bindings/python/_hmath_native/complex.py create mode 100644 bindings/python/_hmath_native/complex_extras.py create mode 100644 bindings/python/_hmath_native/constants.py create mode 100644 bindings/python/_hmath_native/convergence_values.py create mode 100644 bindings/python/_hmath_native/data_structures.py create mode 100644 bindings/python/_hmath_native/datastructure.py create mode 100644 bindings/python/_hmath_native/decomposition.py create mode 100644 bindings/python/_hmath_native/deeplearning_core.py create mode 100644 bindings/python/_hmath_native/deeplearning_layers.py create mode 100644 bindings/python/_hmath_native/deeplearning_metrics.py create mode 100644 bindings/python/_hmath_native/deeplearning_precision.py create mode 100644 bindings/python/_hmath_native/discrete.py create mode 100644 bindings/python/_hmath_native/discrete_values.py create mode 100644 bindings/python/_hmath_native/errors.py create mode 100644 bindings/python/_hmath_native/execution.py create mode 100644 bindings/python/_hmath_native/expression.py create mode 100644 bindings/python/_hmath_native/fourier.py create mode 100644 bindings/python/_hmath_native/fourier_values.py create mode 100644 bindings/python/_hmath_native/geometry.py create mode 100644 bindings/python/_hmath_native/geometry_primitives.py create mode 100644 bindings/python/_hmath_native/graph.py create mode 100644 bindings/python/_hmath_native/graph_core.py create mode 100644 bindings/python/_hmath_native/image.py create mode 100644 bindings/python/_hmath_native/image_color.py create mode 100644 bindings/python/_hmath_native/interchange.py create mode 100644 bindings/python/_hmath_native/interpolation.py create mode 100644 bindings/python/_hmath_native/interpolation_values.py create mode 100644 bindings/python/_hmath_native/iterative.py create mode 100644 bindings/python/_hmath_native/lapack.py create mode 100644 bindings/python/_hmath_native/linear.py create mode 100644 bindings/python/_hmath_native/machinelearning.py create mode 100644 bindings/python/_hmath_native/matrix.py create mode 100644 bindings/python/_hmath_native/matrix_advanced.py create mode 100644 bindings/python/_hmath_native/numbertheory.py create mode 100644 bindings/python/_hmath_native/numbertheory_extras.py create mode 100644 bindings/python/_hmath_native/numeric.py create mode 100644 bindings/python/_hmath_native/numeric_types.py create mode 100644 bindings/python/_hmath_native/ode.py create mode 100644 bindings/python/_hmath_native/optimization.py create mode 100644 bindings/python/_hmath_native/optimization_common.py create mode 100644 bindings/python/_hmath_native/pde.py create mode 100644 bindings/python/_hmath_native/polynomial.py create mode 100644 bindings/python/_hmath_native/probability.py create mode 100644 bindings/python/_hmath_native/probability_values.py create mode 100644 bindings/python/_hmath_native/quaternion.py create mode 100644 bindings/python/_hmath_native/random.py create mode 100644 bindings/python/_hmath_native/random_values.py create mode 100644 bindings/python/_hmath_native/root.py create mode 100644 bindings/python/_hmath_native/rotation.py create mode 100644 bindings/python/_hmath_native/scalar.py create mode 100644 bindings/python/_hmath_native/shape_values.py create mode 100644 bindings/python/_hmath_native/signal.py create mode 100644 bindings/python/_hmath_native/signal_values.py create mode 100644 bindings/python/_hmath_native/sparse.py create mode 100644 bindings/python/_hmath_native/sparse_spectral.py create mode 100644 bindings/python/_hmath_native/special.py create mode 100644 bindings/python/_hmath_native/special_extras.py create mode 100644 bindings/python/_hmath_native/statistics.py create mode 100644 bindings/python/_hmath_native/statistics_advanced.py create mode 100644 bindings/python/_hmath_native/statistics_values.py create mode 100644 bindings/python/_hmath_native/symbolic.py create mode 100644 bindings/python/_hmath_native/tensor.py create mode 100644 bindings/python/_hmath_native/timeseries.py create mode 100644 bindings/python/_hmath_native/timeseries_core.py create mode 100644 bindings/python/_hmath_native/timeseries_diagnostics.py create mode 100644 bindings/python/_hmath_native/trigonometry.py create mode 100644 bindings/python/_hmath_native/trigonometry_extras.py create mode 100644 bindings/python/_hmath_native/units.py create mode 100644 bindings/python/_hmath_native/units_values.py create mode 100644 bindings/python/_hmath_native/vector.py create mode 100644 bindings/schema/algebra-functions.json create mode 100644 bindings/schema/algebra-objects.json create mode 100644 bindings/schema/autodiff-objects.json create mode 100644 bindings/schema/buffer-objects.json create mode 100644 bindings/schema/buffer-symbols.txt create mode 100644 bindings/schema/deeplearning-objects.json create mode 100644 bindings/schema/deeplearning.json create mode 100644 bindings/schema/errors-objects.json create mode 100644 bindings/schema/execution-api.json create mode 100644 bindings/schema/expression-objects.json create mode 100644 bindings/schema/expression.json create mode 100644 bindings/schema/foundation-functions.json create mode 100644 bindings/schema/foundation-objects.json create mode 100644 bindings/schema/geometry-functions.json create mode 100644 bindings/schema/geometry-objects.json create mode 100644 bindings/schema/geometry-symbols.txt create mode 100644 bindings/schema/graph-functions.json create mode 100644 bindings/schema/graph-objects.json create mode 100644 bindings/schema/image-objects.json create mode 100644 bindings/schema/image-symbols.txt create mode 100644 bindings/schema/interchange-functions.json create mode 100644 bindings/schema/interchange-objects.json create mode 100644 bindings/schema/linear-functions.json create mode 100644 bindings/schema/linear-objects.json create mode 100644 bindings/schema/machinelearning-functions.json create mode 100644 bindings/schema/machinelearning-objects.json create mode 100644 bindings/schema/machinelearning-symbols.txt create mode 100644 bindings/schema/matrix-functions.json create mode 100644 bindings/schema/matrix-objects.json create mode 100644 bindings/schema/matrix-value-objects.json create mode 100644 bindings/schema/numeric-object-specializations.json create mode 100644 bindings/schema/numeric-object-symbols.txt create mode 100644 bindings/schema/numeric-symbols.txt create mode 100644 bindings/schema/numeric-types-objects.json create mode 100644 bindings/schema/numeric-types-symbols.txt create mode 100644 bindings/schema/numeric.json create mode 100644 bindings/schema/numerical-functions.json create mode 100644 bindings/schema/numerical-objects.json create mode 100644 bindings/schema/objects.json create mode 100644 bindings/schema/optimization-all-objects.json create mode 100644 bindings/schema/optimization.json create mode 100644 bindings/schema/polynomial-objects.json create mode 100644 bindings/schema/polynomial-operations.json create mode 100644 bindings/schema/public-api.json create mode 100644 bindings/schema/rotation-objects.json create mode 100644 bindings/schema/rotation-symbols.txt create mode 100644 bindings/schema/scalar-extras-objects.json create mode 100644 bindings/schema/scalar-extras-symbols.txt create mode 100644 bindings/schema/shape-objects.json create mode 100644 bindings/schema/spectral-functions.json create mode 100644 bindings/schema/spectral-generic-objects.json create mode 100644 bindings/schema/spectral-objects.json create mode 100644 bindings/schema/stochastic-functions.json create mode 100644 bindings/schema/stochastic-objects.json create mode 100644 bindings/schema/tensor-image-objects.json create mode 100644 bindings/schema/tensor-objects.json create mode 100644 bindings/schema/tensor.json create mode 100644 bindings/schema/timeseries-functions.json create mode 100644 bindings/schema/timeseries-objects.json create mode 100644 bindings/schema/units-values-objects.json create mode 100644 cbits/algebra.c create mode 100644 cbits/autodiff_bindings.c create mode 100644 cbits/buffer.c create mode 100644 cbits/bytes.c create mode 100644 cbits/deeplearning.c create mode 100644 cbits/error_wire.c create mode 100644 cbits/execution.c create mode 100644 cbits/expression.c create mode 100644 cbits/foundation.c create mode 100644 cbits/geometry.c create mode 100644 cbits/graph_bindings.c create mode 100644 cbits/image.c create mode 100644 cbits/interchange.c create mode 100644 cbits/linear.c create mode 100644 cbits/machinelearning.c create mode 100644 cbits/matrix_bindings.c create mode 100644 cbits/matrix_internal.h create mode 100644 cbits/matrix_value.c create mode 100644 cbits/numeric_generated.c create mode 100644 cbits/numeric_internal.h create mode 100644 cbits/numeric_objects.c create mode 100644 cbits/numeric_types.c create mode 100644 cbits/numerical.c create mode 100644 cbits/optimization.c create mode 100644 cbits/optimization_all.c create mode 100644 cbits/polynomial.c create mode 100644 cbits/rotations.c create mode 100644 cbits/scalar_extras.c create mode 100644 cbits/shape.c create mode 100644 cbits/spectral.c create mode 100644 cbits/stochastic.c create mode 100644 cbits/tensor_bindings.c create mode 100644 cbits/timeseries.c create mode 100644 cbits/units.c create mode 100644 cbits/value.c create mode 100644 cbits/value_internal.h create mode 100644 docs/guides/releasing.md create mode 100644 docs/reference/algebra-values.md create mode 100644 docs/reference/autodiff-bindings.md create mode 100644 docs/reference/buffer-bindings.md create mode 100644 docs/reference/deeplearning-bindings.md create mode 100644 docs/reference/errors.md create mode 100644 docs/reference/execution.md create mode 100644 docs/reference/expression-bindings.md create mode 100644 docs/reference/foundation.md create mode 100644 docs/reference/geometry-bindings.md create mode 100644 docs/reference/graph-bindings.md create mode 100644 docs/reference/image-bindings.md create mode 100644 docs/reference/interchange-bindings.md create mode 100644 docs/reference/linear-bindings.md create mode 100644 docs/reference/machinelearning-bindings.md create mode 100644 docs/reference/matrix-bindings.md create mode 100644 docs/reference/matrix-values.md create mode 100644 docs/reference/numeric-bindings.md create mode 100644 docs/reference/numeric-objects.md create mode 100644 docs/reference/numeric-type-functions.md create mode 100644 docs/reference/numeric-types.md create mode 100644 docs/reference/numerical-solvers.md create mode 100644 docs/reference/optimization-bindings.md create mode 100644 docs/reference/polynomial.md create mode 100644 docs/reference/rotations.md create mode 100644 docs/reference/scalar-extras.md create mode 100644 docs/reference/shapes.md create mode 100644 docs/reference/spectral-bindings.md create mode 100644 docs/reference/stochastic.md create mode 100644 docs/reference/tensor-bindings.md create mode 100644 docs/reference/timeseries-bindings.md create mode 100644 docs/reference/units-values.md create mode 100644 docs/reference/values.md create mode 100644 include/hmath_algebra.h create mode 100644 include/hmath_autodiff.h create mode 100644 include/hmath_buffer.h create mode 100644 include/hmath_bytes.h create mode 100644 include/hmath_callback.h create mode 100644 include/hmath_deeplearning.h create mode 100644 include/hmath_error.h create mode 100644 include/hmath_execution.h create mode 100644 include/hmath_expression.h create mode 100644 include/hmath_expression_error.h create mode 100644 include/hmath_foundation.h create mode 100644 include/hmath_geometry.h create mode 100644 include/hmath_graph.h create mode 100644 include/hmath_image.h create mode 100644 include/hmath_interchange.h create mode 100644 include/hmath_interchange_error.h create mode 100644 include/hmath_linear.h create mode 100644 include/hmath_machinelearning.h create mode 100644 include/hmath_matrix.h create mode 100644 include/hmath_matrix_value.h create mode 100644 include/hmath_numeric.h create mode 100644 include/hmath_numeric_objects.h create mode 100644 include/hmath_numeric_types.h create mode 100644 include/hmath_numerical.h create mode 100644 include/hmath_optimization.h create mode 100644 include/hmath_optimization_all.h create mode 100644 include/hmath_polynomial.h create mode 100644 include/hmath_rotations.h create mode 100644 include/hmath_scalar_extras.h create mode 100644 include/hmath_shape.h create mode 100644 include/hmath_spectral.h create mode 100644 include/hmath_stochastic.h create mode 100644 include/hmath_tensor_bindings.h create mode 100644 include/hmath_timeseries.h create mode 100644 include/hmath_units.h create mode 100644 include/hmath_value.h create mode 100644 src/HMath/FFI/AlgebraAll.hs create mode 100644 src/HMath/FFI/AlgebraCodec.hs create mode 100644 src/HMath/FFI/Autodiff.hs create mode 100644 src/HMath/FFI/AutodiffChecked.hs create mode 100644 src/HMath/FFI/AutodiffValue.hs create mode 100644 src/HMath/FFI/Boundary.hs create mode 100644 src/HMath/FFI/Buffer.hs create mode 100644 src/HMath/FFI/Buffer/Codec.hs create mode 100644 src/HMath/FFI/Bytes.hs create mode 100644 src/HMath/FFI/Coefficient.hs create mode 100644 src/HMath/FFI/DeepLearning.hs create mode 100644 src/HMath/FFI/Execution.hs create mode 100644 src/HMath/FFI/Expression.hs create mode 100644 src/HMath/FFI/Foundation.hs create mode 100644 src/HMath/FFI/FoundationCodec.hs create mode 100644 src/HMath/FFI/Geometry.hs create mode 100644 src/HMath/FFI/Graph.hs create mode 100644 src/HMath/FFI/GraphCodec.hs create mode 100644 src/HMath/FFI/Image.hs create mode 100644 src/HMath/FFI/InterchangeAll.hs create mode 100644 src/HMath/FFI/InterchangeCodec.hs create mode 100644 src/HMath/FFI/InterchangeElement.hs create mode 100644 src/HMath/FFI/InterchangeError.hs create mode 100644 src/HMath/FFI/LinearAll.hs create mode 100644 src/HMath/FFI/LinearCodec.hs create mode 100644 src/HMath/FFI/MachineLearning.hs create mode 100644 src/HMath/FFI/MachineLearning/Codec.hs create mode 100644 src/HMath/FFI/MachineLearning/Types.hs create mode 100644 src/HMath/FFI/MathError.hs create mode 100644 src/HMath/FFI/Matrix.hs create mode 100644 src/HMath/FFI/MatrixValue.hs create mode 100644 src/HMath/FFI/Numeric.hs create mode 100644 src/HMath/FFI/NumericObjects.hs create mode 100644 src/HMath/FFI/NumericTypes.hs create mode 100644 src/HMath/FFI/NumericTypes/Core.hs create mode 100644 src/HMath/FFI/NumericalAll.hs create mode 100644 src/HMath/FFI/NumericalCodec.hs create mode 100644 src/HMath/FFI/OptimizationAll.hs create mode 100644 src/HMath/FFI/Optimizer.hs create mode 100644 src/HMath/FFI/Ordering.hs create mode 100644 src/HMath/FFI/Polynomial.hs create mode 100644 src/HMath/FFI/RandomCodec.hs create mode 100644 src/HMath/FFI/Rotations.hs create mode 100644 src/HMath/FFI/ScalarExtras.hs create mode 100644 src/HMath/FFI/ShapeAll.hs create mode 100644 src/HMath/FFI/ShapeCodec.hs create mode 100644 src/HMath/FFI/SpectralAll.hs create mode 100644 src/HMath/FFI/Stochastic.hs create mode 100644 src/HMath/FFI/TensorAll.hs create mode 100644 src/HMath/FFI/TensorCodec.hs create mode 100644 src/HMath/FFI/TimeSeries.hs create mode 100644 src/HMath/FFI/Units.hs create mode 100644 src/HMath/FFI/Value.hs create mode 100644 test/native/autodiff_bindings.py create mode 100644 test/native/autodiff_checked_contracts.c create mode 100644 test/native/autodiff_checked_contracts.cpp create mode 100644 test/native/autodiff_contracts.c create mode 100644 test/native/buffer_contracts.c create mode 100644 test/native/buffer_contracts.cpp create mode 100644 test/native/callback_errors.py create mode 100644 test/native/deeplearning_bindings.py create mode 100644 test/native/deeplearning_contracts.c create mode 100644 test/native/deeplearning_contracts.cpp create mode 100644 test/native/execution_blas_spy.c create mode 100644 test/native/execution_smoke.c create mode 100644 test/native/expanded_bindings.py create mode 100644 test/native/expression_bindings.py create mode 100644 test/native/expression_contracts.c create mode 100644 test/native/foundation_bindings.py create mode 100644 test/native/foundation_contracts.c create mode 100644 test/native/foundation_contracts.cpp create mode 100644 test/native/geometry.c create mode 100644 test/native/image.c create mode 100644 test/native/interchange_bindings.py create mode 100644 test/native/interchange_contracts.c create mode 100644 test/native/interchange_contracts.cpp create mode 100644 test/native/kernel_storage.c create mode 100644 test/native/linear_bindings.py create mode 100644 test/native/linear_contracts.c create mode 100644 test/native/machinelearning.c create mode 100644 test/native/matrix_contracts.c create mode 100644 test/native/numeric_contracts.c create mode 100644 test/native/numeric_contracts.cpp create mode 100644 test/native/numeric_objects_contracts.c create mode 100644 test/native/numeric_objects_contracts.cpp create mode 100644 test/native/numeric_types.c create mode 100644 test/native/numeric_variants.c create mode 100644 test/native/numerical_bindings.py create mode 100644 test/native/optimization_bindings.py create mode 100644 test/native/optimization_contracts.c create mode 100644 test/native/polynomial_bindings.py create mode 100644 test/native/polynomial_contracts.c create mode 100644 test/native/rotations.c create mode 100644 test/native/scalar_extras.c create mode 100644 test/native/spectral_bindings.py create mode 100644 test/native/spectral_contracts.c create mode 100644 test/native/stochastic_bindings.py create mode 100644 test/native/stochastic_contracts.c create mode 100644 test/native/structural_matrix_contracts.c create mode 100644 test/native/structured_contracts.c create mode 100644 test/native/tensor_bindings.py create mode 100644 test/native/tensor_contracts.c create mode 100644 test/native/tensor_contracts.cpp create mode 100644 test/native/units_bindings.py create mode 100644 test/native/value_bindings.py create mode 100644 test/release_candidate.py create mode 100644 test/release_publishing.py create mode 100644 tools/build_c_sdk.py create mode 100644 tools/check_algebra_equivalence.py create mode 100644 tools/check_autodiff_coefficients.py create mode 100644 tools/check_autodiff_equivalence.py create mode 100644 tools/check_binding_coverage.py create mode 100644 tools/check_buffer_equivalence.py create mode 100644 tools/check_c_sdk.py create mode 100644 tools/check_deeplearning_equivalence.py create mode 100644 tools/check_execution.py create mode 100644 tools/check_expression_equivalence.py create mode 100644 tools/check_foundation_equivalence.py create mode 100644 tools/check_geometry_equivalence.py create mode 100644 tools/check_graph_equivalence.py create mode 100644 tools/check_image_equivalence.py create mode 100644 tools/check_interchange_bindings_equivalence.py create mode 100644 tools/check_linear_equivalence.py create mode 100644 tools/check_machinelearning_equivalence.py create mode 100644 tools/check_matrix_equivalence.py create mode 100644 tools/check_matrix_value_equivalence.py create mode 100644 tools/check_numeric_equality.py create mode 100644 tools/check_numeric_equivalence.py create mode 100644 tools/check_numeric_objects_equivalence.py create mode 100644 tools/check_numeric_types_equivalence.py create mode 100644 tools/check_numerical_equivalence.py create mode 100644 tools/check_optimization_equivalence.py create mode 100644 tools/check_polynomial_equivalence.py create mode 100644 tools/check_release_remote.py create mode 100644 tools/check_rotation_equivalence.py create mode 100644 tools/check_scalar_extras.py create mode 100644 tools/check_shape_equivalence.py create mode 100644 tools/check_spectral_equivalence.py create mode 100644 tools/check_stochastic_equivalence.py create mode 100644 tools/check_structural_matrix_equivalence.py create mode 100644 tools/check_tensor_equivalence.py create mode 100644 tools/check_timeseries_equivalence.py create mode 100644 tools/check_units_equivalence.py create mode 100644 tools/generate_algebra_bindings.py create mode 100644 tools/generate_buffer_bindings.py create mode 100644 tools/generate_deeplearning_bindings.py create mode 100644 tools/generate_expression_bindings.py create mode 100644 tools/generate_foundation_bindings.py create mode 100644 tools/generate_geometry_bindings.py create mode 100644 tools/generate_graph_bindings.py create mode 100644 tools/generate_image_bindings.py create mode 100644 tools/generate_interchange_bindings.py create mode 100644 tools/generate_linear_bindings.py create mode 100644 tools/generate_machinelearning_bindings.py create mode 100644 tools/generate_matrix_bindings.py create mode 100644 tools/generate_matrix_value_bindings.py create mode 100644 tools/generate_numeric_bindings.py create mode 100644 tools/generate_numeric_objects.py create mode 100644 tools/generate_numeric_types.py create mode 100644 tools/generate_numerical_bindings.py create mode 100644 tools/generate_optimization_bindings.py create mode 100644 tools/generate_polynomial_bindings.py create mode 100644 tools/generate_rotation_bindings.py create mode 100644 tools/generate_scalar_extras.py create mode 100644 tools/generate_shape_bindings.py create mode 100644 tools/generate_spectral_bindings.py create mode 100644 tools/generate_stochastic_bindings.py create mode 100644 tools/generate_tensor_bindings.py create mode 100644 tools/generate_timeseries_bindings.py create mode 100644 tools/generate_units_bindings.py create mode 100644 tools/numeric_specializations.py create mode 100644 tools/publish_github_release.py create mode 100644 tools/release_manifest.py create mode 100644 tools/release_version.py create mode 100644 tools/select_release_candidate.py create mode 100644 tools/verify_release_candidate.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 9ad78a0..8589918 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -36,14 +36,11 @@ jobs: run: | python -m pip install -r requirements-docs.txt python tools/build_docs.py - - name: Verify Python documentation examples against the released package + - name: Verify Python examples against this source revision run: | - python - <<'PY' - import pathlib, subprocess, sys, tomllib - version = tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'] - subprocess.run([sys.executable, '-m', 'pip', 'install', f'hmath-python[numpy,cffi]=={version}'], check=True) - PY - python tools/check_docs_examples.py + python -m pip install numpy cffi + python meson-build.py . build-docs/libhmath.so --builddir build-docs/cabal --offline + HMATH_LIBRARY="$PWD/build-docs/libhmath.so" PYTHONPATH="$PWD/bindings/python" python tools/check_docs_examples.py - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 with: path: site diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..c8e1a80 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: MPL-2.0 +name: Prepare HMath release + +on: + workflow_dispatch: + workflow_call: + outputs: + version: + description: Version checked against all language packages + value: ${{ jobs.preflight.outputs.version }} + +permissions: + contents: read + +jobs: + preflight: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + - uses: ./.github/actions/setup-haskell + with: + ghc-version: '9.10.3' + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: build-docs/cabal + key: docs-haddock-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**') }} + restore-keys: docs-haddock- + - name: Check every public API before preparing a complete release + run: | + python tools/generate_numeric_bindings.py --check + python tools/generate_matrix_bindings.py --check + python -m pip install -r requirements-docs.txt + python tools/build_docs.py + interface=$(python - <<'PY' + import json, pathlib + plan = json.loads(pathlib.Path('build-docs/cabal/cache/plan.json').read_text()) + library = next(u for u in plan['install-plan'] if u.get('pkg-name') == 'hmath' and u.get('component-name') == 'lib') + print(pathlib.Path(library['dist-dir']) / 'doc/html/hmath/hmath.haddock') + PY + ) + python tools/check_binding_coverage.py --interface "$interface" --require-complete + - name: Read the single project version + id: version + run: echo "version=$(python tools/release_version.py)" >> "$GITHUB_OUTPUT" + validate: + needs: preflight + uses: ./.github/workflows/validate.yml + with: + full-matrix: true + distributions: + needs: preflight + uses: ./.github/workflows/python-wheels.yml + haskell-source: + needs: distributions + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: ./.github/actions/setup-haskell + with: + ghc-version: '9.10.3' + - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 + with: + name: native-distributions + path: source-artifacts + - name: Build the actual Cabal source archive + run: | + version=$(python tools/release_version.py) + mkdir "$RUNNER_TEMP/hmath-source" + tar -xzf "source-artifacts/hmath-$version.tar.gz" -C "$RUNNER_TEMP/hmath-source" + cd "$RUNNER_TEMP/hmath-source/hmath-$version" + cabal check + cabal build lib:hmath flib:hmath --offline -O0 + ready: + needs: [preflight, validate, distributions, haskell-source] + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 + with: + pattern: '*-distributions' + path: candidate + merge-multiple: true + - name: Record checksums and source identity + run: python tools/release_manifest.py candidate --commit "$GITHUB_SHA" --run-id "$GITHUB_RUN_ID" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: release-candidate + path: candidate/* + if-no-files-found: error diff --git a/.github/workflows/publish-python.yml b/.github/workflows/publish-python.yml index 14dbec8..4ce732e 100644 --- a/.github/workflows/publish-python.yml +++ b/.github/workflows/publish-python.yml @@ -1,5 +1,5 @@ # SPDX-License-Identifier: MPL-2.0 -name: Publish Python and GitHub Release +name: Publish HMath release on: workflow_dispatch: @@ -9,73 +9,102 @@ on: type: choice options: [testpypi, pypi] default: testpypi + candidate_run_id: + description: Prepared run ID (blank resumes the staged candidate or selects the latest successful preparation for this commit) + type: string + required: false permissions: contents: read + actions: read concurrency: - group: publish-python-${{ inputs.index }} + group: publish-hmath-${{ inputs.index }} cancel-in-progress: false jobs: - build: + select: if: github.repository == 'wavefnd/hmath' && github.ref == 'refs/heads/master' - uses: ./.github/workflows/python-wheels.yml + runs-on: ubuntu-24.04 + outputs: + run_id: ${{ steps.candidate.outputs.candidate_run_id }} + version: ${{ steps.candidate.outputs.version }} + source_sha: ${{ steps.candidate.outputs.candidate_sha }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Select an existing verified candidate without rebuilding it + id: candidate + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_RUN_ID: ${{ inputs.candidate_run_id }} + run: python tools/select_release_candidate.py --repository "$GITHUB_REPOSITORY" --commit "$GITHUB_SHA" --run-id "$CANDIDATE_RUN_ID" publish: - needs: build + needs: select runs-on: ubuntu-24.04 environment: name: ${{ inputs.index }} permissions: id-token: write + contents: write + actions: read steps: - - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Download the selected immutable candidate + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_RUN_ID: ${{ needs.select.outputs.run_id }} + run: gh run download "$CANDIDATE_RUN_ID" --repo "$GITHUB_REPOSITORY" --name release-candidate --dir candidate + - name: Verify all artifacts and source identity + env: + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + VERSION: ${{ needs.select.outputs.version }} + RUN_ID: ${{ needs.select.outputs.run_id }} + run: python tools/verify_release_candidate.py candidate --commit "$SOURCE_SHA" --version "$VERSION" --run-id "$RUN_ID" + - name: Verify existing package hashes before external writes + id: remote + env: + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + run: python tools/check_release_remote.py --python candidate --native candidate --commit "$SOURCE_SHA" --index '${{ inputs.index }}' + - name: Require Hackage configuration for a new Haskell upload + if: inputs.index == 'pypi' && steps.remote.outputs.haskell_complete != 'true' + env: + HACKAGE_TOKEN: ${{ secrets.HACKAGE_TOKEN }} + run: test -n "$HACKAGE_TOKEN" + - name: Verify and stage all GitHub assets before package publication + if: inputs.index == 'pypi' + env: + GH_TOKEN: ${{ github.token }} + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + run: python tools/publish_github_release.py candidate --repository "$GITHUB_REPOSITORY" --commit "$SOURCE_SHA" --stage-only + - uses: ./.github/actions/setup-haskell + if: inputs.index == 'pypi' && steps.remote.outputs.haskell_complete != 'true' with: - name: python-distributions - path: dist/ + ghc-version: '9.10.3' + - name: Publish the verified Cabal source package + if: inputs.index == 'pypi' && steps.remote.outputs.haskell_complete != 'true' + env: + HACKAGE_TOKEN: ${{ secrets.HACKAGE_TOKEN }} + VERSION: ${{ needs.select.outputs.version }} + run: cabal upload --publish --token="$HACKAGE_TOKEN" "candidate/hmath-$VERSION.tar.gz" + - name: Stage Python-only upload files + run: | + mkdir dist + cp candidate/*.whl candidate/hmath_python-*.tar.gz dist/ - name: Publish to TestPyPI - if: inputs.index == 'testpypi' + if: inputs.index == 'testpypi' && steps.remote.outputs.python_complete != 'true' uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 with: repository-url: https://test.pypi.org/legacy/ + skip-existing: true - name: Publish to PyPI - if: inputs.index == 'pypi' + if: inputs.index == 'pypi' && steps.remote.outputs.python_complete != 'true' uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 - - github-release: - if: inputs.index == 'pypi' - needs: [build, publish] - runs-on: ubuntu-24.04 - permissions: - contents: write - steps: - - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 with: - name: python-distributions - path: dist/ - - name: Create the versioned GitHub release + skip-existing: true + - name: Publish the staged GitHub release + if: inputs.index == 'pypi' env: GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - RELEASE_VERSION: ${{ needs.build.outputs.version }} - RELEASE_SHA: ${{ github.sha }} - run: | - tag="v$RELEASE_VERSION" - error_log="$RUNNER_TEMP/release-tag-error.log" - if ! existing="$(gh api "repos/$GH_REPO/commits/$tag" --jq .sha 2>"$error_log")"; then - if ! grep -Eq '\(HTTP (404|422)\)' "$error_log"; then - cat "$error_log" >&2 - exit 1 - fi - existing="" - fi - if [ -n "$existing" ] && [ "$existing" != "$RELEASE_SHA" ]; then - echo "Tag $tag points to another commit; refusing to publish mismatched artifacts." - exit 1 - fi - gh release create "$tag" dist/* \ - --target "$RELEASE_SHA" \ - --title "HMath $RELEASE_VERSION" \ - --generate-notes \ - --latest + SOURCE_SHA: ${{ needs.select.outputs.source_sha }} + run: python tools/publish_github_release.py candidate --repository "$GITHUB_REPOSITORY" --commit "$SOURCE_SHA" diff --git a/.github/workflows/python-wheels.yml b/.github/workflows/python-wheels.yml index 7dbd531..12b0704 100644 --- a/.github/workflows/python-wheels.yml +++ b/.github/workflows/python-wheels.yml @@ -39,15 +39,39 @@ jobs: - name: Build self-contained manylinux wheel and source distribution run: | docker run --rm --volume "$PWD:/io" \ + --env SOURCE_DATE_EPOCH="$(git show -s --format=%ct HEAD)" \ quay.io/pypa/manylinux_2_28_x86_64@sha256:e0adf18521ad35192df733a6c62d35df7801957d24e0470238aacecfab2188a3 \ bash /io/tools/build_python_wheel.sh python -m pip install twine - python -m twine check --strict dist/* + python -m twine check --strict dist/*.whl dist/hmath_python-*.tar.gz - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: python-distributions - path: dist/* + path: | + dist/*.whl + dist/hmath_python-*.tar.gz if-no-files-found: error + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: native-distributions + path: dist/native/* + if-no-files-found: error + + c-sdk: + needs: build + runs-on: ubuntu-24.04 + container: python:3.12-slim-bookworm + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 + with: + name: native-distributions + path: /tmp/hmath-native + - name: Verify the relocated SDK without GHC + run: | + apt-get update + apt-get install -y --no-install-recommends build-essential pkg-config cmake + python tools/check_c_sdk.py /tmp/hmath-native/hmath-*-linux-x86_64.tar.gz test: needs: build @@ -70,4 +94,10 @@ jobs: python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" python -m pip install numpy cffi python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/bindings/python/test_bindings.py" + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/test/native/expanded_bindings.py" + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/test/native/autodiff_bindings.py" + for contract in value polynomial optimization units expression linear stochastic numerical spectral foundation tensor; do + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/test/native/${contract}_bindings.py" + done + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/test/native/callback_errors.py" python "$GITHUB_WORKSPACE/tools/check_docs_examples.py" diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index a4242c3..84f0f73 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -46,6 +46,7 @@ jobs: ${{ steps.haskell.outputs.cabal-store }} dist-newstyle build-ci/cabal + build-ci/numeric-oracle build-interchange/cabal key: cabal-${{ runner.os }}-${{ matrix.ghc }}-${{ matrix.buildtype }}-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**', 'test/**', 'bench/**') }} restore-keys: cabal-${{ runner.os }}-${{ matrix.ghc }}-${{ matrix.buildtype }}- @@ -114,6 +115,7 @@ jobs: ${{ steps.haskell.outputs.cabal-store }} dist-newstyle build-ci/cabal + build-ci/numeric-oracle build-interchange/cabal key: cabal-extended-${{ runner.os }}-9.10.3-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**', 'test/**', 'bench/**') }} restore-keys: | diff --git a/MANIFEST.in b/MANIFEST.in index a12c9d3..b946f33 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -6,10 +6,11 @@ recursive-include include *.h recursive-include bindings/python/_hmath_native/licenses * recursive-include bindings/python *.py LICENSE recursive-include bindings/wave *.wave -recursive-include docs *.md +recursive-include docs *.md *.css *.js recursive-include tools *.py *.sh -recursive-include test *.hs *.c *.py *.txt +recursive-include test *.hs *.c *.cpp *.py *.txt recursive-include examples *.hs *.c *.py recursive-include bench *.hs *.c recursive-include meson *.in recursive-include .github/workflows *.yml +recursive-include bindings/schema *.json *.txt diff --git a/bindings/python/_hmath_native/_algebra_base.py b/bindings/python/_hmath_native/_algebra_base.py new file mode 100644 index 0000000..71831a5 --- /dev/null +++ b/bindings/python/_hmath_native/_algebra_base.py @@ -0,0 +1,99 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original algebra instance selection and independent Value ownership.""" + +import ctypes as C + +from . import _value as V +from ._foundation_base import _invoke as plain_invoke + + +def _snapshot(spec, value): + if spec[0] == "list": + return [_snapshot(spec[1], item) for item in value] + if spec[0] == "tuple": + value = tuple(value) + if len(value) != len(spec) - 1: + raise ValueError("tuple arity differs from original signature") + return tuple(_snapshot(s, item) for s, item in zip(spec[1:], value)) + return value + + +def _candidate(spec, value): + if spec[0] in ("a", "s", "v", "Additive", "Matrix", "Vector", "Tensor"): + if spec[0] == "v": + return value[0] if value else None + return value + if spec[0] in ("list", "tuple"): + specs = [spec[1]] * len(value) if spec[0] == "list" else spec[1:] + for child, item in zip(specs, value): + result = _candidate(child, item) + if result is not None: + return result + return None + + +def invoke(symbol, specs, arguments, mode="value", dtype=None): + if mode == "value": + return plain_invoke(symbol, specs, arguments) + arguments = [_snapshot(s, value) for s, value in zip(specs, arguments)] + prototype = dtype + if prototype is None: + for spec, value in zip(specs, arguments): + prototype = _candidate(spec, value) + if prototype is not None: + break + if isinstance(prototype, V.Value): + prototype = prototype.clone() + elif isinstance(prototype, str) and dtype is not None: + if prototype in ("bool", "string"): + prototype = V.encode(False if prototype == "bool" else "") + else: + prototype = V.scalar(0, prototype) + elif hasattr(prototype, "dtype"): + prototype = V.scalar(0, prototype.dtype) + elif isinstance(prototype, (bool, str)): + prototype = V.encode(prototype) + else: + prototype = V.scalar(prototype if prototype is not None else 0) + owners = [prototype] + try: + target = prototype.dtype + + def prepare(spec, value): + head, *children = spec + if head in ("a", "s"): + if isinstance(value, V.Value): + item = value.clone() + elif prototype.info[0] in (3, 10): + item = V.encode(value) + else: + item = V.scalar(value, target) + owners.append(item) + return item + if head == "v": + return [prepare(["a"], item) for item in value] + if head == "list": + return [prepare(children[0], item) for item in value] + if head == "tuple": + return tuple(prepare(s, item) for s, item in zip(children, value)) + if head in ("Integer", "Rational"): + item = ( + value.clone() + if isinstance(value, V.Value) + else V.scalar(value, head.lower()) + ) + owners.append(item) + return item + return value + + prepared = [prepare(s, value) for s, value in zip(specs, arguments)] + return V.decode(V.invoke(symbol, prototype, *prepared)) + finally: + for owner in owners: + owner.close() + + +def initialize(owner, symbol, specs, arguments, mode, dtype): + result = invoke(symbol, specs, arguments, mode, dtype) + owner._ptr, owner._lock, owner._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () diff --git a/bindings/python/_hmath_native/_autodiff_value.py b/bindings/python/_hmath_native/_autodiff_value.py new file mode 100644 index 0000000..3df1279 --- /dev/null +++ b/bindings/python/_hmath_native/_autodiff_value.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless ownership bridge for the original Autodiff, separate from Numeric.Dual.""" + +import ctypes as C + +from . import _value as v +from . import autodiff as ad + + +def import_value(value): + import hmath + + if not isinstance(value, (ad.Expr, ad.ADTensor, ad.Dual)): + raise TypeError("expected original Autodiff Expr, ADTensor or Dual") + result = v.Value._adopt() + hmath.initialize() + with ad._locked(value): + result._owners = tuple(value._keepers) + ad._check( + v.api( + "hmath_ad_value_import", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, value._ptr, C.byref(result._ptr)) + ) + return result + + +def export_value(value, owner=None): + import hmath + + if not isinstance(value, v.Value): + value = v.encode(value) + else: + value = value.clone() + try: + with value._lock: + if owner is None: + kind = value.info[0] + owner = {287: ad.Expr, 288: ad.ADTensor}.get(kind, ad.Dual) + result = owner._adopt(C.c_void_p(), keepers=value._owners) + hmath.initialize() + ad._check( + v.api( + "hmath_ad_value_export", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, value._ptr, C.byref(result._ptr)) + ) + return result + finally: + value.close() + + +def _decode(value, owner): + try: + return export_value(value, owner) + finally: + value.close() + + +v.register(287, lambda value: _decode(value, ad.Expr)) +v.register(288, lambda value: _decode(value, ad.ADTensor)) +v.register(289, lambda value: _decode(value, ad.Dual)) +v.register_encoder(ad.Expr, import_value) +v.register_encoder(ad.ADTensor, import_value) +v.register_encoder(ad.Dual, import_value) diff --git a/bindings/python/_hmath_native/_buffer_base.py b/bindings/python/_hmath_native/_buffer_base.py new file mode 100644 index 0000000..4c885aa --- /dev/null +++ b/bindings/python/_hmath_native/_buffer_base.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Buffer owners, scoped borrows and exact Storable transport.""" + +import operator + +from . import _value as V +from ._foundation_base import FoundationValue, register +from ._numerical_base import _invoke + + +def _call(name, arguments, callback=None): + specs = [["Value"] for _ in arguments] + if callback is not None: + specs[callback] = ["function", ["Value"], ["Value"]] + return _invoke("hmath_buffer_" + name, specs, arguments) + + +def _typed(value, dtype=None): + if isinstance(value, V.Value): + kind, code, count = value.info + actual = 16 if kind == 3 else 17 if kind == 10 and count == 1 else code + expected = {"bool": 16, "char": 17}.get(dtype, V.DTYPES.get(dtype, dtype)) + if dtype is not None and actual != expected: + raise TypeError("explicit storage type differs from the actual scalar") + return value.clone() + if dtype == 16 or dtype == "bool": + if not isinstance(value, bool): + raise TypeError("Bool storage requires bool") + return V.encode(value) + if dtype == 17 or dtype == "char": + if not isinstance(value, str) or len(value) != 1: + raise TypeError("Char storage requires one character") + return V.encode(value) + if dtype is None: + if isinstance(value, (bool, str)): + return V.encode(value) + if isinstance(value, int): + dtype = "intp" + return V.scalar(value, dtype) + + +def _boxed(name, values, dtype=None): + if dtype is None: + return _call(name, [list(values)]) + owners = [] + try: + owners = [_typed(item, dtype) for item in values] + return _call(name, [owners]) + finally: + for owner in owners: + owner.close() + + +def _initialize(owner, result): + owner._ptr, owner._lock, owner._owners = result._ptr, result._lock, result._owners + import ctypes as C + + result._ptr, result._owners = C.c_void_p(), () + + +class Boxed(FoundationValue): + """Original immutable Boxed a. dtype optionally selects scalar element type.""" + + _source_type = "HMath.API.Buffer.Boxed" + + def __init__(self, values, *, strict=False, dtype=None): + _initialize( + self, _boxed("strict_boxed" if strict else "lazy_boxed", values, dtype) + ) + + @property + def values(self): + return _call("boxed_values", [self]) + + def __len__(self): + return _call("boxed_length", [self]) + + def map(self, function): + return _call("map_strict", [function, self], 0) + + +class UnboxedDouble(FoundationValue): + """Actual immutable unboxed Double array, including NaN and infinity.""" + + _source_type = "HMath.API.Buffer.UnboxedDouble" + + def __init__(self, values): + _initialize(self, _call("unboxed_double", [[float(x) for x in values]])) + + @property + def values(self): + return _call("unboxed_values", [self]) + + +class STBuffer(FoundationValue): + """Mutable original ST region: valid only in its run_st_buffer callback.""" + + _source_type = "HMath.API.Buffer.STBuffer" + + @property + def active(self): + return _call("st_active", [self]) + + def read(self, index): + return _call("read_st_buffer", [self, operator.index(index)]) + + def write(self, index, value): + return _call("write_st_buffer", [self, operator.index(index), value]) + + def freeze(self): + return _call("freeze_st_buffer", [self]) + + def thaw(self, boxed): + return _call("thaw_st_buffer", [self, boxed]) + + +class IOBuffer(FoundationValue): + """Actual pinned, synchronized Storable IO buffer. Freeze and thaw copy.""" + + _source_type = "HMath.API.Buffer.IOBuffer" + + def __init__(self, count, initial, *, dtype=None): + _initialize(self, _new_io(count, initial, dtype)) + + @property + def dtype(self): + code = self.info[1] + return {16: "bool", 17: "char"}.get(code, V.DTYPE_NAMES.get(code)) + + def __len__(self): + return _call("io_buffer_length", [self]) + + @property + def layout(self): + """Actual (dtype, Storable size, alignment, element count).""" + return _call("storage_info", [self]) + + def read(self, index): + return _call("read_io_buffer", [self, operator.index(index)]) + + def write(self, index, value): + owner = _typed(value, self.dtype) + try: + return _call("write_io_buffer", [self, operator.index(index), owner]) + finally: + owner.close() + + def freeze(self): + return _call("freeze_io_buffer", [self]) + + def with_pointer(self, callback): + return _call("with_io_buffer", [self, callback], 1) + + +class BorrowedPointer(FoundationValue): + """Checked view of the actual Ptr a, valid only in with_pointer's callback. + + The raw address must never be retained. Do not reenter locking operations on + the same IOBuffer while borrowed. Reads/writes through this view are checked + and use the original Storable instance, including Bool/Char ABI layouts. + """ + + _source_type = "HMath.API.Buffer.BorrowedPointer" + + @property + def dtype(self): + code = self.info[1] + return {16: "bool", 17: "char"}.get(code, V.DTYPE_NAMES.get(code)) + + @property + def active(self): + return _call("pointer_active", [self]) + + @property + def layout(self): + return _call("pointer_info", [self]) + + @property + def address(self): + return _call("pointer_address", [self]) + + def read(self, index): + return _call("pointer_read", [self, operator.index(index)]) + + def write(self, index, value): + owner = _typed(value, self.dtype) + try: + return _call("pointer_write", [self, operator.index(index), owner]) + finally: + owner.close() + + +for _owner in (Boxed, UnboxedDouble, STBuffer, IOBuffer, BorrowedPointer): + register(_owner._source_type, _owner) + + +def _new_io(count, initial, dtype=None): + owner = _typed(initial, dtype) + try: + return _call("new_io_buffer", [operator.index(count), owner]) + finally: + owner.close() + + +def _thaw_io(boxed, dtype=None, prototype=None): + if dtype is None: + return _call("thaw_io_buffer", [prototype, boxed]) + if prototype is not None: + raise TypeError("supply dtype or prototype, not both") + values = boxed.values + owners = [] + typed_box = None + exemplar = None + try: + owners = [_typed(item, dtype) for item in values] + typed_box = _call("lazy_boxed", [owners]) + exemplar = ( + owners[0] + if owners + else _typed( + "\0" + if dtype in (17, "char") + else False + if dtype in (16, "bool") + else 0, + dtype, + ) + ) + return _call("thaw_io_buffer", [exemplar, typed_box]) + finally: + if exemplar is not None and not owners: + exemplar.close() + if typed_box is not None: + typed_box.close() + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_bytes.py b/bindings/python/_hmath_native/_bytes.py new file mode 100644 index 0000000..e393995 --- /dev/null +++ b/bindings/python/_hmath_native/_bytes.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Immutable native bytes, with owned copies and read-only borrowed views.""" + +import ctypes as C + +from . import _value as value + + +class Bytes(value.Value): + def __new__(cls, source): + import hmath + + data = bytes(source) + result = cls._adopt() + hmath.initialize() + hmath._check( + value.api( + "hmath_bytes_copy", + C.c_int, + C.c_void_p, + C.c_void_p, + C.c_size_t, + C.POINTER(C.c_void_p), + )(None, C.c_char_p(data), len(data), C.byref(result._ptr)) + ) + return result + + def _span(self): + import hmath + + pointer, count = C.c_void_p(), C.c_size_t() + if not self._ptr: + raise ValueError("bytes are closed") + hmath._check( + value.api( + "hmath_bytes_data", + C.c_int, + C.c_void_p, + C.POINTER(C.c_void_p), + C.POINTER(C.c_size_t), + )(self._ptr, C.byref(pointer), C.byref(count)) + ) + return pointer.value or 0, count.value + + def __bytes__(self): + with self._lock: + pointer, count = self._span() + return C.string_at(pointer, count) + + def view(self): + """Return a read-only byte view retaining an independent native owner.""" + with self._lock: + owner = self.clone() + try: + pointer, count = self._span() + raw = (C.c_ubyte * count).from_address(pointer) + raw._hmath_owner = owner + return memoryview(raw).cast("B").toreadonly() + except BaseException: + owner.close() + raise + + def __len__(self): + return self.info[2] + + +value.register(450, Bytes) +value.register_encoder(bytes, Bytes) +value.register_encoder(bytearray, Bytes) diff --git a/bindings/python/_hmath_native/_callback_error.py b/bindings/python/_hmath_native/_callback_error.py new file mode 100644 index 0000000..02e7abc --- /dev/null +++ b/bindings/python/_hmath_native/_callback_error.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Status-selected structured error payloads for the shared callback wire.""" + +import ctypes as C + +from ._expression_error import ErrorKind, ExprError +from ._interchange_error import fill as fill_interchange +from ._math_error import fill as fill_math +from ._numeric import _int + + +def fill(pointer, error, owners): + """Return11/12/13 for a domain error, or0 for an ordinary Python exception.""" + if fill_math(pointer, error, owners): + return 11 + expression = ( + error + if isinstance(error, ExprError) + else getattr(error, "expression_error", None) + ) + if isinstance(expression, ExprError): + pointer.contents.kind = ErrorKind(expression.kind) + fields = ( + expression.position.offset, + expression.position.line, + expression.position.column, + ) + for index in range(6): + pointer.contents.details[index] = _int(fields[index]) if index < 3 else 0 + data = expression.message.encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(data) + owners.append(buffer) + pointer.contents.message = C.cast(buffer, C.c_void_p) + pointer.contents.message_length = len(data) + return 12 + if fill_interchange(pointer, error, owners): + return 13 + return 0 diff --git a/bindings/python/_hmath_native/_compat.py b/bindings/python/_hmath_native/_compat.py new file mode 100644 index 0000000..742c9a4 --- /dev/null +++ b/bindings/python/_hmath_native/_compat.py @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Small compatibility helpers for the supported Python 3.9 baseline.""" + +from itertools import zip_longest + + +def zip_equal(*iterables): + """Zip equal-length inputs, rejecting an unmatched tail on Python 3.9+.""" + missing = object() + for values in zip_longest(*iterables, fillvalue=missing): + if any(value is missing for value in values): + raise ValueError("zip arguments have different lengths") + yield values diff --git a/bindings/python/_hmath_native/_expression_base.py b/bindings/python/_hmath_native/_expression_base.py new file mode 100644 index 0000000..c3c49b9 --- /dev/null +++ b/bindings/python/_hmath_native/_expression_base.py @@ -0,0 +1,1276 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original positioned expression trees and bounded symbolic transformations.""" + +import ctypes as C +from dataclasses import dataclass +from enum import IntEnum +from fractions import Fraction + +from . import _value as v +from . import ( + polynomial as _polynomial, # noqa: F401 - register exact polynomial/series owners +) +from ._compat import zip_equal +from ._expression_catalog import CATALOG +from ._expression_error import ErrorKind, ExprError, SourcePos +from ._numeric import _int + +_SPEC = {entry["module"] + "." + entry["name"]: entry for entry in CATALOG} + + +class UnaryOp(IntEnum): + NEGATE = 0 + + +class BinaryOp(IntEnum): + ADD = 0 + SUBTRACT = 1 + MULTIPLY = 2 + DIVIDE = 3 + POWER = 4 + + +class NamedConstant(IntEnum): + PI = 0 + EULER = 1 + TAU = 2 + + +class Precision(IntEnum): + EXACT_RATIONAL = 0 + FLOAT64 = 1 + + +class Builtin(IntEnum): + SIN = 0 + COS = 1 + TAN = 2 + EXP = 3 + LOG = 4 + SQRT = 5 + ABS = 6 + SIGNUM = 7 + FLOOR = 8 + CEILING = 9 + MIN = 10 + MAX = 11 + ASIN = 12 + ACOS = 13 + ATAN = 14 + SINH = 15 + COSH = 16 + TANH = 17 + + +class Property(IntEnum): + REAL = 0 + NON_ZERO = 1 + POSITIVE = 2 + NON_NEGATIVE = 3 + INTEGRAL = 4 + NEGATIVE = 5 + NON_POSITIVE = 6 + + +class Direction(IntEnum): + FROM_LEFT = 0 + FROM_RIGHT = 1 + TWO_SIDED = 2 + + +class RelationOp(IntEnum): + EQUAL = 0 + NOT_EQUAL = 1 + LESS = 2 + LESS_EQUAL = 3 + GREATER = 4 + GREATER_EQUAL = 5 + + +@dataclass(frozen=True) +class Limits: + maximum_steps: int = 100000 + maximum_depth: int = 128 + maximum_nodes: int = 20000 + maximum_input_chars: int = 100000 + maximum_integer_bits: int = 1024 + maximum_cache_entries: int = 64 + + +class Value: + """Original tagged expression value; ExactValue and FloatValue stay distinct.""" + + +@dataclass(frozen=True) +class ExactValue(Value): + value: Fraction + + +@dataclass(frozen=True) +class FloatValue(Value): + value: float + + +Bindings = dict[str, Value] + + +@dataclass(frozen=True) +class SymbolicOptions: + limits: Limits + assumptions: object + + +@dataclass(frozen=True) +class PolynomialFactorization: + leading: Fraction + terms: list + + +@dataclass(frozen=True) +class RewriteRule: + pattern: object + replacement: object + requirements: list + + +@dataclass(frozen=True) +class Series: + center: Fraction + minimum_power: int + terms: list + + +@dataclass(frozen=True) +class Relation: + operator: RelationOp + left: object + right: object + + +@dataclass(frozen=True) +class Guarded: + value: object + conditions: list + + +@dataclass(frozen=True) +class _Sum: + name: str + arguments: tuple = () + + +class LimitResult(_Sum): + pass + + +class RelationResult(_Sum): + pass + + +class LinearSolution(_Sum): + pass + + +class Expr(v.Value): + """Immutable original Expr, retaining its source position and full AST.""" + + def __init__(self, position, node): + result = _raw("HMath.Expression.Expr", position, node) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + @property + def position(self): + return expression_position(self) + + @property + def node(self): + return expression_node(self) + + def __eq__(self, other): + if not isinstance(other, Expr): + return NotImplemented + return _extra("hmath_expression_compare", self, other) == 0 + + def __lt__(self, other): + if not isinstance(other, Expr): + return NotImplemented + return _extra("hmath_expression_compare", self, other) < 0 + + def __le__(self, other): + if not isinstance(other, Expr): + return NotImplemented + return _extra("hmath_expression_compare", self, other) <= 0 + + def __gt__(self, other): + if not isinstance(other, Expr): + return NotImplemented + return _extra("hmath_expression_compare", self, other) > 0 + + def __ge__(self, other): + if not isinstance(other, Expr): + return NotImplemented + return _extra("hmath_expression_compare", self, other) >= 0 + + __hash__ = None + + +class ExprNode(v.Value): + @property + def fields(self): + """(constructor code, payload...), preserving child Expr owners. + + Codes:0Literal,1Variable,2Constant,3Unary,4Binary,5Call,6Let. + """ + fields = _extra("hmath_expression_node_fields", self) + kind = fields[0] + if kind == 2: + return (kind, NamedConstant(fields[1])) + if kind == 3: + return (kind, UnaryOp(fields[1]), fields[2]) + if kind == 4: + return (kind, BinaryOp(fields[1]), *fields[2:]) + return fields + + def __eq__(self, other): + if not isinstance(other, ExprNode): + return NotImplemented + return _extra("hmath_expression_node_compare", self, other) == 0 + + def __lt__(self, other): + if not isinstance(other, ExprNode): + return NotImplemented + return _extra("hmath_expression_node_compare", self, other) < 0 + + __hash__ = None + + +class Registry(v.Value): + pass + + +class Compiled(v.Value): + pass + + +class ExpressionCache(v.Value): + pass + + +class Pattern(v.Value): + @property + def fields(self): + """(constructor code, payload...): Any,Exactly,Unary,Binary,Call.""" + fields = _extra("hmath_symbolic_pattern_fields", self) + if fields[0] == 2: + return (fields[0], UnaryOp(fields[1]), *fields[2:]) + if fields[0] == 3: + return (fields[0], BinaryOp(fields[1]), *fields[2:]) + return fields + + def __eq__(self, other): + if not isinstance(other, Pattern): + return NotImplemented + return _extra("hmath_symbolic_pattern_equal", self, other) + + __hash__ = None + + +class Assumptions(v.Value): + pass + + +class SymbolicMatrix(v.Value): + pass + + +for _kind, _owner in [ + (80, Expr), + (81, ExprNode), + (82, Registry), + (83, Compiled), + (84, ExpressionCache), + (85, Pattern), + (86, Assumptions), + (87, SymbolicMatrix), +]: + v.register(_kind, _owner) + +_ENUMS = { + cls.__name__: cls + for cls in [ + UnaryOp, + BinaryOp, + NamedConstant, + Precision, + Builtin, + ErrorKind, + Property, + Direction, + RelationOp, + ] +} +_RECORDS = { + "SourcePos": (SourcePos, ["offset", "line", "column"], ["Int"] * 3), + "Limits": ( + Limits, + [ + "maximum_steps", + "maximum_depth", + "maximum_nodes", + "maximum_input_chars", + "maximum_integer_bits", + "maximum_cache_entries", + ], + ["Int"] * 6, + ), + "ExprError": ( + ExprError, + ["kind", "position", "message"], + ["ErrorKind", "SourcePos", "String"], + ), + "SymbolicOptions": ( + SymbolicOptions, + ["limits", "assumptions"], + ["Limits", "Assumptions"], + ), + "PolynomialFactorization": ( + PolynomialFactorization, + ["leading", "terms"], + ["Rational", "[(Expr,Int)]"], + ), + "RewriteRule": ( + RewriteRule, + ["pattern", "replacement", "requirements"], + ["Pattern", "Expr", "[(String,Property)]"], + ), + "Series": ( + Series, + ["center", "minimum_power", "terms"], + ["Rational", "Int", "[Expr]"], + ), + "Relation": ( + Relation, + ["operator", "left", "right"], + ["RelationOp", "Expr", "Expr"], + ), + "Guarded": (Guarded, ["value", "conditions"], ["Generic", "[(Expr,Property)]"]), +} + + +def _split(hint): + depth = 0 + start = 0 + parts = [] + for index, char in enumerate(hint): + if char in "[(": + depth += 1 + elif char in "])": + depth -= 1 + elif char == "," and depth == 0: + parts.append(hint[start:index]) + start = index + 1 + parts.append(hint[start:]) + return parts + + +def _pack(items, hints, tuple_=False): + values = [] + try: + for item, hint in zip_equal(items, hints): + values.append(_typed(item, hint)) + return v.encode(tuple(values) if tuple_ else values) + finally: + for value in values: + value.close() + + +def _typed(value, hint): + if isinstance(value, v.Value): + return value.clone() + if isinstance(value, _Sum): + entry = next( + e + for e in CATALOG + if e["name"] == value.name and e["module"] == "HMath.Symbolic" + ) + return _raw(entry["module"] + "." + entry["name"], *value.arguments) + if hint == "Int" or hint in _ENUMS: + if hint in _ENUMS: + value = _ENUMS[hint](value) + return v._create("hmath_value_index", [C.c_ssize_t], [_int(value)]) + if hint == "Rational": + return v.scalar(value, "rational") + if hint == "Double": + return v.scalar(value, "float64") + if hint == "String": + if not isinstance(value, str): + raise TypeError("expected String") + return v.encode(value) + if hint == "Bool": + if not isinstance(value, bool): + raise TypeError("expected Bool") + return v.encode(value) + if hint == "ExpressionValue": + if isinstance(value, ExactValue): + return _pack([0, value.value], ["Int", "Rational"], True) + if isinstance(value, FloatValue): + return _pack([1, value.value], ["Int", "Double"], True) + raise TypeError("expected ExactValue or FloatValue") + if hint == "Bindings": + items = list(value.items()) if isinstance(value, dict) else list(value) + return _typed(items, "[(String,ExpressionValue)]") + if hint.startswith("Maybe"): + return v.encode(None) if value is None else _typed(value, hint[5:]) + if hint.startswith("["): + items = list(value) + return _pack(items, [hint[1:-1]] * len(items)) + if hint.startswith("("): + return _pack(tuple(value), _split(hint[1:-1]), True) + if hint in _RECORDS: + cls, names, hints = _RECORDS[hint] + if not isinstance(value, cls): + raise TypeError("expected " + hint) + return _pack([getattr(value, name) for name in names], hints, True) + if hint == "Generic": + for record, (cls, _, _) in _RECORDS.items(): + if isinstance(value, cls): + return _typed(value, record) + if isinstance(value, Value): + return _typed(value, "ExpressionValue") + return v.encode(value) + return v.encode(value) + + +def _decode(value, hint): + if hint in _ENUMS: + return _ENUMS[hint](value) + if hint == "ExpressionValue": + return ExactValue(value[1]) if value[0] == 0 else FloatValue(value[1]) + if hint in _RECORDS: + cls, _, hints = _RECORDS[hint] + return cls(*[_decode(item, field) for item, field in zip_equal(value, hints)]) + if hint == "Guarded[Expr]": + return Guarded(value[0], [(expr, Property(prop)) for expr, prop in value[1]]) + if hint == "LimitResult": + names = ["FiniteLimit", "PositiveInfinity", "NegativeInfinity", "DoesNotExist"] + return LimitResult(names[value[0]], tuple(value[1:])) + if hint == "RelationResult": + return ( + RelationResult("Truth", (value[1],)) + if value[0] == 0 + else RelationResult("Unresolved", (_decode(value[1], "Relation"),)) + ) + if hint == "LinearSolution": + return ( + LinearSolution("Inconsistent") + if value[0] == 0 + else LinearSolution("ParametricSolution", (value[1], value[2])) + ) + if hint.startswith("Maybe"): + return None if value is None else _decode(value, hint[5:]) + if hint.startswith("["): + return [_decode(item, hint[1:-1]) for item in value] + if hint.startswith("("): + return tuple( + _decode(item, field) for item, field in zip_equal(value, _split(hint[1:-1])) + ) + return value + + +def _raw(name, *arguments): + entry = _SPEC[name] + if len(arguments) != len(entry["arguments"]): + raise TypeError(name + " argument count differs") + values = [] + try: + for value, (_, hint) in zip_equal(arguments, entry["arguments"]): + values.append(_typed(value, hint)) + return v.invoke(entry["c"], *values) + finally: + for value in values: + value.close() + + +def _invoke(name, *arguments): + return _decode(v.decode(_raw(name, *arguments)), _SPEC[name]["result"]) + + +def _extra(symbol, *args): + return v.decode(v.invoke(symbol, *args)) + + +# BEGIN GENERATED +def unknown_position(): + """HMath.Expression.unknownPosition: original semantics and checked errors.""" + return _invoke("HMath.Expression.unknownPosition") + + +def source_offset(position): + """HMath.Expression.sourceOffset: original semantics and checked errors.""" + return _invoke("HMath.Expression.sourceOffset", position) + + +def source_line(position): + """HMath.Expression.sourceLine: original semantics and checked errors.""" + return _invoke("HMath.Expression.sourceLine", position) + + +def source_column(position): + """HMath.Expression.sourceColumn: original semantics and checked errors.""" + return _invoke("HMath.Expression.sourceColumn", position) + + +Negate = UnaryOp.NEGATE + +Add = BinaryOp.ADD + +Subtract = BinaryOp.SUBTRACT + +Multiply = BinaryOp.MULTIPLY + +Divide = BinaryOp.DIVIDE + +Power = BinaryOp.POWER + +Pi = NamedConstant.PI + +Euler = NamedConstant.EULER + +Tau = NamedConstant.TAU + +ExactRational = Precision.EXACT_RATIONAL + +Float64 = Precision.FLOAT64 + +SyntaxError = ErrorKind.SYNTAX_ERROR + +UnknownName = ErrorKind.UNKNOWN_NAME + +TypeMismatch = ErrorKind.TYPE_MISMATCH + +DomainFailure = ErrorKind.DOMAIN_FAILURE + +NonFinite = ErrorKind.NON_FINITE + +StepLimit = ErrorKind.STEP_LIMIT + +DepthLimit = ErrorKind.DEPTH_LIMIT + +MemoryLimit = ErrorKind.MEMORY_LIMIT + +InvalidLimits = ErrorKind.INVALID_LIMITS + +Unsupported = ErrorKind.UNSUPPORTED + +Sin = Builtin.SIN + +Cos = Builtin.COS + +Tan = Builtin.TAN + +Exp = Builtin.EXP + +Log = Builtin.LOG + +Sqrt = Builtin.SQRT + +Abs = Builtin.ABS + +Signum = Builtin.SIGNUM + +Floor = Builtin.FLOOR + +Ceiling = Builtin.CEILING + +Min = Builtin.MIN + +Max = Builtin.MAX + +Asin = Builtin.ASIN + +Acos = Builtin.ACOS + +Atan = Builtin.ATAN + +Sinh = Builtin.SINH + +Cosh = Builtin.COSH + +Tanh = Builtin.TANH + + +def expression_position(expression): + """HMath.Expression.expressionPosition: original semantics and checked errors.""" + return _invoke("HMath.Expression.expressionPosition", expression) + + +def expression_node(expression): + """HMath.Expression.expressionNode: original semantics and checked errors.""" + return _invoke("HMath.Expression.expressionNode", expression) + + +def Literal(value): + """HMath.Expression.Literal: original semantics and checked errors.""" + return _invoke("HMath.Expression.Literal", value) + + +def Variable(name): + """HMath.Expression.Variable: original semantics and checked errors.""" + return _invoke("HMath.Expression.Variable", name) + + +def Constant(constant): + """HMath.Expression.Constant: original semantics and checked errors.""" + return _invoke("HMath.Expression.Constant", constant) + + +def Unary(operator, child): + """HMath.Expression.Unary: original semantics and checked errors.""" + return _invoke("HMath.Expression.Unary", operator, child) + + +def Binary(operator, left, right): + """HMath.Expression.Binary: original semantics and checked errors.""" + return _invoke("HMath.Expression.Binary", operator, left, right) + + +def Call(name, arguments): + """HMath.Expression.Call: original semantics and checked errors.""" + return _invoke("HMath.Expression.Call", name, arguments) + + +def Let(name, value, body): + """HMath.Expression.Let: original semantics and checked errors.""" + return _invoke("HMath.Expression.Let", name, value, body) + + +def literal(value): + """HMath.Expression.literal: original semantics and checked errors.""" + return _invoke("HMath.Expression.literal", value) + + +def variable(name): + """HMath.Expression.variable: original semantics and checked errors.""" + return _invoke("HMath.Expression.variable", name) + + +def constant(constant): + """HMath.Expression.constant: original semantics and checked errors.""" + return _invoke("HMath.Expression.constant", constant) + + +def unary(operator, child): + """HMath.Expression.unary: original semantics and checked errors.""" + return _invoke("HMath.Expression.unary", operator, child) + + +def binary(operator, left, right): + """HMath.Expression.binary: original semantics and checked errors.""" + return _invoke("HMath.Expression.binary", operator, left, right) + + +def call(name, arguments): + """HMath.Expression.call: original semantics and checked errors.""" + return _invoke("HMath.Expression.call", name, arguments) + + +def let_in(name, value, body): + """HMath.Expression.letIn: original semantics and checked errors.""" + return _invoke("HMath.Expression.letIn", name, value, body) + + +def default_limits(): + """HMath.Expression.defaultLimits: original semantics and checked errors.""" + return _invoke("HMath.Expression.defaultLimits") + + +def maximum_steps(limits): + """HMath.Expression.maximumSteps: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumSteps", limits) + + +def maximum_depth(limits): + """HMath.Expression.maximumDepth: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumDepth", limits) + + +def maximum_nodes(limits): + """HMath.Expression.maximumNodes: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumNodes", limits) + + +def maximum_input_chars(limits): + """HMath.Expression.maximumInputChars: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumInputChars", limits) + + +def maximum_integer_bits(limits): + """HMath.Expression.maximumIntegerBits: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumIntegerBits", limits) + + +def maximum_cache_entries(limits): + """HMath.Expression.maximumCacheEntries: original semantics and checked errors.""" + return _invoke("HMath.Expression.maximumCacheEntries", limits) + + +def error_kind(error): + """HMath.Expression.errorKind: original semantics and checked errors.""" + return _invoke("HMath.Expression.errorKind", error) + + +def error_position(error): + """HMath.Expression.errorPosition: original semantics and checked errors.""" + return _invoke("HMath.Expression.errorPosition", error) + + +def error_message(error): + """HMath.Expression.errorMessage: original semantics and checked errors.""" + return _invoke("HMath.Expression.errorMessage", error) + + +def validate_limits(limits): + """HMath.Expression.validateLimits: original semantics and checked errors.""" + return _invoke("HMath.Expression.validateLimits", limits) + + +def validate_expression(limits, expression): + """HMath.Expression.validateExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.validateExpression", limits, expression) + + +def parse_expression(limits, source): + """HMath.Expression.parseExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.parseExpression", limits, source) + + +def pretty_expression(expression): + """HMath.Expression.prettyExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.prettyExpression", expression) + + +def free_variables(expression): + """HMath.Expression.freeVariables: original semantics and checked errors.""" + return _invoke("HMath.Expression.freeVariables", expression) + + +def default_registry(): + """HMath.Expression.defaultRegistry: original semantics and checked errors.""" + return _invoke("HMath.Expression.defaultRegistry") + + +def empty_registry(): + """HMath.Expression.emptyRegistry: original semantics and checked errors.""" + return _invoke("HMath.Expression.emptyRegistry") + + +def register_function(name, builtin, registry): + """HMath.Expression.registerFunction: original semantics and checked errors.""" + return _invoke("HMath.Expression.registerFunction", name, builtin, registry) + + +def allowed_functions(registry): + """HMath.Expression.allowedFunctions: original semantics and checked errors.""" + return _invoke("HMath.Expression.allowedFunctions", registry) + + +def type_check_expression(limits, precision, registry, bindings, expression): + """HMath.Expression.typeCheckExpression: original semantics and checked errors.""" + return _invoke( + "HMath.Expression.typeCheckExpression", + limits, + precision, + registry, + bindings, + expression, + ) + + +def evaluate_expression(limits, precision, registry, bindings, expression): + """HMath.Expression.evaluateExpression: original semantics and checked errors.""" + return _invoke( + "HMath.Expression.evaluateExpression", + limits, + precision, + registry, + bindings, + expression, + ) + + +def evaluate_text(limits, precision, registry, bindings, source): + """HMath.Expression.evaluateText: original semantics and checked errors.""" + return _invoke( + "HMath.Expression.evaluateText", limits, precision, registry, bindings, source + ) + + +def evaluate_compiled(limits, precision, registry, bindings, compiled): + """HMath.Expression.evaluateCompiled: original semantics and checked errors.""" + return _invoke( + "HMath.Expression.evaluateCompiled", + limits, + precision, + registry, + bindings, + compiled, + ) + + +def compile_expression(limits, expression): + """HMath.Expression.compileExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.compileExpression", limits, expression) + + +def compiled_node_count(compiled): + """HMath.Expression.compiledNodeCount: original semantics and checked errors.""" + return _invoke("HMath.Expression.compiledNodeCount", compiled) + + +def optimize_expression(limits, precision, expression): + """HMath.Expression.optimizeExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.optimizeExpression", limits, precision, expression) + + +def empty_expression_cache(): + """HMath.Expression.emptyExpressionCache: original semantics and checked errors.""" + return _invoke("HMath.Expression.emptyExpressionCache") + + +def cache_size(cache): + """HMath.Expression.cacheSize: original semantics and checked errors.""" + return _invoke("HMath.Expression.cacheSize", cache) + + +def cached_expression(limits, source, cache): + """HMath.Expression.cachedExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.cachedExpression", limits, source, cache) + + +def format_scientific(digits, value): + """HMath.Expression.formatScientific: original semantics and checked errors.""" + return _invoke("HMath.Expression.formatScientific", digits, value) + + +def format_radix(radix, value): + """HMath.Expression.formatRadix: original semantics and checked errors.""" + return _invoke("HMath.Expression.formatRadix", radix, value) + + +def serialize_expression(limits, expression): + """HMath.Expression.serializeExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.serializeExpression", limits, expression) + + +def deserialize_expression(limits, serialized): + """HMath.Expression.deserializeExpression: original semantics and checked errors.""" + return _invoke("HMath.Expression.deserializeExpression", limits, serialized) + + +def expression_hash(limits, expression): + """HMath.Expression.expressionHash: original semantics and checked errors.""" + return _invoke("HMath.Expression.expressionHash", limits, expression) + + +Real = Property.REAL + +NonZero = Property.NON_ZERO + +Positive = Property.POSITIVE + +NonNegative = Property.NON_NEGATIVE + +Integral = Property.INTEGRAL + +Negative = Property.NEGATIVE + +NonPositive = Property.NON_POSITIVE + +FromLeft = Direction.FROM_LEFT + +FromRight = Direction.FROM_RIGHT + +TwoSided = Direction.TWO_SIDED + +Equal = RelationOp.EQUAL + +NotEqual = RelationOp.NOT_EQUAL + +Less = RelationOp.LESS + +LessEqual = RelationOp.LESS_EQUAL + +Greater = RelationOp.GREATER + +GreaterEqual = RelationOp.GREATER_EQUAL + + +def assumptions(entries): + """HMath.Symbolic.assumptions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.assumptions", entries) + + +def no_assumptions(): + """HMath.Symbolic.noAssumptions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.noAssumptions") + + +def proves(assumptions, property, expression): + """HMath.Symbolic.proves: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.proves", assumptions, property, expression) + + +def default_symbolic_options(): + """HMath.Symbolic.defaultSymbolicOptions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.defaultSymbolicOptions") + + +def symbolic_limits(options): + """HMath.Symbolic.symbolicLimits: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.symbolicLimits", options) + + +def symbolic_assumptions(options): + """HMath.Symbolic.symbolicAssumptions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.symbolicAssumptions", options) + + +def normalize(options, expression): + """HMath.Symbolic.normalize: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.normalize", options, expression) + + +def simplify(options, expression): + """HMath.Symbolic.simplify: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.simplify", options, expression) + + +def expand(options, expression): + """HMath.Symbolic.expand: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.expand", options, expression) + + +def collect_terms(options, expression): + """HMath.Symbolic.collectTerms: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.collectTerms", options, expression) + + +def trigonometric_simplify(options, expression): + """HMath.Symbolic.trigonometricSimplify: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.trigonometricSimplify", options, expression) + + +def logarithmic_simplify(options, expression): + """HMath.Symbolic.logarithmicSimplify: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.logarithmicSimplify", options, expression) + + +def factor_polynomial(options, variable, expression): + """HMath.Symbolic.factorPolynomial: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.factorPolynomial", options, variable, expression) + + +def rational_simplify(options, variable, expression): + """HMath.Symbolic.rationalSimplify: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.rationalSimplify", options, variable, expression) + + +def differentiate(options, variable, expression): + """HMath.Symbolic.differentiate: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.differentiate", options, variable, expression) + + +def integrate_basic(options, variable, expression): + """HMath.Symbolic.integrateBasic: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.integrateBasic", options, variable, expression) + + +def to_polynomial(options, variable, expression): + """HMath.Symbolic.toPolynomial: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.toPolynomial", options, variable, expression) + + +def exact_polynomial_roots(options, variable, expression): + """HMath.Symbolic.exactPolynomialRoots: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.exactPolynomialRoots", options, variable, expression) + + +def numerical_polynomial_roots(options, variable, expression): + """HMath.Symbolic.numericalPolynomialRoots: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.numericalPolynomialRoots", options, variable, expression + ) + + +def factor_leading(factorization): + """HMath.Symbolic.factorLeading: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.factorLeading", factorization) + + +def factor_terms(factorization): + """HMath.Symbolic.factorTerms: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.factorTerms", factorization) + + +def substitute(limits, bindings, expression): + """HMath.Symbolic.substitute: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.substitute", limits, bindings, expression) + + +def Any(name): + """HMath.Symbolic.Any: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.Any", name) + + +def Exactly(expression): + """HMath.Symbolic.Exactly: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.Exactly", expression) + + +def UnaryPattern(operator, child): + """HMath.Symbolic.UnaryPattern: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.UnaryPattern", operator, child) + + +def BinaryPattern(operator, left, right): + """HMath.Symbolic.BinaryPattern: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.BinaryPattern", operator, left, right) + + +def CallPattern(name, arguments): + """HMath.Symbolic.CallPattern: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.CallPattern", name, arguments) + + +def match_pattern(limits, pattern, expression): + """HMath.Symbolic.matchPattern: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.matchPattern", limits, pattern, expression) + + +def rewrite_pattern(rule): + """HMath.Symbolic.rewritePattern: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.rewritePattern", rule) + + +def rewrite_replacement(rule): + """HMath.Symbolic.rewriteReplacement: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.rewriteReplacement", rule) + + +def rewrite_requirements(rule): + """HMath.Symbolic.rewriteRequirements: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.rewriteRequirements", rule) + + +def apply_rewrite(options, rule, expression): + """HMath.Symbolic.applyRewrite: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.applyRewrite", options, rule, expression) + + +def gradient(options, variables, expression): + """HMath.Symbolic.gradient: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.gradient", options, variables, expression) + + +def hessian(options, variables, expression): + """HMath.Symbolic.hessian: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.hessian", options, variables, expression) + + +def jacobian(options, variables, expressions): + """HMath.Symbolic.jacobian: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.jacobian", options, variables, expressions) + + +def integrate_by_parts(options, variable, u, dv): + """HMath.Symbolic.integrateByParts: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.integrateByParts", options, variable, u, dv) + + +def integrate_substitution(options, variable, temporary, inner, outer, integrand): + """HMath.Symbolic.integrateSubstitution: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.integrateSubstitution", + options, + variable, + temporary, + inner, + outer, + integrand, + ) + + +def integrate_rational(options, variable, numerator, denominator): + """HMath.Symbolic.integrateRational: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.integrateRational", options, variable, numerator, denominator + ) + + +def FiniteLimit(value): + """HMath.Symbolic.FiniteLimit: original semantics and checked errors.""" + return LimitResult("FiniteLimit", (value,)) + + +PositiveInfinity = LimitResult("PositiveInfinity") + +NegativeInfinity = LimitResult("NegativeInfinity") + +DoesNotExist = LimitResult("DoesNotExist") + + +def symbolic_limit(options, variable, center, direction, expression): + """HMath.Symbolic.symbolicLimit: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.symbolicLimit", options, variable, center, direction, expression + ) + + +def series_center(series): + """HMath.Symbolic.seriesCenter: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.seriesCenter", series) + + +def series_minimum_power(series): + """HMath.Symbolic.seriesMinimumPower: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.seriesMinimumPower", series) + + +def series_terms(series): + """HMath.Symbolic.seriesTerms: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.seriesTerms", series) + + +def taylor_series(options, variable, center, order, expression): + """HMath.Symbolic.taylorSeries: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.taylorSeries", options, variable, center, order, expression + ) + + +def laurent_series(options, variable, center, order, expression): + """HMath.Symbolic.laurentSeries: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.laurentSeries", options, variable, center, order, expression + ) + + +def maclaurin_series(options, variable, order, expression): + """HMath.Symbolic.maclaurinSeries: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.maclaurinSeries", options, variable, order, expression + ) + + +def formal_power_series(options, coefficients): + """HMath.Symbolic.formalPowerSeries: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.formalPowerSeries", options, coefficients) + + +def multiply_formal_series(options, left, right): + """HMath.Symbolic.multiplyFormalSeries: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.multiplyFormalSeries", options, left, right) + + +def reciprocal_formal_series(options, series): + """HMath.Symbolic.reciprocalFormalSeries: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.reciprocalFormalSeries", options, series) + + +def from_polynomial(variable, polynomial): + """HMath.Symbolic.fromPolynomial: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.fromPolynomial", variable, polynomial) + + +def Truth(value): + """HMath.Symbolic.Truth: original semantics and checked errors.""" + return RelationResult("Truth", (value,)) + + +def Unresolved(relation): + """HMath.Symbolic.Unresolved: original semantics and checked errors.""" + return RelationResult("Unresolved", (relation,)) + + +def simplify_relation(options, relation): + """HMath.Symbolic.simplifyRelation: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.simplifyRelation", options, relation) + + +def solve_linear_inequality(options, variable, relation): + """HMath.Symbolic.solveLinearInequality: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.solveLinearInequality", options, variable, relation) + + +Inconsistent = LinearSolution("Inconsistent") + + +def ParametricSolution(bindings, free_variables): + """HMath.Symbolic.ParametricSolution: original semantics and checked errors.""" + return LinearSolution("ParametricSolution", (bindings, free_variables)) + + +def solve_linear_equations(options, variables, equations): + """HMath.Symbolic.solveLinearEquations: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.solveLinearEquations", options, variables, equations) + + +def symbolic_matrix(options, rows): + """HMath.Symbolic.symbolicMatrix: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.symbolicMatrix", options, rows) + + +def matrix_expressions(matrix): + """HMath.Symbolic.matrixExpressions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.matrixExpressions", matrix) + + +def matrix_add(options, left, right): + """HMath.Symbolic.matrixAdd: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.matrixAdd", options, left, right) + + +def matrix_multiply(options, left, right): + """HMath.Symbolic.matrixMultiply: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.matrixMultiply", options, left, right) + + +def symbolic_determinant(options, matrix): + """HMath.Symbolic.symbolicDeterminant: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.symbolicDeterminant", options, matrix) + + +def guarded_value(guarded): + """HMath.Symbolic.guardedValue: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.guardedValue", guarded) + + +def required_conditions(guarded): + """HMath.Symbolic.requiredConditions: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.requiredConditions", guarded) + + +def symbolic_eigenvalues(options, matrix): + """HMath.Symbolic.symbolicEigenvalues: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.symbolicEigenvalues", options, matrix) + + +def numerical_substitution(options, precision, bindings, expression): + """HMath.Symbolic.numericalSubstitution: original semantics and checked errors.""" + return _invoke( + "HMath.Symbolic.numericalSubstitution", options, precision, bindings, expression + ) + + +def to_la_te_x(limits, expression): + """HMath.Symbolic.toLaTeX: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.toLaTeX", limits, expression) + + +def to_math_ml(limits, expression): + """HMath.Symbolic.toMathML: original semantics and checked errors.""" + return _invoke("HMath.Symbolic.toMathML", limits, expression) + + +# END GENERATED diff --git a/bindings/python/_hmath_native/_expression_catalog.py b/bindings/python/_hmath_native/_expression_catalog.py new file mode 100644 index 0000000..0a51eb8 --- /dev/null +++ b/bindings/python/_hmath_native/_expression_catalog.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_expression_bindings.py. +import json +CATALOG = json.loads('[{"module":"HMath.Expression","name":"SourcePos","arguments":[["offset","Int"],["line","Int"],["column","Int"]],"result":"SourcePos","expression":"E.SourcePos","python":"source_pos","c":"hmath_expression_source_pos_create"},{"module":"HMath.Expression","name":"unknownPosition","arguments":[],"result":"SourcePos","expression":"E.unknownPosition","python":"unknown_position","c":"hmath_expression_unknown_position"},{"module":"HMath.Expression","name":"sourceOffset","arguments":[["position","SourcePos"]],"result":"Int","expression":"E.sourceOffset","python":"source_offset","c":"hmath_expression_source_offset"},{"module":"HMath.Expression","name":"sourceLine","arguments":[["position","SourcePos"]],"result":"Int","expression":"E.sourceLine","python":"source_line","c":"hmath_expression_source_line"},{"module":"HMath.Expression","name":"sourceColumn","arguments":[["position","SourcePos"]],"result":"Int","expression":"E.sourceColumn","python":"source_column","c":"hmath_expression_source_column"},{"module":"HMath.Expression","name":"Negate","arguments":[],"result":"UnaryOp","expression":"E.Negate","python":"negate","c":"hmath_expression_negate_create"},{"module":"HMath.Expression","name":"Add","arguments":[],"result":"BinaryOp","expression":"E.Add","python":"add","c":"hmath_expression_add_create"},{"module":"HMath.Expression","name":"Subtract","arguments":[],"result":"BinaryOp","expression":"E.Subtract","python":"subtract","c":"hmath_expression_subtract_create"},{"module":"HMath.Expression","name":"Multiply","arguments":[],"result":"BinaryOp","expression":"E.Multiply","python":"multiply","c":"hmath_expression_multiply_create"},{"module":"HMath.Expression","name":"Divide","arguments":[],"result":"BinaryOp","expression":"E.Divide","python":"divide","c":"hmath_expression_divide_create"},{"module":"HMath.Expression","name":"Power","arguments":[],"result":"BinaryOp","expression":"E.Power","python":"power","c":"hmath_expression_power_create"},{"module":"HMath.Expression","name":"Pi","arguments":[],"result":"NamedConstant","expression":"E.Pi","python":"pi","c":"hmath_expression_pi_create"},{"module":"HMath.Expression","name":"Euler","arguments":[],"result":"NamedConstant","expression":"E.Euler","python":"euler","c":"hmath_expression_euler_create"},{"module":"HMath.Expression","name":"Tau","arguments":[],"result":"NamedConstant","expression":"E.Tau","python":"tau","c":"hmath_expression_tau_create"},{"module":"HMath.Expression","name":"ExactRational","arguments":[],"result":"Precision","expression":"E.ExactRational","python":"exact_rational","c":"hmath_expression_exact_rational_create"},{"module":"HMath.Expression","name":"Float64","arguments":[],"result":"Precision","expression":"E.Float64","python":"float64","c":"hmath_expression_float64_create"},{"module":"HMath.Expression","name":"SyntaxError","arguments":[],"result":"ErrorKind","expression":"E.SyntaxError","python":"syntax_error","c":"hmath_expression_syntax_error_create"},{"module":"HMath.Expression","name":"UnknownName","arguments":[],"result":"ErrorKind","expression":"E.UnknownName","python":"unknown_name","c":"hmath_expression_unknown_name_create"},{"module":"HMath.Expression","name":"TypeMismatch","arguments":[],"result":"ErrorKind","expression":"E.TypeMismatch","python":"type_mismatch","c":"hmath_expression_type_mismatch_create"},{"module":"HMath.Expression","name":"DomainFailure","arguments":[],"result":"ErrorKind","expression":"E.DomainFailure","python":"domain_failure","c":"hmath_expression_domain_failure_create"},{"module":"HMath.Expression","name":"NonFinite","arguments":[],"result":"ErrorKind","expression":"E.NonFinite","python":"non_finite","c":"hmath_expression_non_finite_create"},{"module":"HMath.Expression","name":"StepLimit","arguments":[],"result":"ErrorKind","expression":"E.StepLimit","python":"step_limit","c":"hmath_expression_step_limit_create"},{"module":"HMath.Expression","name":"DepthLimit","arguments":[],"result":"ErrorKind","expression":"E.DepthLimit","python":"depth_limit","c":"hmath_expression_depth_limit_create"},{"module":"HMath.Expression","name":"MemoryLimit","arguments":[],"result":"ErrorKind","expression":"E.MemoryLimit","python":"memory_limit","c":"hmath_expression_memory_limit_create"},{"module":"HMath.Expression","name":"InvalidLimits","arguments":[],"result":"ErrorKind","expression":"E.InvalidLimits","python":"invalid_limits","c":"hmath_expression_invalid_limits_create"},{"module":"HMath.Expression","name":"Unsupported","arguments":[],"result":"ErrorKind","expression":"E.Unsupported","python":"unsupported","c":"hmath_expression_unsupported_create"},{"module":"HMath.Expression","name":"Sin","arguments":[],"result":"Builtin","expression":"E.Sin","python":"sin","c":"hmath_expression_sin_create"},{"module":"HMath.Expression","name":"Cos","arguments":[],"result":"Builtin","expression":"E.Cos","python":"cos","c":"hmath_expression_cos_create"},{"module":"HMath.Expression","name":"Tan","arguments":[],"result":"Builtin","expression":"E.Tan","python":"tan","c":"hmath_expression_tan_create"},{"module":"HMath.Expression","name":"Exp","arguments":[],"result":"Builtin","expression":"E.Exp","python":"exp","c":"hmath_expression_exp_create"},{"module":"HMath.Expression","name":"Log","arguments":[],"result":"Builtin","expression":"E.Log","python":"log","c":"hmath_expression_log_create"},{"module":"HMath.Expression","name":"Sqrt","arguments":[],"result":"Builtin","expression":"E.Sqrt","python":"sqrt","c":"hmath_expression_sqrt_create"},{"module":"HMath.Expression","name":"Abs","arguments":[],"result":"Builtin","expression":"E.Abs","python":"abs","c":"hmath_expression_abs_create"},{"module":"HMath.Expression","name":"Signum","arguments":[],"result":"Builtin","expression":"E.Signum","python":"signum","c":"hmath_expression_signum_create"},{"module":"HMath.Expression","name":"Floor","arguments":[],"result":"Builtin","expression":"E.Floor","python":"floor","c":"hmath_expression_floor_create"},{"module":"HMath.Expression","name":"Ceiling","arguments":[],"result":"Builtin","expression":"E.Ceiling","python":"ceiling","c":"hmath_expression_ceiling_create"},{"module":"HMath.Expression","name":"Min","arguments":[],"result":"Builtin","expression":"E.Min","python":"min","c":"hmath_expression_min_create"},{"module":"HMath.Expression","name":"Max","arguments":[],"result":"Builtin","expression":"E.Max","python":"max","c":"hmath_expression_max_create"},{"module":"HMath.Expression","name":"Asin","arguments":[],"result":"Builtin","expression":"E.Asin","python":"asin","c":"hmath_expression_asin_create"},{"module":"HMath.Expression","name":"Acos","arguments":[],"result":"Builtin","expression":"E.Acos","python":"acos","c":"hmath_expression_acos_create"},{"module":"HMath.Expression","name":"Atan","arguments":[],"result":"Builtin","expression":"E.Atan","python":"atan","c":"hmath_expression_atan_create"},{"module":"HMath.Expression","name":"Sinh","arguments":[],"result":"Builtin","expression":"E.Sinh","python":"sinh","c":"hmath_expression_sinh_create"},{"module":"HMath.Expression","name":"Cosh","arguments":[],"result":"Builtin","expression":"E.Cosh","python":"cosh","c":"hmath_expression_cosh_create"},{"module":"HMath.Expression","name":"Tanh","arguments":[],"result":"Builtin","expression":"E.Tanh","python":"tanh","c":"hmath_expression_tanh_create"},{"module":"HMath.Expression","name":"Expr","arguments":[["position","SourcePos"],["node","ExprNode"]],"result":"Expr","expression":"E.Expr","python":"expr","c":"hmath_expression_expr_create"},{"module":"HMath.Expression","name":"expressionPosition","arguments":[["expression","Expr"]],"result":"SourcePos","expression":"E.expressionPosition","python":"expression_position","c":"hmath_expression_expression_position"},{"module":"HMath.Expression","name":"expressionNode","arguments":[["expression","Expr"]],"result":"ExprNode","expression":"E.expressionNode","python":"expression_node","c":"hmath_expression_expression_node"},{"module":"HMath.Expression","name":"Literal","arguments":[["value","Rational"]],"result":"ExprNode","expression":"E.Literal","python":"literal","c":"hmath_expression_literal_create"},{"module":"HMath.Expression","name":"Variable","arguments":[["name","String"]],"result":"ExprNode","expression":"E.Variable","python":"variable","c":"hmath_expression_variable_create"},{"module":"HMath.Expression","name":"Constant","arguments":[["constant","NamedConstant"]],"result":"ExprNode","expression":"E.Constant","python":"constant","c":"hmath_expression_constant_create"},{"module":"HMath.Expression","name":"Unary","arguments":[["operator","UnaryOp"],["child","Expr"]],"result":"ExprNode","expression":"E.Unary","python":"unary","c":"hmath_expression_unary_create"},{"module":"HMath.Expression","name":"Binary","arguments":[["operator","BinaryOp"],["left","Expr"],["right","Expr"]],"result":"ExprNode","expression":"E.Binary","python":"binary","c":"hmath_expression_binary_create"},{"module":"HMath.Expression","name":"Call","arguments":[["name","String"],["arguments","[Expr]"]],"result":"ExprNode","expression":"E.Call","python":"call","c":"hmath_expression_call_create"},{"module":"HMath.Expression","name":"Let","arguments":[["name","String"],["value","Expr"],["body","Expr"]],"result":"ExprNode","expression":"E.Let","python":"let","c":"hmath_expression_let_create"},{"module":"HMath.Expression","name":"literal","arguments":[["value","Rational"]],"result":"Expr","expression":"E.literal","python":"literal","c":"hmath_expression_literal"},{"module":"HMath.Expression","name":"variable","arguments":[["name","String"]],"result":"Expr","expression":"E.variable","python":"variable","c":"hmath_expression_variable"},{"module":"HMath.Expression","name":"constant","arguments":[["constant","NamedConstant"]],"result":"Expr","expression":"E.constant","python":"constant","c":"hmath_expression_constant"},{"module":"HMath.Expression","name":"unary","arguments":[["operator","UnaryOp"],["child","Expr"]],"result":"Expr","expression":"E.unary","python":"unary","c":"hmath_expression_unary"},{"module":"HMath.Expression","name":"binary","arguments":[["operator","BinaryOp"],["left","Expr"],["right","Expr"]],"result":"Expr","expression":"E.binary","python":"binary","c":"hmath_expression_binary"},{"module":"HMath.Expression","name":"call","arguments":[["name","String"],["arguments","[Expr]"]],"result":"Expr","expression":"E.call","python":"call","c":"hmath_expression_call"},{"module":"HMath.Expression","name":"letIn","arguments":[["name","String"],["value","Expr"],["body","Expr"]],"result":"Expr","expression":"E.letIn","python":"let_in","c":"hmath_expression_let_in"},{"module":"HMath.Expression","name":"Limits","arguments":[["maximum_steps","Int"],["maximum_depth","Int"],["maximum_nodes","Int"],["maximum_input_chars","Int"],["maximum_integer_bits","Int"],["maximum_cache_entries","Int"]],"result":"Limits","expression":"E.Limits","python":"limits","c":"hmath_expression_limits_create"},{"module":"HMath.Expression","name":"defaultLimits","arguments":[],"result":"Limits","expression":"E.defaultLimits","python":"default_limits","c":"hmath_expression_default_limits"},{"module":"HMath.Expression","name":"maximumSteps","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumSteps","python":"maximum_steps","c":"hmath_expression_maximum_steps"},{"module":"HMath.Expression","name":"maximumDepth","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumDepth","python":"maximum_depth","c":"hmath_expression_maximum_depth"},{"module":"HMath.Expression","name":"maximumNodes","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumNodes","python":"maximum_nodes","c":"hmath_expression_maximum_nodes"},{"module":"HMath.Expression","name":"maximumInputChars","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumInputChars","python":"maximum_input_chars","c":"hmath_expression_maximum_input_chars"},{"module":"HMath.Expression","name":"maximumIntegerBits","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumIntegerBits","python":"maximum_integer_bits","c":"hmath_expression_maximum_integer_bits"},{"module":"HMath.Expression","name":"maximumCacheEntries","arguments":[["limits","Limits"]],"result":"Int","expression":"E.maximumCacheEntries","python":"maximum_cache_entries","c":"hmath_expression_maximum_cache_entries"},{"module":"HMath.Expression","name":"ExprError","arguments":[["kind","ErrorKind"],["position","SourcePos"],["message","String"]],"result":"ExprError","expression":"E.ExprError","python":"expr_error","c":"hmath_expression_expr_error_create"},{"module":"HMath.Expression","name":"errorKind","arguments":[["error","ExprError"]],"result":"ErrorKind","expression":"E.errorKind","python":"error_kind","c":"hmath_expression_error_kind_get"},{"module":"HMath.Expression","name":"errorPosition","arguments":[["error","ExprError"]],"result":"SourcePos","expression":"E.errorPosition","python":"error_position","c":"hmath_expression_error_position"},{"module":"HMath.Expression","name":"errorMessage","arguments":[["error","ExprError"]],"result":"String","expression":"E.errorMessage","python":"error_message","c":"hmath_expression_error_message"},{"module":"HMath.Expression","name":"validateLimits","arguments":[["limits","Limits"]],"result":"Unit","expression":"E.validateLimits","python":"validate_limits","c":"hmath_expression_validate_limits"},{"module":"HMath.Expression","name":"validateExpression","arguments":[["limits","Limits"],["expression","Expr"]],"result":"Unit","expression":"E.validateExpression","python":"validate_expression","c":"hmath_expression_validate_expression"},{"module":"HMath.Expression","name":"parseExpression","arguments":[["limits","Limits"],["source","String"]],"result":"Expr","expression":"E.parseExpression","python":"parse_expression","c":"hmath_expression_parse_expression"},{"module":"HMath.Expression","name":"prettyExpression","arguments":[["expression","Expr"]],"result":"String","expression":"E.prettyExpression","python":"pretty_expression","c":"hmath_expression_pretty_expression"},{"module":"HMath.Expression","name":"freeVariables","arguments":[["expression","Expr"]],"result":"[String]","expression":"E.freeVariables","python":"free_variables","c":"hmath_expression_free_variables"},{"module":"HMath.Expression","name":"ExactValue","arguments":[["value","Rational"]],"result":"ExpressionValue","expression":"E.ExactValue","python":"exact_value","c":"hmath_expression_exact_value_create"},{"module":"HMath.Expression","name":"FloatValue","arguments":[["value","Double"]],"result":"ExpressionValue","expression":"E.FloatValue","python":"float_value","c":"hmath_expression_float_value_create"},{"module":"HMath.Expression","name":"defaultRegistry","arguments":[],"result":"Registry","expression":"E.defaultRegistry","python":"default_registry","c":"hmath_expression_default_registry"},{"module":"HMath.Expression","name":"emptyRegistry","arguments":[],"result":"Registry","expression":"E.emptyRegistry","python":"empty_registry","c":"hmath_expression_empty_registry"},{"module":"HMath.Expression","name":"registerFunction","arguments":[["name","String"],["builtin","Builtin"],["registry","Registry"]],"result":"Registry","expression":"E.registerFunction","python":"register_function","c":"hmath_expression_register_function"},{"module":"HMath.Expression","name":"allowedFunctions","arguments":[["registry","Registry"]],"result":"[String]","expression":"E.allowedFunctions","python":"allowed_functions","c":"hmath_expression_allowed_functions"},{"module":"HMath.Expression","name":"typeCheckExpression","arguments":[["limits","Limits"],["precision","Precision"],["registry","Registry"],["bindings","Bindings"],["expression","Expr"]],"result":"Precision","expression":"E.typeCheckExpression","python":"type_check_expression","c":"hmath_expression_type_check_expression"},{"module":"HMath.Expression","name":"evaluateExpression","arguments":[["limits","Limits"],["precision","Precision"],["registry","Registry"],["bindings","Bindings"],["expression","Expr"]],"result":"ExpressionValue","expression":"E.evaluateExpression","python":"evaluate_expression","c":"hmath_expression_evaluate_expression"},{"module":"HMath.Expression","name":"evaluateText","arguments":[["limits","Limits"],["precision","Precision"],["registry","Registry"],["bindings","Bindings"],["source","String"]],"result":"ExpressionValue","expression":"E.evaluateText","python":"evaluate_text","c":"hmath_expression_evaluate_text"},{"module":"HMath.Expression","name":"evaluateCompiled","arguments":[["limits","Limits"],["precision","Precision"],["registry","Registry"],["bindings","Bindings"],["compiled","Compiled"]],"result":"ExpressionValue","expression":"E.evaluateCompiled","python":"evaluate_compiled","c":"hmath_expression_evaluate_compiled"},{"module":"HMath.Expression","name":"compileExpression","arguments":[["limits","Limits"],["expression","Expr"]],"result":"Compiled","expression":"E.compileExpression","python":"compile_expression","c":"hmath_expression_compile_expression"},{"module":"HMath.Expression","name":"compiledNodeCount","arguments":[["compiled","Compiled"]],"result":"Int","expression":"E.compiledNodeCount","python":"compiled_node_count","c":"hmath_expression_compiled_node_count"},{"module":"HMath.Expression","name":"optimizeExpression","arguments":[["limits","Limits"],["precision","Precision"],["expression","Expr"]],"result":"Expr","expression":"E.optimizeExpression","python":"optimize_expression","c":"hmath_expression_optimize_expression"},{"module":"HMath.Expression","name":"emptyExpressionCache","arguments":[],"result":"ExpressionCache","expression":"E.emptyExpressionCache","python":"empty_expression_cache","c":"hmath_expression_empty_expression_cache"},{"module":"HMath.Expression","name":"cacheSize","arguments":[["cache","ExpressionCache"]],"result":"Int","expression":"E.cacheSize","python":"cache_size","c":"hmath_expression_cache_size"},{"module":"HMath.Expression","name":"cachedExpression","arguments":[["limits","Limits"],["source","String"],["cache","ExpressionCache"]],"result":"(Compiled,ExpressionCache)","expression":"E.cachedExpression","python":"cached_expression","c":"hmath_expression_cached_expression"},{"module":"HMath.Expression","name":"formatScientific","arguments":[["digits","Int"],["value","ExpressionValue"]],"result":"String","expression":"E.formatScientific","python":"format_scientific","c":"hmath_expression_format_scientific"},{"module":"HMath.Expression","name":"formatRadix","arguments":[["radix","Int"],["value","ExpressionValue"]],"result":"String","expression":"E.formatRadix","python":"format_radix","c":"hmath_expression_format_radix"},{"module":"HMath.Expression","name":"serializeExpression","arguments":[["limits","Limits"],["expression","Expr"]],"result":"String","expression":"E.serializeExpression","python":"serialize_expression","c":"hmath_expression_serialize_expression"},{"module":"HMath.Expression","name":"deserializeExpression","arguments":[["limits","Limits"],["serialized","String"]],"result":"Expr","expression":"E.deserializeExpression","python":"deserialize_expression","c":"hmath_expression_deserialize_expression"},{"module":"HMath.Expression","name":"expressionHash","arguments":[["limits","Limits"],["expression","Expr"]],"result":"Word64","expression":"E.expressionHash","python":"expression_hash","c":"hmath_expression_expression_hash"},{"module":"HMath.Symbolic","name":"Real","arguments":[],"result":"Property","expression":"S.Real","python":"real","c":"hmath_symbolic_real_create"},{"module":"HMath.Symbolic","name":"NonZero","arguments":[],"result":"Property","expression":"S.NonZero","python":"non_zero","c":"hmath_symbolic_non_zero_create"},{"module":"HMath.Symbolic","name":"Positive","arguments":[],"result":"Property","expression":"S.Positive","python":"positive","c":"hmath_symbolic_positive_create"},{"module":"HMath.Symbolic","name":"NonNegative","arguments":[],"result":"Property","expression":"S.NonNegative","python":"non_negative","c":"hmath_symbolic_non_negative_create"},{"module":"HMath.Symbolic","name":"Integral","arguments":[],"result":"Property","expression":"S.Integral","python":"integral","c":"hmath_symbolic_integral_create"},{"module":"HMath.Symbolic","name":"Negative","arguments":[],"result":"Property","expression":"S.Negative","python":"negative","c":"hmath_symbolic_negative_create"},{"module":"HMath.Symbolic","name":"NonPositive","arguments":[],"result":"Property","expression":"S.NonPositive","python":"non_positive","c":"hmath_symbolic_non_positive_create"},{"module":"HMath.Symbolic","name":"FromLeft","arguments":[],"result":"Direction","expression":"S.FromLeft","python":"from_left","c":"hmath_symbolic_from_left_create"},{"module":"HMath.Symbolic","name":"FromRight","arguments":[],"result":"Direction","expression":"S.FromRight","python":"from_right","c":"hmath_symbolic_from_right_create"},{"module":"HMath.Symbolic","name":"TwoSided","arguments":[],"result":"Direction","expression":"S.TwoSided","python":"two_sided","c":"hmath_symbolic_two_sided_create"},{"module":"HMath.Symbolic","name":"Equal","arguments":[],"result":"RelationOp","expression":"S.Equal","python":"equal","c":"hmath_symbolic_equal_create"},{"module":"HMath.Symbolic","name":"NotEqual","arguments":[],"result":"RelationOp","expression":"S.NotEqual","python":"not_equal","c":"hmath_symbolic_not_equal_create"},{"module":"HMath.Symbolic","name":"Less","arguments":[],"result":"RelationOp","expression":"S.Less","python":"less","c":"hmath_symbolic_less_create"},{"module":"HMath.Symbolic","name":"LessEqual","arguments":[],"result":"RelationOp","expression":"S.LessEqual","python":"less_equal","c":"hmath_symbolic_less_equal_create"},{"module":"HMath.Symbolic","name":"Greater","arguments":[],"result":"RelationOp","expression":"S.Greater","python":"greater","c":"hmath_symbolic_greater_create"},{"module":"HMath.Symbolic","name":"GreaterEqual","arguments":[],"result":"RelationOp","expression":"S.GreaterEqual","python":"greater_equal","c":"hmath_symbolic_greater_equal_create"},{"module":"HMath.Symbolic","name":"assumptions","arguments":[["entries","[(String,[Property])]"]],"result":"Assumptions","expression":"S.assumptions","python":"assumptions","c":"hmath_symbolic_assumptions"},{"module":"HMath.Symbolic","name":"noAssumptions","arguments":[],"result":"Assumptions","expression":"S.noAssumptions","python":"no_assumptions","c":"hmath_symbolic_no_assumptions"},{"module":"HMath.Symbolic","name":"proves","arguments":[["assumptions","Assumptions"],["property","Property"],["expression","Expr"]],"result":"Bool","expression":"S.proves","python":"proves","c":"hmath_symbolic_proves"},{"module":"HMath.Symbolic","name":"SymbolicOptions","arguments":[["limits","Limits"],["assumptions","Assumptions"]],"result":"SymbolicOptions","expression":"S.SymbolicOptions","python":"symbolic_options","c":"hmath_symbolic_symbolic_options_create"},{"module":"HMath.Symbolic","name":"defaultSymbolicOptions","arguments":[],"result":"SymbolicOptions","expression":"S.defaultSymbolicOptions","python":"default_symbolic_options","c":"hmath_symbolic_default_symbolic_options"},{"module":"HMath.Symbolic","name":"symbolicLimits","arguments":[["options","SymbolicOptions"]],"result":"Limits","expression":"S.symbolicLimits","python":"symbolic_limits","c":"hmath_symbolic_symbolic_limits"},{"module":"HMath.Symbolic","name":"symbolicAssumptions","arguments":[["options","SymbolicOptions"]],"result":"Assumptions","expression":"S.symbolicAssumptions","python":"symbolic_assumptions","c":"hmath_symbolic_symbolic_assumptions"},{"module":"HMath.Symbolic","name":"normalize","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.normalize","python":"normalize","c":"hmath_symbolic_normalize"},{"module":"HMath.Symbolic","name":"simplify","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.simplify","python":"simplify","c":"hmath_symbolic_simplify"},{"module":"HMath.Symbolic","name":"expand","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.expand","python":"expand","c":"hmath_symbolic_expand"},{"module":"HMath.Symbolic","name":"collectTerms","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.collectTerms","python":"collect_terms","c":"hmath_symbolic_collect_terms"},{"module":"HMath.Symbolic","name":"trigonometricSimplify","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.trigonometricSimplify","python":"trigonometric_simplify","c":"hmath_symbolic_trigonometric_simplify"},{"module":"HMath.Symbolic","name":"logarithmicSimplify","arguments":[["options","SymbolicOptions"],["expression","Expr"]],"result":"Expr","expression":"S.logarithmicSimplify","python":"logarithmic_simplify","c":"hmath_symbolic_logarithmic_simplify"},{"module":"HMath.Symbolic","name":"factorPolynomial","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"PolynomialFactorization","expression":"S.factorPolynomial","python":"factor_polynomial","c":"hmath_symbolic_factor_polynomial"},{"module":"HMath.Symbolic","name":"rationalSimplify","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"Expr","expression":"S.rationalSimplify","python":"rational_simplify","c":"hmath_symbolic_rational_simplify"},{"module":"HMath.Symbolic","name":"differentiate","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"Expr","expression":"S.differentiate","python":"differentiate","c":"hmath_symbolic_differentiate"},{"module":"HMath.Symbolic","name":"integrateBasic","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"Expr","expression":"S.integrateBasic","python":"integrate_basic","c":"hmath_symbolic_integrate_basic"},{"module":"HMath.Symbolic","name":"toPolynomial","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"Polynomial","expression":"S.toPolynomial","python":"to_polynomial","c":"hmath_symbolic_to_polynomial"},{"module":"HMath.Symbolic","name":"exactPolynomialRoots","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"([(Rational,Int)],Expr)","expression":"S.exactPolynomialRoots","python":"exact_polynomial_roots","c":"hmath_symbolic_exact_polynomial_roots"},{"module":"HMath.Symbolic","name":"numericalPolynomialRoots","arguments":[["options","SymbolicOptions"],["variable","String"],["expression","Expr"]],"result":"[Complex]","expression":"S.numericalPolynomialRoots","python":"numerical_polynomial_roots","c":"hmath_symbolic_numerical_polynomial_roots"},{"module":"HMath.Symbolic","name":"PolynomialFactorization","arguments":[["leading","Rational"],["terms","[(Expr,Int)]"]],"result":"PolynomialFactorization","expression":"S.PolynomialFactorization","python":"polynomial_factorization","c":"hmath_symbolic_polynomial_factorization_create"},{"module":"HMath.Symbolic","name":"factorLeading","arguments":[["factorization","PolynomialFactorization"]],"result":"Rational","expression":"S.factorLeading","python":"factor_leading","c":"hmath_symbolic_factor_leading"},{"module":"HMath.Symbolic","name":"factorTerms","arguments":[["factorization","PolynomialFactorization"]],"result":"[(Expr,Int)]","expression":"S.factorTerms","python":"factor_terms","c":"hmath_symbolic_factor_terms"},{"module":"HMath.Symbolic","name":"substitute","arguments":[["limits","Limits"],["bindings","[(String,Expr)]"],["expression","Expr"]],"result":"Expr","expression":"S.substitute","python":"substitute","c":"hmath_symbolic_substitute"},{"module":"HMath.Symbolic","name":"Any","arguments":[["name","String"]],"result":"Pattern","expression":"S.Any","python":"any","c":"hmath_symbolic_any_create"},{"module":"HMath.Symbolic","name":"Exactly","arguments":[["expression","Expr"]],"result":"Pattern","expression":"S.Exactly","python":"exactly","c":"hmath_symbolic_exactly_create"},{"module":"HMath.Symbolic","name":"UnaryPattern","arguments":[["operator","UnaryOp"],["child","Pattern"]],"result":"Pattern","expression":"S.UnaryPattern","python":"unary_pattern","c":"hmath_symbolic_unary_pattern_create"},{"module":"HMath.Symbolic","name":"BinaryPattern","arguments":[["operator","BinaryOp"],["left","Pattern"],["right","Pattern"]],"result":"Pattern","expression":"S.BinaryPattern","python":"binary_pattern","c":"hmath_symbolic_binary_pattern_create"},{"module":"HMath.Symbolic","name":"CallPattern","arguments":[["name","String"],["arguments","[Pattern]"]],"result":"Pattern","expression":"S.CallPattern","python":"call_pattern","c":"hmath_symbolic_call_pattern_create"},{"module":"HMath.Symbolic","name":"matchPattern","arguments":[["limits","Limits"],["pattern","Pattern"],["expression","Expr"]],"result":"Maybe[(String,Expr)]","expression":"S.matchPattern","python":"match_pattern","c":"hmath_symbolic_match_pattern"},{"module":"HMath.Symbolic","name":"RewriteRule","arguments":[["pattern","Pattern"],["replacement","Expr"],["requirements","[(String,Property)]"]],"result":"RewriteRule","expression":"S.RewriteRule","python":"rewrite_rule","c":"hmath_symbolic_rewrite_rule_create"},{"module":"HMath.Symbolic","name":"rewritePattern","arguments":[["rule","RewriteRule"]],"result":"Pattern","expression":"S.rewritePattern","python":"rewrite_pattern","c":"hmath_symbolic_rewrite_pattern"},{"module":"HMath.Symbolic","name":"rewriteReplacement","arguments":[["rule","RewriteRule"]],"result":"Expr","expression":"S.rewriteReplacement","python":"rewrite_replacement","c":"hmath_symbolic_rewrite_replacement"},{"module":"HMath.Symbolic","name":"rewriteRequirements","arguments":[["rule","RewriteRule"]],"result":"[(String,Property)]","expression":"S.rewriteRequirements","python":"rewrite_requirements","c":"hmath_symbolic_rewrite_requirements"},{"module":"HMath.Symbolic","name":"applyRewrite","arguments":[["options","SymbolicOptions"],["rule","RewriteRule"],["expression","Expr"]],"result":"Expr","expression":"S.applyRewrite","python":"apply_rewrite","c":"hmath_symbolic_apply_rewrite"},{"module":"HMath.Symbolic","name":"gradient","arguments":[["options","SymbolicOptions"],["variables","[String]"],["expression","Expr"]],"result":"[Expr]","expression":"S.gradient","python":"gradient","c":"hmath_symbolic_gradient"},{"module":"HMath.Symbolic","name":"hessian","arguments":[["options","SymbolicOptions"],["variables","[String]"],["expression","Expr"]],"result":"[[Expr]]","expression":"S.hessian","python":"hessian","c":"hmath_symbolic_hessian"},{"module":"HMath.Symbolic","name":"jacobian","arguments":[["options","SymbolicOptions"],["variables","[String]"],["expressions","[Expr]"]],"result":"[[Expr]]","expression":"S.jacobian","python":"jacobian","c":"hmath_symbolic_jacobian"},{"module":"HMath.Symbolic","name":"integrateByParts","arguments":[["options","SymbolicOptions"],["variable","String"],["u","Expr"],["dv","Expr"]],"result":"Expr","expression":"S.integrateByParts","python":"integrate_by_parts","c":"hmath_symbolic_integrate_by_parts"},{"module":"HMath.Symbolic","name":"integrateSubstitution","arguments":[["options","SymbolicOptions"],["variable","String"],["temporary","String"],["inner","Expr"],["outer","Expr"],["integrand","Expr"]],"result":"Expr","expression":"S.integrateSubstitution","python":"integrate_substitution","c":"hmath_symbolic_integrate_substitution"},{"module":"HMath.Symbolic","name":"integrateRational","arguments":[["options","SymbolicOptions"],["variable","String"],["numerator","Expr"],["denominator","Expr"]],"result":"Expr","expression":"S.integrateRational","python":"integrate_rational","c":"hmath_symbolic_integrate_rational"},{"module":"HMath.Symbolic","name":"FiniteLimit","arguments":[["value","Rational"]],"result":"LimitResult","expression":"S.FiniteLimit","python":"finite_limit","c":"hmath_symbolic_finite_limit_create"},{"module":"HMath.Symbolic","name":"PositiveInfinity","arguments":[],"result":"LimitResult","expression":"S.PositiveInfinity","python":"positive_infinity","c":"hmath_symbolic_positive_infinity_create"},{"module":"HMath.Symbolic","name":"NegativeInfinity","arguments":[],"result":"LimitResult","expression":"S.NegativeInfinity","python":"negative_infinity","c":"hmath_symbolic_negative_infinity_create"},{"module":"HMath.Symbolic","name":"DoesNotExist","arguments":[],"result":"LimitResult","expression":"S.DoesNotExist","python":"does_not_exist","c":"hmath_symbolic_does_not_exist_create"},{"module":"HMath.Symbolic","name":"symbolicLimit","arguments":[["options","SymbolicOptions"],["variable","String"],["center","Rational"],["direction","Direction"],["expression","Expr"]],"result":"LimitResult","expression":"S.symbolicLimit","python":"symbolic_limit","c":"hmath_symbolic_symbolic_limit"},{"module":"HMath.Symbolic","name":"Series","arguments":[["center","Rational"],["minimum_power","Int"],["terms","[Expr]"]],"result":"Series","expression":"S.Series","python":"series","c":"hmath_symbolic_series_create"},{"module":"HMath.Symbolic","name":"seriesCenter","arguments":[["series","Series"]],"result":"Rational","expression":"S.seriesCenter","python":"series_center","c":"hmath_symbolic_series_center"},{"module":"HMath.Symbolic","name":"seriesMinimumPower","arguments":[["series","Series"]],"result":"Int","expression":"S.seriesMinimumPower","python":"series_minimum_power","c":"hmath_symbolic_series_minimum_power"},{"module":"HMath.Symbolic","name":"seriesTerms","arguments":[["series","Series"]],"result":"[Expr]","expression":"S.seriesTerms","python":"series_terms","c":"hmath_symbolic_series_terms"},{"module":"HMath.Symbolic","name":"taylorSeries","arguments":[["options","SymbolicOptions"],["variable","String"],["center","Rational"],["order","Int"],["expression","Expr"]],"result":"Series","expression":"S.taylorSeries","python":"taylor_series","c":"hmath_symbolic_taylor_series"},{"module":"HMath.Symbolic","name":"laurentSeries","arguments":[["options","SymbolicOptions"],["variable","String"],["center","Rational"],["order","Int"],["expression","Expr"]],"result":"Series","expression":"S.laurentSeries","python":"laurent_series","c":"hmath_symbolic_laurent_series"},{"module":"HMath.Symbolic","name":"maclaurinSeries","arguments":[["options","SymbolicOptions"],["variable","String"],["order","Int"],["expression","Expr"]],"result":"Series","expression":"S.maclaurinSeries","python":"maclaurin_series","c":"hmath_symbolic_maclaurin_series"},{"module":"HMath.Symbolic","name":"formalPowerSeries","arguments":[["options","SymbolicOptions"],["coefficients","[Rational]"]],"result":"PowerSeries","expression":"S.formalPowerSeries","python":"formal_power_series","c":"hmath_symbolic_formal_power_series"},{"module":"HMath.Symbolic","name":"multiplyFormalSeries","arguments":[["options","SymbolicOptions"],["left","PowerSeries"],["right","PowerSeries"]],"result":"PowerSeries","expression":"S.multiplyFormalSeries","python":"multiply_formal_series","c":"hmath_symbolic_multiply_formal_series"},{"module":"HMath.Symbolic","name":"reciprocalFormalSeries","arguments":[["options","SymbolicOptions"],["series","PowerSeries"]],"result":"PowerSeries","expression":"S.reciprocalFormalSeries","python":"reciprocal_formal_series","c":"hmath_symbolic_reciprocal_formal_series"},{"module":"HMath.Symbolic","name":"fromPolynomial","arguments":[["variable","String"],["polynomial","Polynomial"]],"result":"Expr","expression":"S.fromPolynomial","python":"from_polynomial","c":"hmath_symbolic_from_polynomial"},{"module":"HMath.Symbolic","name":"Relation","arguments":[["operator","RelationOp"],["left","Expr"],["right","Expr"]],"result":"Relation","expression":"S.Relation","python":"relation","c":"hmath_symbolic_relation_create"},{"module":"HMath.Symbolic","name":"Truth","arguments":[["value","Bool"]],"result":"RelationResult","expression":"S.Truth","python":"truth","c":"hmath_symbolic_truth_create"},{"module":"HMath.Symbolic","name":"Unresolved","arguments":[["relation","Relation"]],"result":"RelationResult","expression":"S.Unresolved","python":"unresolved","c":"hmath_symbolic_unresolved_create"},{"module":"HMath.Symbolic","name":"simplifyRelation","arguments":[["options","SymbolicOptions"],["relation","Relation"]],"result":"RelationResult","expression":"S.simplifyRelation","python":"simplify_relation","c":"hmath_symbolic_simplify_relation"},{"module":"HMath.Symbolic","name":"solveLinearInequality","arguments":[["options","SymbolicOptions"],["variable","String"],["relation","Relation"]],"result":"RelationResult","expression":"S.solveLinearInequality","python":"solve_linear_inequality","c":"hmath_symbolic_solve_linear_inequality"},{"module":"HMath.Symbolic","name":"Inconsistent","arguments":[],"result":"LinearSolution","expression":"S.Inconsistent","python":"inconsistent","c":"hmath_symbolic_inconsistent_create"},{"module":"HMath.Symbolic","name":"ParametricSolution","arguments":[["bindings","[(String,Expr)]"],["free_variables","[String]"]],"result":"LinearSolution","expression":"S.ParametricSolution","python":"parametric_solution","c":"hmath_symbolic_parametric_solution_create"},{"module":"HMath.Symbolic","name":"solveLinearEquations","arguments":[["options","SymbolicOptions"],["variables","[String]"],["equations","[(Expr,Expr)]"]],"result":"LinearSolution","expression":"S.solveLinearEquations","python":"solve_linear_equations","c":"hmath_symbolic_solve_linear_equations"},{"module":"HMath.Symbolic","name":"symbolicMatrix","arguments":[["options","SymbolicOptions"],["rows","[[Expr]]"]],"result":"SymbolicMatrix","expression":"S.symbolicMatrix","python":"symbolic_matrix","c":"hmath_symbolic_symbolic_matrix"},{"module":"HMath.Symbolic","name":"matrixExpressions","arguments":[["matrix","SymbolicMatrix"]],"result":"[[Expr]]","expression":"S.matrixExpressions","python":"matrix_expressions","c":"hmath_symbolic_matrix_expressions"},{"module":"HMath.Symbolic","name":"matrixAdd","arguments":[["options","SymbolicOptions"],["left","SymbolicMatrix"],["right","SymbolicMatrix"]],"result":"SymbolicMatrix","expression":"S.matrixAdd","python":"matrix_add","c":"hmath_symbolic_matrix_add"},{"module":"HMath.Symbolic","name":"matrixMultiply","arguments":[["options","SymbolicOptions"],["left","SymbolicMatrix"],["right","SymbolicMatrix"]],"result":"SymbolicMatrix","expression":"S.matrixMultiply","python":"matrix_multiply","c":"hmath_symbolic_matrix_multiply"},{"module":"HMath.Symbolic","name":"symbolicDeterminant","arguments":[["options","SymbolicOptions"],["matrix","SymbolicMatrix"]],"result":"Expr","expression":"S.symbolicDeterminant","python":"symbolic_determinant","c":"hmath_symbolic_symbolic_determinant"},{"module":"HMath.Symbolic","name":"Guarded","arguments":[["value","Generic"],["conditions","[(Expr,Property)]"]],"result":"Guarded","expression":"(S.Guarded :: Value -> [(E.Expr,S.Property)] -> S.Guarded Value)","python":"guarded","c":"hmath_symbolic_guarded_create"},{"module":"HMath.Symbolic","name":"guardedValue","arguments":[["guarded","Guarded"]],"result":"Generic","expression":"(S.guardedValue :: S.Guarded Value -> Value)","python":"guarded_value","c":"hmath_symbolic_guarded_value"},{"module":"HMath.Symbolic","name":"requiredConditions","arguments":[["guarded","Guarded"]],"result":"[(Expr,Property)]","expression":"(S.requiredConditions :: S.Guarded Value -> [(E.Expr,S.Property)])","python":"required_conditions","c":"hmath_symbolic_required_conditions"},{"module":"HMath.Symbolic","name":"symbolicEigenvalues","arguments":[["options","SymbolicOptions"],["matrix","SymbolicMatrix"]],"result":"Guarded[Expr]","expression":"S.symbolicEigenvalues","python":"symbolic_eigenvalues","c":"hmath_symbolic_symbolic_eigenvalues"},{"module":"HMath.Symbolic","name":"numericalSubstitution","arguments":[["options","SymbolicOptions"],["precision","Precision"],["bindings","[(String,ExpressionValue)]"],["expression","Expr"]],"result":"ExpressionValue","expression":"S.numericalSubstitution","python":"numerical_substitution","c":"hmath_symbolic_numerical_substitution"},{"module":"HMath.Symbolic","name":"toLaTeX","arguments":[["limits","Limits"],["expression","Expr"]],"result":"String","expression":"S.toLaTeX","python":"to_la_te_x","c":"hmath_symbolic_to_la_te_x"},{"module":"HMath.Symbolic","name":"toMathML","arguments":[["limits","Limits"],["expression","Expr"]],"result":"String","expression":"S.toMathML","python":"to_math_ml","c":"hmath_symbolic_to_math_ml"}]') diff --git a/bindings/python/_hmath_native/_expression_error.py b/bindings/python/_hmath_native/_expression_error.py new file mode 100644 index 0000000..4122ee6 --- /dev/null +++ b/bindings/python/_hmath_native/_expression_error.py @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless original positioned ExprError values and domain-error query.""" + +import ctypes as C +from dataclasses import dataclass +from enum import IntEnum + + +class ErrorKind(IntEnum): + SYNTAX_ERROR = 0 + UNKNOWN_NAME = 1 + TYPE_MISMATCH = 2 + DOMAIN_FAILURE = 3 + NON_FINITE = 4 + STEP_LIMIT = 5 + DEPTH_LIMIT = 6 + MEMORY_LIMIT = 7 + INVALID_LIMITS = 8 + UNSUPPORTED = 9 + + +@dataclass(frozen=True, order=True) +class SourcePos: + offset: int = 0 + line: int = 0 + column: int = 0 + + +@dataclass(frozen=True) +class ExprError(Exception): + kind: ErrorKind + position: SourcePos + message: str + + def __str__(self): + return f"{self.kind.name} at {self.position.line}:{self.position.column}: {self.message}" + + +class Wire(C.Structure): + _fields_ = [ + ("kind", C.c_uint32), + ("offset", C.c_ssize_t), + ("line", C.c_ssize_t), + ("column", C.c_ssize_t), + ("message", C.c_void_p), + ("message_length", C.c_size_t), + ] + + +def last_expression_error(library): + try: + getter = C.CFUNCTYPE(C.c_int, C.POINTER(Wire))( + ("hmath_last_expression_error", library) + ) + except AttributeError: + return None + wire = Wire() + if not getter(C.byref(wire)): + return None + message = ( + C.string_at(wire.message, wire.message_length).decode("utf-8", "surrogatepass") + if wire.message_length + else "" + ) + return ExprError( + ErrorKind(wire.kind), SourcePos(wire.offset, wire.line, wire.column), message + ) diff --git a/bindings/python/_hmath_native/_foundation_base.py b/bindings/python/_hmath_native/_foundation_base.py new file mode 100644 index 0000000..403cc20 --- /dev/null +++ b/bindings/python/_hmath_native/_foundation_base.py @@ -0,0 +1,179 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Persistent owners, exact generic choices and original callback transport.""" + +import ctypes as C +import importlib + +from . import _value as V +from ._linear_base import _callback_scope, _take_callback_failure +from ._stochastic_base import _prepare + +_TYPES = {} + + +def register(source_type, owner): + if source_type in _TYPES and _TYPES[source_type] is not owner: + raise ValueError("foundation type already registered") + _TYPES[source_type] = owner + + +class FoundationValue(V.Value): + _source_type = None + + def __init__(self, *_args): + raise TypeError("use the original public constructors") + + def _initialize(self, symbol, specs, arguments, mode="value", prototype=None): + result = _invoke(symbol, specs, arguments, mode, prototype=prototype) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + @property + def source_type(self): + return self._source_type + + @property + def parts(self): + return V.decode(V.invoke("hmath_foundation_object_parts", self)) + + +class Either(FoundationValue): + """Original generic Either: inspect parts for ('Left',error)/('Right',value).""" + + _source_type = "HMath.Internal.Either" + + +class Just(FoundationValue): + """Distinguishes a successful optional None from absent Nothing.""" + + _source_type = "HMath.Internal.Just" + + +class OrderedType(FoundationValue): + """Owned original Ord dictionary, including explicit nested optional types.""" + + _source_type = "HMath.Internal.OrderedType" + + +_TYPES["HMath.Internal.Either"] = Either +_TYPES["HMath.Internal.Just"] = Just +_TYPES["HMath.Internal.OrderedType"] = OrderedType + + +def _decode(value): + name = V.decode(V.invoke("hmath_foundation_object_type", value)) + owner = _TYPES.get(name) + if owner is None: + namespace = { + "HMath.DataStructure": "data_structures", + "HMath.Discrete": "discrete_values", + "HMath.Algorithms": "algorithm_values", + "HMath.Combinatorics": "combinatorics_values", + "HMath.API.Convergence": "convergence_values", + "HMath.Algebra": "algebra", + "HMath.API.Algebra": "algebra_api", + "HMath.API.Shape": "shape_values", + "HMath.API.Buffer": "buffer_values", + }[name.rsplit(".", 1)[0]] + importlib.import_module("." + namespace, __package__) + owner = _TYPES.get(name) + if owner is None: + raise TypeError("unknown foundation source type") + with value._lock: + result = owner._adopt(value._ptr, value._owners) + value._ptr, value._owners = C.c_void_p(), () + return result + + +V.register(400, _decode) + + +def left(value): + return V.decode(V.invoke("hmath_foundation_left", value)) + + +def right(value): + return V.decode(V.invoke("hmath_foundation_right", value)) + + +def just(value): + return V.decode(V.invoke("hmath_foundation_just", value)) + + +def ordered_type(prototype): + return V.decode(V.invoke("hmath_foundation_ordered_type", prototype)) + + +def optional_type(prototype): + return V.decode(V.invoke("hmath_foundation_optional_type", prototype)) + + +def _invoke(symbol, specs, arguments, mode="value", dtype=None, prototype=None): + owners = [] + callbacks = [] + order_prototype = prototype + try: + if mode == "numeric": + source_values = list(arguments[0]) + if isinstance(dtype, V.Value): + prototype = dtype.clone() + elif dtype is not None: + prototype = V.scalar(0, dtype) + elif source_values and isinstance(source_values[0], V.Value): + prototype = source_values[0].clone() + else: + prototype = V.scalar(source_values[0] if source_values else 0) + owners.append(prototype) + inferred = prototype.dtype + values = [] + for value in source_values: + scalar = ( + value.clone() + if isinstance(value, V.Value) + else V.scalar(value, inferred) + ) + owners.append(scalar) + values.append(scalar) + prepared = [prototype, values] + else: + adjusted = [] + + # Rational parameters in the concrete combinatorial algorithms are + # exact even when Python callers supply ordinary integer literals. + def rational(spec, value): + if spec == ["Rational"]: + item = ( + value.clone() + if isinstance(value, V.Value) + else V.scalar(value, "rational") + ) + owners.append(item) + return item + if spec[0] == "list": + return [rational(spec[1], item) for item in value] + return value + + for spec, value in zip(specs, arguments): + adjusted.append(rational(spec, value)) + prepared = [ + _prepare(spec, value, owners, callbacks) + for spec, value in zip(specs, adjusted) + ] + if order_prototype is not None: + symbol = { + "hmath_foundation_datastructure_heap_from_list": "hmath_foundation_heap_from_list_typed", + "hmath_foundation_discrete_multiset": "hmath_foundation_multiset_typed", + }.get(symbol, symbol + "_typed") + prepared.insert(0, order_prototype) + scopes = _callback_scope(callbacks) + try: + result = V.invoke(symbol, *prepared) + except BaseException: + failure = _take_callback_failure(scopes) + if failure is not None: + raise failure + raise + return V.decode(result) + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_geometry_base.py b/bindings/python/_hmath_native/_geometry_base.py new file mode 100644 index 0000000..6b9a886 --- /dev/null +++ b/bindings/python/_hmath_native/_geometry_base.py @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Typed Geometry representation; algorithms remain in the original modules.""" + +from enum import IntEnum + +from . import _value as V +from ._image_base import _prepare_argument + + +class Ordering(IntEnum): + LT = -1 + EQ = 0 + GT = 1 + + +class GeometryValue(V.Value): + @property + def parts(self): + return _invoke("hmath_geometry_parts", [["GeometryObject"]], [self]) + + @property + def coordinates(self): + name, fields = self.parts + if name in ("P2", "P3"): + return list(fields) + if name == "PointND": + return fields[0] + raise TypeError("coordinates requires Point2, Point3 or PointND") + + def __eq__(self, other): + if not isinstance(other, GeometryValue): + return NotImplemented + return _invoke("hmath_geometry_equal", [["GeometryObject"]] * 2, [self, other]) + + __hash__ = None + + +def _invoke(symbol, specifications, arguments): + owners = [] + try: + for specification, argument in zip(specifications, arguments): + value = ( + argument + if specification == ["Matrix Double"] + else _prepare_argument(specification, argument) + ) + owners.append(V.encode(value)) + return V.invoke(symbol, *owners).decode() + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_graph_base.py b/bindings/python/_hmath_native/_graph_base.py new file mode 100644 index 0000000..6e42da1 --- /dev/null +++ b/bindings/python/_hmath_native/_graph_base.py @@ -0,0 +1,100 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Type marshaling and callback lifetime for the original Graph algorithms.""" + +import ctypes as C +import operator + +from ._value import Value, api, decode, encode, invoke + + +def _prepare(spec, argument): + kind = spec[0] + if kind == "Double": + return float(argument) + if kind in ("Int", "Integer"): + return operator.index(argument) + if kind == "Word64": + number = operator.index(argument) + if not 0 <= number <= (1 << 64) - 1: + raise OverflowError("seed must fit Word64") + return number + if kind == "Bool": + if not isinstance(argument, bool): + raise TypeError("expected bool") + return argument + if kind == "String": + if not isinstance(argument, str): + raise TypeError("expected str") + return argument + if kind == "list": + return [_prepare(spec[1], item) for item in argument] + if kind == "tuple": + arguments = tuple(argument) + if len(arguments) != len(spec) - 1: + raise ValueError("tuple arity differs") + return tuple(_prepare(t, v) for t, v in zip(spec[1:], arguments)) + if kind == "maybe": + return None if argument is None else _prepare(spec[1], argument) + if kind == "unit": + if argument != (): + raise TypeError("expected unit ()") + return () + if not isinstance(argument, Value): + raise TypeError("expected an owned Graph-domain object") + return argument + + +def _invoke(symbol, specifications, arguments): + return decode( + invoke(symbol, *[_prepare(t, a) for t, a in zip(specifications, arguments)]) + ) + + +def _astar(graph, heuristic, start, end): + import hmath + + hmath.initialize() + if not callable(heuristic): + raise TypeError("heuristic must be callable") + failures = [] + callback_type = C.CFUNCTYPE(C.c_int, C.c_ssize_t, C.c_void_p, C.POINTER(C.c_double)) + + @callback_type + def callback(vertex, _, out): + try: + out[0] = float(heuristic(vertex)) + return 0 + except BaseException as error: # noqa: BLE001 - exceptions must not cross a C callback + failures.append(error) + return 6 + + inputs = [encode(graph), encode(operator.index(start)), encode(operator.index(end))] + result = Value._adopt(owners=(callback,)) + try: + status = api( + "hmath_graph_a_star", + C.c_int, + C.c_void_p, + C.c_void_p, + callback_type, + C.c_void_p, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )( + None, + inputs[0]._ptr, + callback, + None, + inputs[1]._ptr, + inputs[2]._ptr, + C.byref(result._ptr), + ) + if failures: + raise failures[0] + hmath._check(status) + return decode(result) + finally: + result.close() + for value in inputs: + value.close() diff --git a/bindings/python/_hmath_native/_image_base.py b/bindings/python/_hmath_native/_image_base.py new file mode 100644 index 0000000..9eb359f --- /dev/null +++ b/bindings/python/_hmath_native/_image_base.py @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Image representation and synchronous callback ownership, without algorithms.""" + +import ctypes as C + +from . import _value as V +from ._graph_base import _prepare + + +def _prepare_argument(specification, argument): + if isinstance(argument, V.Value): + return argument + if specification[0] == "list": + return [_prepare_argument(specification[1], item) for item in argument] + if specification[0] == "tuple": + if not isinstance(argument, tuple) or len(argument) != len(specification) - 1: + raise TypeError("tuple arity differs from its original signature") + return tuple( + _prepare_argument(typ, item) + for typ, item in zip(specification[1:], argument) + ) + return _prepare(specification, argument) + + +def _invoke(symbol, specifications, arguments): + import hmath + + inputs = [] + callbacks = [] + failures = [] + types = [C.c_void_p] + native = [None] + result = V.Value._adopt() + hmath.initialize() + try: + for specification, argument in zip(specifications, arguments): + if specification[0] == "function": + if not callable(argument): + raise TypeError("expected a deterministic callable") + callback_type = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p) + ) + + def callback(pointer, _, out, function=argument): + try: + values = V.borrow(pointer).decode() + answer = function(*values) + owner = ( + answer.clone() + if isinstance(answer, V.Value) + else V.scalar(float(answer), "float64") + ) + try: + V.api("hmath_value_retain", None, C.c_void_p)(owner._ptr) + out[0] = owner._ptr + finally: + owner.close() + return 0 + except BaseException as error: # noqa: BLE001 - never unwind through C + failures.append(error) + return 6 + + adapter = callback_type(callback) + callbacks.append(adapter) + types.extend([callback_type, C.c_void_p]) + native.extend([adapter, None]) + else: + owner = V.encode(_prepare_argument(specification, argument)) + inputs.append(owner) + types.append(C.c_void_p) + native.append(owner._ptr) + types.append(C.POINTER(C.c_void_p)) + native.append(C.byref(result._ptr)) + status = V.api(symbol, C.c_int, *types)(*native) + if failures: + raise failures[0] + hmath._check(status) + return result.decode() + finally: + result.close() + for owner in inputs: + owner.close() diff --git a/bindings/python/_hmath_native/_interchange_base.py b/bindings/python/_hmath_native/_interchange_base.py new file mode 100644 index 0000000..dbf0f89 --- /dev/null +++ b/bindings/python/_hmath_native/_interchange_base.py @@ -0,0 +1,394 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original interchange values, Element witnesses and scoped callback owners.""" + +import ctypes as C +import operator +import os + +from . import _value as value +from ._bytes import Bytes +from ._callback_error import fill +from ._interchange_error import InterchangeError, InterchangeErrorKind +from ._math_error import Wire +from ._numerical_base import _CallbackState +from ._numerical_base import _invoke as _native_invoke + +_PREFIX = "hmath_interchange_value_" +_CALLBACK = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p), C.POINTER(Wire) +) +_FAILURE_MESSAGE = C.create_string_buffer(b"Python interchange callback failed") +_DTYPES = ( + "bool", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + "int64", + "uint64", + "float32", + "float64", + "complex64", + "complex128", +) + + +class Array(value.Value): + @property + def shape(self): + return _invoke(_PREFIX + "array_shape", [["Value"]], [self]) + + @property + def strides(self): + return _invoke(_PREFIX + "array_strides", [["Value"]], [self]) + + @property + def offset(self): + return _invoke(_PREFIX + "array_offset", [["Value"]], [self]) + + @property + def dtype(self): + return _invoke(_PREFIX + "array_d_type", [["Value"]], [self]) + + @property + def backing_bytes(self): + return _invoke(_PREFIX + "array_bytes", [["Value"]], [self]) + + def __eq__(self, other): + if not isinstance(other, Array): + return NotImplemented + return _invoke(_PREFIX + "equal_array", [["Value"], ["Value"]], [self, other]) + + __hash__ = None + + +class Limits(value.Value): + pass + + +class DType(value.Value): + pass + + +class Endian(value.Value): + pass + + +class Order(value.Value): + pass + + +class Compression(value.Value): + pass + + +class RawSpec(value.Value): + pass + + +class GetProgram(value.Value): + def decode(self, data, *, boxed=False): + return _invoke( + _PREFIX + "run_decoder", + [["Value"], ["ByteString"]], + [self, data], + boxed=boxed, + ) + + +class PutProgram(value.Value): + def to_bytes(self): + return _invoke(_PREFIX + "put_bytes", [["Value"]], [self]) + + +class MappedArray(value.Value): + @property + def shape(self): + return _invoke(_PREFIX + "mapped_shape", [["Value"]], [self]) + + def read_bytes(self, offset, count): + return _invoke( + _PREFIX + "mapped_read_bytes", + [["Value"], ["Int"], ["Int"]], + [self, offset, count], + ) + + def at(self, indices, *, dtype="float64", boxed=False): + return _mapped_value(self, indices, dtype, boxed) + + +class BinaryHandle(value.Value): + def close(self): + if not getattr(self, "_ptr", None): + return + try: + _invoke(_PREFIX + "close_handle", [["Value"]], [self]) + finally: + super().close() + + def seek(self, offset, whence=0): + return _invoke( + _PREFIX + "seek_handle", + [["Value"], ["Int"], ["Integer"]], + [self, whence, offset], + ) + + def tell(self): + return _invoke(_PREFIX + "tell_handle", [["Value"]], [self]) + + def flush(self): + return _invoke(_PREFIX + "flush_handle", [["Value"]], [self]) + + +for kind, owner in { + 451: Array, + 452: BinaryHandle, + 457: Limits, + 458: DType, + 459: Endian, + 460: Order, + 461: Compression, + 462: RawSpec, + 463: GetProgram, + 464: PutProgram, + 465: MappedArray, +}.items(): + value.register(kind, owner) + + +def _decode_error(owner): + try: + kind, message = _invoke(_PREFIX + "error_fields", [["Value"]], [owner]) + return InterchangeError(InterchangeErrorKind(kind), message) + finally: + owner.close() + + +def _encode_error(error): + name = ("invalid_data", "unsupported", "limit_exceeded", "interchange_io_error")[ + InterchangeErrorKind(error.kind) + ] + return _invoke(_PREFIX + name, [["String"]], [error.message], boxed=True) + + +value.register(453, _decode_error) +value.register_encoder(InterchangeError, _encode_error) + + +def _prepare(specification, argument, temporary): + kind = specification[0] + if kind in ("io", "either"): + return _prepare(specification[1], argument, temporary) + if kind == "function": + if isinstance(argument, value.Value): + return argument + owner = _callback(argument, specification[-1]) + temporary.append(owner) + return owner + if kind == "ByteString": + if isinstance(argument, Bytes): + return argument + if not isinstance(argument, (bytes, bytearray, memoryview)): + raise TypeError("expected bytes, a byte buffer, or native Bytes") + owner = Bytes(argument) + temporary.append(owner) + return owner + if kind == "Char": + if not isinstance(argument, str) or len(argument) != 1: + raise TypeError("delimiter requires exactly one Unicode codepoint") + return argument + if kind == "String": + argument = ( + os.fspath(argument) if isinstance(argument, os.PathLike) else argument + ) + if not isinstance(argument, str): + raise TypeError("expected a Unicode string") + return argument + if kind in ("Int", "Integer", "Word32"): + return operator.index(argument) + if kind == "Bool": + if not isinstance(argument, bool): + raise TypeError("expected bool") + return argument + if kind == "maybe": + return ( + None + if argument is None + else _prepare(specification[1], argument, temporary) + ) + if kind == "list": + return [_prepare(specification[1], item, temporary) for item in argument] + if kind == "tuple": + fields = tuple(argument) + if len(fields) != len(specification) - 1: + raise ValueError("tuple arity differs") + return tuple( + _prepare(t, v, temporary) for t, v in zip(specification[1:], fields) + ) + return argument + + +def _callback(function, result_spec): + import hmath + + if not callable(function): + raise TypeError("expected a callable original IO/decoder argument") + state = _CallbackState() + + @_CALLBACK + def callback(pointer, _, out, wire): + temporary = [] + try: + arguments = value.decode(value.borrow(pointer)) + returned = function(*arguments) + encoded = value.encode(_prepare(result_spec, returned, temporary)) + state.retained.extend( + owner for owner in encoded._owners if owner is not state + ) + out[0] = encoded._ptr + encoded._ptr, encoded._owners = C.c_void_p(), () + return 0 + except BaseException as error: # noqa: BLE001 - nothing may unwind through ctypes + try: + status = fill(wire, error, state.buffers) + except BaseException: + status = 0 # noqa: BLE001 - malformed errors stay contained + if status: + return status + state.failures.append(error) + wire.contents.message = C.cast(_FAILURE_MESSAGE, C.c_void_p) + wire.contents.message_length = len(_FAILURE_MESSAGE.value) + return 6 + finally: + for owner in temporary: + owner.close() + + owner = value.Value._adopt(owners=(callback, state)) + hmath.initialize() + hmath._check( + value.api( + "hmath_linear_callback", + C.c_int, + C.c_void_p, + _CALLBACK, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, callback, None, C.byref(owner._ptr)) + ) + return owner + + +def _invoke(symbol, specifications, arguments, *, boxed=False): + temporary = [] + try: + prepared = [ + _prepare(t, v, temporary) for t, v in zip(specifications, arguments) + ] + return _native_invoke( + symbol, [["Value"] for _ in prepared], prepared, boxed=boxed + ) + finally: + for owner in temporary: + owner.close() + + +def _dtype_name(dtype, array=None): + if dtype is None: + native = _invoke(_PREFIX + "array_d_type", [["Value"]], [array]) + try: + return _DTYPES[_invoke(_PREFIX + "dtype_code", [["Value"]], [native])] + finally: + native.close() + if isinstance(dtype, DType): + return _DTYPES[_invoke(_PREFIX + "dtype_code", [["Value"]], [dtype])] + name = getattr(dtype, "name", dtype) + aliases = { + "bool8": "bool", + "f32": "float32", + "f64": "float64", + "c64": "complex64", + "c128": "complex128", + "i8": "int8", + "u8": "uint8", + "i16": "int16", + "u16": "uint16", + "i32": "int32", + "u32": "uint32", + "i64": "int64", + "u64": "uint64", + } + name = aliases.get(str(name).lower(), str(name).lower()) + if name not in _DTYPES: + raise ValueError("dtype has no original fixed-width Element instance") + return name + + +def _scalar(source, dtype): + if isinstance(source, value.Value): + return source.clone() + if dtype == "bool": + if not isinstance(source, bool): + raise TypeError("Bool8 values must be bool") + return value.encode(source) + return value.scalar(source, dtype) + + +def _prototype(dtype): + return _scalar(False if dtype == "bool" else 0, dtype) + + +def _element_type(dtype): + with _prototype(_dtype_name(dtype)) as prototype: + return _invoke(_PREFIX + "element_type", [["Value"]], [prototype]) + + +def _get_element(endian, dtype): + with _prototype(_dtype_name(dtype)) as prototype: + return _invoke( + _PREFIX + "get_element", [["Value"], ["Value"]], [prototype, endian] + ) + + +def _put_element(endian, source, dtype): + dtype = _dtype_name(dtype) + with _prototype(dtype) as prototype, _scalar(source, dtype) as scalar: + return _invoke( + _PREFIX + "put_element", [["Value"]] * 3, [prototype, endian, scalar] + ) + + +def _from_values(limits, endian, shape, values, dtype): + dtype = _dtype_name(dtype) + items = [] + try: + for item in values: + items.append(_scalar(item, dtype)) + with _prototype(dtype) as prototype, value.encode(items) as encoded: + return _invoke( + _PREFIX + "from_values", + [["Value"], ["Value"], ["Value"], ["list", ["Int"]], ["Value"]], + [prototype, limits, endian, shape, encoded], + ) + finally: + for item in items: + item.close() + + +def _to_values(operation, array, dtype, boxed): + dtype = _dtype_name(dtype, array) + with _prototype(dtype) as prototype: + return _invoke( + _PREFIX + operation, [["Value"], ["Value"]], [prototype, array], boxed=boxed + ) + + +def _mapped_value(mapping, indices, dtype, boxed): + with _prototype(_dtype_name(dtype)) as prototype: + return _invoke( + _PREFIX + "mapped_value", + [["Value"], ["Value"], ["list", ["Int"]]], + [prototype, mapping, indices], + boxed=boxed, + ) diff --git a/bindings/python/_hmath_native/_interchange_error.py b/bindings/python/_hmath_native/_interchange_error.py new file mode 100644 index 0000000..d8d6ab4 --- /dev/null +++ b/bindings/python/_hmath_native/_interchange_error.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: MPL-2.0 +"""The four original interchange errors, with lossless message payloads.""" + +import ctypes as C +from dataclasses import dataclass +from enum import IntEnum + + +class InterchangeErrorKind(IntEnum): + INVALID_DATA = 0 + UNSUPPORTED = 1 + LIMIT_EXCEEDED = 2 + IO_ERROR = 3 + + +@dataclass(frozen=True) +class InterchangeError(Exception): + kind: InterchangeErrorKind + message: str + + def __str__(self): + return self.kind.name + ": " + self.message + + +class Wire(C.Structure): + _fields_ = [ + ("kind", C.c_uint32), + ("message", C.c_void_p), + ("message_length", C.c_size_t), + ] + + +def last_interchange_error(library): + try: + getter = C.CFUNCTYPE(C.c_int, C.POINTER(Wire))( + ("hmath_last_interchange_error", library) + ) + except AttributeError: + return None + wire = Wire() + if not getter(C.byref(wire)): + return None + message = C.string_at(wire.message, wire.message_length).decode( + "utf-8", "surrogatepass" + ) + return InterchangeError(InterchangeErrorKind(wire.kind), message) + + +def fill(pointer, error, owners): + if not isinstance(error, InterchangeError): + error = getattr(error, "interchange_error", None) + if not isinstance(error, InterchangeError): + return False + pointer.contents.kind = error.kind + encoded = error.message.encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(encoded) + owners.append(buffer) + pointer.contents.message = C.cast(buffer, C.c_void_p) + pointer.contents.message_length = len(encoded) + return True diff --git a/bindings/python/_hmath_native/_linear_base.py b/bindings/python/_hmath_native/_linear_base.py new file mode 100644 index 0000000..2514841 --- /dev/null +++ b/bindings/python/_hmath_native/_linear_base.py @@ -0,0 +1,356 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Owned typed representation and callbacks; algorithms stay in Haskell.""" + +import ctypes as C +import importlib +from fractions import Fraction + +from . import _value as V +from ._callback_error import fill +from ._math_error import Wire + +_REGISTRY = {} + + +def register(source_type, owner): + if source_type in _REGISTRY and _REGISTRY[source_type] is not owner: + raise ValueError("linear source type already registered") + _REGISTRY[source_type] = owner + + +class LinearValue(V.Value): + """Original immutable object. All derived outputs own independent references.""" + + _source_type = None + + def __init__(self, *_args, **_kwargs): + raise TypeError( + "construct this abstract type through its original public functions" + ) + + def _initialize(self, symbol, generic, specs, args, dtype=None): + value = _invoke(symbol, generic, specs, args, dtype=dtype) + self._ptr, self._lock, self._owners = value._ptr, value._lock, value._owners + value._ptr, value._owners = C.c_void_p(), () + + @property + def source_type(self): + return self._source_type + + @property + def parts(self): + """Public constructor name and exact positional fields (abstract types reject).""" + return V.decode(V.invoke("hmath_linear_object_parts", self)) + + +def _decode(value): + name = V.decode(V.invoke("hmath_linear_object_type", value)) + if name in ("HMath.Matrix.LU.LU", "HMath.Matrix.QR.QR"): + import hmath + + from ._matrix_base import LU, QR + + owner = (LU if name.endswith(".LU") else QR)._adopt( + "float64", "l" if name.endswith(".LU") else "q" + ) + try: + with value._lock: + hmath._check( + V.api( + "hmath_linear_export_legacy", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, value._ptr, C.byref(owner._ptr)) + ) + return owner + finally: + value.close() + owner = _REGISTRY.get(name) + if owner is None: + namespace = { + "HMath.Vector": "vector", + "HMath.Matrix.Advanced": "matrix_advanced", + "HMath.Matrix.Decomposition": "decomposition", + "HMath.Matrix.Iterative": "iterative", + "HMath.Matrix.LAPACK": "lapack", + "HMath.Sparse": "sparse", + "HMath.Sparse.Spectral": "sparse_spectral", + "HMath.Backend": "backend", + }[name.rsplit(".", 1)[0]] + importlib.import_module("." + namespace, __package__) + owner = _REGISTRY.get(name) + if owner is None: + raise TypeError("unknown original linear object type") + with value._lock: + result = owner._adopt(value._ptr, value._owners) + value._ptr, value._owners = C.c_void_p(), () + return result + + +V.register(100, _decode) + + +def _infer(arguments): + from ._matrix_base import Matrix + + for value in arguments: + if isinstance(value, V.Value): + kind, dtype, _ = value.info + if kind == 294 or (kind == 100 and dtype in (16, 17, 18)): + return value + if kind in (1, 9, 100) and dtype >= 0: + if dtype in V.DTYPE_NAMES: + return V.DTYPE_NAMES[dtype] + for owner in value._owners: + if isinstance(owner, V.Value) and owner.info[0] == 1: + return owner + elif isinstance(value, Matrix): + return value.dtype + elif isinstance(value, (list, tuple)): + result = _infer(value) + if result is not None: + return result + elif isinstance(value, Fraction): + return "rational" + elif isinstance(value, complex): + return "complex128" + return None + + +def _prototype(dtype): + if isinstance(dtype, str) and dtype in ("bool", "string"): + return V.encode(False if dtype == "bool" else "") + return ( + dtype.clone() if isinstance(dtype, V.Value) else V.scalar(0, dtype or "float64") + ) + + +def _scalar(value, dtype): + if isinstance(value, V.Value): + return value.clone() + if isinstance(dtype, V.Value): + if dtype.info[0] == 100 and dtype.info[1] in (16, 17): + return V.encode(value) + raise TypeError("structured coefficients require typed scalar Values") + if dtype in ("bool", "string"): + return V.encode(value) + return V.scalar(value, dtype) + + +def _prepare(spec, value, dtype, owners, callbacks): + head, *args = spec + if head in ("a", "b", "c", "Double", "Float", "Integer", "Rational", "Complex"): + target = { + "Double": "float64", + "Float": "float32", + "Integer": "integer", + "Rational": "rational", + }.get(head, dtype) + if head == "Complex": + target = "complex64" if args[0] == ["Float"] else "complex128" + result = _scalar(value, target) + owners.append(result) + return result + if head == "list": + return [_prepare(args[0], item, dtype, owners, callbacks) for item in value] + if head == "tuple": + value = tuple(value) + if len(value) != len(args): + raise ValueError("tuple arity differs from original signature") + return tuple( + _prepare(s, item, dtype, owners, callbacks) for s, item in zip(args, value) + ) + if head == "Maybe": + return ( + None + if value is None + else _prepare(args[0], value, dtype, owners, callbacks) + ) + if head == "function": + if isinstance(value, V.Value): + callbacks.extend(_callback_states(value)) + return value + result = _callback(value, args[-1], dtype) + owners.append(result) + callbacks.append(result) + return result + return value + + +_CALLBACK = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p), C.POINTER(Wire) +) + + +class _CallbackState: + def __init__(self): + self._callback_errors = [] + self.payload = [] + self.returned_owners = [] + + +def _callback_states(value): + """Find retained Python callback errors through native Value owner graphs.""" + result = [] + seen = set() + + def visit(item): + if id(item) in seen: + return + seen.add(id(item)) + if isinstance(item, _CallbackState): + result.append(item) + for child in item.returned_owners: + visit(child) + elif isinstance(item, V.Value): + for child in item._owners: + visit(child) + elif isinstance(item, (list, tuple)): + for child in item: + visit(child) + + visit(value) + return result + + +def _callback_scope(callbacks): + states = [] + seen = set() + for callback in callbacks: + candidates = ( + [callback] + if isinstance(callback, _CallbackState) + else _callback_states(callback) + ) + for state in candidates: + if id(state) not in seen: + seen.add(id(state)) + states.append((state, len(state._callback_errors))) + return states + + +def _take_callback_failure(scopes): + first = None + for state, before in scopes: + if len(state._callback_errors) > before: + if first is None: + first = state._callback_errors[before] + del state._callback_errors[before:] + return first + + +def _callback(function, result_spec, dtype): + import hmath + + if not callable(function): + raise TypeError("expected a callable original function argument") + state = _CallbackState() + pending = state._callback_errors + payload = state.payload + + @_CALLBACK + def callback(pointer, _userdata, out, wire): + argument = None + owners = [] + try: + argument = V.decode(V.borrow(pointer)) + result = ( + function(*argument) + if isinstance(argument, tuple) + else function(argument) + ) + prepared = _prepare(result_spec, result, dtype, owners, []) + encoded = V.encode(prepared) + # Native StablePtr cloning does not retain newly-created Python + # callbacks/userdata. Keep every returned dependency transitively. + state.returned_owners.extend( + owner + for owner in encoded._owners + if owner is not state and owner is not callback + ) + out[0] = encoded._ptr + encoded._ptr, encoded._owners = C.c_void_p(), () + return 0 + except BaseException as error: # noqa: BLE001 - ctypes callbacks cannot propagate exceptions + try: + handled = fill(wire, error, payload) + except BaseException: # noqa: BLE001 - malformed payloads cannot escape ctypes + handled = 0 + if handled: + return handled + pending.append(error) + try: + description = str(error) + except BaseException: # noqa: BLE001 - exception formatting must not escape ctypes + description = type(error).__name__ + message = description.encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(message) + payload.append(buffer) + wire.contents.message = C.cast(buffer, C.c_void_p) + wire.contents.message_length = len(message) + return 9 + finally: + for owner in owners: + owner.close() + + owner = V.Value._adopt(owners=(callback, state)) + hmath.initialize() + hmath._check( + V.api( + "hmath_linear_callback", + C.c_int, + C.c_void_p, + _CALLBACK, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, callback, None, C.byref(owner._ptr)) + ) + owner._callback_errors = pending + return owner + + +def _invoke(symbol, generic, specs, arguments, dtype=None): + owners = [] + callbacks = [] + try: + dtype = dtype if dtype is not None else _infer(arguments) or "float64" + prepared = [ + _prepare(spec, value, dtype, owners, callbacks) + for spec, value in zip(specs, arguments) + ] + if generic: + if symbol == "hmath_linear_matrix_advanced_zip_matrix_with": + left = _prototype(_infer([arguments[1]]) or dtype) + right = _prototype(_infer([arguments[2]]) or dtype) + output = _prototype(dtype) + owners.extend([left, right, output]) + prototype = (left, right, output) + else: + if symbol in ( + "hmath_linear_matrix_advanced_hermitian_matrix", + "hmath_linear_matrix_advanced_conjugate_transpose", + ): + dtype = {"complex64": "float32", "complex128": "float64"}.get( + dtype, dtype + ) + prototype = _prototype(dtype) + owners.append(prototype) + prepared.insert(0, prototype) + snapshots = [] + if generic: + source = prototype[-1] if isinstance(prototype, tuple) else prototype + snapshots = [source.clone()] + scopes = _callback_scope(callbacks) + try: + result = V.invoke(symbol, *prepared, owners=snapshots) + except BaseException: + failure = _take_callback_failure(scopes) + if failure is not None: + raise failure + raise + return V.decode(result) + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_math_error.py b/bindings/python/_hmath_native/_math_error.py new file mode 100644 index 0000000..74e542b --- /dev/null +++ b/bindings/python/_hmath_native/_math_error.py @@ -0,0 +1,154 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless original MathError values and C callback transport.""" + +import ctypes as C +import json +from enum import IntEnum + +from ._numeric import _int + + +class MathErrorKind(IntEnum): + NEGATIVE_DIMENSIONS = 1 + ELEMENT_COUNT_OVERFLOW = 2 + ELEMENT_COUNT_MISMATCH = 3 + SHAPE_MISMATCH = 4 + INNER_DIMENSION_MISMATCH = 5 + INDEX_OUT_OF_BOUNDS = 6 + SLICE_OUT_OF_BOUNDS = 7 + VECTOR_LENGTH_MISMATCH = 8 + NON_SQUARE_MATRIX = 9 + INVALID_TOLERANCE = 10 + SINGULAR_MATRIX = 11 + NEAR_SINGULAR_MATRIX = 12 + NON_FINITE_MATRIX_ENTRY = 13 + NON_FINITE_VECTOR_ENTRY = 14 + NON_FINITE_RESULT = 15 + RIGHT_HAND_SIDE_MISMATCH = 16 + DOMAIN_ERROR = 17 + INVALID_ARGUMENT = 18 + NON_CONVERGENCE = 19 + RANK_DEFICIENT = 20 + NOT_POSITIVE_DEFINITE = 21 + + +_ARITY = (0, 2, 2, 2, 4, 2, 4, 6, 2, 2, 0, 1, 1, 2, 1, 0, 2, 0, 0, 1, 1, 1) +_NAMES = ( + "", + "NegativeDimensions", + "ElementCountOverflow", + "ElementCountMismatch", + "ShapeMismatch", + "InnerDimensionMismatch", + "IndexOutOfBounds", + "SliceOutOfBounds", + "VectorLengthMismatch", + "NonSquareMatrix", + "InvalidTolerance", + "SingularMatrix", + "NearSingularMatrix", + "NonFiniteMatrixEntry", + "NonFiniteVectorEntry", + "NonFiniteResult", + "RightHandSideMismatch", + "DomainError", + "InvalidArgument", + "NonConvergence", + "RankDeficient", + "NotPositiveDefinite", +) + + +class MathError(Exception): + """A source MathError constructor, integer fields and full string payload. + + Raise this from checked Python callbacks to return a Haskell Left value. + The solver may recover from that Left according to its original algorithm. + Unexpected Python exceptions instead abort and rethrow after native cleanup. + """ + + status = 11 + + def __init__(self, kind, details=(), message=""): + self.kind = MathErrorKind(kind) + self.details = tuple(_int(value) for value in details) + self.message = str(message) + if len(self.details) != _ARITY[self.kind]: + raise ValueError( + f"{self.kind.name} needs {_ARITY[self.kind]} integer fields" + ) + super().__init__(self.kind, self.details, self.message) + + def __str__(self): + name = _NAMES[self.kind] + if self.kind in (1, 2, 9, 13): + return f"{name} ({self.details[0]},{self.details[1]})" + if self.kind in (4, 6, 7): + pairs = " ".join( + f"({self.details[i]},{self.details[i + 1]})" + for i in range(0, len(self.details), 2) + ) + return name + " " + pairs + if self.kind in (17, 18, 19): + payload = json.dumps(self.message, ensure_ascii=False) + return ( + name + + " " + + payload + + (f" {self.details[0]}" if self.kind == 19 else "") + ) + return name + ((" " + " ".join(map(str, self.details))) if self.details else "") + + +class Wire(C.Structure): + _fields_ = [ + ("kind", C.c_uint32), + ("details", C.c_ssize_t * 6), + ("message", C.c_void_p), + ("message_length", C.c_size_t), + ] + + +def decode(wire): + kind = MathErrorKind(wire.kind) + payload = ( + C.string_at(wire.message, wire.message_length).decode("utf-8", "surrogatepass") + if wire.message_length + else "" + ) + return MathError(kind, wire.details[: _ARITY[kind]], payload) + + +def fill(pointer, error, owners): + """Copy payload into a caller-owned callback buffer set, including NUL.""" + if not isinstance(error, MathError): + error = getattr(error, "math_error", None) + if not isinstance(error, MathError): + return False + # Public exceptions can be subclassed or have attributes replaced after + # construction. Validate again before ctypes can narrow integer fields. + kind = MathErrorKind(error.kind) + details = tuple(_int(value) for value in error.details) + if len(details) != _ARITY[kind]: + raise ValueError(f"{kind.name} needs {_ARITY[kind]} integer fields") + pointer.contents.kind = kind + for index in range(6): + pointer.contents.details[index] = details[index] if index < len(details) else 0 + payload = error.message.encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(payload) + owners.append(buffer) + pointer.contents.message = C.cast(buffer, C.c_void_p) + pointer.contents.message_length = len(payload) + return True + + +def last_math_error(library): + """Query without changing native status; older ABI1 libraries return None.""" + try: + getter = C.CFUNCTYPE(C.c_int, C.POINTER(Wire))( + ("hmath_last_math_error", library) + ) + except AttributeError: + return None + wire = Wire() + return decode(wire) if getter(C.byref(wire)) else None diff --git a/bindings/python/_hmath_native/_matrix_base.py b/bindings/python/_hmath_native/_matrix_base.py new file mode 100644 index 0000000..2665b32 --- /dev/null +++ b/bindings/python/_hmath_native/_matrix_base.py @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Direct typed bindings for HMath.Matrix, Matrix.LU and Matrix.QR. + +Constructors and operations preserve original Maybe (None) / Either (exception) +conventions. Objects are immutable, own independent references, and pin the +Haskell runtime until close(). There are no implicit dtype conversions. +""" + +import ctypes as C +import threading +from contextlib import ExitStack + +from ._numeric import _int + + +def _function(name, result, *types): + import hmath + + return C.CFUNCTYPE(result, *types)((name, hmath._lib)) + + +class _Owned: + @classmethod + def _adopt(cls, dtype, kind): + result = object.__new__(cls) + result._ptr, result._dtype, result._kind = C.c_void_p(), dtype, kind + result._lock = threading.RLock() + return result + + def close(self): + with self._lock: + if self._ptr: + _function("hmath_dense_release", None, C.c_void_p)(self._ptr) + self._ptr = C.c_void_p() + + def __enter__(self): + with self._lock: + if not self._ptr: + raise ValueError("dense object is closed") + return self + + def __exit__(self, *_): + self.close() + + def __del__(self): + if getattr(self, "_ptr", None): + self.close() + + @property + def dtype(self): + return self._dtype + + +class Matrix(_Owned): + """Immutable dense Matrix; create with from_list[_checked] and an explicit dtype.""" + + def to_list(self): + return to_list(self) + + @property + def shape(self): + return shape(self) + + +class LU(_Owned): + """Original immutable LU factors; create with lu_decompose.""" + + +class QR(_Owned): + """Original immutable column-pivoted QR factors; create with qr_decompose.""" + + +def _copy_values(obj, indices=False): + import hmath + + count = C.c_size_t() + hmath._check( + _function( + "hmath_dense_count", C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_size_t) + )(None, obj._ptr, C.byref(count)) + ) + scalar = ( + C.c_ssize_t if indices else C.c_float if obj._dtype == "float32" else C.c_double + ) + values = (scalar * count.value)() + symbol = ( + "hmath_dense_indices_copy" + if indices + else "hmath_dense_values_f" + ("32" if obj._dtype == "float32" else "64") + ) + hmath._check( + _function( + symbol, C.c_int, C.c_void_p, C.c_void_p, C.POINTER(scalar), C.c_size_t + )(None, obj._ptr, values, count.value) + ) + return list(values) + + +def to_list(matrix): + """HMath.Matrix.toList, in logical row-major order.""" + if not isinstance(matrix, Matrix): + raise TypeError("expected Matrix") + from . import _matrix_value + from ._value import Value + + if isinstance(matrix, Value): + return _matrix_value.to_list(matrix) + with matrix._lock: + if not matrix._ptr: + raise ValueError("dense object is closed") + return _copy_values(matrix) + + +def shape(matrix): + """HMath.Matrix.shape; zero dimensions retain their original shape.""" + import hmath + + if not isinstance(matrix, Matrix): + raise TypeError("expected Matrix") + from . import _matrix_value + from ._value import Value + + if isinstance(matrix, Value): + return _matrix_value.shape(matrix) + rows, columns = C.c_ssize_t(), C.c_ssize_t() + with matrix._lock: + if not matrix._ptr: + raise ValueError("dense object is closed") + hmath._check( + _function( + "hmath_dense_shape", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_ssize_t), + C.POINTER(C.c_ssize_t), + )(None, matrix._ptr, C.byref(rows), C.byref(columns)) + ) + return rows.value, columns.value + + +def _invoke(stem, kinds, result_kind, mode, arguments, dtype=None): + import hmath + + objects = [value for kind, value in zip(kinds, arguments) if kind in "mlq"] + for obj in objects: + if not isinstance(obj, _Owned): + raise TypeError("expected a dense HMath object") + if objects: + dtype = objects[0].dtype + if dtype is None: + dtype = "float64" + from . import _matrix_value + from ._value import Value + + if dtype not in ("float32", "float64") or any( + isinstance(obj, Value) for obj in objects + ): + return _matrix_value.invoke(stem, kinds, arguments, dtype) + real = C.c_float if dtype == "float32" else C.c_double + types, values = [C.c_void_p], [None] + for kind, argument in zip(kinds, arguments): + if kind in "mlq": + if not isinstance(argument, {"m": Matrix, "l": LU, "q": QR}[kind]): + raise TypeError("dense object kind mismatch") + if argument._dtype != dtype: + raise TypeError("dense operands must have the same dtype") + types.append(C.c_void_p) + values.append(argument._ptr) + elif kind == "i": + types.append(C.c_ssize_t) + values.append(_int(argument)) + elif kind == "f": + types.append(real) + values.append(argument) + elif kind == "v": + argument = tuple(argument) + array = (real * len(argument))(*argument) + types.extend([C.POINTER(real), C.c_size_t]) + values.extend([array, len(argument)]) + owner = None + if result_kind in "mlqvp": + owner = {"m": Matrix, "l": LU, "q": QR, "v": _Owned, "p": _Owned}[ + result_kind + ]._adopt(dtype, result_kind) + output = owner._ptr + else: + output = (C.c_ssize_t if result_kind == "i" else real)() + types.append(C.POINTER(type(output))) + values.append(C.byref(output)) + found = C.c_int() + if mode == "maybe" and result_kind == "f": + types.append(C.POINTER(C.c_int)) + values.append(C.byref(found)) + function = _function( + stem + ("_f32" if dtype == "float32" else "_f64"), C.c_int, *types + ) + hmath.initialize() + with ExitStack() as locks: + for obj in sorted({id(obj): obj for obj in objects}.values(), key=id): + locks.enter_context(obj._lock) + if not obj._ptr: + raise ValueError("dense object is closed") + # Re-read pointers under their locks; close() may have replaced one + # while Python was constructing the argument buffers. + cursor = 1 + for kind, argument in zip(kinds, arguments): + if kind in "mlq": + values[cursor] = argument._ptr + cursor += 2 if kind == "v" else 1 + hmath._check(function(*values)) + if owner is not None: + if not owner._ptr: + return None + if result_kind in "vp": + try: + return _copy_values(owner, indices=result_kind == "p") + finally: + owner.close() + return owner + return None if mode == "maybe" and not found.value else output.value + + +# Register the lossless Dense Value decoder after legacy owner definitions. +from . import _matrix_value as _matrix_value # noqa: PLC0414 diff --git a/bindings/python/_hmath_native/_matrix_value.py b/bindings/python/_hmath_native/_matrix_value.py new file mode 100644 index 0000000..4a0fa1b --- /dev/null +++ b/bindings/python/_hmath_native/_matrix_value.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless Matrix coefficient/ownership bridge to the original operations.""" + +import ctypes as C + +from . import _value as V +from ._matrix_base import Matrix + + +class MatrixValue(V.Value, Matrix): + """A Matrix with a standard typed element and shared Value owner.""" + + @property + def dtype(self): + return {16: "bool", 17: "string", 18: "exact"}.get( + self.info[1], V.DTYPE_NAMES.get(self.info[1]) + ) + + +def _export(matrix): + import hmath + + result = V.Value._adopt() + with matrix._lock: + if not matrix._ptr: + raise ValueError("dense object is closed") + hmath._check( + V.api( + "hmath_dense_to_value", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, matrix._ptr, C.byref(result._ptr)) + ) + return result + + +def _decode(value): + import hmath + + _, dtype, _ = value.info + if dtype in (0, 1): + result = Matrix._adopt("float32" if dtype == 1 else "float64", "m") + try: + with value._lock: + hmath._check( + V.api( + "hmath_dense_from_value", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, value._ptr, C.byref(result._ptr)) + ) + return result + finally: + value.close() + with value._lock: + result = MatrixValue._adopt(value._ptr, value._owners) + value._ptr, value._owners = C.c_void_p(), () + return result + + +V.register(9, _decode) +V.register_encoder(Matrix, _export) + + +def shape(matrix): + return V.decode(V.invoke("hmath_matrix_value_shape", matrix)) + + +def to_list(matrix): + return V.decode(V.invoke("hmath_matrix_value_to_list", matrix)) + + +def _prototype(dtype): + if isinstance(dtype, V.Value): + return dtype.clone() + if dtype == "bool": + return V.encode(False) + if dtype == "string": + return V.encode("") + return V.scalar(0, dtype) + + +def invoke(stem, kinds, arguments, dtype): + objects = [value for kind, value in zip(kinds, arguments) if kind in "mlq"] + if any(kind in "lq" for kind in kinds) or stem.startswith( + ("hmath_dense_lu_", "hmath_dense_qr_") + ): + raise TypeError("the original LU/QR operations require Float or Double") + if objects: + dtype = objects[0].dtype + if any(not isinstance(value, Matrix) for value in objects): + raise TypeError("expected Matrix") + if any(value.dtype != dtype for value in objects): + raise TypeError("Matrix coefficient types differ") + converted, owners = [], [] + try: + if not objects: + prototype = _prototype(dtype) + owners.append(prototype) + converted.append(prototype) + for kind, value in zip(kinds, arguments): + if kind == "f": + scalar = ( + value.clone() + if isinstance(value, V.Value) + else V.encode(value) + if dtype in ("bool", "string") + else V.scalar(value, dtype) + ) + owners.append(scalar) + converted.append(scalar) + elif kind == "v": + values = [] + for item in value: + scalar = ( + item.clone() + if isinstance(item, V.Value) + else V.encode(item) + if dtype in ("bool", "string") + else V.scalar(item, dtype) + ) + owners.append(scalar) + values.append(scalar) + converted.append(values) + else: + converted.append(value) + symbol = "hmath_matrix_value_" + stem.removeprefix("hmath_dense_") + return V.decode(V.invoke(symbol, *converted)) + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_neural_base.py b/bindings/python/_hmath_native/_neural_base.py new file mode 100644 index 0000000..6a5c29a --- /dev/null +++ b/bindings/python/_hmath_native/_neural_base.py @@ -0,0 +1,953 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original neural selectors, state records and exact AD/Tensor/RNG ownership.""" + +from dataclasses import dataclass +from enum import IntEnum + +from . import _value as v +from . import ( + random_values as _random_values, # noqa: F401 - register full original RNG240 +) +from ._compat import zip_equal +from ._neural_catalog import CATALOG +from ._numeric import _int +from ._tensor_core import _typed as _tensor_typed + +_SPEC = {entry["module"] + "." + entry["name"]: entry for entry in CATALOG} + + +@dataclass(frozen=True) +class _Constructor: + name: str + arguments: tuple = () + + +class Activation(_Constructor): + pass + + +class Loss(_Constructor): + pass + + +class Initializer(_Constructor): + pass + + +class Reduction(IntEnum): + SUM = 0 + MEAN = 1 + + +class Training(IntEnum): + TRAINING = 0 + INFERENCE = 1 + + +class PoolMode(IntEnum): + MAX_POOL = 0 + AVERAGE_POOL = 1 + + +class Quantization(IntEnum): + SYMMETRIC = 0 + ASYMMETRIC = 1 + + +class Precision(IntEnum): + FP16 = 0 + BF16 = 1 + + +@dataclass(frozen=True) +class BatchNormState: + running_mean: list + running_variance: list + batches_seen: int + + +@dataclass(frozen=True) +class ConvOptions: + stride: list + padding: list + dilation: list + groups: int + + +@dataclass(frozen=True) +class LossScaler: + scale: float + growth_interval: int + finite_steps: int + + +@dataclass(frozen=True) +class ClassificationMetrics: + accuracy: float + precision: list + recall: list + f1: list + + +class KVCache(v.Value): + """Original immutable owned key/value cache. Construct with empty_cache.""" + + +class QuantizedTensor(v.Value): + """Actual original INT8 tensor and calibration, not reconstructed metadata.""" + + @property + def values(self): + return quantized_values(self) + + @property + def scales(self): + return quantization_scales(self) + + @property + def zero_points(self): + return quantization_zero_points(self) + + +_ENUMS = { + "Reduction": (Reduction, "Core", ["Sum", "Mean"]), + "Training": (Training, "Layers", ["Training", "Inference"]), + "PoolMode": (PoolMode, "Layers", ["MaxPool", "AveragePool"]), + "Quantization": (Quantization, "Precision", ["Symmetric", "Asymmetric"]), + "Precision": (Precision, "Precision", ["FP16", "BF16"]), +} +_RECORDS = { + "BatchNormState": ( + BatchNormState, + "Layers", + ["running_mean", "running_variance", "batches_seen"], + ["runningMean", "runningVariance", "batchesSeen"], + ), + "ConvOptions": ( + ConvOptions, + "Layers", + ["stride", "padding", "dilation", "groups"], + [ + "convolutionStride", + "convolutionPadding", + "convolutionDilation", + "convolutionGroups", + ], + ), + "LossScaler": ( + LossScaler, + "Precision", + ["scale", "growth_interval", "finite_steps"], + ["lossScale", "scaleGrowthInterval", "finiteSteps"], + ), + "ClassificationMetrics": ( + ClassificationMetrics, + "Metrics", + ["accuracy", "precision", "recall", "f1"], + ["accuracy", "precisionByClass", "recallByClass", "f1ByClass"], + ), +} + + +def _sequence(values, hint): + encoded = [] + try: + for value in values: + encoded.append(_typed(value, hint)) + return v.encode(encoded) + finally: + for value in encoded: + value.close() + + +def _typed(value, hint): + if isinstance(value, v.Value): + return value.clone() + if isinstance(value, _Constructor): + return _raw(value.name, *value.arguments) + if hint == "Double": + return v.scalar(value, "float64") + if hint == "Int": + return _tensor_typed(_int(value), "Int") + if hint == "Bool": + return _tensor_typed(value, "Bool") + if hint in _ENUMS: + cls, module, names = _ENUMS[hint] + kind = cls(value) + return _raw("HMath.DeepLearning." + module + "." + names[kind]) + if hint in _RECORDS: + cls, module, fields, _ = _RECORDS[hint] + if not isinstance(value, cls): + raise TypeError("expected " + hint) + return _raw( + "HMath.DeepLearning." + module + "." + hint, + *[getattr(value, field) for field in fields], + ) + if hint == "ADExpr": + from . import autodiff as ad + + if isinstance(value, ad.Expr): + return v.encode(value) + with ad.constant(value) as expression: + return v.encode(expression) + if hint.startswith("Maybe"): + return v.encode(None) if value is None else _typed(value, hint[5:]) + if hint.startswith("["): + return _sequence(value, hint[1:-1]) + return v.encode(value) + + +def _raw(name, *arguments): + entry = _SPEC[name] + if len(arguments) != len(entry["arguments"]): + raise TypeError(name + " argument count differs") + values = [] + try: + for value, (_, hint) in zip_equal(arguments, entry["arguments"]): + values.append(_typed(value, hint)) + return v.invoke(entry["c"], *values) + finally: + for value in values: + value.close() + + +def _invoke(name, *arguments): + return v.decode(_raw(name, *arguments)) + + +def _record(value, name): + cls, module, _, selectors = _RECORDS[name] + try: + return cls( + *[ + _invoke("HMath.DeepLearning." + module + "." + selector, value) + for selector in selectors + ] + ) + finally: + value.close() + + +v.register(278, lambda value: _record(value, "BatchNormState")) +v.register(280, lambda value: _record(value, "ConvOptions")) +v.register(282, KVCache) +v.register(285, QuantizedTensor) +v.register(286, lambda value: _record(value, "LossScaler")) +v.register(290, lambda value: _record(value, "ClassificationMetrics")) + +# BEGIN GENERATED +Sigmoid = Activation("HMath.DeepLearning.Core.Sigmoid") + +Activation.SIGMOID = Sigmoid + +Tanh = Activation("HMath.DeepLearning.Core.Tanh") + +Activation.TANH = Tanh + +ReLU = Activation("HMath.DeepLearning.Core.ReLU") + +Activation.RELU = ReLU + +SELU = Activation("HMath.DeepLearning.Core.SELU") + +Activation.SELU = SELU + +GELU = Activation("HMath.DeepLearning.Core.GELU") + +Activation.GELU = GELU + +SiLU = Activation("HMath.DeepLearning.Core.SiLU") + +Activation.SILU = SiLU + +Mish = Activation("HMath.DeepLearning.Core.Mish") + +Activation.MISH = Mish + +Softplus = Activation("HMath.DeepLearning.Core.Softplus") + +Activation.SOFTPLUS = Softplus + +Softsign = Activation("HMath.DeepLearning.Core.Softsign") + +Activation.SOFTSIGN = Softsign + +HardSigmoid = Activation("HMath.DeepLearning.Core.HardSigmoid") + +Activation.HARD_SIGMOID = HardSigmoid + +HardSwish = Activation("HMath.DeepLearning.Core.HardSwish") + +Activation.HARD_SWISH = HardSwish + + +def LeakyReLU(parameter): + return Activation("HMath.DeepLearning.Core.LeakyReLU", (parameter,)) + + +Activation.LEAKY_RELU = staticmethod(LeakyReLU) + + +def PReLU(parameter): + return Activation("HMath.DeepLearning.Core.PReLU", (parameter,)) + + +Activation.PRELU = staticmethod(PReLU) + + +def ELU(parameter): + return Activation("HMath.DeepLearning.Core.ELU", (parameter,)) + + +Activation.ELU = staticmethod(ELU) + +Sum = Reduction.SUM + +Mean = Reduction.MEAN + +MeanSquaredError = Loss("HMath.DeepLearning.Core.MeanSquaredError") + +Loss.MEAN_SQUARED_ERROR = MeanSquaredError + +MeanAbsoluteError = Loss("HMath.DeepLearning.Core.MeanAbsoluteError") + +Loss.MEAN_ABSOLUTE_ERROR = MeanAbsoluteError + +BinaryCrossEntropy = Loss("HMath.DeepLearning.Core.BinaryCrossEntropy") + +Loss.BINARY_CROSS_ENTROPY = BinaryCrossEntropy + +CategoricalCrossEntropy = Loss("HMath.DeepLearning.Core.CategoricalCrossEntropy") + +Loss.CATEGORICAL_CROSS_ENTROPY = CategoricalCrossEntropy + +NegativeLogLikelihood = Loss("HMath.DeepLearning.Core.NegativeLogLikelihood") + +Loss.NEGATIVE_LOG_LIKELIHOOD = NegativeLogLikelihood + +KLDivergence = Loss("HMath.DeepLearning.Core.KLDivergence") + +Loss.KL_DIVERGENCE = KLDivergence + +CosineLoss = Loss("HMath.DeepLearning.Core.CosineLoss") + +Loss.COSINE_LOSS = CosineLoss + + +def Huber(parameter): + return Loss("HMath.DeepLearning.Core.Huber", (parameter,)) + + +Loss.HUBER = staticmethod(Huber) + + +def SmoothL1(parameter): + return Loss("HMath.DeepLearning.Core.SmoothL1", (parameter,)) + + +Loss.SMOOTH_L1 = staticmethod(SmoothL1) + + +def Hinge(parameter): + return Loss("HMath.DeepLearning.Core.Hinge", (parameter,)) + + +Loss.HINGE = staticmethod(Hinge) + + +def activation(method, value): + """HMath.DeepLearning.Core.activation: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.activation", method, value) + + +def activation_derivative(method, value): + """HMath.DeepLearning.Core.activationDerivative: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.activationDerivative", method, value) + + +def activation_expr(method, value): + """HMath.DeepLearning.Core.activationExpr: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.activationExpr", method, value) + + +def softmax(values): + """HMath.DeepLearning.Core.softmax: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.softmax", values) + + +def log_softmax(values): + """HMath.DeepLearning.Core.logSoftmax: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.logSoftmax", values) + + +def sparsemax(values): + """HMath.DeepLearning.Core.sparsemax: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.sparsemax", values) + + +def gated_linear_unit(values, gate): + """HMath.DeepLearning.Core.gatedLinearUnit: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.gatedLinearUnit", values, gate) + + +def softmax_expr(values): + """HMath.DeepLearning.Core.softmaxExpr: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.softmaxExpr", values) + + +def log_softmax_expr(values): + """HMath.DeepLearning.Core.logSoftmaxExpr: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.logSoftmaxExpr", values) + + +def sparsemax_expr(values): + """HMath.DeepLearning.Core.sparsemaxExpr: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.sparsemaxExpr", values) + + +def loss(method, reduction, target, prediction): + """HMath.DeepLearning.Core.loss: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.loss", method, reduction, target, prediction + ) + + +def loss_gradient(method, reduction, target, prediction): + """HMath.DeepLearning.Core.lossGradient: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.lossGradient", method, reduction, target, prediction + ) + + +def loss_expr(method, reduction, target, prediction): + """HMath.DeepLearning.Core.lossExpr: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.lossExpr", method, reduction, target, prediction + ) + + +def binary_cross_entropy_logits(reduction, target, logits): + """HMath.DeepLearning.Core.binaryCrossEntropyLogits: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.binaryCrossEntropyLogits", reduction, target, logits + ) + + +def categorical_cross_entropy_logits(target, logits): + """HMath.DeepLearning.Core.categoricalCrossEntropyLogits: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.categoricalCrossEntropyLogits", target, logits + ) + + +def regularization(l1, l2, weights): + """HMath.DeepLearning.Core.regularization: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.regularization", l1, l2, weights) + + +def contrastive_loss(margin, similar, left, right): + """HMath.DeepLearning.Core.contrastiveLoss: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.contrastiveLoss", margin, similar, left, right + ) + + +def triplet_loss(margin, anchor, positive, negative): + """HMath.DeepLearning.Core.tripletLoss: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.tripletLoss", margin, anchor, positive, negative + ) + + +def focal_loss(alpha, gamma, target, prediction): + """HMath.DeepLearning.Core.focalLoss: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.focalLoss", alpha, gamma, target, prediction + ) + + +def dice_loss(smooth, target, prediction): + """HMath.DeepLearning.Core.diceLoss: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.diceLoss", smooth, target, prediction) + + +def iou_loss(smooth, target, prediction): + """HMath.DeepLearning.Core.iouLoss: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.iouLoss", smooth, target, prediction) + + +def ctc_loss(blank, labels, log_probabilities): + """HMath.DeepLearning.Core.ctcLoss: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Core.ctcLoss", blank, labels, log_probabilities) + + +def ctc_loss_gradient(blank, labels, log_probabilities): + """HMath.DeepLearning.Core.ctcLossGradient: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.ctcLossGradient", blank, labels, log_probabilities + ) + + +def ctc_loss_expr(blank, labels, log_probabilities): + """HMath.DeepLearning.Core.ctcLossExpr: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Core.ctcLossExpr", blank, labels, log_probabilities + ) + + +Inference = Training.INFERENCE + + +def dropout(mode, probability, rng, input): + """HMath.DeepLearning.Layers.dropout: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.dropout", mode, probability, rng, input) + + +def spatial_dropout(mode, probability, rng, input): + """HMath.DeepLearning.Layers.spatialDropout: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.spatialDropout", mode, probability, rng, input + ) + + +def running_mean(state): + """HMath.DeepLearning.Layers.runningMean: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.runningMean", state) + + +def running_variance(state): + """HMath.DeepLearning.Layers.runningVariance: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.runningVariance", state) + + +def batches_seen(state): + """HMath.DeepLearning.Layers.batchesSeen: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.batchesSeen", state) + + +def batch_norm(mode, momentum, epsilon, gamma, beta, state, input): + """HMath.DeepLearning.Layers.batchNorm: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.batchNorm", + mode, + momentum, + epsilon, + gamma, + beta, + state, + input, + ) + + +def layer_norm(axes, epsilon, input): + """HMath.DeepLearning.Layers.layerNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.layerNorm", axes, epsilon, input) + + +def rms_norm(axes, epsilon, input): + """HMath.DeepLearning.Layers.rmsNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.rmsNorm", axes, epsilon, input) + + +def instance_norm(epsilon, input): + """HMath.DeepLearning.Layers.instanceNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.instanceNorm", epsilon, input) + + +def group_norm(groups, epsilon, input): + """HMath.DeepLearning.Layers.groupNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.groupNorm", groups, epsilon, input) + + +def weight_norm(axis, scales, input): + """HMath.DeepLearning.Layers.weightNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.weightNorm", axis, scales, input) + + +XavierUniform = Initializer("HMath.DeepLearning.Layers.XavierUniform") + +Initializer.XAVIER_UNIFORM = XavierUniform + +XavierNormal = Initializer("HMath.DeepLearning.Layers.XavierNormal") + +Initializer.XAVIER_NORMAL = XavierNormal + +KaimingUniform = Initializer("HMath.DeepLearning.Layers.KaimingUniform") + +Initializer.KAIMING_UNIFORM = KaimingUniform + +KaimingNormal = Initializer("HMath.DeepLearning.Layers.KaimingNormal") + +Initializer.KAIMING_NORMAL = KaimingNormal + + +def Orthogonal(scale): + return Initializer("HMath.DeepLearning.Layers.Orthogonal", (scale,)) + + +Initializer.ORTHOGONAL = staticmethod(Orthogonal) + + +def TruncatedNormal(mean, standard_deviation, bound): + return Initializer( + "HMath.DeepLearning.Layers.TruncatedNormal", (mean, standard_deviation, bound) + ) + + +Initializer.TRUNCATED_NORMAL = staticmethod(TruncatedNormal) + + +def initialize_weights(method, fan_in, fan_out, shape, rng): + """HMath.DeepLearning.Layers.initializeWeights: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.initializeWeights", + method, + fan_in, + fan_out, + shape, + rng, + ) + + +def embedding(weights, indices): + """HMath.DeepLearning.Layers.embedding: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.embedding", weights, indices) + + +def dense(input, weights, bias): + """HMath.DeepLearning.Layers.dense: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.dense", input, weights, bias) + + +def dense_ad(input, weights, bias): + """HMath.DeepLearning.Layers.denseAD: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.denseAD", input, weights, bias) + + +def convolution_stride(options): + """HMath.DeepLearning.Layers.convolutionStride: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.convolutionStride", options) + + +def convolution_padding(options): + """HMath.DeepLearning.Layers.convolutionPadding: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.convolutionPadding", options) + + +def convolution_dilation(options): + """HMath.DeepLearning.Layers.convolutionDilation: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.convolutionDilation", options) + + +def convolution_groups(options): + """HMath.DeepLearning.Layers.convolutionGroups: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.convolutionGroups", options) + + +def convolution(options, input, weights, bias): + """HMath.DeepLearning.Layers.convolution: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.convolution", options, input, weights, bias + ) + + +def depthwise_convolution(options, input, weights, bias): + """HMath.DeepLearning.Layers.depthwiseConvolution: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.depthwiseConvolution", options, input, weights, bias + ) + + +def convolution_ad(options, input, weights, bias): + """HMath.DeepLearning.Layers.convolutionAD: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.convolutionAD", options, input, weights, bias + ) + + +def transposed_convolution(output_padding, options, input, weights, bias): + """HMath.DeepLearning.Layers.transposedConvolution: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.transposedConvolution", + output_padding, + options, + input, + weights, + bias, + ) + + +MaxPool = PoolMode.MAX_POOL + +AveragePool = PoolMode.AVERAGE_POOL + + +def pooling(mode, kernel, stride, padding, input): + """HMath.DeepLearning.Layers.pooling: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.pooling", mode, kernel, stride, padding, input + ) + + +def adaptive_pooling(mode, shape, input): + """HMath.DeepLearning.Layers.adaptivePooling: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.adaptivePooling", mode, shape, input) + + +def global_pooling(mode, input): + """HMath.DeepLearning.Layers.globalPooling: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.globalPooling", mode, input) + + +def scaled_dot_product_attention(query, key, value, mask, bias): + """HMath.DeepLearning.Layers.scaledDotProductAttention: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.scaledDotProductAttention", + query, + key, + value, + mask, + bias, + ) + + +def multihead_attention(heads, query, key, value, mask): + """HMath.DeepLearning.Layers.multiheadAttention: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.multiheadAttention", heads, query, key, value, mask + ) + + +def causal_mask(queries, keys, offset): + """HMath.DeepLearning.Layers.causalMask: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.causalMask", queries, keys, offset) + + +def rotary_embedding(base, offset, input): + """HMath.DeepLearning.Layers.rotaryEmbedding: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.rotaryEmbedding", base, offset, input) + + +def sinusoidal_encoding(length, dimensions, offset): + """HMath.DeepLearning.Layers.sinusoidalEncoding: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.sinusoidalEncoding", length, dimensions, offset + ) + + +def alibi_bias(slope, queries, keys, offset): + """HMath.DeepLearning.Layers.alibiBias: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.alibiBias", slope, queries, keys, offset) + + +def empty_cache(capacity, key_dimensions, value_dimensions): + """HMath.DeepLearning.Layers.emptyCache: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.emptyCache", + capacity, + key_dimensions, + value_dimensions, + ) + + +def append_cache(cache, key, value): + """HMath.DeepLearning.Layers.appendCache: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.appendCache", cache, key, value) + + +def cache_values(cache): + """HMath.DeepLearning.Layers.cacheValues: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.cacheValues", cache) + + +def transformer_feed_forward( + activation, input, first_weights, first_bias, second_weights, second_bias +): + """HMath.DeepLearning.Layers.transformerFeedForward: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.transformerFeedForward", + activation, + input, + first_weights, + first_bias, + second_weights, + second_bias, + ) + + +def layer_norm_ad(axes, epsilon, input): + """HMath.DeepLearning.Layers.layerNormAD: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.layerNormAD", axes, epsilon, input) + + +def rms_norm_ad(axes, epsilon, input): + """HMath.DeepLearning.Layers.rmsNormAD: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Layers.rmsNormAD", axes, epsilon, input) + + +def scaled_dot_product_attention_ad(query, key, value, mask): + """HMath.DeepLearning.Layers.scaledDotProductAttentionAD: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Layers.scaledDotProductAttentionAD", query, key, value, mask + ) + + +Symmetric = Quantization.SYMMETRIC + +Asymmetric = Quantization.ASYMMETRIC + + +def quantize(scheme, axis, input): + """HMath.DeepLearning.Precision.quantize: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.quantize", scheme, axis, input) + + +def dequantize(quantized): + """HMath.DeepLearning.Precision.dequantize: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.dequantize", quantized) + + +def quantized_values(quantized): + """HMath.DeepLearning.Precision.quantizedValues: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.quantizedValues", quantized) + + +def quantization_scales(quantized): + """HMath.DeepLearning.Precision.quantizationScales: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.quantizationScales", quantized) + + +def quantization_zero_points(quantized): + """HMath.DeepLearning.Precision.quantizationZeroPoints: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.quantizationZeroPoints", quantized) + + +def int8_gemm(left, right): + """HMath.DeepLearning.Precision.int8Gemm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.int8Gemm", left, right) + + +FP16 = Precision.FP16 + +BF16 = Precision.BF16 + + +def reduced_gemm(precision, left, right): + """HMath.DeepLearning.Precision.reducedGemm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.reducedGemm", precision, left, right) + + +def loss_scale(state): + """HMath.DeepLearning.Precision.lossScale: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.lossScale", state) + + +def scale_growth_interval(state): + """HMath.DeepLearning.Precision.scaleGrowthInterval: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.scaleGrowthInterval", state) + + +def finite_steps(state): + """HMath.DeepLearning.Precision.finiteSteps: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.finiteSteps", state) + + +def initial_loss_scaler(scale, growth_interval): + """HMath.DeepLearning.Precision.initialLossScaler: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Precision.initialLossScaler", scale, growth_interval + ) + + +def scale_loss(state, loss): + """HMath.DeepLearning.Precision.scaleLoss: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.scaleLoss", state, loss) + + +def unscale_gradients(state, gradients): + """HMath.DeepLearning.Precision.unscaleGradients: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.unscaleGradients", state, gradients) + + +def update_loss_scaler(finite, state): + """HMath.DeepLearning.Precision.updateLossScaler: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.updateLossScaler", finite, state) + + +def gradient_norm(gradient): + """HMath.DeepLearning.Precision.gradientNorm: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.gradientNorm", gradient) + + +def clip_gradients(maximum, gradient): + """HMath.DeepLearning.Precision.clipGradients: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Precision.clipGradients", maximum, gradient) + + +def accuracy(metrics): + """HMath.DeepLearning.Metrics.accuracy: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.accuracy", metrics) + + +def precision_by_class(metrics): + """HMath.DeepLearning.Metrics.precisionByClass: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.precisionByClass", metrics) + + +def recall_by_class(metrics): + """HMath.DeepLearning.Metrics.recallByClass: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.recallByClass", metrics) + + +def f1_by_class(metrics): + """HMath.DeepLearning.Metrics.f1ByClass: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.f1ByClass", metrics) + + +def confusion_matrix(classes, truth, prediction): + """HMath.DeepLearning.Metrics.confusionMatrix: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Metrics.confusionMatrix", classes, truth, prediction + ) + + +def classification_metrics(classes, truth, prediction): + """HMath.DeepLearning.Metrics.classificationMetrics: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Metrics.classificationMetrics", classes, truth, prediction + ) + + +def top_k_accuracy(k, truth, scores): + """HMath.DeepLearning.Metrics.topKAccuracy: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.topKAccuracy", k, truth, scores) + + +def roc_auc(truth, scores): + """HMath.DeepLearning.Metrics.rocAUC: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.rocAUC", truth, scores) + + +def pr_auc(truth, scores): + """HMath.DeepLearning.Metrics.prAUC: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.prAUC", truth, scores) + + +def perplexity(negative_log_probabilities): + """HMath.DeepLearning.Metrics.perplexity: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.perplexity", negative_log_probabilities) + + +def cosine_similarity_matrix(left, right): + """HMath.DeepLearning.Metrics.cosineSimilarityMatrix: original defaults, errors, state and graph rules.""" + return _invoke("HMath.DeepLearning.Metrics.cosineSimilarityMatrix", left, right) + + +def margin_ranking_loss(margin, left, right, labels): + """HMath.DeepLearning.Metrics.marginRankingLoss: original defaults, errors, state and graph rules.""" + return _invoke( + "HMath.DeepLearning.Metrics.marginRankingLoss", margin, left, right, labels + ) + + +# END GENERATED diff --git a/bindings/python/_hmath_native/_neural_catalog.py b/bindings/python/_hmath_native/_neural_catalog.py new file mode 100644 index 0000000..14a322e --- /dev/null +++ b/bindings/python/_hmath_native/_neural_catalog.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_deeplearning_bindings.py. +import json +CATALOG=json.loads('[{"module":"HMath.DeepLearning.Core","name":"Sigmoid","arguments":[],"result":"Activation","python":"sigmoid","c":"hmath_neural_core_sigmoid_create","expression":"C.Sigmoid"},{"module":"HMath.DeepLearning.Core","name":"Tanh","arguments":[],"result":"Activation","python":"tanh","c":"hmath_neural_core_tanh_create","expression":"C.Tanh"},{"module":"HMath.DeepLearning.Core","name":"ReLU","arguments":[],"result":"Activation","python":"relu","c":"hmath_neural_core_relu_create","expression":"C.ReLU"},{"module":"HMath.DeepLearning.Core","name":"SELU","arguments":[],"result":"Activation","python":"selu","c":"hmath_neural_core_selu_create","expression":"C.SELU"},{"module":"HMath.DeepLearning.Core","name":"GELU","arguments":[],"result":"Activation","python":"gelu","c":"hmath_neural_core_gelu_create","expression":"C.GELU"},{"module":"HMath.DeepLearning.Core","name":"SiLU","arguments":[],"result":"Activation","python":"silu","c":"hmath_neural_core_silu_create","expression":"C.SiLU"},{"module":"HMath.DeepLearning.Core","name":"Mish","arguments":[],"result":"Activation","python":"mish","c":"hmath_neural_core_mish_create","expression":"C.Mish"},{"module":"HMath.DeepLearning.Core","name":"Softplus","arguments":[],"result":"Activation","python":"softplus","c":"hmath_neural_core_softplus_create","expression":"C.Softplus"},{"module":"HMath.DeepLearning.Core","name":"Softsign","arguments":[],"result":"Activation","python":"softsign","c":"hmath_neural_core_softsign_create","expression":"C.Softsign"},{"module":"HMath.DeepLearning.Core","name":"HardSigmoid","arguments":[],"result":"Activation","python":"hard_sigmoid","c":"hmath_neural_core_hard_sigmoid_create","expression":"C.HardSigmoid"},{"module":"HMath.DeepLearning.Core","name":"HardSwish","arguments":[],"result":"Activation","python":"hard_swish","c":"hmath_neural_core_hard_swish_create","expression":"C.HardSwish"},{"module":"HMath.DeepLearning.Core","name":"LeakyReLU","arguments":[["parameter","Double"]],"result":"Activation","python":"leaky_relu","c":"hmath_neural_core_leaky_relu_create","expression":"C.LeakyReLU"},{"module":"HMath.DeepLearning.Core","name":"PReLU","arguments":[["parameter","Double"]],"result":"Activation","python":"prelu","c":"hmath_neural_core_prelu_create","expression":"C.PReLU"},{"module":"HMath.DeepLearning.Core","name":"ELU","arguments":[["parameter","Double"]],"result":"Activation","python":"elu","c":"hmath_neural_core_elu_create","expression":"C.ELU"},{"module":"HMath.DeepLearning.Core","name":"Sum","arguments":[],"result":"Reduction","python":"sum","c":"hmath_neural_core_sum_create","expression":"C.Sum"},{"module":"HMath.DeepLearning.Core","name":"Mean","arguments":[],"result":"Reduction","python":"mean","c":"hmath_neural_core_mean_create","expression":"C.Mean"},{"module":"HMath.DeepLearning.Core","name":"MeanSquaredError","arguments":[],"result":"Loss","python":"mean_squared_error","c":"hmath_neural_core_mean_squared_error_create","expression":"C.MeanSquaredError"},{"module":"HMath.DeepLearning.Core","name":"MeanAbsoluteError","arguments":[],"result":"Loss","python":"mean_absolute_error","c":"hmath_neural_core_mean_absolute_error_create","expression":"C.MeanAbsoluteError"},{"module":"HMath.DeepLearning.Core","name":"BinaryCrossEntropy","arguments":[],"result":"Loss","python":"binary_cross_entropy","c":"hmath_neural_core_binary_cross_entropy_create","expression":"C.BinaryCrossEntropy"},{"module":"HMath.DeepLearning.Core","name":"CategoricalCrossEntropy","arguments":[],"result":"Loss","python":"categorical_cross_entropy","c":"hmath_neural_core_categorical_cross_entropy_create","expression":"C.CategoricalCrossEntropy"},{"module":"HMath.DeepLearning.Core","name":"NegativeLogLikelihood","arguments":[],"result":"Loss","python":"negative_log_likelihood","c":"hmath_neural_core_negative_log_likelihood_create","expression":"C.NegativeLogLikelihood"},{"module":"HMath.DeepLearning.Core","name":"KLDivergence","arguments":[],"result":"Loss","python":"kl_divergence","c":"hmath_neural_core_kl_divergence_create","expression":"C.KLDivergence"},{"module":"HMath.DeepLearning.Core","name":"CosineLoss","arguments":[],"result":"Loss","python":"cosine_loss","c":"hmath_neural_core_cosine_loss_create","expression":"C.CosineLoss"},{"module":"HMath.DeepLearning.Core","name":"Huber","arguments":[["parameter","Double"]],"result":"Loss","python":"huber","c":"hmath_neural_core_huber_create","expression":"C.Huber"},{"module":"HMath.DeepLearning.Core","name":"SmoothL1","arguments":[["parameter","Double"]],"result":"Loss","python":"smooth_l1","c":"hmath_neural_core_smooth_l1_create","expression":"C.SmoothL1"},{"module":"HMath.DeepLearning.Core","name":"Hinge","arguments":[["parameter","Double"]],"result":"Loss","python":"hinge","c":"hmath_neural_core_hinge_create","expression":"C.Hinge"},{"module":"HMath.DeepLearning.Core","name":"activation","arguments":[["method","Activation"],["value","Double"]],"result":"Double","python":"activation","c":"hmath_neural_core_activation","expression":"C.activation"},{"module":"HMath.DeepLearning.Core","name":"activationDerivative","arguments":[["method","Activation"],["value","Double"]],"result":"Double","python":"activation_derivative","c":"hmath_neural_core_activation_derivative","expression":"C.activationDerivative"},{"module":"HMath.DeepLearning.Core","name":"activationExpr","arguments":[["method","Activation"],["value","ADExpr"]],"result":"ADExpr","python":"activation_expr","c":"hmath_neural_core_activation_expr","expression":"C.activationExpr"},{"module":"HMath.DeepLearning.Core","name":"softmax","arguments":[["values","[Double]"]],"result":"[Double]","python":"softmax","c":"hmath_neural_core_softmax","expression":"C.softmax"},{"module":"HMath.DeepLearning.Core","name":"logSoftmax","arguments":[["values","[Double]"]],"result":"[Double]","python":"log_softmax","c":"hmath_neural_core_log_softmax","expression":"C.logSoftmax"},{"module":"HMath.DeepLearning.Core","name":"sparsemax","arguments":[["values","[Double]"]],"result":"[Double]","python":"sparsemax","c":"hmath_neural_core_sparsemax","expression":"C.sparsemax"},{"module":"HMath.DeepLearning.Core","name":"gatedLinearUnit","arguments":[["values","[Double]"],["gate","[Double]"]],"result":"[Double]","python":"gated_linear_unit","c":"hmath_neural_core_gated_linear_unit","expression":"C.gatedLinearUnit"},{"module":"HMath.DeepLearning.Core","name":"softmaxExpr","arguments":[["values","[ADExpr]"]],"result":"[ADExpr]","python":"softmax_expr","c":"hmath_neural_core_softmax_expr","expression":"C.softmaxExpr"},{"module":"HMath.DeepLearning.Core","name":"logSoftmaxExpr","arguments":[["values","[ADExpr]"]],"result":"[ADExpr]","python":"log_softmax_expr","c":"hmath_neural_core_log_softmax_expr","expression":"C.logSoftmaxExpr"},{"module":"HMath.DeepLearning.Core","name":"sparsemaxExpr","arguments":[["values","[ADExpr]"]],"result":"[ADExpr]","python":"sparsemax_expr","c":"hmath_neural_core_sparsemax_expr","expression":"C.sparsemaxExpr"},{"module":"HMath.DeepLearning.Core","name":"loss","arguments":[["method","Loss"],["reduction","Reduction"],["target","[Double]"],["prediction","[Double]"]],"result":"Double","python":"loss","c":"hmath_neural_core_loss","expression":"C.loss"},{"module":"HMath.DeepLearning.Core","name":"lossGradient","arguments":[["method","Loss"],["reduction","Reduction"],["target","[Double]"],["prediction","[Double]"]],"result":"[Double]","python":"loss_gradient","c":"hmath_neural_core_loss_gradient","expression":"C.lossGradient"},{"module":"HMath.DeepLearning.Core","name":"lossExpr","arguments":[["method","Loss"],["reduction","Reduction"],["target","[Double]"],["prediction","[ADExpr]"]],"result":"ADExpr","python":"loss_expr","c":"hmath_neural_core_loss_expr","expression":"C.lossExpr"},{"module":"HMath.DeepLearning.Core","name":"binaryCrossEntropyLogits","arguments":[["reduction","Reduction"],["target","[Double]"],["logits","[Double]"]],"result":"Double","python":"binary_cross_entropy_logits","c":"hmath_neural_core_binary_cross_entropy_logits","expression":"C.binaryCrossEntropyLogits"},{"module":"HMath.DeepLearning.Core","name":"categoricalCrossEntropyLogits","arguments":[["target","[Double]"],["logits","[Double]"]],"result":"Double","python":"categorical_cross_entropy_logits","c":"hmath_neural_core_categorical_cross_entropy_logits","expression":"C.categoricalCrossEntropyLogits"},{"module":"HMath.DeepLearning.Core","name":"regularization","arguments":[["l1","Double"],["l2","Double"],["weights","[Double]"]],"result":"Double","python":"regularization","c":"hmath_neural_core_regularization","expression":"C.regularization"},{"module":"HMath.DeepLearning.Core","name":"contrastiveLoss","arguments":[["margin","Double"],["similar","Bool"],["left","[Double]"],["right","[Double]"]],"result":"Double","python":"contrastive_loss","c":"hmath_neural_core_contrastive_loss","expression":"C.contrastiveLoss"},{"module":"HMath.DeepLearning.Core","name":"tripletLoss","arguments":[["margin","Double"],["anchor","[Double]"],["positive","[Double]"],["negative","[Double]"]],"result":"Double","python":"triplet_loss","c":"hmath_neural_core_triplet_loss","expression":"C.tripletLoss"},{"module":"HMath.DeepLearning.Core","name":"focalLoss","arguments":[["alpha","Double"],["gamma","Double"],["target","[Double]"],["prediction","[Double]"]],"result":"Double","python":"focal_loss","c":"hmath_neural_core_focal_loss","expression":"C.focalLoss"},{"module":"HMath.DeepLearning.Core","name":"diceLoss","arguments":[["smooth","Double"],["target","[Double]"],["prediction","[Double]"]],"result":"Double","python":"dice_loss","c":"hmath_neural_core_dice_loss","expression":"C.diceLoss"},{"module":"HMath.DeepLearning.Core","name":"iouLoss","arguments":[["smooth","Double"],["target","[Double]"],["prediction","[Double]"]],"result":"Double","python":"iou_loss","c":"hmath_neural_core_iou_loss","expression":"C.iouLoss"},{"module":"HMath.DeepLearning.Core","name":"ctcLoss","arguments":[["blank","Int"],["labels","[Int]"],["log_probabilities","[[Double]]"]],"result":"Double","python":"ctc_loss","c":"hmath_neural_core_ctc_loss","expression":"C.ctcLoss"},{"module":"HMath.DeepLearning.Core","name":"ctcLossGradient","arguments":[["blank","Int"],["labels","[Int]"],["log_probabilities","[[Double]]"]],"result":"(Double,[[Double]])","python":"ctc_loss_gradient","c":"hmath_neural_core_ctc_loss_gradient","expression":"C.ctcLossGradient"},{"module":"HMath.DeepLearning.Core","name":"ctcLossExpr","arguments":[["blank","Int"],["labels","[Int]"],["log_probabilities","[[ADExpr]]"]],"result":"ADExpr","python":"ctc_loss_expr","c":"hmath_neural_core_ctc_loss_expr","expression":"C.ctcLossExpr"},{"module":"HMath.DeepLearning.Layers","name":"Training","arguments":[],"result":"Training","python":"training","c":"hmath_neural_layers_training_create","expression":"L.Training"},{"module":"HMath.DeepLearning.Layers","name":"Inference","arguments":[],"result":"Training","python":"inference","c":"hmath_neural_layers_inference_create","expression":"L.Inference"},{"module":"HMath.DeepLearning.Layers","name":"dropout","arguments":[["mode","Training"],["probability","Double"],["rng","RNG"],["input","Tensor"]],"result":"(Tensor,Tensor,RNG)","python":"dropout","c":"hmath_neural_layers_dropout","expression":"L.dropout"},{"module":"HMath.DeepLearning.Layers","name":"spatialDropout","arguments":[["mode","Training"],["probability","Double"],["rng","RNG"],["input","Tensor"]],"result":"(Tensor,Tensor,RNG)","python":"spatial_dropout","c":"hmath_neural_layers_spatial_dropout","expression":"L.spatialDropout"},{"module":"HMath.DeepLearning.Layers","name":"BatchNormState","arguments":[["running_mean","[Double]"],["running_variance","[Double]"],["batches_seen","Int"]],"result":"BatchNormState","python":"batch_norm_state","c":"hmath_neural_layers_batch_norm_state_create","expression":"L.BatchNormState"},{"module":"HMath.DeepLearning.Layers","name":"runningMean","arguments":[["state","BatchNormState"]],"result":"[Double]","python":"running_mean","c":"hmath_neural_layers_running_mean","expression":"L.runningMean"},{"module":"HMath.DeepLearning.Layers","name":"runningVariance","arguments":[["state","BatchNormState"]],"result":"[Double]","python":"running_variance","c":"hmath_neural_layers_running_variance","expression":"L.runningVariance"},{"module":"HMath.DeepLearning.Layers","name":"batchesSeen","arguments":[["state","BatchNormState"]],"result":"Int","python":"batches_seen","c":"hmath_neural_layers_batches_seen","expression":"L.batchesSeen"},{"module":"HMath.DeepLearning.Layers","name":"batchNorm","arguments":[["mode","Training"],["momentum","Double"],["epsilon","Double"],["gamma","[Double]"],["beta","[Double]"],["state","BatchNormState"],["input","Tensor"]],"result":"(Tensor,BatchNormState)","python":"batch_norm","c":"hmath_neural_layers_batch_norm","expression":"L.batchNorm"},{"module":"HMath.DeepLearning.Layers","name":"layerNorm","arguments":[["axes","Int"],["epsilon","Double"],["input","Tensor"]],"result":"Tensor","python":"layer_norm","c":"hmath_neural_layers_layer_norm","expression":"L.layerNorm"},{"module":"HMath.DeepLearning.Layers","name":"rmsNorm","arguments":[["axes","Int"],["epsilon","Double"],["input","Tensor"]],"result":"Tensor","python":"rms_norm","c":"hmath_neural_layers_rms_norm","expression":"L.rmsNorm"},{"module":"HMath.DeepLearning.Layers","name":"instanceNorm","arguments":[["epsilon","Double"],["input","Tensor"]],"result":"Tensor","python":"instance_norm","c":"hmath_neural_layers_instance_norm","expression":"L.instanceNorm"},{"module":"HMath.DeepLearning.Layers","name":"groupNorm","arguments":[["groups","Int"],["epsilon","Double"],["input","Tensor"]],"result":"Tensor","python":"group_norm","c":"hmath_neural_layers_group_norm","expression":"L.groupNorm"},{"module":"HMath.DeepLearning.Layers","name":"weightNorm","arguments":[["axis","Int"],["scales","[Double]"],["input","Tensor"]],"result":"Tensor","python":"weight_norm","c":"hmath_neural_layers_weight_norm","expression":"L.weightNorm"},{"module":"HMath.DeepLearning.Layers","name":"XavierUniform","arguments":[],"result":"Initializer","python":"xavier_uniform","c":"hmath_neural_layers_xavier_uniform_create","expression":"L.XavierUniform"},{"module":"HMath.DeepLearning.Layers","name":"XavierNormal","arguments":[],"result":"Initializer","python":"xavier_normal","c":"hmath_neural_layers_xavier_normal_create","expression":"L.XavierNormal"},{"module":"HMath.DeepLearning.Layers","name":"KaimingUniform","arguments":[],"result":"Initializer","python":"kaiming_uniform","c":"hmath_neural_layers_kaiming_uniform_create","expression":"L.KaimingUniform"},{"module":"HMath.DeepLearning.Layers","name":"KaimingNormal","arguments":[],"result":"Initializer","python":"kaiming_normal","c":"hmath_neural_layers_kaiming_normal_create","expression":"L.KaimingNormal"},{"module":"HMath.DeepLearning.Layers","name":"Orthogonal","arguments":[["scale","Double"]],"result":"Initializer","python":"orthogonal","c":"hmath_neural_layers_orthogonal_create","expression":"L.Orthogonal"},{"module":"HMath.DeepLearning.Layers","name":"TruncatedNormal","arguments":[["mean","Double"],["standard_deviation","Double"],["bound","Double"]],"result":"Initializer","python":"truncated_normal","c":"hmath_neural_layers_truncated_normal_create","expression":"L.TruncatedNormal"},{"module":"HMath.DeepLearning.Layers","name":"initializeWeights","arguments":[["method","Initializer"],["fan_in","Int"],["fan_out","Int"],["shape","[Int]"],["rng","RNG"]],"result":"(Tensor,RNG)","python":"initialize_weights","c":"hmath_neural_layers_initialize_weights","expression":"L.initializeWeights"},{"module":"HMath.DeepLearning.Layers","name":"embedding","arguments":[["weights","Tensor"],["indices","[Int]"]],"result":"Tensor","python":"embedding","c":"hmath_neural_layers_embedding","expression":"L.embedding"},{"module":"HMath.DeepLearning.Layers","name":"dense","arguments":[["input","Tensor"],["weights","Tensor"],["bias","[Double]"]],"result":"Tensor","python":"dense","c":"hmath_neural_layers_dense","expression":"L.dense"},{"module":"HMath.DeepLearning.Layers","name":"denseAD","arguments":[["input","ADTensor"],["weights","ADTensor"],["bias","[ADExpr]"]],"result":"ADTensor","python":"dense_ad","c":"hmath_neural_layers_dense_ad","expression":"L.denseAD"},{"module":"HMath.DeepLearning.Layers","name":"ConvOptions","arguments":[["stride","[Int]"],["padding","[Int]"],["dilation","[Int]"],["groups","Int"]],"result":"ConvOptions","python":"conv_options","c":"hmath_neural_layers_conv_options_create","expression":"L.ConvOptions"},{"module":"HMath.DeepLearning.Layers","name":"convolutionStride","arguments":[["options","ConvOptions"]],"result":"[Int]","python":"convolution_stride","c":"hmath_neural_layers_convolution_stride","expression":"L.convolutionStride"},{"module":"HMath.DeepLearning.Layers","name":"convolutionPadding","arguments":[["options","ConvOptions"]],"result":"[Int]","python":"convolution_padding","c":"hmath_neural_layers_convolution_padding","expression":"L.convolutionPadding"},{"module":"HMath.DeepLearning.Layers","name":"convolutionDilation","arguments":[["options","ConvOptions"]],"result":"[Int]","python":"convolution_dilation","c":"hmath_neural_layers_convolution_dilation","expression":"L.convolutionDilation"},{"module":"HMath.DeepLearning.Layers","name":"convolutionGroups","arguments":[["options","ConvOptions"]],"result":"Int","python":"convolution_groups","c":"hmath_neural_layers_convolution_groups","expression":"L.convolutionGroups"},{"module":"HMath.DeepLearning.Layers","name":"convolution","arguments":[["options","ConvOptions"],["input","Tensor"],["weights","Tensor"],["bias","[Double]"]],"result":"Tensor","python":"convolution","c":"hmath_neural_layers_convolution","expression":"L.convolution"},{"module":"HMath.DeepLearning.Layers","name":"depthwiseConvolution","arguments":[["options","ConvOptions"],["input","Tensor"],["weights","Tensor"],["bias","[Double]"]],"result":"Tensor","python":"depthwise_convolution","c":"hmath_neural_layers_depthwise_convolution","expression":"L.depthwiseConvolution"},{"module":"HMath.DeepLearning.Layers","name":"convolutionAD","arguments":[["options","ConvOptions"],["input","ADTensor"],["weights","ADTensor"],["bias","[ADExpr]"]],"result":"ADTensor","python":"convolution_ad","c":"hmath_neural_layers_convolution_ad","expression":"L.convolutionAD"},{"module":"HMath.DeepLearning.Layers","name":"transposedConvolution","arguments":[["output_padding","[Int]"],["options","ConvOptions"],["input","Tensor"],["weights","Tensor"],["bias","[Double]"]],"result":"Tensor","python":"transposed_convolution","c":"hmath_neural_layers_transposed_convolution","expression":"L.transposedConvolution"},{"module":"HMath.DeepLearning.Layers","name":"MaxPool","arguments":[],"result":"PoolMode","python":"max_pool","c":"hmath_neural_layers_max_pool_create","expression":"L.MaxPool"},{"module":"HMath.DeepLearning.Layers","name":"AveragePool","arguments":[],"result":"PoolMode","python":"average_pool","c":"hmath_neural_layers_average_pool_create","expression":"L.AveragePool"},{"module":"HMath.DeepLearning.Layers","name":"pooling","arguments":[["mode","PoolMode"],["kernel","[Int]"],["stride","[Int]"],["padding","[Int]"],["input","Tensor"]],"result":"Tensor","python":"pooling","c":"hmath_neural_layers_pooling","expression":"L.pooling"},{"module":"HMath.DeepLearning.Layers","name":"adaptivePooling","arguments":[["mode","PoolMode"],["shape","[Int]"],["input","Tensor"]],"result":"Tensor","python":"adaptive_pooling","c":"hmath_neural_layers_adaptive_pooling","expression":"L.adaptivePooling"},{"module":"HMath.DeepLearning.Layers","name":"globalPooling","arguments":[["mode","PoolMode"],["input","Tensor"]],"result":"Tensor","python":"global_pooling","c":"hmath_neural_layers_global_pooling","expression":"L.globalPooling"},{"module":"HMath.DeepLearning.Layers","name":"scaledDotProductAttention","arguments":[["query","Tensor"],["key","Tensor"],["value","Tensor"],["mask","Maybe[[Bool]]"],["bias","Maybe[[Double]]"]],"result":"(Tensor,Tensor)","python":"scaled_dot_product_attention","c":"hmath_neural_layers_scaled_dot_product_attention","expression":"L.scaledDotProductAttention"},{"module":"HMath.DeepLearning.Layers","name":"multiheadAttention","arguments":[["heads","Int"],["query","Tensor"],["key","Tensor"],["value","Tensor"],["mask","Maybe[[Bool]]"]],"result":"Tensor","python":"multihead_attention","c":"hmath_neural_layers_multihead_attention","expression":"L.multiheadAttention"},{"module":"HMath.DeepLearning.Layers","name":"causalMask","arguments":[["queries","Int"],["keys","Int"],["offset","Int"]],"result":"[[Bool]]","python":"causal_mask","c":"hmath_neural_layers_causal_mask","expression":"L.causalMask"},{"module":"HMath.DeepLearning.Layers","name":"rotaryEmbedding","arguments":[["base","Double"],["offset","Int"],["input","Tensor"]],"result":"Tensor","python":"rotary_embedding","c":"hmath_neural_layers_rotary_embedding","expression":"L.rotaryEmbedding"},{"module":"HMath.DeepLearning.Layers","name":"sinusoidalEncoding","arguments":[["length","Int"],["dimensions","Int"],["offset","Int"]],"result":"Tensor","python":"sinusoidal_encoding","c":"hmath_neural_layers_sinusoidal_encoding","expression":"L.sinusoidalEncoding"},{"module":"HMath.DeepLearning.Layers","name":"alibiBias","arguments":[["slope","Double"],["queries","Int"],["keys","Int"],["offset","Int"]],"result":"[[Double]]","python":"alibi_bias","c":"hmath_neural_layers_alibi_bias","expression":"L.alibiBias"},{"module":"HMath.DeepLearning.Layers","name":"emptyCache","arguments":[["capacity","Int"],["key_dimensions","Int"],["value_dimensions","Int"]],"result":"KVCache","python":"empty_cache","c":"hmath_neural_layers_empty_cache","expression":"L.emptyCache"},{"module":"HMath.DeepLearning.Layers","name":"appendCache","arguments":[["cache","KVCache"],["key","Tensor"],["value","Tensor"]],"result":"KVCache","python":"append_cache","c":"hmath_neural_layers_append_cache","expression":"L.appendCache"},{"module":"HMath.DeepLearning.Layers","name":"cacheValues","arguments":[["cache","KVCache"]],"result":"(Tensor,Tensor)","python":"cache_values","c":"hmath_neural_layers_cache_values","expression":"L.cacheValues"},{"module":"HMath.DeepLearning.Layers","name":"transformerFeedForward","arguments":[["activation","Activation"],["input","Tensor"],["first_weights","Tensor"],["first_bias","[Double]"],["second_weights","Tensor"],["second_bias","[Double]"]],"result":"Tensor","python":"transformer_feed_forward","c":"hmath_neural_layers_transformer_feed_forward","expression":"L.transformerFeedForward"},{"module":"HMath.DeepLearning.Layers","name":"layerNormAD","arguments":[["axes","Int"],["epsilon","Double"],["input","ADTensor"]],"result":"ADTensor","python":"layer_norm_ad","c":"hmath_neural_layers_layer_norm_ad","expression":"L.layerNormAD"},{"module":"HMath.DeepLearning.Layers","name":"rmsNormAD","arguments":[["axes","Int"],["epsilon","Double"],["input","ADTensor"]],"result":"ADTensor","python":"rms_norm_ad","c":"hmath_neural_layers_rms_norm_ad","expression":"L.rmsNormAD"},{"module":"HMath.DeepLearning.Layers","name":"scaledDotProductAttentionAD","arguments":[["query","ADTensor"],["key","ADTensor"],["value","ADTensor"],["mask","Maybe[[Bool]]"]],"result":"ADTensor","python":"scaled_dot_product_attention_ad","c":"hmath_neural_layers_scaled_dot_product_attention_ad","expression":"L.scaledDotProductAttentionAD"},{"module":"HMath.DeepLearning.Precision","name":"Symmetric","arguments":[],"result":"Quantization","python":"symmetric","c":"hmath_neural_precision_symmetric_create","expression":"P.Symmetric"},{"module":"HMath.DeepLearning.Precision","name":"Asymmetric","arguments":[],"result":"Quantization","python":"asymmetric","c":"hmath_neural_precision_asymmetric_create","expression":"P.Asymmetric"},{"module":"HMath.DeepLearning.Precision","name":"quantize","arguments":[["scheme","Quantization"],["axis","MaybeInt"],["input","Tensor"]],"result":"QuantizedTensor","python":"quantize","c":"hmath_neural_precision_quantize","expression":"P.quantize"},{"module":"HMath.DeepLearning.Precision","name":"dequantize","arguments":[["quantized","QuantizedTensor"]],"result":"Tensor","python":"dequantize","c":"hmath_neural_precision_dequantize","expression":"P.dequantize"},{"module":"HMath.DeepLearning.Precision","name":"quantizedValues","arguments":[["quantized","QuantizedTensor"]],"result":"[Int8]","python":"quantized_values","c":"hmath_neural_precision_quantized_values","expression":"P.quantizedValues"},{"module":"HMath.DeepLearning.Precision","name":"quantizationScales","arguments":[["quantized","QuantizedTensor"]],"result":"[Double]","python":"quantization_scales","c":"hmath_neural_precision_quantization_scales","expression":"P.quantizationScales"},{"module":"HMath.DeepLearning.Precision","name":"quantizationZeroPoints","arguments":[["quantized","QuantizedTensor"]],"result":"[Int]","python":"quantization_zero_points","c":"hmath_neural_precision_quantization_zero_points","expression":"P.quantizationZeroPoints"},{"module":"HMath.DeepLearning.Precision","name":"int8Gemm","arguments":[["left","QuantizedTensor"],["right","QuantizedTensor"]],"result":"Tensor","python":"int8_gemm","c":"hmath_neural_precision_int8_gemm","expression":"P.int8Gemm"},{"module":"HMath.DeepLearning.Precision","name":"FP16","arguments":[],"result":"Precision","python":"fp16","c":"hmath_neural_precision_fp16_create","expression":"P.FP16"},{"module":"HMath.DeepLearning.Precision","name":"BF16","arguments":[],"result":"Precision","python":"bf16","c":"hmath_neural_precision_bf16_create","expression":"P.BF16"},{"module":"HMath.DeepLearning.Precision","name":"reducedGemm","arguments":[["precision","Precision"],["left","Tensor"],["right","Tensor"]],"result":"Tensor","python":"reduced_gemm","c":"hmath_neural_precision_reduced_gemm","expression":"P.reducedGemm"},{"module":"HMath.DeepLearning.Precision","name":"LossScaler","arguments":[["scale","Double"],["growth_interval","Int"],["finite_steps","Int"]],"result":"LossScaler","python":"loss_scaler","c":"hmath_neural_precision_loss_scaler_create","expression":"P.LossScaler"},{"module":"HMath.DeepLearning.Precision","name":"lossScale","arguments":[["state","LossScaler"]],"result":"Double","python":"loss_scale","c":"hmath_neural_precision_loss_scale","expression":"P.lossScale"},{"module":"HMath.DeepLearning.Precision","name":"scaleGrowthInterval","arguments":[["state","LossScaler"]],"result":"Int","python":"scale_growth_interval","c":"hmath_neural_precision_scale_growth_interval","expression":"P.scaleGrowthInterval"},{"module":"HMath.DeepLearning.Precision","name":"finiteSteps","arguments":[["state","LossScaler"]],"result":"Int","python":"finite_steps","c":"hmath_neural_precision_finite_steps","expression":"P.finiteSteps"},{"module":"HMath.DeepLearning.Precision","name":"initialLossScaler","arguments":[["scale","Double"],["growth_interval","Int"]],"result":"LossScaler","python":"initial_loss_scaler","c":"hmath_neural_precision_initial_loss_scaler","expression":"P.initialLossScaler"},{"module":"HMath.DeepLearning.Precision","name":"scaleLoss","arguments":[["state","LossScaler"],["loss","Double"]],"result":"Double","python":"scale_loss","c":"hmath_neural_precision_scale_loss","expression":"P.scaleLoss"},{"module":"HMath.DeepLearning.Precision","name":"unscaleGradients","arguments":[["state","LossScaler"],["gradients","[Double]"]],"result":"(Bool,[Double])","python":"unscale_gradients","c":"hmath_neural_precision_unscale_gradients","expression":"P.unscaleGradients"},{"module":"HMath.DeepLearning.Precision","name":"updateLossScaler","arguments":[["finite","Bool"],["state","LossScaler"]],"result":"LossScaler","python":"update_loss_scaler","c":"hmath_neural_precision_update_loss_scaler","expression":"P.updateLossScaler"},{"module":"HMath.DeepLearning.Precision","name":"gradientNorm","arguments":[["gradient","[Double]"]],"result":"Double","python":"gradient_norm","c":"hmath_neural_precision_gradient_norm","expression":"P.gradientNorm"},{"module":"HMath.DeepLearning.Precision","name":"clipGradients","arguments":[["maximum","Double"],["gradient","[Double]"]],"result":"[Double]","python":"clip_gradients","c":"hmath_neural_precision_clip_gradients","expression":"P.clipGradients"},{"module":"HMath.DeepLearning.Metrics","name":"ClassificationMetrics","arguments":[["accuracy","Double"],["precision","[Double]"],["recall","[Double]"],["f1","[Double]"]],"result":"ClassificationMetrics","python":"classification_metrics","c":"hmath_neural_metrics_classification_metrics_create","expression":"M.ClassificationMetrics"},{"module":"HMath.DeepLearning.Metrics","name":"accuracy","arguments":[["metrics","ClassificationMetrics"]],"result":"Double","python":"accuracy","c":"hmath_neural_metrics_accuracy","expression":"M.accuracy"},{"module":"HMath.DeepLearning.Metrics","name":"precisionByClass","arguments":[["metrics","ClassificationMetrics"]],"result":"[Double]","python":"precision_by_class","c":"hmath_neural_metrics_precision_by_class","expression":"M.precisionByClass"},{"module":"HMath.DeepLearning.Metrics","name":"recallByClass","arguments":[["metrics","ClassificationMetrics"]],"result":"[Double]","python":"recall_by_class","c":"hmath_neural_metrics_recall_by_class","expression":"M.recallByClass"},{"module":"HMath.DeepLearning.Metrics","name":"f1ByClass","arguments":[["metrics","ClassificationMetrics"]],"result":"[Double]","python":"f1_by_class","c":"hmath_neural_metrics_f1_by_class","expression":"M.f1ByClass"},{"module":"HMath.DeepLearning.Metrics","name":"confusionMatrix","arguments":[["classes","Int"],["truth","[Int]"],["prediction","[Int]"]],"result":"[[Int]]","python":"confusion_matrix","c":"hmath_neural_metrics_confusion_matrix","expression":"M.confusionMatrix"},{"module":"HMath.DeepLearning.Metrics","name":"classificationMetrics","arguments":[["classes","Int"],["truth","[Int]"],["prediction","[Int]"]],"result":"ClassificationMetrics","python":"classification_metrics","c":"hmath_neural_metrics_classification_metrics","expression":"M.classificationMetrics"},{"module":"HMath.DeepLearning.Metrics","name":"topKAccuracy","arguments":[["k","Int"],["truth","[Int]"],["scores","[[Double]]"]],"result":"Double","python":"top_k_accuracy","c":"hmath_neural_metrics_top_k_accuracy","expression":"M.topKAccuracy"},{"module":"HMath.DeepLearning.Metrics","name":"rocAUC","arguments":[["truth","[Bool]"],["scores","[Double]"]],"result":"Double","python":"roc_auc","c":"hmath_neural_metrics_roc_auc","expression":"M.rocAUC"},{"module":"HMath.DeepLearning.Metrics","name":"prAUC","arguments":[["truth","[Bool]"],["scores","[Double]"]],"result":"Double","python":"pr_auc","c":"hmath_neural_metrics_pr_auc","expression":"M.prAUC"},{"module":"HMath.DeepLearning.Metrics","name":"perplexity","arguments":[["negative_log_probabilities","[Double]"]],"result":"Double","python":"perplexity","c":"hmath_neural_metrics_perplexity","expression":"M.perplexity"},{"module":"HMath.DeepLearning.Metrics","name":"cosineSimilarityMatrix","arguments":[["left","Tensor"],["right","Tensor"]],"result":"Tensor","python":"cosine_similarity_matrix","c":"hmath_neural_metrics_cosine_similarity_matrix","expression":"M.cosineSimilarityMatrix"},{"module":"HMath.DeepLearning.Metrics","name":"marginRankingLoss","arguments":[["margin","Double"],["left","[Double]"],["right","[Double]"],["labels","[Double]"]],"result":"Double","python":"margin_ranking_loss","c":"hmath_neural_metrics_margin_ranking_loss","expression":"M.marginRankingLoss"}]') diff --git a/bindings/python/_hmath_native/_neural_core.py b/bindings/python/_hmath_native/_neural_core.py new file mode 100644 index 0000000..8eb4d4b --- /dev/null +++ b/bindings/python/_hmath_native/_neural_core.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.DeepLearning.Core complete typed adapters.""" + +from ._neural_base import ( + ELU, + GELU, + SELU, + Activation, + BinaryCrossEntropy, + CategoricalCrossEntropy, + CosineLoss, + HardSigmoid, + HardSwish, + Hinge, + Huber, + KLDivergence, + LeakyReLU, + Loss, + Mean, + MeanAbsoluteError, + MeanSquaredError, + Mish, + NegativeLogLikelihood, + PReLU, + Reduction, + ReLU, + Sigmoid, + SiLU, + SmoothL1, + Softplus, + Softsign, + Sum, + Tanh, + activation, + activation_derivative, + activation_expr, + binary_cross_entropy_logits, + ctc_loss, + ctc_loss_expr, + ctc_loss_gradient, + log_softmax_expr, + loss, + loss_expr, + loss_gradient, + softmax_expr, + sparsemax_expr, +) + +__all__ = [ + "ELU", + "GELU", + "SELU", + "Activation", + "BinaryCrossEntropy", + "CategoricalCrossEntropy", + "CosineLoss", + "HardSigmoid", + "HardSwish", + "Hinge", + "Huber", + "KLDivergence", + "LeakyReLU", + "Loss", + "Mean", + "MeanAbsoluteError", + "MeanSquaredError", + "Mish", + "NegativeLogLikelihood", + "PReLU", + "ReLU", + "Reduction", + "SiLU", + "Sigmoid", + "SmoothL1", + "Softplus", + "Softsign", + "Sum", + "Tanh", + "activation", + "activation_derivative", + "activation_expr", + "binary_cross_entropy_logits", + "ctc_loss", + "ctc_loss_expr", + "ctc_loss_gradient", + "log_softmax_expr", + "loss", + "loss_expr", + "loss_gradient", + "softmax_expr", + "sparsemax_expr", +] diff --git a/bindings/python/_hmath_native/_neural_metrics.py b/bindings/python/_hmath_native/_neural_metrics.py new file mode 100644 index 0000000..f4ea060 --- /dev/null +++ b/bindings/python/_hmath_native/_neural_metrics.py @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.DeepLearning.Metrics complete typed adapters.""" + +from ._neural_base import ( + ClassificationMetrics, + accuracy, + classification_metrics, + confusion_matrix, + cosine_similarity_matrix, + f1_by_class, + pr_auc, + precision_by_class, + recall_by_class, + roc_auc, + top_k_accuracy, +) + +__all__ = [ + "ClassificationMetrics", + "accuracy", + "classification_metrics", + "confusion_matrix", + "cosine_similarity_matrix", + "f1_by_class", + "pr_auc", + "precision_by_class", + "recall_by_class", + "roc_auc", + "top_k_accuracy", +] diff --git a/bindings/python/_hmath_native/_neural_precision.py b/bindings/python/_hmath_native/_neural_precision.py new file mode 100644 index 0000000..a0cc772 --- /dev/null +++ b/bindings/python/_hmath_native/_neural_precision.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.DeepLearning.Precision complete typed adapters.""" + +from ._neural_base import ( + BF16, + FP16, + Asymmetric, + LossScaler, + Precision, + Quantization, + QuantizedTensor, + Symmetric, + dequantize, + finite_steps, + initial_loss_scaler, + int8_gemm, + loss_scale, + quantization_scales, + quantization_zero_points, + quantize, + quantized_values, + reduced_gemm, + scale_growth_interval, + scale_loss, + unscale_gradients, + update_loss_scaler, +) + +__all__ = [ + "BF16", + "FP16", + "Asymmetric", + "LossScaler", + "Precision", + "Quantization", + "QuantizedTensor", + "Symmetric", + "dequantize", + "finite_steps", + "initial_loss_scaler", + "int8_gemm", + "loss_scale", + "quantization_scales", + "quantization_zero_points", + "quantize", + "quantized_values", + "reduced_gemm", + "scale_growth_interval", + "scale_loss", + "unscale_gradients", + "update_loss_scaler", +] diff --git a/bindings/python/_hmath_native/_numeric.py b/bindings/python/_hmath_native/_numeric.py new file mode 100644 index 0000000..0f061be --- /dev/null +++ b/bindings/python/_hmath_native/_numeric.py @@ -0,0 +1,278 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Marshaling shared by generated bindings; no numerical algorithms live here.""" + +import ctypes as C +import operator +from fractions import Fraction +from typing import NamedTuple + + +class SFResult(NamedTuple): + """Original special-function value and estimated absolute error.""" + + sf_value: float + sf_error: float + + +_BOUNDED = { + "int8": C.c_int8, + "int16": C.c_int16, + "int32": C.c_int32, + "int64": C.c_int64, + "uint8": C.c_uint8, + "uint16": C.c_uint16, + "uint32": C.c_uint32, + "uint64": C.c_uint64, + "intp": C.c_ssize_t, + "uintp": C.c_size_t, +} + + +def _bounded(value, kind): + value = operator.index(value) + bits = C.sizeof(_BOUNDED[kind]) * 8 + lower = 0 if kind.startswith("uint") else -(1 << (bits - 1)) + upper = (1 << bits) - 1 if kind.startswith("uint") else (1 << (bits - 1)) - 1 + if not lower <= value <= upper: + raise OverflowError(f"argument is outside the Haskell {kind} range") + return value + + +def _decimal(value): + """Transport arbitrary Python integers without Python's decimal digit cap.""" + value = operator.index(value) + negative = value < 0 + value = abs(value) + chunks = [] + while value: + value, digit = divmod(value, 10**9) + chunks.append(digit) + digits = str(chunks.pop()) if chunks else "0" + digits += "".join(f"{digit:09d}" for digit in reversed(chunks)) + return ("-" + digits if negative else digits).encode("ascii") + + +def _integer(data): + negative = data.startswith(b"-") + if negative: + data = data[1:] + value = 0 + for start in range(0, len(data), 9): + chunk = data[start : start + 9] + value = value * 10 ** len(chunk) + int(chunk) + return -value if negative else value + + +def _int(value): + value = operator.index(value) + bits = C.sizeof(C.c_ssize_t) * 8 + if not -(1 << (bits - 1)) <= value < (1 << (bits - 1)): + raise OverflowError("argument does not fit the Haskell Int type") + return value + + +def _call( + symbol, kinds, result, arguments, dtype, result_extra=0, *, symbol_suffix=None +): + # Lazy import avoids a cycle with the existing hmath module. + import hmath + + if dtype not in ("float32", "float64", None): + raise ValueError("dtype must be 'float32' or 'float64'") + real = C.c_float if dtype == "float32" else C.c_double + suffix = "_f32" if dtype == "float32" else "_f64" if dtype else "" + if symbol_suffix is not None: + suffix = symbol_suffix + hmath.initialize() + types, values = [C.c_void_p], [None] + count = 0 + for kind, argument in zip(kinds, arguments): + if kind in _BOUNDED: + types.append(_BOUNDED[kind]) + values.append(_bounded(argument, kind)) + elif kind.endswith("s") and kind[:-1] in _BOUNDED: + sequence = tuple(argument) + element = _BOUNDED[kind[:-1]] + types.extend([C.POINTER(element), C.c_size_t]) + values.extend( + [ + (element * len(sequence))( + *(_bounded(v, kind[:-1]) for v in sequence) + ), + len(sequence), + ] + ) + elif kind in ("qs", "cs"): + if kind == "qs": + sequence = tuple(Fraction(v) for v in argument) + flattened = [ + component + for v in sequence + for component in (_decimal(v.numerator), _decimal(v.denominator)) + ] + element = C.c_char_p + else: + sequence = tuple(complex(v) for v in argument) + flattened = [ + component for v in sequence for component in (v.real, v.imag) + ] + element = real + types.extend([C.POINTER(element), C.c_size_t]) + values.extend([(element * len(flattened))(*flattened), len(sequence)]) + elif kind == "f": + types.append(real) + values.append(argument) + elif kind == "z": + types.append(C.c_char_p) + values.append(_decimal(argument)) + elif kind == "i": + types.append(C.c_ssize_t) + values.append(_int(argument)) + elif kind == "b": + if not isinstance(argument, bool): + raise TypeError("expected a Boolean") + types.append(C.c_int) + values.append(argument) + elif kind == "q": + rational = Fraction(argument) + types.extend([C.c_char_p, C.c_char_p]) + values.extend( + [_decimal(rational.numerator), _decimal(rational.denominator)] + ) + elif kind in ("p", "c"): + pair = (argument.real, argument.imag) if kind == "c" else tuple(argument) + if len(pair) != 2: + raise ValueError("expected a pair") + types.extend([real, real]) + values.extend(pair) + elif kind == "fs": + sequence = tuple(argument) + count = len(sequence) + types.extend([C.POINTER(real), C.c_size_t]) + values.extend([(real * count)(*sequence), count]) + elif kind in ("zs", "is"): + sequence = tuple(argument) + element = C.c_char_p if kind == "zs" else C.c_ssize_t + conversion = _decimal if kind == "zs" else _int + types.extend([C.POINTER(element), C.c_size_t]) + values.extend( + [ + (element * len(sequence))(*(conversion(v) for v in sequence)), + len(sequence), + ] + ) + else: + raise RuntimeError(f"unknown argument kind: {kind}") + if result in ("fd", "zd", "id", "qd", "cd") or ( + result.endswith("d") and result[:-1] in _BOUNDED + ): + element = { + "fd": real, + "cd": real, + "zd": C.c_void_p, + "id": C.c_ssize_t, + "qd": C.c_void_p, + **{name + "d": typ for name, typ in _BOUNDED.items()}, + }[result] + pointer, length = C.POINTER(element)(), C.c_size_t() + types.extend([C.POINTER(C.POINTER(element)), C.POINTER(C.c_size_t)]) + values.extend([C.byref(pointer), C.byref(length)]) + function = C.CFUNCTYPE(C.c_int, *types)((symbol + suffix, hmath._lib)) + free = C.CFUNCTYPE(None, C.c_void_p)(("hmath_numeric_buffer_free", hmath._lib)) + try: + hmath._check(function(*values)) + if result in ("zd", "qd"): + decoded = [ + _integer(C.string_at(pointer[i])) + for i in range(length.value * (2 if result == "qd" else 1)) + ] + return ( + [ + Fraction(decoded[i], decoded[i + 1]) + for i in range(0, len(decoded), 2) + ] + if result == "qd" + else decoded + ) + if result == "cd": + return [ + complex(pointer[i], pointer[i + 1]) + for i in range(0, 2 * length.value, 2) + ] + return list(pointer[: length.value]) + finally: + if pointer: + if result in ("zd", "qd"): + for i in range(length.value * (2 if result == "qd" else 1)): + free(pointer[i]) + free(pointer) + result_kinds = ( + [result] + if result in _BOUNDED + else { + "f": "f", + "ff": "ff", + "fff": "fff", + "ffff": "ffff", + "sf": "ff", + "sf2": "ffff", + "sf4": "ffffffff", + "fsf": "fff", + "c": "ff", + "b": "b", + "z": "z", + "zz": "zz", + "zzz": "zzz", + "zzzz": "zzzz", + "i": "i", + "q": "zz", + "zf": "zf", + "fs": "s", + }[result] + ) + outputs = [] + count += result_extra + for kind in result_kinds: + output = { + "f": real, + "b": C.c_int, + "i": C.c_ssize_t, + "z": C.c_void_p, + "s": real * count, + **_BOUNDED, + }[kind]() + outputs.append((kind, output)) + types.append(C.POINTER(real) if kind == "s" else C.POINTER(type(output))) + values.append(output if kind == "s" else C.byref(output)) + if kind == "s": + types.append(C.c_size_t) + values.append(count) + # Construct a private function object: concurrent callers do not mutate a + # shared ctypes function's argtypes. CDLL/CFUNCTYPE release the GIL in C. + function = C.CFUNCTYPE(C.c_int, *types)((symbol + suffix, hmath._lib)) + free = C.CFUNCTYPE(None, C.c_void_p)(("hmath_numeric_string_free", hmath._lib)) + try: + hmath._check(function(*values)) + decoded = [] + for kind, output in outputs: + if kind == "z": + decoded.append(_integer(C.string_at(output))) + elif kind == "s": + decoded.append(list(output)) + else: + decoded.append(bool(output.value) if kind == "b" else output.value) + finally: + for kind, output in outputs: + if kind == "z": + free(output) + if result == "q": + return Fraction(*decoded) + if result == "c": + return complex(*decoded) + if result == "sf": + return SFResult(*decoded) + if result in ("sf2", "sf4"): + return tuple(SFResult(*decoded[i : i + 2]) for i in range(0, len(decoded), 2)) + if result == "fsf": + return decoded[0], SFResult(*decoded[1:]) + return decoded[0] if len(decoded) == 1 else tuple(decoded) diff --git a/bindings/python/_hmath_native/_numeric_modules.py b/bindings/python/_hmath_native/_numeric_modules.py new file mode 100644 index 0000000..7d350fc --- /dev/null +++ b/bindings/python/_hmath_native/_numeric_modules.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. + +NUMERIC_MODULES = ( + 'algorithms', + 'api_algebra', + 'basic', + 'combinatorics', + 'complex', + 'constants', + 'datastructure', + 'deeplearning_core', + 'deeplearning_metrics', + 'deeplearning_precision', + 'discrete', + 'fourier', + 'geometry_primitives', + 'graph_core', + 'image_color', + 'interpolation', + 'linear', + 'numbertheory', + 'numeric', + 'optimization_common', + 'probability', + 'random', + 'scalar', + 'signal', + 'special', + 'statistics', + 'statistics_advanced', + 'tensor', + 'timeseries_core', + 'timeseries_diagnostics', + 'trigonometry', + 'units', +) diff --git a/bindings/python/_hmath_native/_numeric_objects.py b/bindings/python/_hmath_native/_numeric_objects.py new file mode 100644 index 0000000..a8d9481 --- /dev/null +++ b/bindings/python/_hmath_native/_numeric_objects.py @@ -0,0 +1,112 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Typed-owner dispatch for original generic numerical functions only.""" + +from . import _value as V +from ._numerical_base import _invoke + +_ORDERED = { + "hmath_basic_clamp", + "hmath_scalar_minimum_scalar", + "hmath_scalar_maximum_scalar", +} + + +def _owner(argument): + return isinstance(argument, V.Value) or ( + type(argument).__module__ == "_hmath_native.autodiff" + and type(argument).__name__ in ("Dual", "Expr") + ) + + +def _contains_owner(argument): + return _owner(argument) or ( + isinstance(argument, (list, tuple)) + and any(_contains_owner(item) for item in argument) + ) + + +def _uses_value(arguments, dtype, *, ordered=False): + return ( + not isinstance(dtype, str) + or dtype == "value" + or any(_contains_owner(argument) for argument in arguments) + or ( + ordered + and any( + isinstance(argument, (bool, str, list, tuple)) for argument in arguments + ) + ) + ) + + +def _uses_equality_value(arguments, dtype): + return ( + _uses_value(arguments, dtype) + or dtype not in {"float32", "float64"} + or any( + isinstance(item, bool) or not isinstance(item, (int, float, complex)) + for argument in arguments + if isinstance(argument, (list, tuple)) + for item in argument + ) + ) + + +def _leaves(argument): + if isinstance(argument, (list, tuple)): + for item in argument: + yield from _leaves(item) + else: + yield argument + + +def _call_value(symbol, kinds, arguments, dtype): + temporary = [] + prototype = None + try: + if _owner(dtype): + prototype = V.encode(dtype) + elif symbol.startswith("hmath_geometry_primitives_"): + prototype = ( + V.scalar(0, dtype) + if dtype in V.DTYPES and dtype not in {"float32", "float64"} + else V.encode(None) + ) + elif symbol in _ORDERED: + prototype = V.encode(arguments[0]) + else: + candidates = [item for argument in arguments for item in _leaves(argument)] + candidate = next((item for item in candidates if _owner(item)), None) + if candidate is None: + if not candidates: + raise ValueError( + "empty generic inputs require dtype=" + ) + candidate = candidates[0] + prototype = V.encode(candidate) + inputs = [] + primitive = prototype.info[0] == 1 and prototype.info[1] in V.DTYPE_NAMES + + def coefficient(argument): + if primitive and not _owner(argument): + result = V.scalar(argument, V.DTYPE_NAMES[prototype.info[1]]) + temporary.append(result) + return result + return argument + + for kind, argument in zip(kinds, arguments): + if symbol in _ORDERED: + prepared = coefficient(argument) + elif kind == "fs": + prepared = [coefficient(item) for item in argument] + else: + prepared = coefficient(argument) + inputs.append(prepared) + return _invoke( + symbol + "_value", [["Value"]] * (len(inputs) + 1), [prototype, *inputs] + ) + finally: + if prototype is not None: + prototype.close() + for owner in temporary: + owner.close() diff --git a/bindings/python/_hmath_native/_numeric_types_runtime.py b/bindings/python/_hmath_native/_numeric_types_runtime.py new file mode 100644 index 0000000..825e63d --- /dev/null +++ b/bindings/python/_hmath_native/_numeric_types_runtime.py @@ -0,0 +1,361 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Ownership/representation for the original Numeric and Constants operations.""" + +import ctypes as C +import numbers +import operator +from enum import IntEnum +from fractions import Fraction + +from . import _value +from ._numeric import _decimal + + +class RoundingMode(IntEnum): + NEAREST_EVEN = 0 + TOWARD_ZERO = 1 + TOWARD_POSITIVE = 2 + TOWARD_NEGATIVE = 3 + + +class NumericException(IntEnum): + INVALID_OPERATION = 0 + DIVISION_BY_ZERO = 1 + NUMERIC_OVERFLOW = 2 + NUMERIC_UNDERFLOW = 3 + INEXACT = 4 + + +class IEEEClass(IntEnum): + NOT_A_NUMBER = 0 + POSITIVE_INFINITY = 1 + NEGATIVE_INFINITY = 2 + POSITIVE_ZERO = 3 + NEGATIVE_ZERO = 4 + SUBNORMAL = 5 + NORMAL = 6 + + +def _index(value, bits=None, unsigned=False): + value = operator.index(value) + bits = bits or C.sizeof(C.c_ssize_t) * 8 + low = 0 if unsigned else -(1 << (bits - 1)) + high = (1 << bits) - 1 if unsigned else (1 << (bits - 1)) - 1 + if not low <= value <= high: + raise OverflowError("argument outside its native representation") + return value + + +def _transfer(value): + with value._lock: + result = NumericValue._adopt(value._ptr, value._owners) + value._ptr, value._owners = C.c_void_p(), () + return result + + +def number(value, dtype=None): + """Box an exact standard coefficient; dtype follows common Value transport.""" + if isinstance(value, _value.Value): + return _transfer(value.clone()) + return _transfer(_value.scalar(value, dtype)) + + +def _box(value): + return value.clone() if isinstance(value, _value.Value) else _value.encode(value) + + +def _call_named(name, arguments, raw=False): + from .numeric_types import _SIGNATURES + + return _invoke(name, _SIGNATURES[name], arguments, raw) + + +def _literal(value, like): + if isinstance(value, _value.Value): + return _transfer(value.clone()) + if isinstance(value, numbers.Integral): + return _call_named("literal_integer", [like, operator.index(value)], True) + if isinstance(value, (numbers.Real, Fraction)): + return _call_named("literal_rational", [like, Fraction(value)], True) + raise TypeError("use an explicitly typed NumericValue for this operand") + + +class NumericValue(_value.Value): + """Immutable Haskell-backed value. Each live reference pins the runtime. + + Operators invoke the original Num/Fractional/Floating instance. Scalar + children stay boxed in properties, preserving dtype through callbacks. + Explicit .value decodes standard scalar/container representations. + """ + + @property + def value(self): + kind, dtype, _ = self.info + if kind == 1 and dtype >= 20: + raise TypeError("use primal/tangent or quaternion components") + if kind in (1, 2, 3, 4, 5, 10): + return self.clone().decode() + raise TypeError("opaque numeric representation: use its original getters") + + @property + def type_name(self): + return _call_named("type_name", [self]) + + @property + def primal(self): + return _call_named("primal", [self], True) + + @property + def tangent(self): + return _call_named("tangent", [self], True) + + @property + def rounded_value(self): + return _call_named("rounded_value", [self], True) + + @property + def numerical_exceptions(self): + return _call_named("numerical_exceptions", [self]) + + @property + def components(self): + kind, dtype, _ = self.info + if kind == 53: + return tuple( + _call_named("dual_quaternion_component", [self, i], True) + for i in range(2) + ) + if (kind == 1 and dtype == 21) or kind == 52: + return tuple( + _call_named("quaternion_component", [self, i], True) for i in range(4) + ) + raise TypeError("components requires Quaternion or DualQuaternion") + + def _binary(self, other, operation): + operand = _literal(other, self) + try: + return _call_named("binary", [operation, self, operand], True) + finally: + operand.close() + + def __add__(self, other): + return self._binary(other, 0) + + def __sub__(self, other): + return self._binary(other, 1) + + def __mul__(self, other): + return self._binary(other, 2) + + def __truediv__(self, other): + return self._binary(other, 3) + + def __pow__(self, other): + if isinstance(other, numbers.Integral): + return _call_named("integer_power", [self, operator.index(other)], True) + return self._binary(other, 4) + + def __radd__(self, other): + return self.__add__(other) + + def __rmul__(self, other): + # Multiplication order matters for Quaternion, even with a literal. + operand = _literal(other, self) + try: + return _call_named("binary", [2, operand, self], True) + finally: + operand.close() + + def __rsub__(self, other): + operand = _literal(other, self) + try: + return _call_named("binary", [1, operand, self], True) + finally: + operand.close() + + def __rtruediv__(self, other): + operand = _literal(other, self) + try: + return _call_named("binary", [3, operand, self], True) + finally: + operand.close() + + def __neg__(self): + return _call_named("unary", [0, self], True) + + def __abs__(self): + return _call_named("unary", [1, self], True) + + def __eq__(self, other): + try: + operand = _literal(other, self) + except (TypeError, ValueError): + return False + try: + return _call_named("equal", [self, operand]) + finally: + operand.close() + + __hash__ = None + + +def _floating_method(operation): + def method(self): + return _call_named("unary", [operation, self], True) + + return method + + +for _name, _operation in ( + ("signum", 2), + ("recip", 3), + ("exp", 4), + ("log", 5), + ("sqrt", 6), + ("sin", 7), + ("cos", 8), + ("tan", 9), + ("asin", 10), + ("acos", 11), + ("atan", 12), + ("sinh", 13), + ("cosh", 14), + ("tanh", 15), + ("asinh", 16), + ("acosh", 17), + ("atanh", 18), +): + setattr(NumericValue, _name, _floating_method(_operation)) + + +def _decode_enum(value): + import hmath + + try: + kind = value.info[0] + result = C.c_int() + with value._lock: + hmath._check( + _value.api( + "hmath_numeric_types_enum_value", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_int), + )(None, value._ptr, C.byref(result)) + ) + return (IEEEClass if kind == 49 else NumericException)(result.value) + finally: + value.close() + + +for _kind in (40, 41, 42, 43, 44, 45, 46, 47, 48, 52, 53): + _value.register(_kind, NumericValue) +for _kind in (49, 50): + _value.register(_kind, _decode_enum) +for _dtype in (20, 21): + _value.register_scalar(_dtype, NumericValue) + + +def _invoke(name, kinds, arguments, raw=False): + import hmath + + hmath.initialize() + native_types = [C.c_void_p] + native_values = [None] + values = [] + callbacks = [] + errors = [] + result = NumericValue._adopt() + try: + for kind, argument in zip(kinds, arguments): + if kind in ("o", "big", "fixed", "decimal", "interval", "half", "bhalf"): + value = _box(argument) + values.append(value) + native_types.append(C.c_void_p) + native_values.append(value._ptr) + elif kind in ("i", "i32", "u16"): + if kind == "i32" and isinstance(argument, str): + argument = _value.DTYPES[argument] + typ = {"i": C.c_ssize_t, "i32": C.c_int, "u16": C.c_uint16}[kind] + native_types.append(typ) + native_values.append(_index(argument, C.sizeof(typ) * 8, kind == "u16")) + elif kind in ("f32", "f64"): + native_types.append(C.c_float if kind == "f32" else C.c_double) + native_values.append(argument) + elif kind == "mode": + native_types.append(C.c_int) + native_values.append(RoundingMode(argument)) + elif kind in ("z", "q"): + parts = ( + [operator.index(argument)] + if kind == "z" + else [Fraction(argument).numerator, Fraction(argument).denominator] + ) + native_types.extend([C.c_char_p] * len(parts)) + native_values.extend(_decimal(v) for v in parts) + elif kind in ("text", "flags"): + if kind == "text": + if not isinstance(argument, str): + raise TypeError("expected a String") + sequence = list(map(ord, argument)) + typ = C.c_uint32 + else: + sequence = [NumericException(v) for v in argument] + typ = C.c_int + data = (typ * len(sequence))(*sequence) + native_types.extend([C.POINTER(typ), C.c_size_t]) + native_values.extend([data, len(sequence)]) + elif kind == "callback": + if not callable(argument): + raise TypeError("expected a callable") + callback_type = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p) + ) + + def adapter(pointer, userdata, out, function=argument): + incoming = _transfer(_value.borrow(pointer)) + converted = None + try: + outcome = function(incoming) + converted = _literal(outcome, incoming) + with converted._lock: + _value.api("hmath_value_retain", None, C.c_void_p)( + converted._ptr + ) + out[0] = converted._ptr + return 0 + except BaseException as error: # noqa: BLE001 - never unwind a Python exception through C + errors.append(error) + return 6 + finally: + if converted is not None: + converted.close() + incoming.close() + + callback = callback_type(adapter) + callbacks.append(callback) + native_types.extend([callback_type, C.c_void_p]) + native_values.extend([callback, None]) + else: + raise RuntimeError("unknown NumericTypes argument kind") + result._owners = tuple(owner for value in values for owner in value._owners) + native_types.append(C.POINTER(C.c_void_p)) + native_values.append(C.byref(result._ptr)) + # Every Value input is a separately retained private owner; no original + # Python lock is held across reentrant Haskell/C/Python callbacks. + status = _value.api("hmath_numeric_types_" + name, C.c_int, *native_types)( + *native_values + ) + if errors: + raise errors[0] + hmath._check(status) + if raw: + return result + return result.decode() + except BaseException: + result.close() + raise + finally: + for value in values: + value.close() diff --git a/bindings/python/_hmath_native/_numerical_base.py b/bindings/python/_hmath_native/_numerical_base.py new file mode 100644 index 0000000..261610d --- /dev/null +++ b/bindings/python/_hmath_native/_numerical_base.py @@ -0,0 +1,175 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Typed values and callback ownership for original numerical solvers.""" + +import ctypes as C +import operator +from fractions import Fraction + +from . import _value as value +from ._callback_error import fill +from ._linear_base import _callback_states +from ._linear_base import _CallbackState as _NativeCallbackState +from ._math_error import Wire + +_CALLBACK = C.CFUNCTYPE( + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + C.POINTER(Wire), +) +_FAILURE_MESSAGE = C.create_string_buffer(b"Python numerical callback failed") + + +class _CallbackState(_NativeCallbackState): + def __init__(self): + super().__init__() + self.failures = self._callback_errors + self.buffers = self.payload + self.retained = self.returned_owners + + +def _prepare(specification, argument, temporary): + kind = specification[0] + if kind == "either": + return _prepare(specification[1], argument, temporary) + if kind == "function": + if isinstance(argument, value.Value): + if argument.info[0] != 101: + raise TypeError("expected a native callback Value") + return argument + callback = _callback(argument, specification[-1]) + temporary.append(callback) + return callback + if kind == "list": + return [_prepare(specification[1], item, temporary) for item in argument] + if kind == "tuple": + fields = tuple(argument) + if len(fields) != len(specification) - 1: + raise ValueError("tuple arity differs") + return tuple( + _prepare(spec, item, temporary) + for spec, item in zip(specification[1:], fields) + ) + if kind == "maybe": + return ( + None + if argument is None + else _prepare(specification[1], argument, temporary) + ) + if kind == "Double": + return float(argument) + if kind in ("Int", "Integer"): + return operator.index(argument) + if kind == "Word64": + prepared = value.scalar(argument, "uint64") + temporary.append(prepared) + return prepared + if kind == "ComplexDouble": + return complex(argument) + if kind == "Rational": + if not isinstance(argument, (int, Fraction)): + raise TypeError("exact Rational requires an integer or Fraction") + return Fraction(argument) + if kind == "Bool": + if not isinstance(argument, bool): + raise TypeError("expected bool") + return argument + if kind == "String": + if not isinstance(argument, str): + raise TypeError("expected str") + return argument + # Typed native owners and Estimate's arbitrary payload pass to the shared + # encoder. The Haskell instance validates their actual coefficient/domain. + return argument + + +def _callback(function, result_specification): + import hmath + + if not callable(function): + raise TypeError("expected a callable original function argument") + state = _CallbackState() + + @_CALLBACK + def callback(pointer, _, out, error_wire): + temporary = [] + try: + arguments = value.decode(value.borrow(pointer)) + result = function(*arguments) + encoded = value.encode(_prepare(result_specification, result, temporary)) + state.retained.extend( + owner for owner in encoded._owners if owner is not state + ) + out[0] = encoded._ptr + encoded._ptr, encoded._owners = C.c_void_p(), () + return 0 + except BaseException as error: # noqa: BLE001 - no Python exception may unwind through C + try: + handled = fill(error_wire, error, state.buffers) + except BaseException: # noqa: BLE001 - malformed error payloads remain contained + handled = False + if handled: + return handled + state.failures.append(error) + # Avoid invoking arbitrary exception __str__ inside a C callback. + error_wire.contents.message = C.cast(_FAILURE_MESSAGE, C.c_void_p) + error_wire.contents.message_length = len(_FAILURE_MESSAGE.value) + return 6 + finally: + for item in temporary: + item.close() + + owner = value.Value._adopt(owners=(callback, state)) + hmath.initialize() + hmath._check( + value.api( + "hmath_linear_callback", + C.c_int, + C.c_void_p, + _CALLBACK, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, callback, None, C.byref(owner._ptr)) + ) + return owner + + +def _invoke(symbol, specifications, arguments, *, boxed=False): + temporary, inputs = [], [] + snapshots = [] + try: + for specification, argument in zip(specifications, arguments): + prepared = _prepare(specification, argument, temporary) + inputs.append(value.encode(prepared)) + snapshots = [ + (state, len(state._callback_errors)) for state in _callback_states(inputs) + ] + + def take_failure(): + original = None + for state, before in snapshots: + errors = state._callback_errors + if len(errors) > before: + if original is None: + original = errors[before] + del errors[before:] + return original + + try: + result = value.invoke(symbol, *inputs) + except BaseException: + original = take_failure() + if original is not None: + raise original from None + raise + original = take_failure() + if original is not None: + result.close() + raise original from None + return result if boxed else value.decode(result) + finally: + for item in inputs: + item.close() + for item in temporary: + item.close() diff --git a/bindings/python/_hmath_native/_optimization_all.py b/bindings/python/_hmath_native/_optimization_all.py new file mode 100644 index 0000000..c0b9d3d --- /dev/null +++ b/bindings/python/_hmath_native/_optimization_all.py @@ -0,0 +1,1096 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Haskell optimization functions with records and checked callbacks.""" + +import ctypes as C +import threading +import weakref +from dataclasses import dataclass +from typing import Callable as _Callable + +from . import _value as v +from ._math_error import Wire, fill +from ._numeric import _int + +P, Z = C.c_void_p, C.c_size_t +# This file's catalog is generated into a Python module for wheel installations. +from ._optimization_catalog import CATALOG + +_SPEC = {entry["name"]: entry for entry in CATALOG} +_pending = threading.local() + +# Source type aliases use Python return values; raise hmath.errors.MathError +# to supply the original Either's Left branch from a checked callback. +Objective = _Callable[[list[float]], float] +Gradient = _Callable[[list[float]], list[float]] +Hessian = _Callable[[list[float]], list[list[float]]] +ResidualFunction = Gradient +JacobianFunction = Hessian + + +@dataclass(frozen=True) +class OptimizeOptions: + max_iterations: int = 1000 + max_evaluations: int = 20000 + tolerance: float = 1e-8 + learning_rate: float = 0.01 + + +@dataclass(frozen=True) +class OptimizeResult: + point: list + value: float + gradient_norm: float + iterations: int + evaluations: int + converged: bool + + +@dataclass(frozen=True) +class LPResult: + point: list + value: float + basis: list + iterations: int + + +@dataclass(frozen=True) +class EarlyStopping: + best_score: object = None + stale_steps: int = 0 + stopped: bool = False + + +@dataclass(frozen=True) +class _Constructor: + name: str + arguments: tuple = () + + +class LearningRate(_Constructor): + pass + + +class ScalarMethod(_Constructor): + pass + + +class QuasiNewton(_Constructor): + pass + + +class NewtonMethod(_Constructor): + pass + + +class LeastSquaresLoss(_Constructor): + pass + + +class Constraint(_Constructor): + pass + + +class PenaltyMethod(_Constructor): + pass + + +class GlobalMethod(_Constructor): + pass + + +class LineSearch(_Constructor): + pass + + +class _CallbackOwner: + def __init__(self, function, role, scalar_input=False): + self.function, self.role, self.scalar_input = function, role, scalar_input + self.buffers = {} + self.callback = None + + +_CALLBACK = C.CFUNCTYPE(C.c_int, P, P, C.POINTER(P), C.POINTER(Wire)) + + +def _callback(function, role, scalar_input=False): + if isinstance(function, v.Value): + return function.clone() + if not callable(function): + raise TypeError("optimization callback must be callable") + owner = _CallbackOwner(function, role, scalar_input) + reference = weakref.proxy(owner) + + @_CALLBACK + def bridge(argument, userdata, out, error): + buffers = [] + reference.buffers[threading.get_ident()] = buffers + try: + value = v.decode(v.borrow(argument)) + if reference.scalar_input: + value = value[0] + result = ( + reference.function(*value) + if reference.role == 3 + else reference.function(value) + ) + encoded = _typed( + result, ("Double", "Vector", "Matrix", "Vector", "Bool")[reference.role] + ) + try: + with encoded._lock: + v.api("hmath_value_retain", None, P)(encoded._ptr) + out[0] = encoded._ptr + finally: + encoded.close() + return 0 + except BaseException as exception: # noqa: BLE001 - contain all exceptions at the C boundary + try: + if fill(error, exception, buffers): + return 11 + _pending.exception = exception + message = str(exception).encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(message) + buffers.append(buffer) + error.contents.kind = 0 + error.contents.message = C.cast(buffer, P) + error.contents.message_length = len(message) + status = getattr(exception, "status", 6) + return status if isinstance(status, int) and status != 11 else 6 + except BaseException: # noqa: BLE001 - contain failures in exception transport + # Even an exception's __str__ or error-buffer allocation may + # fail. Preserve the original exception and return a status. + _pending.exception = exception + return 6 + + owner.callback = bridge + result = v.Value._adopt(owners=[owner]) + import hmath + + hmath.initialize() + hmath._check( + v.api( + "hmath_optimization_callback", + C.c_int, + P, + C.c_int, + _CALLBACK, + P, + C.POINTER(P), + )(None, role, bridge, None, C.byref(result._ptr)) + ) + return result + + +def _sequence(values, hint, tuple_=False): + encoded = [] + try: + for value in values: + encoded.append(_typed(value, hint)) + return v.encode(tuple(encoded) if tuple_ else encoded) + finally: + for value in encoded: + value.close() + + +def _legacy_state(value): + from .optimization import OptimizerState + + if not isinstance(value, OptimizerState): + raise TypeError("expected OptimizerState") + result = v.Value._adopt() + import hmath + + with value._lock: + if not value._ptr: + raise ValueError("optimizer state is closed") + hmath._check( + v.api("hmath_optimization_state_import", C.c_int, P, P, C.POINTER(P))( + None, value._ptr, C.byref(result._ptr) + ) + ) + return result + + +def _typed(value, hint): + if isinstance(value, v.Value): + return value.clone() + if isinstance(value, _Constructor): + return _raw(value.name, *value.arguments) + if hint == "Double": + return v.scalar(value, "float64") + if hint == "Int": + return v._create("hmath_value_index", [C.c_ssize_t], [_int(value)]) + if hint == "Bool": + if not isinstance(value, bool): + raise TypeError("expected Bool") + return v.encode(value) + if hint == "Word64": + return v.scalar(value, "uint64") + if hint == "Vector": + return _sequence(value, "Double") + if hint == "Matrix": + return _sequence(value, "Vector") + if hint == "Indices": + return _sequence(value, "Int") + if hint == "Blocks": + return _sequence(value, "Indices") + if hint == "GenericMatrix": + return v.encode([list(row) for row in value]) + if hint == "Bounds": + rows = [] + try: + for pair in value: + pair = tuple(pair) + if len(pair) != 2: + raise ValueError("bounds require lower/upper pairs") + rows.append(_sequence(pair, "Double", True)) + return v.encode(rows) + finally: + for row in rows: + row.close() + if hint == "MaybeDouble": + return v.encode(None) if value is None else v.scalar(value, "float64") + if hint in ( + "Objective", + "Gradient", + "Hessian", + "Prox", + "Monitor", + "ScalarObjective", + ): + return _callback( + value, + { + "Objective": 0, + "ScalarObjective": 0, + "Gradient": 1, + "Hessian": 2, + "Prox": 3, + "Monitor": 4, + }[hint], + hint == "ScalarObjective", + ) + if hint in ("Gradients", "Objectives", "Constraints"): + return _sequence( + value, + { + "Gradients": "Gradient", + "Objectives": "Objective", + "Constraints": "Constraint", + }[hint], + ) + if hint == "State": + return _legacy_state(value) + if hint == "GradientMethod": + from .optimization import GradientMethod + + method = GradientMethod(value) + names = [ + "GradientDescent", + "Momentum", + "Nesterov", + "AdaGrad", + "RMSProp", + "AdaDelta", + "Adam", + "AdamW", + "AMSGrad", + "AdaMax", + "Nadam", + "RAdam", + ] + return _raw(names[int(method)]) + if isinstance(value, OptimizeOptions): + return _raw( + "OptimizeOptions", + value.max_iterations, + value.max_evaluations, + value.tolerance, + value.learning_rate, + ) + if isinstance(value, OptimizeResult): + return _raw( + "OptimizeResult", + value.point, + value.value, + value.gradient_norm, + value.iterations, + value.evaluations, + value.converged, + ) + if isinstance(value, LPResult): + return _raw("LPResult", value.point, value.value, value.basis, value.iterations) + if isinstance(value, EarlyStopping): + return _raw("EarlyStopping", value.best_score, value.stale_steps, value.stopped) + return v.encode(value) + + +def _raw(name, *arguments): + spec = _SPEC[name] + if len(arguments) != len(spec["arguments"]): + raise TypeError(f"{name} requires {len(spec['arguments'])} arguments") + values = [] + try: + for value, hint in zip(arguments, spec["arguments"]): + values.append(_typed(value, hint)) + return v.invoke(spec["c"], *values) + except BaseException: # cleanups then rethrow original Python callback exception + if getattr(_pending, "exception", None) is not None: + error = _pending.exception + del _pending.exception + raise error + raise + finally: + for value in values: + value.close() + + +def _invoke(name, *arguments): + return v.decode(_raw(name, *arguments)) + + +class _Function(v.Value): + def __call__(self, *arguments): + # A callback may close this function reentrantly. Hold an independent + # native reference and callback-owner snapshot for the entire call. + pinned = self.clone() + role = pinned.info[2] + hints = [["Vector"], ["Vector"], ["Vector"], ["Double", "Vector"], ["Result"]][ + role + ] + if len(arguments) != len(hints): + pinned.close() + raise TypeError("function argument count differs") + values = [] + result = v.Value._adopt(owners=pinned._owners) + import hmath + + try: + for value, hint in zip(arguments, hints): + values.append(_typed(value, hint)) + pointers = (P * len(values))(*(value._ptr for value in values)) + with pinned._lock: + hmath._check( + v.api( + "hmath_optimization_function_apply", + C.c_int, + P, + P, + C.POINTER(P), + Z, + C.POINTER(P), + )(None, pinned._ptr, pointers, len(values), C.byref(result._ptr)) + ) + return v.decode(result) + except BaseException: + if getattr(_pending, "exception", None) is not None: + error = _pending.exception + del _pending.exception + raise error + raise + finally: + for value in values: + value.close() + result.close() + pinned.close() + + +def _fields(value, names): + try: + return [_invoke(name, value) for name in names] + finally: + value.close() + + +def _decode_state(value): + from .optimization import OptimizerState + + result = OptimizerState._adopt(P()) + import hmath + + try: + with value._lock: + hmath._check( + v.api("hmath_optimization_state_export", C.c_int, P, P, C.POINTER(P))( + None, value._ptr, C.byref(result._ptr) + ) + ) + return result + finally: + value.close() + + +v.register( + 20, + lambda value: OptimizeOptions( + *_fields( + value, + [ + "optMaxIterations", + "optMaxEvaluations", + "optTolerance", + "optLearningRate", + ], + ) + ), +) +v.register( + 21, + lambda value: OptimizeResult( + *_fields( + value, + [ + "optPoint", + "optValue", + "optGradientNorm", + "optIterations", + "optEvaluations", + "optConverged", + ], + ) + ), +) +v.register( + 22, + lambda value: LPResult( + *_fields(value, ["lpPoint", "lpValue", "lpBasis", "lpIterations"]) + ), +) +v.register( + 24, + lambda value: EarlyStopping( + *_fields(value, ["bestScore", "staleSteps", "stopped"]) + ), +) +v.register(34, _decode_state) +v.register(35, _Function) + + +def ConstantRate(rate): + return LearningRate("ConstantRate", (rate,)) + + +LearningRate.CONSTANT_RATE = staticmethod(ConstantRate) + + +def StepDecay(initial_rate, period, decay): + return LearningRate("StepDecay", (initial_rate, period, decay)) + + +LearningRate.STEP_DECAY = staticmethod(StepDecay) + + +def ExponentialDecay(initial_rate, decay): + return LearningRate("ExponentialDecay", (initial_rate, decay)) + + +LearningRate.EXPONENTIAL_DECAY = staticmethod(ExponentialDecay) + + +def CosineAnnealing(maximum, minimum, period): + return LearningRate("CosineAnnealing", (maximum, minimum, period)) + + +LearningRate.COSINE_ANNEALING = staticmethod(CosineAnnealing) + + +def Warmup(steps, base): + return LearningRate("Warmup", (steps, base)) + + +LearningRate.WARMUP = staticmethod(Warmup) + +GoldenSection = ScalarMethod("GoldenSection") +ScalarMethod.GOLDEN_SECTION = GoldenSection + +TernarySearch = ScalarMethod("TernarySearch") +ScalarMethod.TERNARY_SEARCH = TernarySearch + +BrentSearch = ScalarMethod("BrentSearch") +ScalarMethod.BRENT_SEARCH = BrentSearch + +BFGS = QuasiNewton("BFGS") +QuasiNewton.BFGS = BFGS + + +def LBFGS(memory): + return QuasiNewton("LBFGS", (memory,)) + + +QuasiNewton.LBFGS = staticmethod(LBFGS) + +DFP = QuasiNewton("DFP") +QuasiNewton.DFP = DFP + +SR1 = QuasiNewton("SR1") +QuasiNewton.SR1 = SR1 + +Newton = NewtonMethod("Newton") +NewtonMethod.NEWTON = Newton + +NewtonCG = NewtonMethod("NewtonCG") +NewtonMethod.NEWTON_CG = NewtonCG + + +def TrustRegion(radius): + return NewtonMethod("TrustRegion", (radius,)) + + +NewtonMethod.TRUST_REGION = staticmethod(TrustRegion) + + +def Dogleg(radius): + return NewtonMethod("Dogleg", (radius,)) + + +NewtonMethod.DOGLEG = staticmethod(Dogleg) + +SquaredLoss = LeastSquaresLoss("SquaredLoss") +LeastSquaresLoss.SQUARED_LOSS = SquaredLoss + + +def HuberLoss(scale): + return LeastSquaresLoss("HuberLoss", (scale,)) + + +LeastSquaresLoss.HUBER_LOSS = staticmethod(HuberLoss) + + +def CauchyLoss(scale): + return LeastSquaresLoss("CauchyLoss", (scale,)) + + +LeastSquaresLoss.CAUCHY_LOSS = staticmethod(CauchyLoss) + + +def SoftL1(scale): + return LeastSquaresLoss("SoftL1", (scale,)) + + +LeastSquaresLoss.SOFT_L1 = staticmethod(SoftL1) + + +def Equality(objective, gradient): + return Constraint("Equality", (objective, gradient)) + + +Constraint.EQUALITY = staticmethod(Equality) + + +def LessEqual(objective, gradient): + return Constraint("LessEqual", (objective, gradient)) + + +Constraint.LESS_EQUAL = staticmethod(LessEqual) + +QuadraticPenalty = PenaltyMethod("QuadraticPenalty") +PenaltyMethod.QUADRATIC_PENALTY = QuadraticPenalty + +LogBarrier = PenaltyMethod("LogBarrier") +PenaltyMethod.LOG_BARRIER = LogBarrier + +InteriorPoint = PenaltyMethod("InteriorPoint") +PenaltyMethod.INTERIOR_POINT = InteriorPoint + +AugmentedLagrangian = PenaltyMethod("AugmentedLagrangian") +PenaltyMethod.AUGMENTED_LAGRANGIAN = AugmentedLagrangian + +SimulatedAnnealing = GlobalMethod("SimulatedAnnealing") +GlobalMethod.SIMULATED_ANNEALING = SimulatedAnnealing + +DifferentialEvolution = GlobalMethod("DifferentialEvolution") +GlobalMethod.DIFFERENTIAL_EVOLUTION = DifferentialEvolution + +GeneticAlgorithm = GlobalMethod("GeneticAlgorithm") +GlobalMethod.GENETIC_ALGORITHM = GeneticAlgorithm + +ParticleSwarm = GlobalMethod("ParticleSwarm") +GlobalMethod.PARTICLE_SWARM = ParticleSwarm + +CMAES = GlobalMethod("CMAES") +GlobalMethod.CMAES = CMAES + +Armijo = LineSearch("Armijo") +LineSearch.ARMIJO = Armijo + +StrongWolfe = LineSearch("StrongWolfe") +LineSearch.STRONG_WOLFE = StrongWolfe + + +def default_optimize_options(): + """Call HMath.Optimization.Common.defaultOptimizeOptions with original contracts.""" + return _invoke("defaultOptimizeOptions") + + +def checked_options(options): + """Call HMath.Optimization.Common.checkedOptions with original contracts.""" + return _invoke("checkedOptions", options) + + +def checked_point(point): + """Call HMath.Optimization.Common.checkedPoint with original contracts.""" + return _invoke("checkedPoint", point) + + +def checked_value(objective, point): + """Call HMath.Optimization.Common.checkedValue with original contracts.""" + return _invoke("checkedValue", objective, point) + + +def checked_gradient(gradient, point): + """Call HMath.Optimization.Common.checkedGradient with original contracts.""" + return _invoke("checkedGradient", gradient, point) + + +def check_budget(options, evaluations): + """Call HMath.Optimization.Common.checkBudget with original contracts.""" + return _invoke("checkBudget", options, evaluations) + + +def dot(left, right): + """Call HMath.Optimization.Common.dot with original contracts.""" + return _invoke("dot", left, right) + + +def add(left, right): + """Call HMath.Optimization.Common.add with original contracts.""" + return _invoke("add", left, right) + + +def sub(left, right): + """Call HMath.Optimization.Common.sub with original contracts.""" + return _invoke("sub", left, right) + + +def outer(left, right): + """Call HMath.Optimization.Common.outer with original contracts.""" + return _invoke("outer", left, right) + + +def norm(values): + """Call HMath.Optimization.Common.norm with original contracts.""" + return _invoke("norm", values) + + +def scale(factor, values): + """Call HMath.Optimization.Common.scale with original contracts.""" + return _invoke("scale", factor, values) + + +def identity(dimension): + """Call HMath.Optimization.Common.identity with original contracts.""" + return _invoke("identity", dimension) + + +def mat_vec(matrix, vector): + """Call HMath.Optimization.Common.matVec with original contracts.""" + return _invoke("matVec", matrix, vector) + + +def mat_mul(left, right): + """Call HMath.Optimization.Common.matMul with original contracts.""" + return _invoke("matMul", left, right) + + +def transpose(rows): + """Call HMath.Optimization.Common.transpose with original contracts.""" + return _invoke("transpose", rows) + + +def solve_dense(matrix, rhs): + """Call HMath.Optimization.Common.solveDense with original contracts.""" + return _invoke("solveDense", matrix, rhs) + + +def result(iterations, evaluations, converged, objective, gradient, point): + """Call HMath.Optimization.Common.result with original contracts.""" + return _invoke( + "result", iterations, evaluations, converged, objective, gradient, point + ) + + +def learning_rate(schedule, step): + """Call HMath.Optimization.Common.learningRate with original contracts.""" + return _invoke("learningRate", schedule, step) + + +def early_stopping(patience, min_delta, value, state): + """Call HMath.Optimization.Common.earlyStopping with original contracts.""" + return _invoke("earlyStopping", patience, min_delta, value, state) + + +def line_search( + method, budget, objective, gradient, point, direction, value, point_gradient +): + """Call HMath.Optimization.Common.lineSearch with original contracts.""" + return _invoke( + "lineSearch", + method, + budget, + objective, + gradient, + point, + direction, + value, + point_gradient, + ) + + +def opt_max_iterations(value): + """Call HMath.Optimization.Common.optMaxIterations with original contracts.""" + return _invoke("optMaxIterations", value) + + +def opt_max_evaluations(value): + """Call HMath.Optimization.Common.optMaxEvaluations with original contracts.""" + return _invoke("optMaxEvaluations", value) + + +def opt_tolerance(value): + """Call HMath.Optimization.Common.optTolerance with original contracts.""" + return _invoke("optTolerance", value) + + +def opt_learning_rate(value): + """Call HMath.Optimization.Common.optLearningRate with original contracts.""" + return _invoke("optLearningRate", value) + + +def opt_point(value): + """Call HMath.Optimization.Common.optPoint with original contracts.""" + return _invoke("optPoint", value) + + +def opt_value(value): + """Call HMath.Optimization.Common.optValue with original contracts.""" + return _invoke("optValue", value) + + +def opt_gradient_norm(value): + """Call HMath.Optimization.Common.optGradientNorm with original contracts.""" + return _invoke("optGradientNorm", value) + + +def opt_iterations(value): + """Call HMath.Optimization.Common.optIterations with original contracts.""" + return _invoke("optIterations", value) + + +def opt_evaluations(value): + """Call HMath.Optimization.Common.optEvaluations with original contracts.""" + return _invoke("optEvaluations", value) + + +def opt_converged(value): + """Call HMath.Optimization.Common.optConverged with original contracts.""" + return _invoke("optConverged", value) + + +def best_score(value): + """Call HMath.Optimization.Common.bestScore with original contracts.""" + return _invoke("bestScore", value) + + +def stale_steps(value): + """Call HMath.Optimization.Common.staleSteps with original contracts.""" + return _invoke("staleSteps", value) + + +def stopped(value): + """Call HMath.Optimization.Common.stopped with original contracts.""" + return _invoke("stopped", value) + + +def minimize_gradient(method, options, objective, gradient, initial): + """Call HMath.Optimization.FirstOrder.minimizeGradient with original contracts.""" + return _invoke("minimizeGradient", method, options, objective, gradient, initial) + + +def minimize_gradient_with_callback( + monitor, method, options, objective, gradient, initial +): + """Call HMath.Optimization.FirstOrder.minimizeGradientWithCallback with original contracts.""" + return _invoke( + "minimizeGradientWithCallback", + monitor, + method, + options, + objective, + gradient, + initial, + ) + + +def stochastic_gradient(method, rate, gradients, initial): + """Call HMath.Optimization.FirstOrder.stochasticGradient with original contracts.""" + return _invoke("stochasticGradient", method, rate, gradients, initial) + + +def mini_batch_gradient(gradients): + """Call HMath.Optimization.FirstOrder.miniBatchGradient with original contracts.""" + return _invoke("miniBatchGradient", gradients) + + +def projected_gradient(options, objective, gradient, project, initial): + """Call HMath.Optimization.FirstOrder.projectedGradient with original contracts.""" + return _invoke("projectedGradient", options, objective, gradient, project, initial) + + +def proximal_gradient(options, objective, gradient, prox, initial): + """Call HMath.Optimization.FirstOrder.proximalGradient with original contracts.""" + return _invoke("proximalGradient", options, objective, gradient, prox, initial) + + +def fista(options, objective, gradient, prox, initial): + """Call HMath.Optimization.FirstOrder.fista with original contracts.""" + return _invoke("fista", options, objective, gradient, prox, initial) + + +def coordinate_descent(blocks, options, objective, gradient, initial): + """Call HMath.Optimization.FirstOrder.coordinateDescent with original contracts.""" + return _invoke("coordinateDescent", blocks, options, objective, gradient, initial) + + +def minimize_scalar(method, options, objective, lower, upper): + """Call HMath.Optimization.Local.minimizeScalar with original contracts.""" + return _invoke("minimizeScalar", method, options, objective, lower, upper) + + +def minimize_quasi_newton(method, options, objective, gradient, initial): + """Call HMath.Optimization.Local.minimizeQuasiNewton with original contracts.""" + return _invoke("minimizeQuasiNewton", method, options, objective, gradient, initial) + + +def minimize_newton(method, options, objective, gradient, hessian, initial): + """Call HMath.Optimization.Local.minimizeNewton with original contracts.""" + return _invoke( + "minimizeNewton", method, options, objective, gradient, hessian, initial + ) + + +def nonlinear_cg(options, objective, gradient, initial): + """Call HMath.Optimization.Local.nonlinearCG with original contracts.""" + return _invoke("nonlinearCG", options, objective, gradient, initial) + + +def least_squares(loss, damping, options, residual, jacobian, initial): + """Call HMath.Optimization.Local.leastSquares with original contracts.""" + return _invoke("leastSquares", loss, damping, options, residual, jacobian, initial) + + +def nelder_mead(options, objective, initial): + """Call HMath.Optimization.Local.nelderMead with original contracts.""" + return _invoke("nelderMead", options, objective, initial) + + +def powell(initial_step, options, objective, initial): + """Call HMath.Optimization.Local.powell with original contracts.""" + return _invoke("powell", initial_step, options, objective, initial) + + +def feasibility(constraints, point): + """Call HMath.Optimization.Constrained.feasibility with original contracts.""" + return _invoke("feasibility", constraints, point) + + +def constrained_minimize(method, options, objective, gradient, constraints, initial): + """Call HMath.Optimization.Constrained.constrainedMinimize with original contracts.""" + return _invoke( + "constrainedMinimize", + method, + options, + objective, + gradient, + constraints, + initial, + ) + + +def linear_programming(budget, tolerance, cost, matrix, rhs): + """Call HMath.Optimization.Constrained.linearProgramming with original contracts.""" + return _invoke("linearProgramming", budget, tolerance, cost, matrix, rhs) + + +def revised_simplex(budget, tolerance, cost, matrix, rhs, basis): + """Call HMath.Optimization.Constrained.revisedSimplex with original contracts.""" + return _invoke("revisedSimplex", budget, tolerance, cost, matrix, rhs, basis) + + +def quadratic_programming(budget, tolerance, hessian, cost, matrix, rhs): + """Call HMath.Optimization.Constrained.quadraticProgramming with original contracts.""" + return _invoke( + "quadraticProgramming", budget, tolerance, hessian, cost, matrix, rhs + ) + + +def slsqp(options, objective, gradient, hessian, constraints, initial): + """Call HMath.Optimization.Constrained.slsqp with original contracts.""" + return _invoke("slsqp", options, objective, gradient, hessian, constraints, initial) + + +def cobyla(initial_radius, options, objective, constraints, initial): + """Call HMath.Optimization.Constrained.cobyla with original contracts.""" + return _invoke("cobyla", initial_radius, options, objective, constraints, initial) + + +def weighted_objective(weights, objectives): + """Call HMath.Optimization.Constrained.weightedObjective with original contracts.""" + return _invoke("weightedObjective", weights, objectives) + + +def pareto_front(points): + """Call HMath.Optimization.Constrained.paretoFront with original contracts.""" + return _invoke("paretoFront", points) + + +def lp_point(value): + """Call HMath.Optimization.Constrained.lpPoint with original contracts.""" + return _invoke("lpPoint", value) + + +def lp_value(value): + """Call HMath.Optimization.Constrained.lpValue with original contracts.""" + return _invoke("lpValue", value) + + +def lp_basis(value): + """Call HMath.Optimization.Constrained.lpBasis with original contracts.""" + return _invoke("lpBasis", value) + + +def lp_iterations(value): + """Call HMath.Optimization.Constrained.lpIterations with original contracts.""" + return _invoke("lpIterations", value) + + +def global_minimize(method, population_size, seed, options, bounds, objective): + """Call HMath.Optimization.Global.globalMinimize with original contracts.""" + return _invoke( + "globalMinimize", method, population_size, seed, options, bounds, objective + ) + + +def basin_hopping(seed, temperature, hops, options, bounds, objective, initial): + """Call HMath.Optimization.Global.basinHopping with original contracts.""" + return _invoke( + "basinHopping", seed, temperature, hops, options, bounds, objective, initial + ) + + +__all__ = [ + "BFGS", + "CMAES", + "DFP", + "LBFGS", + "SR1", + "Armijo", + "AugmentedLagrangian", + "BrentSearch", + "CauchyLoss", + "ConstantRate", + "Constraint", + "CosineAnnealing", + "DifferentialEvolution", + "Dogleg", + "EarlyStopping", + "Equality", + "ExponentialDecay", + "GeneticAlgorithm", + "GlobalMethod", + "GoldenSection", + "Gradient", + "Hessian", + "HuberLoss", + "InteriorPoint", + "JacobianFunction", + "LPResult", + "LearningRate", + "LeastSquaresLoss", + "LessEqual", + "LineSearch", + "LogBarrier", + "Newton", + "NewtonCG", + "NewtonMethod", + "Objective", + "OptimizeOptions", + "OptimizeResult", + "ParticleSwarm", + "PenaltyMethod", + "QuadraticPenalty", + "QuasiNewton", + "ResidualFunction", + "ScalarMethod", + "SimulatedAnnealing", + "SoftL1", + "SquaredLoss", + "StepDecay", + "StrongWolfe", + "TernarySearch", + "TrustRegion", + "Warmup", + "add", + "basin_hopping", + "best_score", + "check_budget", + "checked_gradient", + "checked_options", + "checked_point", + "checked_value", + "cobyla", + "constrained_minimize", + "coordinate_descent", + "default_optimize_options", + "dot", + "early_stopping", + "feasibility", + "fista", + "global_minimize", + "identity", + "learning_rate", + "least_squares", + "line_search", + "linear_programming", + "lp_basis", + "lp_iterations", + "lp_point", + "lp_value", + "mat_mul", + "mat_vec", + "mini_batch_gradient", + "minimize_gradient", + "minimize_gradient_with_callback", + "minimize_newton", + "minimize_quasi_newton", + "minimize_scalar", + "nelder_mead", + "nonlinear_cg", + "norm", + "opt_converged", + "opt_evaluations", + "opt_gradient_norm", + "opt_iterations", + "opt_learning_rate", + "opt_max_evaluations", + "opt_max_iterations", + "opt_point", + "opt_tolerance", + "opt_value", + "outer", + "pareto_front", + "powell", + "projected_gradient", + "proximal_gradient", + "quadratic_programming", + "result", + "revised_simplex", + "scale", + "slsqp", + "solve_dense", + "stale_steps", + "stochastic_gradient", + "stopped", + "sub", + "transpose", + "weighted_objective", +] diff --git a/bindings/python/_hmath_native/_optimization_catalog.py b/bindings/python/_hmath_native/_optimization_catalog.py new file mode 100644 index 0000000..88d2869 --- /dev/null +++ b/bindings/python/_hmath_native/_optimization_catalog.py @@ -0,0 +1,1284 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_optimization_bindings.py; do not edit. +CATALOG = [ + { + "module": "HMath.Optimization.Common", + "name": "OptimizeOptions", + "python": "optimize_options", + "arguments": ["Int", "Int", "Double", "Double"], + "result": "Options", + "expression": "C.OptimizeOptions", + "c": "hmath_optimization_optimize_options_create", + "parameters": [ + "max_iterations", + "max_evaluations", + "tolerance", + "learning_rate", + ], + }, + { + "module": "HMath.Optimization.Common", + "name": "defaultOptimizeOptions", + "python": "default_optimize_options", + "arguments": [], + "result": "Options", + "expression": "C.defaultOptimizeOptions", + "c": "hmath_optimization_default_optimize_options", + "parameters": [], + }, + { + "module": "HMath.Optimization.Common", + "name": "OptimizeResult", + "python": "optimize_result", + "arguments": ["Vector", "Double", "Double", "Int", "Int", "Bool"], + "result": "Result", + "expression": "C.OptimizeResult", + "c": "hmath_optimization_optimize_result_create", + "parameters": [ + "point", + "value", + "gradient_norm", + "iterations", + "evaluations", + "converged", + ], + }, + { + "module": "HMath.Optimization.Common", + "name": "EarlyStopping", + "python": "early_stopping", + "arguments": ["MaybeDouble", "Int", "Bool"], + "result": "EarlyStopping", + "expression": "C.EarlyStopping", + "c": "hmath_optimization_early_stopping_create", + "parameters": ["best_score", "stale_steps", "stopped"], + }, + { + "module": "HMath.Optimization.Common", + "name": "ConstantRate", + "python": "constant_rate", + "arguments": ["Double"], + "result": "LearningRate", + "expression": "C.ConstantRate", + "c": "hmath_optimization_constant_rate_create", + "parameters": ["rate"], + }, + { + "module": "HMath.Optimization.Common", + "name": "StepDecay", + "python": "step_decay", + "arguments": ["Double", "Int", "Double"], + "result": "LearningRate", + "expression": "C.StepDecay", + "c": "hmath_optimization_step_decay_create", + "parameters": ["initial_rate", "period", "decay"], + }, + { + "module": "HMath.Optimization.Common", + "name": "ExponentialDecay", + "python": "exponential_decay", + "arguments": ["Double", "Double"], + "result": "LearningRate", + "expression": "C.ExponentialDecay", + "c": "hmath_optimization_exponential_decay_create", + "parameters": ["initial_rate", "decay"], + }, + { + "module": "HMath.Optimization.Common", + "name": "CosineAnnealing", + "python": "cosine_annealing", + "arguments": ["Double", "Double", "Int"], + "result": "LearningRate", + "expression": "C.CosineAnnealing", + "c": "hmath_optimization_cosine_annealing_create", + "parameters": ["maximum", "minimum", "period"], + }, + { + "module": "HMath.Optimization.Common", + "name": "Warmup", + "python": "warmup", + "arguments": ["Int", "LearningRate"], + "result": "LearningRate", + "expression": "C.Warmup", + "c": "hmath_optimization_warmup_create", + "parameters": ["steps", "base"], + }, + { + "module": "HMath.Optimization.Common", + "name": "Armijo", + "python": "armijo", + "arguments": [], + "result": "LineSearch", + "expression": "C.Armijo", + "c": "hmath_optimization_armijo_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Common", + "name": "StrongWolfe", + "python": "strong_wolfe", + "arguments": [], + "result": "LineSearch", + "expression": "C.StrongWolfe", + "c": "hmath_optimization_strong_wolfe_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedOptions", + "python": "checked_options", + "arguments": ["Options"], + "result": "Unit", + "expression": "C.checkedOptions", + "c": "hmath_optimization_checked_options", + "parameters": ["options"], + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedPoint", + "python": "checked_point", + "arguments": ["Vector"], + "result": "Unit", + "expression": "C.checkedPoint", + "c": "hmath_optimization_checked_point", + "parameters": ["point"], + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedValue", + "python": "checked_value", + "arguments": ["Objective", "Vector"], + "result": "Double", + "expression": "C.checkedValue", + "c": "hmath_optimization_checked_value", + "parameters": ["objective", "point"], + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedGradient", + "python": "checked_gradient", + "arguments": ["Gradient", "Vector"], + "result": "Vector", + "expression": "C.checkedGradient", + "c": "hmath_optimization_checked_gradient", + "parameters": ["gradient", "point"], + }, + { + "module": "HMath.Optimization.Common", + "name": "checkBudget", + "python": "check_budget", + "arguments": ["Options", "Int"], + "result": "Unit", + "expression": "C.checkBudget", + "c": "hmath_optimization_check_budget", + "parameters": ["options", "evaluations"], + }, + { + "module": "HMath.Optimization.Common", + "name": "dot", + "python": "dot", + "arguments": ["Vector", "Vector"], + "result": "Value", + "expression": "C.dot", + "c": "hmath_optimization_dot", + "parameters": ["left", "right"], + }, + { + "module": "HMath.Optimization.Common", + "name": "add", + "python": "add", + "arguments": ["Vector", "Vector"], + "result": "Value", + "expression": "C.add", + "c": "hmath_optimization_add", + "parameters": ["left", "right"], + }, + { + "module": "HMath.Optimization.Common", + "name": "sub", + "python": "sub", + "arguments": ["Vector", "Vector"], + "result": "Value", + "expression": "C.sub", + "c": "hmath_optimization_sub", + "parameters": ["left", "right"], + }, + { + "module": "HMath.Optimization.Common", + "name": "outer", + "python": "outer", + "arguments": ["Vector", "Vector"], + "result": "Value", + "expression": "C.outer", + "c": "hmath_optimization_outer", + "parameters": ["left", "right"], + }, + { + "module": "HMath.Optimization.Common", + "name": "norm", + "python": "norm", + "arguments": ["Vector"], + "result": "Double", + "expression": "C.norm", + "c": "hmath_optimization_norm", + "parameters": ["values"], + }, + { + "module": "HMath.Optimization.Common", + "name": "scale", + "python": "scale", + "arguments": ["Double", "Vector"], + "result": "Vector", + "expression": "C.scale", + "c": "hmath_optimization_scale", + "parameters": ["factor", "values"], + }, + { + "module": "HMath.Optimization.Common", + "name": "identity", + "python": "identity", + "arguments": ["Int"], + "result": "Matrix", + "expression": "C.identity", + "c": "hmath_optimization_identity", + "parameters": ["dimension"], + }, + { + "module": "HMath.Optimization.Common", + "name": "matVec", + "python": "mat_vec", + "arguments": ["Matrix", "Vector"], + "result": "Vector", + "expression": "C.matVec", + "c": "hmath_optimization_mat_vec", + "parameters": ["matrix", "vector"], + }, + { + "module": "HMath.Optimization.Common", + "name": "matMul", + "python": "mat_mul", + "arguments": ["Matrix", "Matrix"], + "result": "Matrix", + "expression": "C.matMul", + "c": "hmath_optimization_mat_mul", + "parameters": ["left", "right"], + }, + { + "module": "HMath.Optimization.Common", + "name": "transpose", + "python": "transpose", + "arguments": ["GenericMatrix"], + "result": "GenericMatrix", + "expression": "(C.transpose :: [[Value]] -> [[Value]])", + "c": "hmath_optimization_transpose", + "parameters": ["rows"], + }, + { + "module": "HMath.Optimization.Common", + "name": "solveDense", + "python": "solve_dense", + "arguments": ["Matrix", "Vector"], + "result": "Vector", + "expression": "C.solveDense", + "c": "hmath_optimization_solve_dense", + "parameters": ["matrix", "rhs"], + }, + { + "module": "HMath.Optimization.Common", + "name": "result", + "python": "result", + "arguments": ["Int", "Int", "Bool", "Objective", "Gradient", "Vector"], + "result": "Result", + "expression": "C.result", + "c": "hmath_optimization_result", + "parameters": [ + "iterations", + "evaluations", + "converged", + "objective", + "gradient", + "point", + ], + }, + { + "module": "HMath.Optimization.Common", + "name": "learningRate", + "python": "learning_rate", + "arguments": ["LearningRate", "Int"], + "result": "Double", + "expression": "C.learningRate", + "c": "hmath_optimization_learning_rate", + "parameters": ["schedule", "step"], + }, + { + "module": "HMath.Optimization.Common", + "name": "earlyStopping", + "python": "early_stopping", + "arguments": ["Int", "Double", "Double", "EarlyStopping"], + "result": "EarlyStopping", + "expression": "C.earlyStopping", + "c": "hmath_optimization_early_stopping", + "parameters": ["patience", "min_delta", "value", "state"], + }, + { + "module": "HMath.Optimization.Common", + "name": "lineSearch", + "python": "line_search", + "arguments": [ + "LineSearch", + "Int", + "Objective", + "Gradient", + "Vector", + "Vector", + "Double", + "Vector", + ], + "result": "Tuple", + "expression": "C.lineSearch", + "c": "hmath_optimization_line_search", + "parameters": [ + "method", + "budget", + "objective", + "gradient", + "point", + "direction", + "value", + "point_gradient", + ], + }, + { + "module": "HMath.Optimization.Common", + "name": "optMaxIterations", + "python": "opt_max_iterations", + "arguments": ["Options"], + "result": "Value", + "expression": "C.optMaxIterations", + "c": "hmath_optimization_opt_max_iterations", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optMaxEvaluations", + "python": "opt_max_evaluations", + "arguments": ["Options"], + "result": "Value", + "expression": "C.optMaxEvaluations", + "c": "hmath_optimization_opt_max_evaluations", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optTolerance", + "python": "opt_tolerance", + "arguments": ["Options"], + "result": "Value", + "expression": "C.optTolerance", + "c": "hmath_optimization_opt_tolerance", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optLearningRate", + "python": "opt_learning_rate", + "arguments": ["Options"], + "result": "Value", + "expression": "C.optLearningRate", + "c": "hmath_optimization_opt_learning_rate", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optPoint", + "python": "opt_point", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optPoint", + "c": "hmath_optimization_opt_point", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optValue", + "python": "opt_value", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optValue", + "c": "hmath_optimization_opt_value", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optGradientNorm", + "python": "opt_gradient_norm", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optGradientNorm", + "c": "hmath_optimization_opt_gradient_norm", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optIterations", + "python": "opt_iterations", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optIterations", + "c": "hmath_optimization_opt_iterations", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optEvaluations", + "python": "opt_evaluations", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optEvaluations", + "c": "hmath_optimization_opt_evaluations", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "optConverged", + "python": "opt_converged", + "arguments": ["Result"], + "result": "Value", + "expression": "C.optConverged", + "c": "hmath_optimization_opt_converged", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "bestScore", + "python": "best_score", + "arguments": ["EarlyStopping"], + "result": "Value", + "expression": "C.bestScore", + "c": "hmath_optimization_best_score", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "staleSteps", + "python": "stale_steps", + "arguments": ["EarlyStopping"], + "result": "Value", + "expression": "C.staleSteps", + "c": "hmath_optimization_stale_steps", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Common", + "name": "stopped", + "python": "stopped", + "arguments": ["EarlyStopping"], + "result": "Value", + "expression": "C.stopped", + "c": "hmath_optimization_stopped", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "GradientDescent", + "python": "gradient_descent", + "arguments": [], + "result": "GradientMethod", + "expression": "F.GradientDescent", + "c": "hmath_optimization_gradient_descent_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Momentum", + "python": "momentum", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Momentum", + "c": "hmath_optimization_momentum_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Nesterov", + "python": "nesterov", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Nesterov", + "c": "hmath_optimization_nesterov_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaGrad", + "python": "ada_grad", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaGrad", + "c": "hmath_optimization_ada_grad_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "RMSProp", + "python": "rms_prop", + "arguments": [], + "result": "GradientMethod", + "expression": "F.RMSProp", + "c": "hmath_optimization_rms_prop_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaDelta", + "python": "ada_delta", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaDelta", + "c": "hmath_optimization_ada_delta_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Adam", + "python": "adam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Adam", + "c": "hmath_optimization_adam_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdamW", + "python": "adam_w", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdamW", + "c": "hmath_optimization_adam_w_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AMSGrad", + "python": "ams_grad", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AMSGrad", + "c": "hmath_optimization_ams_grad_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaMax", + "python": "ada_max", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaMax", + "c": "hmath_optimization_ada_max_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Nadam", + "python": "nadam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Nadam", + "c": "hmath_optimization_nadam_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "RAdam", + "python": "r_adam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.RAdam", + "c": "hmath_optimization_r_adam_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "initializeOptimizer", + "python": "initialize_optimizer", + "arguments": ["Int"], + "result": "State", + "expression": "F.initializeOptimizer", + "c": "hmath_optimization_initialize_optimizer", + "parameters": ["dimension"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "optimizerStep", + "python": "optimizer_step", + "arguments": ["GradientMethod", "Double", "State", "Vector", "Vector"], + "result": "Tuple", + "expression": "F.optimizerStep", + "c": "hmath_optimization_optimizer_step", + "parameters": ["method", "rate", "state", "parameters", "gradient"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "minimizeGradient", + "python": "minimize_gradient", + "arguments": ["GradientMethod", "Options", "Objective", "Gradient", "Vector"], + "result": "Result", + "expression": "F.minimizeGradient", + "c": "hmath_optimization_minimize_gradient", + "parameters": ["method", "options", "objective", "gradient", "initial"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "minimizeGradientWithCallback", + "python": "minimize_gradient_with_callback", + "arguments": [ + "Monitor", + "GradientMethod", + "Options", + "Objective", + "Gradient", + "Vector", + ], + "result": "Result", + "expression": "F.minimizeGradientWithCallback", + "c": "hmath_optimization_minimize_gradient_with_callback", + "parameters": [ + "monitor", + "method", + "options", + "objective", + "gradient", + "initial", + ], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "stochasticGradient", + "python": "stochastic_gradient", + "arguments": ["GradientMethod", "Double", "Gradients", "Vector"], + "result": "Tuple", + "expression": "F.stochasticGradient", + "c": "hmath_optimization_stochastic_gradient", + "parameters": ["method", "rate", "gradients", "initial"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "miniBatchGradient", + "python": "mini_batch_gradient", + "arguments": ["Gradients"], + "result": "Function", + "expression": "(\\values -> functionValue (GradientFn (F.miniBatchGradient values)))", + "c": "hmath_optimization_mini_batch_gradient", + "parameters": ["gradients"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "projectedGradient", + "python": "projected_gradient", + "arguments": ["Options", "Objective", "Gradient", "Gradient", "Vector"], + "result": "Result", + "expression": "F.projectedGradient", + "c": "hmath_optimization_projected_gradient", + "parameters": ["options", "objective", "gradient", "project", "initial"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "proximalGradient", + "python": "proximal_gradient", + "arguments": ["Options", "Objective", "Gradient", "Prox", "Vector"], + "result": "Result", + "expression": "F.proximalGradient", + "c": "hmath_optimization_proximal_gradient", + "parameters": ["options", "objective", "gradient", "prox", "initial"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "fista", + "python": "fista", + "arguments": ["Options", "Objective", "Gradient", "Prox", "Vector"], + "result": "Result", + "expression": "F.fista", + "c": "hmath_optimization_fista", + "parameters": ["options", "objective", "gradient", "prox", "initial"], + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "coordinateDescent", + "python": "coordinate_descent", + "arguments": ["Blocks", "Options", "Objective", "Gradient", "Vector"], + "result": "Result", + "expression": "F.coordinateDescent", + "c": "hmath_optimization_coordinate_descent", + "parameters": ["blocks", "options", "objective", "gradient", "initial"], + }, + { + "module": "HMath.Optimization.Local", + "name": "GoldenSection", + "python": "golden_section", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.GoldenSection", + "c": "hmath_optimization_golden_section_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "TernarySearch", + "python": "ternary_search", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.TernarySearch", + "c": "hmath_optimization_ternary_search_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "BrentSearch", + "python": "brent_search", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.BrentSearch", + "c": "hmath_optimization_brent_search_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeScalar", + "python": "minimize_scalar", + "arguments": ["ScalarMethod", "Options", "ScalarObjective", "Double", "Double"], + "result": "Result", + "expression": "L.minimizeScalar", + "c": "hmath_optimization_minimize_scalar", + "parameters": ["method", "options", "objective", "lower", "upper"], + }, + { + "module": "HMath.Optimization.Local", + "name": "BFGS", + "python": "bfgs", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.BFGS", + "c": "hmath_optimization_bfgs_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "DFP", + "python": "dfp", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.DFP", + "c": "hmath_optimization_dfp_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "SR1", + "python": "sr1", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.SR1", + "c": "hmath_optimization_sr1_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "LBFGS", + "python": "lbfgs", + "arguments": ["Int"], + "result": "QuasiNewton", + "expression": "L.LBFGS", + "c": "hmath_optimization_lbfgs_create", + "parameters": ["memory"], + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeQuasiNewton", + "python": "minimize_quasi_newton", + "arguments": ["QuasiNewton", "Options", "Objective", "Gradient", "Vector"], + "result": "Result", + "expression": "L.minimizeQuasiNewton", + "c": "hmath_optimization_minimize_quasi_newton", + "parameters": ["method", "options", "objective", "gradient", "initial"], + }, + { + "module": "HMath.Optimization.Local", + "name": "Newton", + "python": "newton", + "arguments": [], + "result": "NewtonMethod", + "expression": "L.Newton", + "c": "hmath_optimization_newton_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "NewtonCG", + "python": "newton_cg", + "arguments": [], + "result": "NewtonMethod", + "expression": "L.NewtonCG", + "c": "hmath_optimization_newton_cg_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "TrustRegion", + "python": "trust_region", + "arguments": ["Double"], + "result": "NewtonMethod", + "expression": "L.TrustRegion", + "c": "hmath_optimization_trust_region_create", + "parameters": ["radius"], + }, + { + "module": "HMath.Optimization.Local", + "name": "Dogleg", + "python": "dogleg", + "arguments": ["Double"], + "result": "NewtonMethod", + "expression": "L.Dogleg", + "c": "hmath_optimization_dogleg_create", + "parameters": ["radius"], + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeNewton", + "python": "minimize_newton", + "arguments": [ + "NewtonMethod", + "Options", + "Objective", + "Gradient", + "Hessian", + "Vector", + ], + "result": "Result", + "expression": "L.minimizeNewton", + "c": "hmath_optimization_minimize_newton", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "hessian", + "initial", + ], + }, + { + "module": "HMath.Optimization.Local", + "name": "nonlinearCG", + "python": "nonlinear_cg", + "arguments": ["Options", "Objective", "Gradient", "Vector"], + "result": "Result", + "expression": "L.nonlinearCG", + "c": "hmath_optimization_nonlinear_cg", + "parameters": ["options", "objective", "gradient", "initial"], + }, + { + "module": "HMath.Optimization.Local", + "name": "SquaredLoss", + "python": "squared_loss", + "arguments": [], + "result": "Loss", + "expression": "L.SquaredLoss", + "c": "hmath_optimization_squared_loss_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Local", + "name": "HuberLoss", + "python": "huber_loss", + "arguments": ["Double"], + "result": "Loss", + "expression": "L.HuberLoss", + "c": "hmath_optimization_huber_loss_create", + "parameters": ["scale"], + }, + { + "module": "HMath.Optimization.Local", + "name": "CauchyLoss", + "python": "cauchy_loss", + "arguments": ["Double"], + "result": "Loss", + "expression": "L.CauchyLoss", + "c": "hmath_optimization_cauchy_loss_create", + "parameters": ["scale"], + }, + { + "module": "HMath.Optimization.Local", + "name": "SoftL1", + "python": "soft_l1", + "arguments": ["Double"], + "result": "Loss", + "expression": "L.SoftL1", + "c": "hmath_optimization_soft_l1_create", + "parameters": ["scale"], + }, + { + "module": "HMath.Optimization.Local", + "name": "leastSquares", + "python": "least_squares", + "arguments": ["Loss", "Double", "Options", "Gradient", "Hessian", "Vector"], + "result": "Result", + "expression": "L.leastSquares", + "c": "hmath_optimization_least_squares", + "parameters": ["loss", "damping", "options", "residual", "jacobian", "initial"], + }, + { + "module": "HMath.Optimization.Local", + "name": "nelderMead", + "python": "nelder_mead", + "arguments": ["Options", "Objective", "Vector"], + "result": "Result", + "expression": "L.nelderMead", + "c": "hmath_optimization_nelder_mead", + "parameters": ["options", "objective", "initial"], + }, + { + "module": "HMath.Optimization.Local", + "name": "powell", + "python": "powell", + "arguments": ["Double", "Options", "Objective", "Vector"], + "result": "Result", + "expression": "L.powell", + "c": "hmath_optimization_powell", + "parameters": ["initial_step", "options", "objective", "initial"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "Equality", + "python": "equality", + "arguments": ["Objective", "Gradient"], + "result": "Constraint", + "expression": "K.Equality", + "c": "hmath_optimization_equality_create", + "parameters": ["objective", "gradient"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LessEqual", + "python": "less_equal", + "arguments": ["Objective", "Gradient"], + "result": "Constraint", + "expression": "K.LessEqual", + "c": "hmath_optimization_less_equal_create", + "parameters": ["objective", "gradient"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "feasibility", + "python": "feasibility", + "arguments": ["Constraints", "Vector"], + "result": "Double", + "expression": "K.feasibility", + "c": "hmath_optimization_feasibility", + "parameters": ["constraints", "point"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "QuadraticPenalty", + "python": "quadratic_penalty", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.QuadraticPenalty", + "c": "hmath_optimization_quadratic_penalty_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LogBarrier", + "python": "log_barrier", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.LogBarrier", + "c": "hmath_optimization_log_barrier_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "InteriorPoint", + "python": "interior_point", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.InteriorPoint", + "c": "hmath_optimization_interior_point_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "AugmentedLagrangian", + "python": "augmented_lagrangian", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.AugmentedLagrangian", + "c": "hmath_optimization_augmented_lagrangian_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "constrainedMinimize", + "python": "constrained_minimize", + "arguments": [ + "PenaltyMethod", + "Options", + "Objective", + "Gradient", + "Constraints", + "Vector", + ], + "result": "Result", + "expression": "K.constrainedMinimize", + "c": "hmath_optimization_constrained_minimize", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "constraints", + "initial", + ], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LPResult", + "python": "lp_result", + "arguments": ["Vector", "Double", "Indices", "Int"], + "result": "LPResult", + "expression": "K.LPResult", + "c": "hmath_optimization_lp_result_create", + "parameters": ["point", "value", "basis", "iterations"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "linearProgramming", + "python": "linear_programming", + "arguments": ["Int", "Double", "Vector", "Matrix", "Vector"], + "result": "LPResult", + "expression": "K.linearProgramming", + "c": "hmath_optimization_linear_programming", + "parameters": ["budget", "tolerance", "cost", "matrix", "rhs"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "revisedSimplex", + "python": "revised_simplex", + "arguments": ["Int", "Double", "Vector", "Matrix", "Vector", "Indices"], + "result": "LPResult", + "expression": "K.revisedSimplex", + "c": "hmath_optimization_revised_simplex", + "parameters": ["budget", "tolerance", "cost", "matrix", "rhs", "basis"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "quadraticProgramming", + "python": "quadratic_programming", + "arguments": ["Int", "Double", "Matrix", "Vector", "Matrix", "Vector"], + "result": "Result", + "expression": "K.quadraticProgramming", + "c": "hmath_optimization_quadratic_programming", + "parameters": ["budget", "tolerance", "hessian", "cost", "matrix", "rhs"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "slsqp", + "python": "slsqp", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Hessian", + "Constraints", + "Vector", + ], + "result": "Result", + "expression": "K.slsqp", + "c": "hmath_optimization_slsqp", + "parameters": [ + "options", + "objective", + "gradient", + "hessian", + "constraints", + "initial", + ], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "cobyla", + "python": "cobyla", + "arguments": ["Double", "Options", "Objective", "Objectives", "Vector"], + "result": "Result", + "expression": "K.cobyla", + "c": "hmath_optimization_cobyla", + "parameters": [ + "initial_radius", + "options", + "objective", + "constraints", + "initial", + ], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "weightedObjective", + "python": "weighted_objective", + "arguments": ["Vector", "Objectives"], + "result": "Function", + "expression": "(\\weights functions -> functionValue (ObjectiveFn " + "(K.weightedObjective weights functions)))", + "c": "hmath_optimization_weighted_objective", + "parameters": ["weights", "objectives"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "paretoFront", + "python": "pareto_front", + "arguments": ["Matrix"], + "result": "Indices", + "expression": "K.paretoFront", + "c": "hmath_optimization_pareto_front", + "parameters": ["points"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpPoint", + "python": "lp_point", + "arguments": ["LPResult"], + "result": "Value", + "expression": "K.lpPoint", + "c": "hmath_optimization_lp_point", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpValue", + "python": "lp_value", + "arguments": ["LPResult"], + "result": "Value", + "expression": "K.lpValue", + "c": "hmath_optimization_lp_value", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpBasis", + "python": "lp_basis", + "arguments": ["LPResult"], + "result": "Value", + "expression": "K.lpBasis", + "c": "hmath_optimization_lp_basis", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpIterations", + "python": "lp_iterations", + "arguments": ["LPResult"], + "result": "Value", + "expression": "K.lpIterations", + "c": "hmath_optimization_lp_iterations", + "parameters": ["value"], + }, + { + "module": "HMath.Optimization.Global", + "name": "SimulatedAnnealing", + "python": "simulated_annealing", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.SimulatedAnnealing", + "c": "hmath_optimization_simulated_annealing_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Global", + "name": "DifferentialEvolution", + "python": "differential_evolution", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.DifferentialEvolution", + "c": "hmath_optimization_differential_evolution_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Global", + "name": "GeneticAlgorithm", + "python": "genetic_algorithm", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.GeneticAlgorithm", + "c": "hmath_optimization_genetic_algorithm_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Global", + "name": "ParticleSwarm", + "python": "particle_swarm", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.ParticleSwarm", + "c": "hmath_optimization_particle_swarm_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Global", + "name": "CMAES", + "python": "cmaes", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.CMAES", + "c": "hmath_optimization_cmaes_create", + "parameters": [], + }, + { + "module": "HMath.Optimization.Global", + "name": "globalMinimize", + "python": "global_minimize", + "arguments": [ + "GlobalMethod", + "Int", + "Word64", + "Options", + "Bounds", + "Objective", + ], + "result": "Result", + "expression": "G.globalMinimize", + "c": "hmath_optimization_global_minimize", + "parameters": [ + "method", + "population_size", + "seed", + "options", + "bounds", + "objective", + ], + }, + { + "module": "HMath.Optimization.Global", + "name": "basinHopping", + "python": "basin_hopping", + "arguments": [ + "Word64", + "Double", + "Int", + "Options", + "Bounds", + "Objective", + "Vector", + ], + "result": "Result", + "expression": "G.basinHopping", + "c": "hmath_optimization_basin_hopping", + "parameters": [ + "seed", + "temperature", + "hops", + "options", + "bounds", + "objective", + "initial", + ], + }, +] diff --git a/bindings/python/_hmath_native/_polynomial_base.py b/bindings/python/_hmath_native/_polynomial_base.py new file mode 100644 index 0000000..a379f5e --- /dev/null +++ b/bindings/python/_hmath_native/_polynomial_base.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lifetime, dtype and callback adapters; mathematics stays in Haskell.""" + +import ctypes as C + +from . import _value as V +from ._math_error import Wire, fill +from ._numeric import _int + + +class Polynomial(V.Value): + """Immutable ascending polynomial. Source exact-zero normalization applies.""" + + def __init__(self, coefficients, *, dtype="float64"): + result = _construct("hmath_polynomial_polynomial", coefficients, dtype) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + @property + def coefficients(self): + return _call("hmath_polynomial_coefficients", self) + + @property + def degree(self): + return _call("hmath_polynomial_polynomial_degree", self) + + def __eq__(self, other): + if not isinstance(other, Polynomial): + return NotImplemented + return _call("hmath_polynomial_polynomial_equal", self, other) + + __hash__ = None + + +class PowerSeries(V.Value): + """Immutable finite coefficient jet; trailing zeros and source order remain.""" + + def __init__(self, coefficients, *, dtype="float64"): + result = _construct("hmath_polynomial_power_series", coefficients, dtype) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + @property + def coefficients(self): + return _call("hmath_polynomial_series_coefficients", self) + + def __eq__(self, other): + if not isinstance(other, PowerSeries): + return NotImplemented + return _call("hmath_polynomial_series_equal", self, other) + + __hash__ = None + + +class RationalFunction(V.Value): + """Reduced exact Rational numerator/denominator from the source constructor.""" + + def __init__(self, numerator, denominator): + result = _call("hmath_polynomial_rational_function", numerator, denominator) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + def __eq__(self, other): + if not isinstance(other, RationalFunction): + return NotImplemented + return _call("hmath_polynomial_rational_function_equal", self, other) + + __hash__ = None + + +V.register(6, Polynomial) +V.register(7, PowerSeries) +V.register(8, RationalFunction) + + +def _call(symbol, *arguments): + return V.decode(V.invoke(symbol, *arguments)) + + +def _prototype(dtype): + return dtype.clone() if isinstance(dtype, V.Value) else V.scalar(0, dtype) + + +def _typed_one(value, dtype): + if isinstance(value, V.Value): + return value.clone() + if isinstance(dtype, V.Value): + raise TypeError("structured coefficients require explicit typed scalar Values") + return V.scalar(value, dtype) + + +def _construct(symbol, coefficients, dtype): + values = [] + try: + for value in coefficients: + values.append(_typed_one(value, dtype)) + with _prototype(dtype) as prototype: + return _call(symbol, prototype, values) + finally: + for value in values: + value.close() + + +def _prototype_call(symbol, dtype, *arguments): + owners = [] + encoded = [] + try: + for argument in arguments: + if isinstance(argument, (list, tuple)): + rows = [] + for row in argument: + pair = [] + for item in row: + value = _typed_one(item, dtype) + owners.append(value) + pair.append(value) + rows.append(tuple(pair)) + encoded.append(rows) + else: + encoded.append(argument) + with _prototype(dtype) as prototype: + return _call(symbol, prototype, *encoded) + finally: + for owner in owners: + owner.close() + + +def _typed_call(symbol, owner_index, scalar_indices, *arguments): + converted = list(arguments) + owners = [] + try: + dtype = arguments[owner_index].dtype + for index in scalar_indices: + value = _typed_one(arguments[index], dtype) + owners.append(value) + converted[index] = value + return _call(symbol, *converted) + finally: + for owner in owners: + owner.close() + + +_CALLBACK = C.CFUNCTYPE( + C.c_int, C.c_double, C.POINTER(C.c_double), C.c_void_p, C.POINTER(Wire) +) + + +def chebyshev_approximation(degree, function): + """Original synchronous degree+1-node Chebyshev approximation on [-1,1].""" + import hmath + + if not callable(function): + raise TypeError("function must be callable") + degree = _int(degree) + errors = [] + payload = [] + + @_CALLBACK + def callback(x, out, _userdata, wire): + try: + out[0] = function(x) + return 0 + except BaseException as error: # noqa: BLE001 - no exception may escape a ctypes callback + if fill(wire, error, payload): + return 11 + errors.append(error) + try: + description = str(error) + except BaseException: # noqa: BLE001 - exception formatting must not escape ctypes + description = type(error).__name__ + message = description.encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(message) + payload.append(buffer) + wire.contents.message = C.cast(buffer, C.c_void_p) + wire.contents.message_length = len(message) + return 9 + + result = V.Value._adopt() + call = V.api( + "hmath_polynomial_chebyshev_approximation", + C.c_int, + C.c_void_p, + C.c_ssize_t, + _CALLBACK, + C.c_void_p, + C.POINTER(C.c_void_p), + ) + hmath.initialize() + status = call(None, degree, callback, None, C.byref(result._ptr)) + if errors: + result.close() + raise errors[0] + hmath._check(status) + return V.decode(result) diff --git a/bindings/python/_hmath_native/_rotations_base.py b/bindings/python/_hmath_native/_rotations_base.py new file mode 100644 index 0000000..48ca072 --- /dev/null +++ b/bindings/python/_hmath_native/_rotations_base.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Ownership/representation for the original finite Quaternion/SO(3)/SE(3) types.""" + +from . import _value as V + + +class _RotationValue(V.Value): + def __eq__(self, other): + if not isinstance(other, type(self)): + return NotImplemented + return V.invoke("hmath_rotations_equal", self, other).decode() + + __hash__ = None + + +class Quaternion(_RotationValue): + """Actual finite HMath.Quaternion.Quaternion; construct via quaternion().""" + + +class SO3(_RotationValue): + """Actual normalized HMath.Rotation.SO3; construct via so3()/exp_so3().""" + + +class SE3(_RotationValue): + """Actual HMath.Rotation.SE3 rigid transform; construct via se3()/exp_se3().""" + + +class DualQuaternion(_RotationValue): + """Actual rigid HMath.Rotation.DualQuaternion, distinct from Numeric's type.""" + + +for _kind, _owner in [(72, Quaternion), (73, SO3), (74, SE3), (75, DualQuaternion)]: + V.register(_kind, _owner) + + +def _call(symbol, kinds, *arguments): + owners = [] + try: + for kind, argument in zip(kinds, arguments): + if isinstance(argument, V.Value): + item = argument.clone() + elif kind == "d": + item = V.scalar(argument, "float64") + elif kind == "v": + item = V.encode([float(x) for x in argument]) + elif kind == "twist": + if not isinstance(argument, tuple) or len(argument) != 2: + raise TypeError("twist is a tuple of two vector lists") + item = V.encode( + tuple([float(x) for x in vector] for vector in argument) + ) + else: + item = V.encode(argument) + owners.append(item) + return V.invoke(symbol, *owners).decode() + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_scalar_extras_base.py b/bindings/python/_hmath_native/_scalar_extras_base.py new file mode 100644 index 0000000..ecb8713 --- /dev/null +++ b/bindings/python/_hmath_native/_scalar_extras_base.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless representations for additional original scalar-domain operations.""" + +import operator + +from . import _value as V +from ._numeric import SFResult + + +class _Selector(V.Value): + @property + def name(self): + return V.invoke("hmath_scalar_selector_name", self).decode() + + def __eq__(self, other): + if not isinstance(other, type(self)): + return NotImplemented + return V.invoke("hmath_scalar_selector_equal", self, other).decode() + + __hash__ = None + + +class Elementary(_Selector): + """Actual HMath.Complex.Elementary selector (Double complex functions).""" + + +class ComplexFunction(_Selector): + """Actual HMath.Trigonometry.ComplexFunction selector (Float/Double).""" + + +V.register(352, Elementary) +V.register(353, ComplexFunction) + + +def _prepare(kind, argument, dtype): + if isinstance(argument, V.Value): + if kind == "TypedComplex" and dtype is not None: + wanted = {"float32": 5, "complex64": 5, "float64": 4, "complex128": 4}[ + dtype + ] + if argument.info[:2] != (1, wanted): + raise TypeError( + "explicit dtype differs from the actual complex coefficient" + ) + return argument.clone() + if kind in ("Int", "Integer"): + return V.encode(operator.index(argument)) + if kind == "Double": + return V.scalar(float(argument), "float64") + if kind in ("ComplexDouble", "TypedComplex"): + target = "complex64" if dtype in ("float32", "complex64") else "complex128" + if dtype not in (None, "float32", "float64", "complex64", "complex128"): + raise ValueError("complex dtype must select Float or Double") + return V.scalar(complex(argument), target) + if kind == "[ComplexDouble]": + return V.encode([complex(x) for x in argument]) + if kind == "SFResult": + value, error = argument + return V.encode((float(value), float(error))) + if kind == "[(Integer,Integer)]": + return V.encode([tuple(operator.index(x) for x in pair) for pair in argument]) + return V.encode(argument) + + +def _invoke(symbol, kinds, arguments, result, dtype=None): + owners = [] + try: + for kind, argument in zip(kinds, arguments): + owners.append(_prepare(kind, argument, dtype)) + value = V.invoke(symbol, *owners).decode() + return SFResult(*value) if result == "SFResult" else value + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_spectral_base.py b/bindings/python/_hmath_native/_spectral_base.py new file mode 100644 index 0000000..5701f07 --- /dev/null +++ b/bindings/python/_hmath_native/_spectral_base.py @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Borrowed-array interface to the original Fourier.fftInPlace.""" + +import ctypes as C + +from . import _value as value + + +def fft_in_place(plan, buffer): + """Transform one writable contiguous native complex128 NumPy array in place.""" + import hmath + import numpy as np + + if ( + not isinstance(buffer, np.ndarray) + or buffer.ndim != 1 + or buffer.dtype != np.dtype("complex128") + or not buffer.dtype.isnative + or not buffer.flags.c_contiguous + or not buffer.flags.aligned + or not buffer.flags.writeable + ): + raise TypeError( + "expected a writable aligned contiguous native complex128 vector" + ) + owned = value.encode(plan) + try: + hmath._check( + value.api( + "hmath_fourier_value_fft_in_place", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_double), + C.c_ssize_t, + )( + None, + owned._ptr, + buffer.ctypes.data_as(C.POINTER(C.c_double)), + buffer.size, + ) + ) + finally: + owned.close() diff --git a/bindings/python/_hmath_native/_stochastic_base.py b/bindings/python/_hmath_native/_stochastic_base.py new file mode 100644 index 0000000..f000b5b --- /dev/null +++ b/bindings/python/_hmath_native/_stochastic_base.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless continuation/record owners and checked callback representations.""" + +import ctypes as C + +from . import _value as V +from ._linear_base import ( + _callback, + _callback_scope, + _callback_states, + _take_callback_failure, +) + + +class StochasticValue(V.Value): + """Immutable original state or record; results own independent references.""" + + def __init__(self, *_args): + raise TypeError("use this type's public constructors or source functions") + + def _initialize(self, symbol, specs, arguments): + result = _invoke(symbol, specs, arguments) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + def __eq__(self, other): + if not isinstance(other, type(self)): + return NotImplemented + return V.decode(V.invoke("hmath_stochastic_equal", self, other)) + + __hash__ = None + + @property + def parts(self): + """Original public variant constructor and positional fields.""" + return V.decode(V.invoke("hmath_stochastic_object_parts", self)) + + +def _prepare(spec, value, owners, callbacks): + head, *args = spec + if head in ("Double", "Integer", "Word64"): + scalar = ( + value.clone() + if isinstance(value, V.Value) + else V.scalar( + value, + {"Double": "float64", "Integer": "integer", "Word64": "uint64"}[head], + ) + ) + owners.append(scalar) + return scalar + if head == "a": + return value + if head == "list": + return [_prepare(args[0], item, owners, callbacks) for item in value] + if head == "tuple": + value = tuple(value) + if len(value) != len(args): + raise ValueError("tuple arity differs from original signature") + return tuple( + _prepare(s, item, owners, callbacks) for s, item in zip(args, value) + ) + if head == "function": + if isinstance(value, V.Value): + callbacks.extend(_callback_states(value)) + return value + if not callable(value): + raise TypeError("expected a callable source function argument") + result_spec = args[-1] + if result_spec[0] == "Either": + result_spec = result_spec[2] + + def wrapped(*arguments): + local = [] + try: + prepared = _prepare(result_spec, value(*arguments), local, []) + return V.encode(prepared) + finally: + for owner in local: + owner.close() + + function = _callback(wrapped, ["Value"], None) + owners.append(function) + callbacks.append(function) + return function + return value + + +def _invoke(symbol, specs, arguments): + owners = [] + callbacks = [] + try: + prepared = [ + _prepare(spec, value, owners, callbacks) + for spec, value in zip(specs, arguments) + ] + scopes = _callback_scope(callbacks) + try: + result = V.invoke(symbol, *prepared) + except BaseException: + failure = _take_callback_failure(scopes) + if failure is not None: + raise failure + raise + return V.decode(result) + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_tensor_catalog.py b/bindings/python/_hmath_native/_tensor_catalog.py new file mode 100644 index 0000000..6d0b5db --- /dev/null +++ b/bindings/python/_hmath_native/_tensor_catalog.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_tensor_bindings.py. +import json +CATALOG = json.loads('[{"module":"HMath.Tensor","name":"RowMajor","python":"row_major","c":"hmath_tensor_object_row_major_create","arguments":[],"result":"Layout"},{"module":"HMath.Tensor","name":"ColumnMajor","python":"column_major","c":"hmath_tensor_object_column_major_create","arguments":[],"result":"Layout"},{"module":"HMath.Tensor","name":"Strided","python":"strided","c":"hmath_tensor_object_strided_create","arguments":[],"result":"Layout"},{"module":"HMath.Tensor","name":"CPU","python":"cpu","c":"hmath_tensor_object_cpu_create","arguments":[],"result":"Device"},{"module":"HMath.Tensor","name":"tensor","python":"tensor","c":"hmath_tensor_object_tensor","arguments":[["kind","Prototype"],["shape","[Int]"],["xs","Elements"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorColumnMajor","python":"tensor_column_major","c":"hmath_tensor_object_tensor_column_major","arguments":[["kind","Prototype"],["shape","[Int]"],["xs","Elements"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorFull","python":"tensor_full","c":"hmath_tensor_object_tensor_full","arguments":[["shape","[Int]"],["fill","Element"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorZeros","python":"tensor_zeros","c":"hmath_tensor_object_tensor_zeros","arguments":[["kind","Prototype"],["shape","[Int]"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorOnes","python":"tensor_ones","c":"hmath_tensor_object_tensor_ones","arguments":[["kind","Prototype"],["shape","[Int]"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorArange","python":"tensor_arange","c":"hmath_tensor_object_tensor_arange","arguments":[["start","Element"],["end","Element"],["step","Element"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorLinspace","python":"tensor_linspace","c":"hmath_tensor_object_tensor_linspace","arguments":[["start","Element"],["end","Element"],["count","Int"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorLogspace","python":"tensor_logspace","c":"hmath_tensor_object_tensor_logspace","arguments":[["base","Element"],["start","Element"],["end","Element"],["count","Int"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorRandom","python":"tensor_random","c":"hmath_tensor_object_tensor_random","arguments":[["seed","Integer"],["shape","[Int]"]],"result":"(Tensor,Integer)"},{"module":"HMath.Tensor","name":"tensorValues","python":"tensor_values","c":"hmath_tensor_object_tensor_values","arguments":[["input","Tensor"]],"result":"Elements"},{"module":"HMath.Tensor","name":"tensorShape","python":"tensor_shape","c":"hmath_tensor_object_tensor_shape","arguments":[["input","Tensor"]],"result":"[Int]"},{"module":"HMath.Tensor","name":"tensorStrides","python":"tensor_strides","c":"hmath_tensor_object_tensor_strides","arguments":[["input","Tensor"]],"result":"[Int]"},{"module":"HMath.Tensor","name":"tensorOffset","python":"tensor_offset","c":"hmath_tensor_object_tensor_offset","arguments":[["input","Tensor"]],"result":"Int"},{"module":"HMath.Tensor","name":"tensorDType","python":"tensor_dtype","c":"hmath_tensor_object_tensor_d_type","arguments":[["input","Tensor"]],"result":"String"},{"module":"HMath.Tensor","name":"tensorDevice","python":"tensor_device","c":"hmath_tensor_object_tensor_device","arguments":[["input","Tensor"]],"result":"Device"},{"module":"HMath.Tensor","name":"tensorLayout","python":"tensor_layout","c":"hmath_tensor_object_tensor_layout","arguments":[["input","Tensor"]],"result":"Layout"},{"module":"HMath.Tensor","name":"numel","python":"numel","c":"hmath_tensor_object_numel","arguments":[["input","Tensor"]],"result":"Int"},{"module":"HMath.Tensor","name":"isContiguous","python":"is_contiguous","c":"hmath_tensor_object_is_contiguous","arguments":[["input","Tensor"]],"result":"Bool"},{"module":"HMath.Tensor","name":"shapeSize","python":"shape_size","c":"hmath_tensor_object_shape_size","arguments":[["shape","[Int]"]],"result":"Int"},{"module":"HMath.Tensor","name":"inferBroadcast","python":"infer_broadcast","c":"hmath_tensor_object_infer_broadcast","arguments":[["left","Tensor"],["right","Tensor"]],"result":"[Int]"},{"module":"HMath.Tensor","name":"contiguous","python":"contiguous","c":"hmath_tensor_object_contiguous","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"indexTensor","python":"index_tensor","c":"hmath_tensor_object_index_tensor","arguments":[["input","Tensor"],["index","[Int]"]],"result":"Element"},{"module":"HMath.Tensor","name":"sliceTensor","python":"slice_tensor","c":"hmath_tensor_object_slice_tensor","arguments":[["axis","Int"],["start","Int"],["count","Int"],["step","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"fancyIndex","python":"fancy_index","c":"hmath_tensor_object_fancy_index","arguments":[["axis","Int"],["indices","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"gather","python":"gather","c":"hmath_tensor_object_gather","arguments":[["axis","Int"],["indices","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"booleanIndex","python":"boolean_index","c":"hmath_tensor_object_boolean_index","arguments":[["mask","Tensor"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"scatter","python":"scatter","c":"hmath_tensor_object_scatter","arguments":[["axis","Int"],["indices","[Int]"],["updates","Tensor"],["target","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"scatterAdd","python":"scatter_add","c":"hmath_tensor_object_scatter_add","arguments":[["axis","Int"],["indices","[Int]"],["updates","Tensor"],["target","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"reshapeTensor","python":"reshape_tensor","c":"hmath_tensor_object_reshape_tensor","arguments":[["shape","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"flattenTensor","python":"flatten_tensor","c":"hmath_tensor_object_flatten_tensor","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"squeeze","python":"squeeze","c":"hmath_tensor_object_squeeze","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"unsqueeze","python":"unsqueeze","c":"hmath_tensor_object_unsqueeze","arguments":[["axis","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"expand","python":"expand","c":"hmath_tensor_object_expand","arguments":[["shape","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"permute","python":"permute","c":"hmath_tensor_object_permute","arguments":[["axes","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"transposeTensor","python":"transpose_tensor","c":"hmath_tensor_object_transpose_tensor","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"moveAxis","python":"move_axis","c":"hmath_tensor_object_move_axis","arguments":[["from","Int"],["to","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"swapAxes","python":"swap_axes","c":"hmath_tensor_object_swap_axes","arguments":[["from","Int"],["to","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"broadcastTo","python":"broadcast_to","c":"hmath_tensor_object_broadcast_to","arguments":[["shape","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"repeatTensor","python":"repeat_tensor","c":"hmath_tensor_object_repeat_tensor","arguments":[["axis","Int"],["count","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tile","python":"tile","c":"hmath_tensor_object_tile","arguments":[["counts","[Int]"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"concatenate","python":"concatenate","c":"hmath_tensor_object_concatenate","arguments":[["kind","Prototype"],["axis","Int"],["inputs","[Tensor]"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"stack","python":"stack","c":"hmath_tensor_object_stack","arguments":[["kind","Prototype"],["axis","Int"],["inputs","[Tensor]"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"splitTensor","python":"split_tensor","c":"hmath_tensor_object_split_tensor","arguments":[["axis","Int"],["segments","[Int]"],["input","Tensor"]],"result":"[Tensor]"},{"module":"HMath.Tensor","name":"chunkTensor","python":"chunk_tensor","c":"hmath_tensor_object_chunk_tensor","arguments":[["axis","Int"],["count","Int"],["input","Tensor"]],"result":"[Tensor]"},{"module":"HMath.Tensor","name":"padTensor","python":"pad_tensor","c":"hmath_tensor_object_pad_tensor","arguments":[["padding","[(Int,Int)]"],["fill","Element"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"roll","python":"roll","c":"hmath_tensor_object_roll","arguments":[["axis","Int"],["shift","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"flipTensor","python":"flip_tensor","c":"hmath_tensor_object_flip_tensor","arguments":[["axis","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"rotate","python":"rotate","c":"hmath_tensor_object_rotate","arguments":[["first","Int"],["second","Int"],["turns","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"sortTensor","python":"sort_tensor","c":"hmath_tensor_object_sort_tensor","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"unique","python":"unique","c":"hmath_tensor_object_unique","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"argsort","python":"argsort","c":"hmath_tensor_object_argsort","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"topk","python":"topk","c":"hmath_tensor_object_topk","arguments":[["count","Int"],["input","Tensor"]],"result":"(Tensor,Tensor)"},{"module":"HMath.Tensor","name":"nonzero","python":"nonzero","c":"hmath_tensor_object_nonzero","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"whereTensor","python":"where_tensor","c":"hmath_tensor_object_where_tensor","arguments":[["mask","Tensor"],["left","Tensor"],["right","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"maskedFill","python":"masked_fill","c":"hmath_tensor_object_masked_fill","arguments":[["mask","Tensor"],["fill","Element"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"maskedSelect","python":"masked_select","c":"hmath_tensor_object_masked_select","arguments":[["mask","Tensor"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"mapTensor","python":"map_tensor","c":"hmath_tensor_object_map_tensor","arguments":[["kind","Prototype"],["cb","Callback"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"zipTensor","python":"zip_tensor","c":"hmath_tensor_object_zip_tensor","arguments":[["kind","Prototype"],["cb","Callback"],["left","Tensor"],["right","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorAdd","python":"tensor_add","c":"hmath_tensor_object_tensor_add","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorSubtract","python":"tensor_subtract","c":"hmath_tensor_object_tensor_subtract","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorMultiply","python":"tensor_multiply","c":"hmath_tensor_object_tensor_multiply","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorDivide","python":"tensor_divide","c":"hmath_tensor_object_tensor_divide","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorEqual","python":"tensor_equal","c":"hmath_tensor_object_tensor_equal","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorLess","python":"tensor_less","c":"hmath_tensor_object_tensor_less","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorAnd","python":"tensor_and","c":"hmath_tensor_object_tensor_and","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorOr","python":"tensor_or","c":"hmath_tensor_object_tensor_or","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorNot","python":"tensor_not","c":"hmath_tensor_object_tensor_not","arguments":[["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"promoteTensor","python":"promote_tensor","c":"hmath_tensor_object_promote_tensor","arguments":[["kind","Prototype"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"sumAxes","python":"sum_axes","c":"hmath_tensor_object_sum_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"productAxes","python":"product_axes","c":"hmath_tensor_object_product_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"meanAxes","python":"mean_axes","c":"hmath_tensor_object_mean_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"varianceAxes","python":"variance_axes","c":"hmath_tensor_object_variance_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"normAxes","python":"norm_axes","c":"hmath_tensor_object_norm_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"minAxes","python":"min_axes","c":"hmath_tensor_object_min_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"maxAxes","python":"max_axes","c":"hmath_tensor_object_max_axes","arguments":[["axes","[Int]"],["keep","Bool"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"argmin","python":"argmin","c":"hmath_tensor_object_argmin","arguments":[["input","Tensor"]],"result":"Int"},{"module":"HMath.Tensor","name":"argmax","python":"argmax","c":"hmath_tensor_object_argmax","arguments":[["input","Tensor"]],"result":"Int"},{"module":"HMath.Tensor","name":"cumulativeSum","python":"cumulative_sum","c":"hmath_tensor_object_cumulative_sum","arguments":[["axis","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"cumulativeProduct","python":"cumulative_product","c":"hmath_tensor_object_cumulative_product","arguments":[["axis","Int"],["input","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensordot","python":"tensordot","c":"hmath_tensor_object_tensordot","arguments":[["leftAxes","[Int]"],["rightAxes","[Int]"],["left","Tensor"],["right","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"einsum","python":"einsum","c":"hmath_tensor_object_einsum","arguments":[["kind","Prototype"],["labels","[String]"],["outputLabels","String"],["inputs","[Tensor]"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"batchedMatmul","python":"batched_matmul","c":"hmath_tensor_object_batched_matmul","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"tensorKronecker","python":"tensor_kronecker","c":"hmath_tensor_object_tensor_kronecker","arguments":[["a","Tensor"],["b","Tensor"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"serializeTensor","python":"serialize_tensor","c":"hmath_tensor_object_serialize_tensor","arguments":[["input","Tensor"]],"result":"String"},{"module":"HMath.Tensor","name":"deserializeTensor","python":"deserialize_tensor","c":"hmath_tensor_object_deserialize_tensor","arguments":[["kind","Prototype"],["text","String"]],"result":"Tensor"},{"module":"HMath.Tensor","name":"inputGraph","python":"input_graph","c":"hmath_tensor_object_input_graph","arguments":[["input","Tensor"]],"result":"TensorGraph"},{"module":"HMath.Tensor","name":"mapGraph","python":"map_graph","c":"hmath_tensor_object_map_graph","arguments":[["kind","Prototype"],["cb","Callback"],["input","TensorGraph"]],"result":"TensorGraph"},{"module":"HMath.Tensor","name":"zipGraph","python":"zip_graph","c":"hmath_tensor_object_zip_graph","arguments":[["kind","Prototype"],["cb","Callback"],["left","TensorGraph"],["right","TensorGraph"]],"result":"TensorGraph"},{"module":"HMath.Tensor","name":"evaluateGraph","python":"evaluate_graph","c":"hmath_tensor_object_evaluate_graph","arguments":[["input","TensorGraph"]],"result":"Tensor"},{"module":"HMath.Tensor.Mutable","name":"newMutable","python":"new_mutable","c":"hmath_tensor_object_new_mutable","arguments":[["shape","[Int]"],["fill","Element"]],"result":"MutableTensor"},{"module":"HMath.Tensor.Mutable","name":"thawTensor","python":"thaw_tensor","c":"hmath_tensor_object_thaw_tensor","arguments":[["input","Tensor"]],"result":"MutableTensor"},{"module":"HMath.Tensor.Mutable","name":"freezeTensor","python":"freeze_tensor","c":"hmath_tensor_object_freeze_tensor","arguments":[["input","MutableTensor"]],"result":"Tensor"},{"module":"HMath.Tensor.Mutable","name":"mutableShape","python":"mutable_shape","c":"hmath_tensor_object_mutable_shape","arguments":[["input","MutableTensor"]],"result":"[Int]"},{"module":"HMath.Tensor.Mutable","name":"readMutable","python":"read_mutable","c":"hmath_tensor_object_read_mutable","arguments":[["input","MutableTensor"],["index","[Int]"]],"result":"Element"},{"module":"HMath.Tensor.Mutable","name":"writeMutable","python":"write_mutable","c":"hmath_tensor_object_write_mutable","arguments":[["input","MutableTensor"],["index","[Int]"],["fill","Element"]],"result":"Unit"},{"module":"HMath.Tensor.Mutable","name":"modifyMutable","python":"modify_mutable","c":"hmath_tensor_object_modify_mutable","arguments":[["input","MutableTensor"],["index","[Int]"],["cb","Callback"]],"result":"Unit"},{"module":"HMath.Tensor.Mutable","name":"sliceMutable","python":"slice_mutable","c":"hmath_tensor_object_slice_mutable","arguments":[["axis","Int"],["start","Int"],["count","Int"],["step","Int"],["input","MutableTensor"]],"result":"MutableTensor"},{"module":"HMath.Tensor.Mutable","name":"transposeMutable","python":"transpose_mutable","c":"hmath_tensor_object_transpose_mutable","arguments":[["input","MutableTensor"]],"result":"MutableTensor"},{"module":"HMath.Tensor.Mutable","name":"mutableAlignment","python":"mutable_alignment","c":"hmath_tensor_object_mutable_alignment","arguments":[["kind","Prototype"]],"result":"Int"},{"module":"HMath.Tensor.Mutable","name":"withMutableBuffer","python":"with_mutable_buffer","c":"hmath_tensor_object_with_mutable_buffer","arguments":[["input","MutableTensor"],["cb","BufferCallback"]],"result":"Generic"}]') diff --git a/bindings/python/_hmath_native/_tensor_core.py b/bindings/python/_hmath_native/_tensor_core.py new file mode 100644 index 0000000..52ebbb3 --- /dev/null +++ b/bindings/python/_hmath_native/_tensor_core.py @@ -0,0 +1,1039 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original typed Tensor and pinned mutable APIs, with deferred graph ownership.""" + +import ctypes as C +import threading +import weakref +from enum import IntEnum + +from . import _value as v +from ._callback_error import fill +from ._compat import zip_equal +from ._math_error import Wire +from ._numeric import _int +from ._numeric_types_runtime import number +from ._tensor_catalog import CATALOG +from ._tensor_object import MutableTensor, Tensor, TensorDouble, TensorGraph + +_SPEC = {item["name"]: item for item in CATALOG} +_pending = threading.local() + + +class Layout(IntEnum): + ROW_MAJOR = 0 + COLUMN_MAJOR = 1 + STRIDED = 2 + + +class Device(IntEnum): + CPU = 0 + + +RowMajor = Layout.ROW_MAJOR +ColumnMajor = Layout.COLUMN_MAJOR +Strided = Layout.STRIDED +CPU = Device.CPU + + +def _prototype(dtype="float64"): + if isinstance(dtype, v.Value): + return dtype.clone() + if dtype in ("bool", "boolean"): + return v.encode(False) + if dtype in ("str", "string", "text"): + return v.encode("") + return v.scalar(0, dtype) + + +def _prototype_of(value): + kind = value.info[0] + symbol = ( + "hmath_tensor_object_graph_prototype" + if kind == 271 + else "hmath_tensor_object_mutable_prototype" + if kind == 272 + else "hmath_tensor_object_prototype" + ) + return v.invoke(symbol, value) + + +def _coerce(value, prototype): + if isinstance(value, v.Value): + return value.clone() + kind, dtype, _ = prototype.info + if kind == 3: + if not isinstance(value, bool): + raise TypeError("expected Bool element") + return v.encode(value) + if kind == 10: + if not isinstance(value, str): + raise TypeError("expected String element") + return v.encode(value) + if kind == 1 and dtype in v.DTYPE_NAMES: + return v.scalar(value, v.DTYPE_NAMES[dtype]) + if kind == 1: + from ._numeric_types_runtime import _literal + + return _literal(value, prototype) + raise TypeError("prototype is not a supported tensor element") + + +def _sequence(items, hint, prototype=None, tuple_=False): + values = [] + try: + for item in items: + values.append(_typed(item, hint, prototype)) + return v.encode(tuple(values) if tuple_ else values) + finally: + for value in values: + value.close() + + +def _typed(value, hint, prototype=None): + if isinstance(value, v.Value): + return value.clone() + if hint == "Int": + return v._create("hmath_value_index", [C.c_ssize_t], [_int(value)]) + if hint == "Integer": + return v.scalar(value, "integer") + if hint == "Bool": + if not isinstance(value, bool): + raise TypeError("expected Bool") + return v.encode(value) + if hint == "String": + if not isinstance(value, str): + raise TypeError("expected String") + return v.encode(value) + if hint == "Element": + return v.encode(value) if prototype is None else _coerce(value, prototype) + if hint == "Prototype": + return _prototype(value) + if hint == "Elements": + if prototype is None: + raise TypeError("element list requires an explicit type prototype") + return _sequence(value, "Element", prototype) + if hint == "[(Int,Int)]": + return _sequence(value, "(Int,Int)") + if hint == "(Int,Int)": + values = tuple(value) + if len(values) != 2: + raise TypeError("expected pair") + return _sequence(values, "Int", tuple_=True) + if hint.startswith("["): + return _sequence(value, hint[1:-1], prototype) + return v.encode(value) + + +def _raw(name, *arguments): + item = _SPEC[name] + if len(arguments) != len(item["arguments"]): + raise TypeError(name + " argument count differs") + prototype = None + values = [] + try: + for argument, (parameter, hint) in zip_equal(arguments, item["arguments"]): + if hint == "Prototype": + prototype = ( + argument.clone() + if isinstance(argument, v.Value) + else _prototype(argument) + ) + break + if prototype is None: + for argument, (parameter, hint) in zip_equal(arguments, item["arguments"]): + if ( + parameter != "mask" + and hint in ("Tensor", "TensorGraph", "MutableTensor") + and isinstance(argument, v.Value) + ): + prototype = _prototype_of(argument) + break + for argument, (_, hint) in zip_equal(arguments, item["arguments"]): + values.append(_typed(argument, hint, prototype)) + return v.invoke(item["c"], *values) + except BaseException: + if getattr(_pending, "exception", None) is not None: + error = _pending.exception + del _pending.exception + raise error + raise + finally: + for value in values: + value.close() + if prototype is not None: + prototype.close() + + +def _invoke(name, *arguments, boxed=False): + result = _raw(name, *arguments) + if boxed: + return result + output = v.decode(result) + if _SPEC[name]["result"] == "Layout": + return Layout(output) + if _SPEC[name]["result"] == "Device": + return Device(output) + if _SPEC[name]["result"] == "Unit": + return None + return output + + +class _Owner: + def __init__(self, function, prototype=None): + self.function = function + self.prototype = None if prototype is None else prototype.clone() + self.callback = None + self.buffers = {} + + +_SCALAR = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p), C.POINTER(Wire) +) +_BUFFER = C.CFUNCTYPE( + C.c_int, C.c_void_p, C.c_void_p, C.c_void_p, C.POINTER(C.c_void_p), C.POINTER(Wire) +) + + +def _callback_error(owner, error, wire): + buffers = [] + # Reentrant error properties may invoke this same callback while encoding + # a payload. Keep both buffer sets alive until their native owner is gone. + owner.buffers.setdefault(threading.get_ident(), []).append(buffers) + try: + status = fill(wire, error, buffers) + if status: + return status + _pending.exception = error + payload = str(error).encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(payload) + buffers.append(buffer) + wire.contents.kind = 0 + wire.contents.message = C.cast(buffer, C.c_void_p) + wire.contents.message_length = len(payload) + return 6 + except BaseException: # noqa: BLE001 - contain exception transport failures + _pending.exception = error + return 6 + + +def _give(out, value): + try: + with value._lock: + v.api("hmath_value_retain", None, C.c_void_p)(value._ptr) + out[0] = value._ptr + finally: + value.close() + + +def _scalar_callback(function, prototype): + if not callable(function): + raise TypeError("expected scalar callable") + owner = _Owner(function, prototype) + reference = weakref.proxy(owner) + + @_SCALAR + def bridge(pointer, userdata, out, error): + arguments = [] + try: + with v.borrow(pointer) as value: + for index in range(value.info[2]): + item = value.item(index) + # Numeric operators on these owned scalar inputs call the + # original dtype instances, retaining Float arithmetic. + if item.info[0] == 1: + try: + arguments.append(number(item)) + finally: + item.close() + else: + arguments.append(v.decode(item)) + answer = reference.function(*arguments) + _give(out, _coerce(answer, reference.prototype)) + return 0 + except BaseException as exception: # noqa: BLE001 - C callback boundary + return _callback_error(reference, exception, error) + finally: + # Like the C tuple, scalar arguments are borrowed for this call. + # Clone a typed scalar or copy .value to retain it after return. + for argument in arguments: + if isinstance(argument, v.Value): + argument.close() + + owner.callback = bridge + result = v.Value._adopt(owners=(owner,)) + import hmath + + hmath.initialize() + hmath._check( + v.api( + "hmath_tensor_object_callback", + C.c_int, + C.c_void_p, + _SCALAR, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, bridge, None, C.byref(result._ptr)) + ) + return result + + +class _ComplexFloat(C.Structure): + _fields_ = [("real", C.c_float), ("imag", C.c_float)] + + +class _ComplexDouble(C.Structure): + _fields_ = [("real", C.c_double), ("imag", C.c_double)] + + +_CTYPES = { + 0: C.c_double, + 1: C.c_float, + 4: _ComplexDouble, + 5: _ComplexFloat, + 6: C.c_int8, + 7: C.c_int16, + 8: C.c_int32, + 9: C.c_int64, + 10: C.c_uint8, + 11: C.c_uint16, + 12: C.c_uint32, + 13: C.c_uint64, + 14: C.c_ssize_t, + 15: C.c_size_t, +} + + +class BorrowedBuffer: + """Pointer access is valid only during with_mutable_buffer's callback.""" + + def __init__(self, address, prototype, shape, strides, itemsize, alignment): + self._address = address + self._prototype = prototype + self.shape, self.strides, self.itemsize, self.alignment = ( + shape, + strides, + itemsize, + alignment, + ) + self._active = True + + @property + def pointer(self): + if not self._active: + raise ValueError("borrowed mutable buffer is outside its callback scope") + kind, dtype, _ = self._prototype.info + type_ = C.c_int if kind == 3 else _CTYPES.get(dtype) + if type_ is None or C.sizeof(type_) != self.itemsize: + raise TypeError("no matching ctypes Storable representation") + return C.cast(self._address, C.POINTER(type_)) + + def _invalidate(self): + self._active = False + self._prototype.close() + + +def _buffer_callback(function): + if not callable(function): + raise TypeError("expected buffer callable") + owner = _Owner(function) + reference = weakref.proxy(owner) + + @_BUFFER + def bridge(address, pointer, userdata, out, error): + buffer = None + try: + with v.borrow(pointer) as metadata: + prototype = metadata.item(0) + fields = [v.decode(metadata.item(index)) for index in range(1, 5)] + buffer = BorrowedBuffer(address, prototype, *fields) + answer = reference.function(buffer) + _give(out, v.encode(answer)) + return 0 + except BaseException as exception: # noqa: BLE001 - C callback boundary + return _callback_error(reference, exception, error) + finally: + if buffer is not None: + buffer._invalidate() + + owner.callback = bridge + result = v.Value._adopt(owners=(owner,)) + import hmath + + hmath.initialize() + hmath._check( + v.api( + "hmath_tensor_object_buffer_callback", + C.c_int, + C.c_void_p, + _BUFFER, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, bridge, None, C.byref(result._ptr)) + ) + return result + + +def tensor(shape, values, *, dtype="float64"): + with _prototype(dtype) as prototype: + return _invoke("tensor", prototype, shape, values) + + +def tensor_column_major(shape, values, *, dtype="float64"): + with _prototype(dtype) as prototype: + return _invoke("tensorColumnMajor", prototype, shape, values) + + +def tensor_zeros(shape, *, dtype="float64"): + with _prototype(dtype) as prototype: + return _invoke("tensorZeros", prototype, shape) + + +def tensor_ones(shape, *, dtype="float64"): + with _prototype(dtype) as prototype: + return _invoke("tensorOnes", prototype, shape) + + +def tensor_full(shape, value, *, dtype=None): + if dtype is None: + return _invoke("tensorFull", shape, value) + with _prototype(dtype) as prototype, _coerce(value, prototype) as fill_value: + if prototype.info[0] == 294: + with _typed(shape, "[Int]") as dimensions: + return v.decode( + v.invoke( + "hmath_tensor_object_full_typed", + prototype, + dimensions, + fill_value, + ) + ) + return _invoke("tensorFull", shape, fill_value) + + +def tensor_arange(start, end, step, *, dtype="float64"): + with _prototype(dtype) as prototype: + values = [] + try: + values = [_coerce(value, prototype) for value in [start, end, step]] + return _invoke("tensorArange", *values) + finally: + for value in values: + value.close() + + +def tensor_linspace(start, end, count, *, dtype="float64"): + with ( + _prototype(dtype) as prototype, + _coerce(start, prototype) as first, + _coerce(end, prototype) as last, + ): + return _invoke("tensorLinspace", first, last, count) + + +def tensor_logspace(base, start, end, count, *, dtype="float64"): + with ( + _prototype(dtype) as prototype, + _coerce(base, prototype) as scale, + _coerce(start, prototype) as first, + _coerce(end, prototype) as last, + ): + return _invoke("tensorLogspace", scale, first, last, count) + + +def _list_operation(name, arguments, tensors, dtype): + tensors = list(tensors) + with ( + _prototype_of(tensors[0]) + if dtype is None and tensors + else _prototype("float64" if dtype is None else dtype) + ) as prototype: + return _invoke(name, prototype, *arguments, tensors) + + +def concatenate(axis, tensors, *, dtype=None): + return _list_operation("concatenate", [axis], tensors, dtype) + + +def stack(axis, tensors, *, dtype=None): + return _list_operation("stack", [axis], tensors, dtype) + + +def einsum(labels, output, tensors, *, dtype=None): + return _list_operation("einsum", [labels, output], tensors, dtype) + + +def promote_tensor(dtype, tensor): + with _prototype(dtype) as prototype: + return _invoke("promoteTensor", prototype, tensor) + + +def deserialize_tensor(source, *, dtype="float64"): + with _prototype(dtype) as prototype: + return _invoke("deserializeTensor", prototype, source) + + +def _mapped(name, function, inputs, dtype): + with ( + _prototype_of(inputs[0]) if dtype is None else _prototype(dtype) as prototype, + _scalar_callback(function, prototype) as callback, + ): + return _invoke(name, prototype, callback, *inputs) + + +def map_tensor(function, tensor, *, dtype=None): + return _mapped("mapTensor", function, [tensor], dtype) + + +def zip_tensor(function, left, right, *, dtype=None): + return _mapped("zipTensor", function, [left, right], dtype) + + +def map_graph(function, graph, *, dtype=None): + return _mapped("mapGraph", function, [graph], dtype) + + +def zip_graph(function, left, right, *, dtype=None): + return _mapped("zipGraph", function, [left, right], dtype) + + +def new_mutable(shape, value, *, dtype="float64"): + with _prototype(dtype) as prototype, _coerce(value, prototype) as fill_value: + return _invoke("newMutable", shape, fill_value) + + +def modify_mutable(tensor, coordinates, function): + with ( + _prototype_of(tensor) as prototype, + _scalar_callback(function, prototype) as callback, + ): + return _invoke("modifyMutable", tensor, coordinates, callback) + + +def mutable_alignment(dtype): + with _prototype(dtype) as prototype: + return _invoke("mutableAlignment", prototype) + + +def with_mutable_buffer(tensor, function): + with _buffer_callback(function) as callback: + return _invoke("withMutableBuffer", tensor, callback) + + +def _equal_tensor(left, right): + return v.decode(v.invoke("hmath_tensor_object_equal_instance", left, right)) + + +def element_type(tensor): + """Return an owned dtype prototype, including exact structural type tokens.""" + return _prototype_of(tensor) + + +# BEGIN GENERATED +def tensor_random(seed, shape): + """HMath.Tensor.tensorRandom: original dtype and failure conditions.""" + return _invoke("tensorRandom", seed, shape) + + +def tensor_values(tensor): + """HMath.Tensor.tensorValues: original dtype and failure conditions.""" + return _invoke("tensorValues", tensor) + + +def tensor_shape(tensor): + """HMath.Tensor.tensorShape: original dtype and failure conditions.""" + return _invoke("tensorShape", tensor) + + +def tensor_strides(tensor): + """HMath.Tensor.tensorStrides: original dtype and failure conditions.""" + return _invoke("tensorStrides", tensor) + + +def tensor_offset(tensor): + """HMath.Tensor.tensorOffset: original dtype and failure conditions.""" + return _invoke("tensorOffset", tensor) + + +def tensor_dtype(tensor): + """HMath.Tensor.tensorDType: original dtype and failure conditions.""" + return _invoke("tensorDType", tensor) + + +def tensor_device(tensor): + """HMath.Tensor.tensorDevice: original dtype and failure conditions.""" + return _invoke("tensorDevice", tensor) + + +def tensor_layout(tensor): + """HMath.Tensor.tensorLayout: original dtype and failure conditions.""" + return _invoke("tensorLayout", tensor) + + +def numel(tensor): + """HMath.Tensor.numel: original dtype and failure conditions.""" + return _invoke("numel", tensor) + + +def is_contiguous(tensor): + """HMath.Tensor.isContiguous: original dtype and failure conditions.""" + return _invoke("isContiguous", tensor) + + +def shape_size(shape): + """HMath.Tensor.shapeSize: original dtype and failure conditions.""" + return _invoke("shapeSize", shape) + + +def infer_broadcast(left, right): + """HMath.Tensor.inferBroadcast: original dtype and failure conditions.""" + return _invoke("inferBroadcast", left, right) + + +def contiguous(tensor): + """HMath.Tensor.contiguous: original dtype and failure conditions.""" + return _invoke("contiguous", tensor) + + +def index_tensor(tensor, coordinates): + """HMath.Tensor.indexTensor: original dtype and failure conditions.""" + return _invoke("indexTensor", tensor, coordinates) + + +def slice_tensor(axis, start, count, step, tensor): + """HMath.Tensor.sliceTensor: original dtype and failure conditions.""" + return _invoke("sliceTensor", axis, start, count, step, tensor) + + +def fancy_index(axis, indices, tensor): + """HMath.Tensor.fancyIndex: original dtype and failure conditions.""" + return _invoke("fancyIndex", axis, indices, tensor) + + +def gather(axis, indices, tensor): + """HMath.Tensor.gather: original dtype and failure conditions.""" + return _invoke("gather", axis, indices, tensor) + + +def boolean_index(mask, tensor): + """HMath.Tensor.booleanIndex: original dtype and failure conditions.""" + return _invoke("booleanIndex", mask, tensor) + + +def scatter(axis, indices, updates, target): + """HMath.Tensor.scatter: original dtype and failure conditions.""" + return _invoke("scatter", axis, indices, updates, target) + + +def scatter_add(axis, indices, updates, target): + """HMath.Tensor.scatterAdd: original dtype and failure conditions.""" + return _invoke("scatterAdd", axis, indices, updates, target) + + +def reshape_tensor(shape, tensor): + """HMath.Tensor.reshapeTensor: original dtype and failure conditions.""" + return _invoke("reshapeTensor", shape, tensor) + + +def flatten_tensor(tensor): + """HMath.Tensor.flattenTensor: original dtype and failure conditions.""" + return _invoke("flattenTensor", tensor) + + +def squeeze(tensor): + """HMath.Tensor.squeeze: original dtype and failure conditions.""" + return _invoke("squeeze", tensor) + + +def unsqueeze(axis, tensor): + """HMath.Tensor.unsqueeze: original dtype and failure conditions.""" + return _invoke("unsqueeze", axis, tensor) + + +def expand(shape, tensor): + """HMath.Tensor.expand: original dtype and failure conditions.""" + return _invoke("expand", shape, tensor) + + +def permute(axes, tensor): + """HMath.Tensor.permute: original dtype and failure conditions.""" + return _invoke("permute", axes, tensor) + + +def transpose_tensor(tensor): + """HMath.Tensor.transposeTensor: original dtype and failure conditions.""" + return _invoke("transposeTensor", tensor) + + +def move_axis(from_axis, to_axis, tensor): + """HMath.Tensor.moveAxis: original dtype and failure conditions.""" + return _invoke("moveAxis", from_axis, to_axis, tensor) + + +def swap_axes(from_axis, to_axis, tensor): + """HMath.Tensor.swapAxes: original dtype and failure conditions.""" + return _invoke("swapAxes", from_axis, to_axis, tensor) + + +def broadcast_to(shape, tensor): + """HMath.Tensor.broadcastTo: original dtype and failure conditions.""" + return _invoke("broadcastTo", shape, tensor) + + +def repeat_tensor(axis, count, tensor): + """HMath.Tensor.repeatTensor: original dtype and failure conditions.""" + return _invoke("repeatTensor", axis, count, tensor) + + +def tile(counts, tensor): + """HMath.Tensor.tile: original dtype and failure conditions.""" + return _invoke("tile", counts, tensor) + + +def split_tensor(axis, segments, tensor): + """HMath.Tensor.splitTensor: original dtype and failure conditions.""" + return _invoke("splitTensor", axis, segments, tensor) + + +def chunk_tensor(axis, count, tensor): + """HMath.Tensor.chunkTensor: original dtype and failure conditions.""" + return _invoke("chunkTensor", axis, count, tensor) + + +def pad_tensor(padding, value, tensor): + """HMath.Tensor.padTensor: original dtype and failure conditions.""" + return _invoke("padTensor", padding, value, tensor) + + +def roll(axis, shift, tensor): + """HMath.Tensor.roll: original dtype and failure conditions.""" + return _invoke("roll", axis, shift, tensor) + + +def flip_tensor(axis, tensor): + """HMath.Tensor.flipTensor: original dtype and failure conditions.""" + return _invoke("flipTensor", axis, tensor) + + +def rotate(first, second, turns, tensor): + """HMath.Tensor.rotate: original dtype and failure conditions.""" + return _invoke("rotate", first, second, turns, tensor) + + +def sort_tensor(tensor): + """HMath.Tensor.sortTensor: original dtype and failure conditions.""" + return _invoke("sortTensor", tensor) + + +def unique(tensor): + """HMath.Tensor.unique: original dtype and failure conditions.""" + return _invoke("unique", tensor) + + +def argsort(tensor): + """HMath.Tensor.argsort: original dtype and failure conditions.""" + return _invoke("argsort", tensor) + + +def topk(count, tensor): + """HMath.Tensor.topk: original dtype and failure conditions.""" + return _invoke("topk", count, tensor) + + +def nonzero(tensor): + """HMath.Tensor.nonzero: original dtype and failure conditions.""" + return _invoke("nonzero", tensor) + + +def where_tensor(mask, left, right): + """HMath.Tensor.whereTensor: original dtype and failure conditions.""" + return _invoke("whereTensor", mask, left, right) + + +def masked_fill(mask, value, tensor): + """HMath.Tensor.maskedFill: original dtype and failure conditions.""" + return _invoke("maskedFill", mask, value, tensor) + + +def masked_select(mask, tensor): + """HMath.Tensor.maskedSelect: original dtype and failure conditions.""" + return _invoke("maskedSelect", mask, tensor) + + +def tensor_add(a, b): + """HMath.Tensor.tensorAdd: original dtype and failure conditions.""" + return _invoke("tensorAdd", a, b) + + +def tensor_subtract(a, b): + """HMath.Tensor.tensorSubtract: original dtype and failure conditions.""" + return _invoke("tensorSubtract", a, b) + + +def tensor_multiply(a, b): + """HMath.Tensor.tensorMultiply: original dtype and failure conditions.""" + return _invoke("tensorMultiply", a, b) + + +def tensor_divide(a, b): + """HMath.Tensor.tensorDivide: original dtype and failure conditions.""" + return _invoke("tensorDivide", a, b) + + +def tensor_equal(a, b): + """HMath.Tensor.tensorEqual: original dtype and failure conditions.""" + return _invoke("tensorEqual", a, b) + + +def tensor_less(a, b): + """HMath.Tensor.tensorLess: original dtype and failure conditions.""" + return _invoke("tensorLess", a, b) + + +def tensor_and(a, b): + """HMath.Tensor.tensorAnd: original dtype and failure conditions.""" + return _invoke("tensorAnd", a, b) + + +def tensor_or(a, b): + """HMath.Tensor.tensorOr: original dtype and failure conditions.""" + return _invoke("tensorOr", a, b) + + +def tensor_not(tensor): + """HMath.Tensor.tensorNot: original dtype and failure conditions.""" + return _invoke("tensorNot", tensor) + + +def sum_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.sumAxes: original dtype and failure conditions.""" + return _invoke("sumAxes", axes, keep_dimensions, tensor) + + +def product_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.productAxes: original dtype and failure conditions.""" + return _invoke("productAxes", axes, keep_dimensions, tensor) + + +def mean_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.meanAxes: original dtype and failure conditions.""" + return _invoke("meanAxes", axes, keep_dimensions, tensor) + + +def variance_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.varianceAxes: original dtype and failure conditions.""" + return _invoke("varianceAxes", axes, keep_dimensions, tensor) + + +def norm_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.normAxes: original dtype and failure conditions.""" + return _invoke("normAxes", axes, keep_dimensions, tensor) + + +def min_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.minAxes: original dtype and failure conditions.""" + return _invoke("minAxes", axes, keep_dimensions, tensor) + + +def max_axes(axes, keep_dimensions, tensor): + """HMath.Tensor.maxAxes: original dtype and failure conditions.""" + return _invoke("maxAxes", axes, keep_dimensions, tensor) + + +def argmin(tensor): + """HMath.Tensor.argmin: original dtype and failure conditions.""" + return _invoke("argmin", tensor) + + +def argmax(tensor): + """HMath.Tensor.argmax: original dtype and failure conditions.""" + return _invoke("argmax", tensor) + + +def cumulative_sum(axis, tensor): + """HMath.Tensor.cumulativeSum: original dtype and failure conditions.""" + return _invoke("cumulativeSum", axis, tensor) + + +def cumulative_product(axis, tensor): + """HMath.Tensor.cumulativeProduct: original dtype and failure conditions.""" + return _invoke("cumulativeProduct", axis, tensor) + + +def tensordot(left_axes, right_axes, left, right): + """HMath.Tensor.tensordot: original dtype and failure conditions.""" + return _invoke("tensordot", left_axes, right_axes, left, right) + + +def batched_matmul(a, b): + """HMath.Tensor.batchedMatmul: original dtype and failure conditions.""" + return _invoke("batchedMatmul", a, b) + + +def tensor_kronecker(a, b): + """HMath.Tensor.tensorKronecker: original dtype and failure conditions.""" + return _invoke("tensorKronecker", a, b) + + +def serialize_tensor(tensor): + """HMath.Tensor.serializeTensor: original dtype and failure conditions.""" + return _invoke("serializeTensor", tensor) + + +def input_graph(tensor): + """HMath.Tensor.inputGraph: original dtype and failure conditions.""" + return _invoke("inputGraph", tensor) + + +def evaluate_graph(tensor): + """HMath.Tensor.evaluateGraph: original dtype and failure conditions.""" + return _invoke("evaluateGraph", tensor) + + +def thaw_tensor(tensor): + """HMath.Tensor.Mutable.thawTensor: original dtype and failure conditions.""" + return _invoke("thawTensor", tensor) + + +def freeze_tensor(tensor): + """HMath.Tensor.Mutable.freezeTensor: original dtype and failure conditions.""" + return _invoke("freezeTensor", tensor) + + +def mutable_shape(tensor): + """HMath.Tensor.Mutable.mutableShape: original dtype and failure conditions.""" + return _invoke("mutableShape", tensor) + + +def read_mutable(tensor, coordinates): + """HMath.Tensor.Mutable.readMutable: original dtype and failure conditions.""" + return _invoke("readMutable", tensor, coordinates) + + +def write_mutable(tensor, coordinates, value): + """HMath.Tensor.Mutable.writeMutable: original dtype and failure conditions.""" + return _invoke("writeMutable", tensor, coordinates, value) + + +def slice_mutable(axis, start, count, step, tensor): + """HMath.Tensor.Mutable.sliceMutable: original dtype and failure conditions.""" + return _invoke("sliceMutable", axis, start, count, step, tensor) + + +def transpose_mutable(tensor): + """HMath.Tensor.Mutable.transposeMutable: original dtype and failure conditions.""" + return _invoke("transposeMutable", tensor) + + +__all__ = [ + "CPU", + "BorrowedBuffer", + "ColumnMajor", + "Device", + "Layout", + "MutableTensor", + "RowMajor", + "Strided", + "Tensor", + "TensorDouble", + "TensorGraph", + "argmax", + "argmin", + "argsort", + "batched_matmul", + "boolean_index", + "broadcast_to", + "chunk_tensor", + "concatenate", + "contiguous", + "cumulative_product", + "cumulative_sum", + "deserialize_tensor", + "einsum", + "element_type", + "evaluate_graph", + "expand", + "fancy_index", + "flatten_tensor", + "flip_tensor", + "freeze_tensor", + "gather", + "index_tensor", + "input_graph", + "is_contiguous", + "map_graph", + "map_tensor", + "masked_fill", + "masked_select", + "max_axes", + "mean_axes", + "min_axes", + "modify_mutable", + "move_axis", + "mutable_alignment", + "mutable_shape", + "new_mutable", + "nonzero", + "norm_axes", + "numel", + "pad_tensor", + "permute", + "product_axes", + "promote_tensor", + "read_mutable", + "repeat_tensor", + "reshape_tensor", + "roll", + "rotate", + "scatter", + "scatter_add", + "serialize_tensor", + "slice_mutable", + "slice_tensor", + "sort_tensor", + "split_tensor", + "squeeze", + "stack", + "sum_axes", + "swap_axes", + "tensor", + "tensor_add", + "tensor_and", + "tensor_arange", + "tensor_column_major", + "tensor_device", + "tensor_divide", + "tensor_dtype", + "tensor_equal", + "tensor_full", + "tensor_kronecker", + "tensor_layout", + "tensor_less", + "tensor_linspace", + "tensor_logspace", + "tensor_multiply", + "tensor_not", + "tensor_offset", + "tensor_ones", + "tensor_or", + "tensor_random", + "tensor_shape", + "tensor_strides", + "tensor_subtract", + "tensor_values", + "tensor_zeros", + "tensordot", + "thaw_tensor", + "tile", + "topk", + "transpose_mutable", + "transpose_tensor", + "unique", + "unsqueeze", + "variance_axes", + "where_tensor", + "with_mutable_buffer", + "write_mutable", + "zip_graph", + "zip_tensor", +] +# END GENERATED diff --git a/bindings/python/_hmath_native/_tensor_object.py b/bindings/python/_hmath_native/_tensor_object.py new file mode 100644 index 0000000..5aa3ed3 --- /dev/null +++ b/bindings/python/_hmath_native/_tensor_object.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Shared owners for the original boxed Tensor, its graphs and pinned views.""" + +import ctypes as C + +from ._value import Value, register + + +def _call(name, *arguments, **keywords): + from . import _tensor_core + + return getattr(_tensor_core, name)(*arguments, **keywords) + + +class Tensor(Value): + """Original immutable Haskell tensor, preserving dtype and strided views.""" + + def __init__(self, shape, values, dtype="float64", *, column_major=False): + result = _call( + "tensor_column_major" if column_major else "tensor", + shape, + values, + dtype=dtype, + ) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + @property + def shape(self): + return _call("tensor_shape", self) + + @property + def strides(self): + return _call("tensor_strides", self) + + @property + def offset(self): + return _call("tensor_offset", self) + + @property + def values(self): + return _call("tensor_values", self) + + @property + def type_name(self): + return _call("tensor_dtype", self) + + @property + def dtype_code(self): + return self.info[1] + + @property + def element_type(self): + return _call("element_type", self) + + @property + def layout(self): + return _call("tensor_layout", self) + + @property + def device(self): + return _call("tensor_device", self) + + @property + def numel(self): + return _call("numel", self) + + @property + def is_contiguous(self): + return _call("is_contiguous", self) + + def to_list(self): + return self.values + + def __eq__(self, other): + if not isinstance(other, Tensor): + return NotImplemented + return _call("_equal_tensor", self, other) + + __hash__ = None + + +class TensorDouble(Tensor): + """Original Tensor Double; shared directly with the Image API's kind161.""" + + +class TensorGraph(Value): + """Lazy original TensorGraph. Owns deferred callback references transitively.""" + + def evaluate(self): + return _call("evaluate_graph", self) + + +class MutableTensor(Value): + """Original pinned mutable view; synchronize concurrent writes externally.""" + + @property + def shape(self): + return _call("mutable_shape", self) + + def read(self, coordinates): + return _call("read_mutable", self, coordinates) + + def write(self, coordinates, value): + return _call("write_mutable", self, coordinates, value) + + def freeze(self): + return _call("freeze_tensor", self) + + +register(161, TensorDouble) +register(270, Tensor) +register(271, TensorGraph) +register(272, MutableTensor) diff --git a/bindings/python/_hmath_native/_timeseries_base.py b/bindings/python/_hmath_native/_timeseries_base.py new file mode 100644 index 0000000..b64d7c3 --- /dev/null +++ b/bindings/python/_hmath_native/_timeseries_base.py @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Representation-only preparation for original TimeSeries inputs.""" + +from ._graph_base import _prepare +from ._value import decode, invoke + + +def _invoke(symbol, specifications, arguments): + temporary = [] + prepared = [] + try: + for specification, argument in zip(specifications, arguments): + if specification == ["OptimizeOptions"]: + from ._optimization_all import _typed + + value = _typed(argument, "OptimizeOptions") + temporary.append(value) + prepared.append(value) + else: + prepared.append(_prepare(specification, argument)) + return decode(invoke(symbol, *prepared)) + finally: + for value in temporary: + value.close() diff --git a/bindings/python/_hmath_native/_units_base.py b/bindings/python/_hmath_native/_units_base.py new file mode 100644 index 0000000..0471fd1 --- /dev/null +++ b/bindings/python/_hmath_native/_units_base.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lifetime and exact scalar representations for the original Units API.""" + +import ctypes as C + +from . import _value as V + + +class _UnitsValue(V.Value): + def __eq__(self, other): + if not isinstance(other, type(self)): + return NotImplemented + return V.decode(V.invoke("hmath_units_value_equal", self, other)) + + __hash__ = None + + def _initialize(self, symbol, types, *args): + result = _call(symbol, types, *args) + self._ptr, self._lock, self._owners = result._ptr, result._lock, result._owners + result._ptr, result._owners = C.c_void_p(), () + + +class Dimension(_UnitsValue): + """Nine exact dimensional exponents; source constructor validation applies.""" + + def __init__(self, exponents): + self._initialize("hmath_units_value_dimension", ["[Integer]"], exponents) + + @property + def exponents(self): + return _call("hmath_units_value_dimension_exponents", ["Dimension"], self) + + +class Unit(_UnitsValue): + """Exact affine conversion SI=value*scale+offset.""" + + def __init__(self, name, dimension, scale, offset): + self._initialize( + "hmath_units_value_unit", + ["String", "Dimension", "Rational", "Rational"], + name, + dimension, + scale, + offset, + ) + + @property + def name(self): + return _call("hmath_units_value_unit_name", ["Unit"], self) + + @property + def dimension(self): + return _call("hmath_units_value_unit_dimension", ["Unit"], self) + + @property + def scale(self): + return _call("hmath_units_value_unit_scale", ["Unit"], self) + + @property + def offset(self): + return _call("hmath_units_value_unit_offset", ["Unit"], self) + + +class Quantity(_UnitsValue): + """Exact SI value and dimensional/absolute-temperature semantics.""" + + def __init__(self, unit, value): + self._initialize( + "hmath_units_value_quantity", ["Unit", "Rational"], unit, value + ) + + @property + def dimension(self): + return _call("hmath_units_value_quantity_dimension", ["Quantity"], self) + + @property + def si_value(self): + return _call("hmath_units_value_si_value", ["Quantity"], self) + + +class SIPrefix(_UnitsValue): + """Original SI-prefix record, including unrestricted constructor text.""" + + def __init__(self, name, symbol, exponent): + self._initialize( + "hmath_units_value_si_prefix", + ["String", "String", "Int"], + name, + symbol, + exponent, + ) + + @property + def name(self): + return _call("hmath_units_value_prefix_name", ["SIPrefix"], self) + + @property + def symbol(self): + return _call("hmath_units_value_prefix_symbol", ["SIPrefix"], self) + + @property + def exponent(self): + return _call("hmath_units_value_prefix_exponent", ["SIPrefix"], self) + + +for _kind, _owner in [(68, Dimension), (69, Unit), (70, Quantity), (71, SIPrefix)]: + V.register(_kind, _owner) + + +def _call(symbol, types, *arguments): + converted = [] + owners = [] + try: + for typ, value in zip(types, arguments): + if typ in ("Rational", "Integer"): + item = ( + value.clone() + if isinstance(value, V.Value) + else V.scalar(value, "rational" if typ == "Rational" else "integer") + ) + converted.append(item) + owners.append(item) + elif typ == "[Integer]": + items = [] + for number in value: + item = ( + number.clone() + if isinstance(number, V.Value) + else V.scalar(number, "integer") + ) + items.append(item) + owners.append(item) + converted.append(items) + else: + converted.append(value) + return V.decode(V.invoke(symbol, *converted)) + finally: + for owner in owners: + owner.close() diff --git a/bindings/python/_hmath_native/_value.py b/bindings/python/_hmath_native/_value.py new file mode 100644 index 0000000..8c2450d --- /dev/null +++ b/bindings/python/_hmath_native/_value.py @@ -0,0 +1,424 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Owned, lossless scalar/container transport for structured HMath APIs. + +This module implements representation and lifetime only. Domain arithmetic lives +in the original Haskell modules. Opaque domains register their Python owner or +decoder rather than implementing an alternate numerical algorithm. +""" + +import ctypes as C +import numbers +import operator +import sys +import threading +from contextlib import ExitStack +from fractions import Fraction + +from ._numeric import _decimal, _integer + +DTYPES = { + "float64": 0, + "float32": 1, + "integer": 2, + "rational": 3, + "complex128": 4, + "complex64": 5, + "int8": 6, + "int16": 7, + "int32": 8, + "int64": 9, + "uint8": 10, + "uint16": 11, + "uint32": 12, + "uint64": 13, + "intp": 14, + "uintp": 15, +} +DTYPE_NAMES = {value: key for key, value in DTYPES.items()} +_REGISTRY = {} +_SCALAR_REGISTRY = {} +_ENCODERS = [] + + +def api(name, result, *types): + import hmath + + return C.CFUNCTYPE(result, *types)((name, hmath._lib)) + + +def register(kind, owner_or_decoder): + """Register an opaque Value subclass or a consuming Value decoder.""" + if kind < 6 or kind == 10: + raise ValueError("kind is reserved for common value transport") + if kind in _REGISTRY and _REGISTRY[kind] is not owner_or_decoder: + raise ValueError("opaque value kind already registered") + _REGISTRY[kind] = owner_or_decoder + + +def register_scalar(dtype, owner_or_decoder): + """Register a consuming decoder/owner for a structured scalar dtype.""" + if dtype in DTYPE_NAMES: + raise ValueError("primitive scalar dtype already has a decoder") + if dtype in _SCALAR_REGISTRY and _SCALAR_REGISTRY[dtype] is not owner_or_decoder: + raise ValueError("structured scalar dtype already registered") + _SCALAR_REGISTRY[dtype] = owner_or_decoder + + +def register_encoder(type_, encoder): + """Register a foreign native owner (e.g. Matrix) without import cycles.""" + if any(existing is type_ for existing, _ in _ENCODERS): + raise ValueError("value encoder already registered") + _ENCODERS.append((type_, encoder)) + + +class Value: + @classmethod + def _adopt(cls, pointer=None, owners=()): + result = object.__new__(cls) + result._ptr = ( + C.c_void_p() + if pointer is None + else pointer + if isinstance(pointer, C.c_void_p) + else C.c_void_p(pointer) + ) + result._lock = threading.RLock() + result._owners = tuple(owners) + return result + + @property + def info(self): + import hmath + + kind, dtype, count = C.c_int(), C.c_int(), C.c_size_t() + with self._lock: + if not self._ptr: + raise ValueError("value is closed") + hmath._check( + api( + "hmath_value_info", + C.c_int, + C.c_void_p, + C.POINTER(C.c_int), + C.POINTER(C.c_int), + C.POINTER(C.c_size_t), + )(self._ptr, C.byref(kind), C.byref(dtype), C.byref(count)) + ) + return kind.value, dtype.value, count.value + + @property + def dtype(self): + return DTYPE_NAMES.get(self.info[1]) + + def clone(self): + result = Value._adopt() + with self._lock: + if not self._ptr: + raise ValueError("value is closed") + api("hmath_value_retain", None, C.c_void_p)(self._ptr) + result._ptr = C.c_void_p(self._ptr.value) + result._owners = self._owners + return result + + def close(self): + with self._lock: + if self._ptr: + api("hmath_value_release", None, C.c_void_p)(self._ptr) + self._ptr = C.c_void_p() + self._owners = () + + def __enter__(self): + with self._lock: + if not self._ptr: + raise ValueError("value is closed") + return self + + def __exit__(self, *_): + self.close() + + def __del__(self, _sys=sys): + # Python no longer supports module imports once interpreter teardown + # clears meta_path; the process reclaims remaining native owners. + if _sys.meta_path is None: + return + if getattr(self, "_ptr", None): + self.close() + + def decode(self): + """Consume this reference into a scalar/container/domain owner.""" + return decode(self) + + def item(self, index): + import hmath + + index = operator.index(index) + if ( + not -(1 << (C.sizeof(C.c_ssize_t) * 8 - 1)) + <= index + < (1 << (C.sizeof(C.c_ssize_t) * 8 - 1)) + ): + raise OverflowError("index does not fit Haskell Int") + result = Value._adopt() + with self._lock: + if not self._ptr: + raise ValueError("value is closed") + result._owners = self._owners + hmath._check( + api( + "hmath_value_item", + C.c_int, + C.c_void_p, + C.c_void_p, + C.c_ssize_t, + C.POINTER(C.c_void_p), + )(None, self._ptr, index, C.byref(result._ptr)) + ) + return result + + +def borrow(pointer, owners=()): + """Acquire an owned reference from a C callback's borrowed Value pointer.""" + if not pointer: + raise ValueError("cannot retain a NULL borrowed value") + result = Value._adopt(pointer, owners) + api("hmath_value_retain", None, C.c_void_p)(result._ptr) + return result + + +def _create(symbol, types=(), arguments=(), owners=()): + import hmath + + result = Value._adopt(owners=owners) + function = api(symbol, C.c_int, C.c_void_p, *types, C.POINTER(C.c_void_p)) + hmath.initialize() + hmath._check(function(None, *arguments, C.byref(result._ptr))) + return result + + +def scalar(value, dtype=None): + """Encode one explicit standard coefficient without an FP intermediary.""" + if dtype is None: + native = getattr(getattr(value, "dtype", None), "name", None) + if native is not None: + if native not in DTYPES: + raise TypeError("unsupported native scalar dtype") + dtype = native + elif isinstance(value, Fraction): + dtype = "rational" + elif isinstance(value, numbers.Integral): + dtype = "integer" + elif isinstance(value, numbers.Real): + dtype = "float64" + elif isinstance(value, numbers.Complex): + dtype = "complex128" + else: + raise TypeError("unsupported scalar representation") + if dtype not in DTYPES: + raise ValueError("unsupported standard coefficient dtype") + if dtype in ("float32", "float64"): + real = C.c_float if dtype == "float32" else C.c_double + return _create( + "hmath_value_f32" if real is C.c_float else "hmath_value_f64", + [real], + [value], + ) + if dtype in ("complex64", "complex128"): + value = complex(value) + real = C.c_float if dtype == "complex64" else C.c_double + return _create( + "hmath_value_complex_f32" + if real is C.c_float + else "hmath_value_complex_f64", + [real, real], + [value.real, value.imag], + ) + if dtype == "rational": + value = Fraction(value) + return _create( + "hmath_value_rational", + [C.c_char_p, C.c_char_p], + [_decimal(value.numerator), _decimal(value.denominator)], + ) + return _create( + "hmath_value_integral", [C.c_int, C.c_char_p], [DTYPES[dtype], _decimal(value)] + ) + + +def encode(value): + """Encode Python's standard lossless values; typed fields can call scalar().""" + if isinstance(value, Value): + return value.clone() + for type_, encoder in _ENCODERS: + if isinstance(value, type_): + return encoder(value) + if value is None: + return _create("hmath_value_none") + if isinstance(value, bool): + return _create("hmath_value_boolean", [C.c_int], [value]) + if isinstance(value, (numbers.Number, Fraction)): + return scalar(value) + if isinstance(value, str): + points = (C.c_uint32 * len(value))(*(ord(character) for character in value)) + return _create( + "hmath_value_text", + [C.POINTER(C.c_uint32), C.c_size_t], + [points, len(value)], + ) + if isinstance(value, (list, tuple)): + items = [] + try: + for item in value: + items.append(encode(item)) + pointers = (C.c_void_p * len(items))(*(item._ptr for item in items)) + owners = tuple(owner for item in items for owner in item._owners) + return _create( + "hmath_value_tuple" if isinstance(value, tuple) else "hmath_value_list", + [C.POINTER(C.c_void_p), C.c_size_t], + [pointers, len(items)], + owners, + ) + finally: + for item in items: + item.close() + raise TypeError(f"unsupported value representation: {type(value).__name__}") + + +def invoke(symbol, *arguments, owners=()): + """Call a named ctx-first, fixed Value*-arguments, Value**-out adapter. + + All temporary inputs are closed. Callback-owner snapshots propagate to the + result so explicitly closing an input owner cannot invalidate a derived + object's borrowed callback/userdata references. + """ + import hmath + + values = [] + try: + for argument in arguments: + values.append(encode(argument)) + result = Value._adopt( + owners=tuple(owners) + + tuple(owner for value in values for owner in value._owners) + ) + function = api( + symbol, + C.c_int, + C.c_void_p, + *([C.c_void_p] * len(values)), + C.POINTER(C.c_void_p), + ) + hmath.initialize() + with ExitStack() as locks: + for value in sorted(values, key=id): + locks.enter_context(value._lock) + if not value._ptr: + raise ValueError("value is closed") + hmath._check( + function(None, *(value._ptr for value in values), C.byref(result._ptr)) + ) + return result + finally: + for value in values: + value.close() + + +def decode(value): + """Consume an owned Value, preserving opaque owners and exact scalar data.""" + import hmath + + if not isinstance(value, Value): + raise TypeError("decode requires an owned Value") + kind, dtype, count = value.info + if (kind >= 6 and kind != 10) or (kind == 1 and dtype in _SCALAR_REGISTRY): + registered = _SCALAR_REGISTRY.get(dtype) if kind == 1 else _REGISTRY.get(kind) + if registered is None: + return value + if isinstance(registered, type) and issubclass(registered, Value): + with value._lock: + result = registered._adopt(value._ptr, value._owners) + value._ptr, value._owners = C.c_void_p(), () + return result + return registered(value) + try: + with value._lock: + if not value._ptr: + raise ValueError("value is closed") + if kind == 0: + return None + if kind == 1: + if dtype in (0, 1, 4, 5): + real = C.c_float if dtype in (1, 5) else C.c_double + first, second = real(), real() + hmath._check( + api( + "hmath_value_get_f32" + if real is C.c_float + else "hmath_value_get_f64", + C.c_int, + C.c_void_p, + C.POINTER(real), + C.POINTER(real), + )(value._ptr, C.byref(first), C.byref(second)) + ) + return ( + complex(first.value, second.value) + if dtype in (4, 5) + else first.value + ) + if dtype in (2, 3) or 6 <= dtype <= 15: + first, second = C.c_void_p(), C.c_void_p() + free = api("hmath_value_string_free", None, C.c_void_p) + try: + hmath._check( + api( + "hmath_value_get_exact", + C.c_int, + C.c_void_p, + C.POINTER(C.c_void_p), + C.POINTER(C.c_void_p), + )(value._ptr, C.byref(first), C.byref(second)) + ) + numerator, denominator = ( + _integer(C.string_at(first)), + _integer(C.string_at(second)), + ) + return ( + Fraction(numerator, denominator) + if dtype == 3 + else numerator + ) + finally: + free(first) + free(second) + raise TypeError("coefficient representation has no Python decoder") + if kind in (2, 3): + result = C.c_ssize_t() if kind == 2 else C.c_int() + hmath._check( + api( + "hmath_value_get_index" + if kind == 2 + else "hmath_value_get_boolean", + C.c_int, + C.c_void_p, + C.POINTER(type(result)), + )(value._ptr, C.byref(result)) + ) + return bool(result.value) if kind == 3 else result.value + if kind in (4, 5): + result = [decode(value.item(index)) for index in range(count)] + return tuple(result) if kind == 5 else result + if kind == 10: + points = (C.c_uint32 * count)() + hmath._check( + api( + "hmath_value_get_text", + C.c_int, + C.c_void_p, + C.POINTER(C.c_uint32), + C.c_size_t, + )(value._ptr, points, count) + ) + return "".join(chr(point) for point in points) + raise TypeError("unknown value kind") + finally: + value.close() diff --git a/bindings/python/_hmath_native/algebra.py b/bindings/python/_hmath_native/algebra.py new file mode 100644 index 0000000..66f999b --- /dev/null +++ b/bindings/python/_hmath_native/algebra.py @@ -0,0 +1,512 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated original algebra interface. +from ._algebra_base import initialize, invoke +from ._foundation_base import FoundationValue, register + + +class Additive(FoundationValue): + """Original HMath.Algebra.Additive owner.""" + + _source_type = "HMath.Algebra.Additive" + + def __init__(self, argument1, *, dtype=None): + initialize( + self, "hmath_algebra_core_new_additive", [["a"]], [argument1], "old", dtype + ) + + @property + def value(self): + return get_additive(self) + + +register("HMath.Algebra.Additive", Additive) + + +class Modular(FoundationValue): + """Original HMath.Algebra.Modular owner.""" + + _source_type = "HMath.Algebra.Modular" + + +register("HMath.Algebra.Modular", Modular) + + +class FiniteField(FoundationValue): + """Original HMath.Algebra.FiniteField owner.""" + + _source_type = "HMath.Algebra.FiniteField" + + +register("HMath.Algebra.FiniteField", FiniteField) + + +class FieldElement(FoundationValue): + """Original HMath.Algebra.FieldElement owner.""" + + _source_type = "HMath.Algebra.FieldElement" + + +register("HMath.Algebra.FieldElement", FieldElement) + + +def linear_combination(argument1, argument2, *, dtype=None): + "Checked linear combination. Supply the zero vector explicitly so the empty combination retains its dimension." + return invoke( + "hmath_algebra_core_linear_combination", + [["v"], ["list", ["tuple", ["s"], ["v"]]]], + [argument1, argument2], + "module", + dtype, + ) + + +def semiring_laws(argument1, *, dtype=None): + "Exhaustive semiring identities on the supplied finite sample. This is a test utility, not a proof for types with an infinite carrier." + return invoke( + "hmath_algebra_core_semiring_laws", [["list", ["a"]]], [argument1], "old", dtype + ) + + +def ring_laws(argument1, *, dtype=None): + "Semiring laws plus additive inverses on a finite sample." + return invoke( + "hmath_algebra_core_ring_laws", [["list", ["a"]]], [argument1], "old", dtype + ) + + +def field_laws(argument1, *, dtype=None): + "Ring laws, commutative multiplication and nonzero inverses." + return invoke( + "hmath_algebra_core_field_laws", [["list", ["a"]]], [argument1], "old", dtype + ) + + +def group_laws(argument1, *, dtype=None): + "Group identities on a finite sample." + return invoke( + "hmath_algebra_core_group_laws", [["list", ["a"]]], [argument1], "old", dtype + ) + + +def module_laws(argument1, argument2, *, dtype=None): + "Check module scalar identity, composition, and both distributive laws. Vectors in the sample must belong to the same runtime space." + return invoke( + "hmath_algebra_core_module_laws", + [["list", ["s"]], ["list", ["v"]]], + [argument1, argument2], + "module", + dtype, + ) + + +def modular(argument1, argument2): + "Construct a residue, requiring m>1; arbitrary signed values are reduced." + return invoke( + "hmath_algebra_core_modular", + [["Integer"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def modular_value(argument1): + "Canonical value in [0,m)." + return invoke( + "hmath_algebra_core_modular_value", [["Modular"]], [argument1], "value" + ) + + +def modular_modulus(argument1): + "Modulus greater than one." + return invoke( + "hmath_algebra_core_modular_modulus", [["Modular"]], [argument1], "value" + ) + + +def add_modular(argument1, argument2): + "Checked residue addition." + return invoke( + "hmath_algebra_core_add_modular", + [["Modular"], ["Modular"]], + [argument1, argument2], + "value", + ) + + +def subtract_modular(argument1, argument2): + "Checked residue subtraction." + return invoke( + "hmath_algebra_core_subtract_modular", + [["Modular"], ["Modular"]], + [argument1, argument2], + "value", + ) + + +def multiply_modular(argument1, argument2): + "Checked residue multiplication." + return invoke( + "hmath_algebra_core_multiply_modular", + [["Modular"], ["Modular"]], + [argument1, argument2], + "value", + ) + + +def inverse_modular(argument1): + "Invert a unit; zero and nonunits are domain errors." + return invoke( + "hmath_algebra_core_inverse_modular", [["Modular"]], [argument1], "value" + ) + + +def power_modular(argument1, argument2): + "Integer power, with negative powers supported for units." + return invoke( + "hmath_algebra_core_power_modular", + [["Modular"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def finite_field(argument1, argument2, argument3): + "Construct GF(p^n) from an irreducible polynomial of positive degree. Primality is proven by trial division. Irreducibility uses successive Frobenius powers and polynomial gcds; n must not exceed the proof budget." + return invoke( + "hmath_algebra_core_finite_field", + [["Int"], ["Integer"], ["list", ["Integer"]]], + [argument1, argument2, argument3], + "value", + ) + + +def prime_field(argument1, argument2): + "Prime field GF(p), represented as F_p[x]/(x)." + return invoke( + "hmath_algebra_core_prime_field", + [["Int"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def field_characteristic(argument1): + "Prime characteristic p." + return invoke( + "hmath_algebra_core_field_characteristic", + [["FiniteField"]], + [argument1], + "value", + ) + + +def field_degree(argument1): + "Extension degree n." + return invoke( + "hmath_algebra_core_field_degree", [["FiniteField"]], [argument1], "value" + ) + + +def field_cardinality(argument1): + "Exact carrier size p^n." + return invoke( + "hmath_algebra_core_field_cardinality", [["FiniteField"]], [argument1], "value" + ) + + +def field_modulus(argument1): + "Ascending coefficients of the monic irreducible defining polynomial." + return invoke( + "hmath_algebra_core_field_modulus", [["FiniteField"]], [argument1], "value" + ) + + +def field_element(argument1, argument2): + "Reduce an arbitrary integer polynomial into a finite field." + return invoke( + "hmath_algebra_core_field_element", + [["FiniteField"], ["list", ["Integer"]]], + [argument1, argument2], + "value", + ) + + +def field_element_coefficients(argument1): + "Canonical ascending residue coefficients (trailing zeros removed)." + return invoke( + "hmath_algebra_core_field_element_coefficients", + [["FieldElement"]], + [argument1], + "value", + ) + + +def field_elements(argument1, argument2): + "Enumerate the complete carrier, rejecting sizes above an explicit storage budget. Enumeration is coefficient-lexicographic and deterministic." + return invoke( + "hmath_algebra_core_field_elements", + [["Int"], ["FiniteField"]], + [argument1, argument2], + "value", + ) + + +def add_field(argument1, argument2): + "Addition; different defining fields are rejected even if isomorphic." + return invoke( + "hmath_algebra_core_add_field", + [["FieldElement"], ["FieldElement"]], + [argument1, argument2], + "value", + ) + + +def negate_field(argument1): + "Additive inverse in the same field." + return invoke( + "hmath_algebra_core_negate_field", [["FieldElement"]], [argument1], "value" + ) + + +def subtract_field(argument1, argument2): + "Checked field subtraction." + return invoke( + "hmath_algebra_core_subtract_field", + [["FieldElement"], ["FieldElement"]], + [argument1, argument2], + "value", + ) + + +def multiply_field(argument1, argument2): + "Checked field multiplication, reduced modulo the defining polynomial." + return invoke( + "hmath_algebra_core_multiply_field", + [["FieldElement"], ["FieldElement"]], + [argument1, argument2], + "value", + ) + + +def inverse_field_element(argument1): + "Nonzero inverse via the finite-field identity a^(q-2)." + return invoke( + "hmath_algebra_core_inverse_field_element", + [["FieldElement"]], + [argument1], + "value", + ) + + +def power_field(argument1, argument2): + "Binary exponentiation, with inverses for negative exponents." + return invoke( + "hmath_algebra_core_power_field", + [["FieldElement"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def finite_field_laws(argument1, argument2): + "Exhaustive carrier checks for small fields, including distributivity, associativity, identities and every nonzero inverse. Budget bounds enumeration; the cubic law checks are intended for small validation fields." + return invoke( + "hmath_algebra_core_finite_field_laws", + [["Int"], ["FiniteField"]], + [argument1, argument2], + "value", + ) + + +def get_additive(argument1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed." + return invoke( + "hmath_algebra_core_get_additive", + [["Additive", ["a"]]], + [argument1], + "old", + dtype, + ) + + +def zero(*, dtype=None): + "Additive identity." + return invoke("hmath_algebra_core_zero", [], [], "old", dtype) + + +def one(*, dtype=None): + "Multiplicative identity." + return invoke("hmath_algebra_core_one", [], [], "old", dtype) + + +def plus(argument1, argument2, *, dtype=None): + "Semiring addition." + return invoke( + "hmath_algebra_core_plus", [["a"], ["a"]], [argument1, argument2], "old", dtype + ) + + +def times(argument1, argument2, *, dtype=None): + "Semiring multiplication." + return invoke( + "hmath_algebra_core_times", [["a"], ["a"]], [argument1, argument2], "old", dtype + ) + + +def negate_ring(argument1, *, dtype=None): + "Additive inverse." + return invoke("hmath_algebra_core_negate_ring", [["a"]], [argument1], "old", dtype) + + +def inverse_field(argument1, *, dtype=None): + "Multiplicative inverse; zero returns a domain error." + return invoke( + "hmath_algebra_core_inverse_field", [["a"]], [argument1], "old", dtype + ) + + +def group_identity(*, dtype=None): + "Group identity." + return invoke("hmath_algebra_core_group_identity", [], [], "old", dtype) + + +def group_combine(argument1, argument2, *, dtype=None): + "Group operation, not necessarily commutative." + return invoke( + "hmath_algebra_core_group_combine", + [["Additive", ["a"]], ["Additive", ["a"]]], + [argument1, argument2], + "old", + dtype, + ) + + +def group_inverse(argument1, *, dtype=None): + "Two-sided inverse." + return invoke( + "hmath_algebra_core_group_inverse", + [["Additive", ["a"]]], + [argument1], + "old", + dtype, + ) + + +def module_scale(argument1, argument2, *, dtype=None): + "Scalar action." + return invoke( + "hmath_algebra_core_module_scale", + [["a"], ["list", ["a"]]], + [argument1, argument2], + "module", + dtype, + ) + + +def module_add(argument1, argument2, *, dtype=None): + "Addition, rejecting incompatible runtime shapes." + return invoke( + "hmath_algebra_core_module_add", + [["list", ["a"]], ["list", ["a"]]], + [argument1, argument2], + "module", + dtype, + ) + + +class Semiring: + """Original HMath.Algebra.Semiring interface; methods select supported source instances.""" + + zero = staticmethod(zero) + one = staticmethod(one) + plus = staticmethod(plus) + times = staticmethod(times) + + +class Ring: + """Original HMath.Algebra.Ring interface; methods select supported source instances.""" + + negate_ring = staticmethod(negate_ring) + + +class Field: + """Original HMath.Algebra.Field interface; methods select supported source instances.""" + + inverse_field = staticmethod(inverse_field) + + +class Group: + """Original HMath.Algebra.Group interface; methods select supported source instances.""" + + group_identity = staticmethod(group_identity) + group_combine = staticmethod(group_combine) + group_inverse = staticmethod(group_inverse) + + +class Module: + """Original HMath.Algebra.Module interface; methods select supported source instances.""" + + module_scale = staticmethod(module_scale) + module_add = staticmethod(module_add) + + +class VectorSpace: + """Original HMath.Algebra.VectorSpace interface; methods select supported source instances.""" + + pass + + +__all__ = [ + "Additive", + "Field", + "FieldElement", + "FiniteField", + "Group", + "Modular", + "Module", + "Ring", + "Semiring", + "VectorSpace", + "add_field", + "add_modular", + "field_cardinality", + "field_characteristic", + "field_degree", + "field_element", + "field_element_coefficients", + "field_elements", + "field_laws", + "field_modulus", + "finite_field", + "finite_field_laws", + "get_additive", + "group_combine", + "group_identity", + "group_inverse", + "group_laws", + "inverse_field", + "inverse_field_element", + "inverse_modular", + "linear_combination", + "modular", + "modular_modulus", + "modular_value", + "module_add", + "module_laws", + "module_scale", + "multiply_field", + "multiply_modular", + "negate_field", + "negate_ring", + "one", + "plus", + "power_field", + "power_modular", + "prime_field", + "ring_laws", + "semiring_laws", + "subtract_field", + "subtract_modular", + "times", + "zero", +] diff --git a/bindings/python/_hmath_native/algebra_api.py b/bindings/python/_hmath_native/algebra_api.py new file mode 100644 index 0000000..3929a45 --- /dev/null +++ b/bindings/python/_hmath_native/algebra_api.py @@ -0,0 +1,318 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated original algebra interface. +from ._algebra_base import initialize, invoke +from ._foundation_base import FoundationValue, register + + +class Exact(FoundationValue): + """Original HMath.API.Algebra.Exact owner.""" + + _source_type = "HMath.API.Algebra.Exact" + + def __init__(self, argument1, *, dtype=None): + initialize( + self, + "hmath_algebra_api_new_exact", + [["Rational"]], + [argument1], + "value", + dtype, + ) + + @property + def value(self): + return get_exact(self) + + @property + def element_type(self): + return exact_element_type() + + +register("HMath.API.Algebra.Exact", Exact) + + +def horner(argument1, argument2, *, dtype=None): + "Coefficients are highest degree first; an empty polynomial is zero." + return invoke( + "hmath_algebra_api_horner", + [["list", ["a"]], ["a"]], + [argument1, argument2], + "api", + dtype, + ) + + +def inner_product(argument1, argument2, *, dtype=None): + "Return sum(conjugate a[i] * b[i]) using the Scalar and Ring operations. Equal list lengths are required; mismatch returns VectorLengthMismatch. Empty lists give the ring zero; instance arithmetic controls precision/overflow." + return invoke( + "hmath_algebra_api_inner_product", + [["list", ["a"]], ["list", ["a"]]], + [argument1, argument2], + "api", + dtype, + ) + + +def get_exact(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return invoke("hmath_algebra_api_get_exact", [["Exact"]], [argument1], "value") + + +def zero(*, dtype=None): + "Additive identity of this ring." + return invoke("hmath_algebra_api_zero", [], [], "api", dtype) + + +def one(*, dtype=None): + "Multiplicative identity of this ring." + return invoke("hmath_algebra_api_one", [], [], "api", dtype) + + +def plus(argument1, argument2, *, dtype=None): + "Add two ring elements; exact instances obey ring laws and IEEE instances retain host rounding." + return invoke( + "hmath_algebra_api_plus", [["a"], ["a"]], [argument1, argument2], "api", dtype + ) + + +def times(argument1, argument2, *, dtype=None): + "Multiply two ring elements using the instance arithmetic." + return invoke( + "hmath_algebra_api_times", [["a"], ["a"]], [argument1, argument2], "api", dtype + ) + + +def negative(argument1, *, dtype=None): + "Return the additive inverse of a ring element." + return invoke("hmath_algebra_api_negative", [["a"]], [argument1], "api", dtype) + + +def integer(argument1, *, dtype=None): + "Embed an unbounded Integer into the domain; instance representation/rounding rules apply." + return invoke("hmath_algebra_api_integer", [["Integer"]], [argument1], "api", dtype) + + +def invert(argument1, *, dtype=None): + "Return multiplicative inverse of a nonzero domain element, or Left MathError for zero/invalid/nonrepresentable inverse." + return invoke("hmath_algebra_api_invert", [["a"]], [argument1], "api", dtype) + + +def conjugate_scalar(argument1, *, dtype=None): + "Return scalar conjugate; real/exact instances use identity and complex instances conjugate imaginary components." + return invoke( + "hmath_algebra_api_conjugate_scalar", [["a"]], [argument1], "api", dtype + ) + + +def machine_epsilon(*, dtype=None): + "Given a type proxy, return floating precision epsilon as Double (2^-52 for Double,2^-23 for Float)." + return invoke("hmath_algebra_api_machine_epsilon", [], [], "api", dtype) + + +def finite_scalar(argument1, *, dtype=None): + "Test whether all real/complex components are finite for this instance." + return invoke("hmath_algebra_api_finite_scalar", [["a"]], [argument1], "api", dtype) + + +def rational(argument1, *, dtype=None): + "Convert exact Rational into the domain, returning Left MathError if it cannot be represented under the instance contract." + return invoke( + "hmath_algebra_api_rational", [["Rational"]], [argument1], "api", dtype + ) + + +def matrix_dimensions(argument1): + "Return logical (rows,columns) of a matrix-like container." + return invoke( + "hmath_algebra_api_matrix_dimensions", [["Matrix", ["a"]]], [argument1], "value" + ) + + +def matrix_elements(argument1): + "Return matrix elements in logical row-major order." + return invoke( + "hmath_algebra_api_matrix_elements", [["Matrix", ["a"]]], [argument1], "value" + ) + + +def matrix_construct(argument1, argument2, argument3, *, dtype=None): + "Given rows,columns,flat row-major elements, construct a matrix-like value or return checked shape/count failure." + return invoke( + "hmath_algebra_api_matrix_construct", + [["Int"], ["Int"], ["list", ["a"]]], + [argument1, argument2, argument3], + "typed", + dtype, + ) + + +def tensor_dimensions(argument1): + "Return tensor-like dimensions in axis order; [] denotes scalar." + return invoke( + "hmath_algebra_api_tensor_dimensions", [["Tensor", ["a"]]], [argument1], "value" + ) + + +def tensor_elements(argument1): + "Return tensor-like elements in logical row-major coordinate order." + return invoke( + "hmath_algebra_api_tensor_elements", [["Tensor", ["a"]]], [argument1], "value" + ) + + +def tensor_construct(argument1, argument2, *, dtype=None): + "Given dimensions then flat values, construct a tensor-like value or return shape/count failure." + return invoke( + "hmath_algebra_api_tensor_construct", + [["list", ["Int"]], ["list", ["a"]]], + [argument1, argument2], + "typed", + dtype, + ) + + +def vector_plus(argument1, argument2, *, dtype=None): + "Add identically shaped vector-space values, returning checked dimension errors on mismatch." + return invoke( + "hmath_algebra_api_vector_plus", + [["Vector", ["a"]], ["Vector", ["a"]]], + [argument1, argument2], + "typed", + dtype, + ) + + +def vector_scale(argument1, argument2, *, dtype=None): + "Given scalar then vector-space value, return its coordinatewise scalar multiple." + return invoke( + "hmath_algebra_api_vector_scale", + [["a"], ["Vector", ["a"]]], + [argument1, argument2], + "typed", + dtype, + ) + + +def differential(argument1): + "Extract associated differential; the Dual instance returns its tangent component." + return invoke( + "hmath_algebra_api_differential", [["Dual", ["a"]]], [argument1], "value" + ) + + +class Ring: + """Original HMath.API.Algebra.Ring interface; methods select supported source instances.""" + + zero = staticmethod(zero) + one = staticmethod(one) + plus = staticmethod(plus) + times = staticmethod(times) + negative = staticmethod(negative) + integer = staticmethod(integer) + + +class Field: + """Original HMath.API.Algebra.Field interface; methods select supported source instances.""" + + invert = staticmethod(invert) + + +class Scalar: + """Original HMath.API.Algebra.Scalar interface; methods select supported source instances.""" + + conjugate_scalar = staticmethod(conjugate_scalar) + + +class FloatingPoint: + """Original HMath.API.Algebra.FloatingPoint interface; methods select supported source instances.""" + + machine_epsilon = staticmethod(machine_epsilon) + finite_scalar = staticmethod(finite_scalar) + + +class Numeric: + """Original HMath.API.Algebra.Numeric interface; methods select supported source instances.""" + + rational = staticmethod(rational) + + +class MatrixLike: + """Original HMath.API.Algebra.MatrixLike interface; methods select supported source instances.""" + + matrix_dimensions = staticmethod(matrix_dimensions) + matrix_elements = staticmethod(matrix_elements) + matrix_construct = staticmethod(matrix_construct) + + +class TensorLike: + """Original HMath.API.Algebra.TensorLike interface; methods select supported source instances.""" + + tensor_dimensions = staticmethod(tensor_dimensions) + tensor_elements = staticmethod(tensor_elements) + tensor_construct = staticmethod(tensor_construct) + + +class VectorSpace: + """Original HMath.API.Algebra.VectorSpace interface; methods select supported source instances.""" + + vector_plus = staticmethod(vector_plus) + vector_scale = staticmethod(vector_scale) + + +class Differentiable: + """Original HMath.API.Algebra.Differentiable interface; methods select supported source instances.""" + + differential = staticmethod(differential) + + +class Differential: + """Original HMath.API.Algebra.Differential interface; methods select supported source instances.""" + + pass + + +def exact_element_type(): + """Typed structural Exact element prototype for ordinary Tensor/Vector APIs.""" + from ._value import decode + from ._value import invoke as native_invoke + + return decode(native_invoke("hmath_algebra_api_exact_element_type")) + + +__all__ = [ + "Differentiable", + "Differential", + "Exact", + "Field", + "FloatingPoint", + "MatrixLike", + "Numeric", + "Ring", + "Scalar", + "TensorLike", + "VectorSpace", + "conjugate_scalar", + "differential", + "exact_element_type", + "finite_scalar", + "get_exact", + "horner", + "inner_product", + "integer", + "invert", + "machine_epsilon", + "matrix_construct", + "matrix_dimensions", + "matrix_elements", + "negative", + "one", + "plus", + "rational", + "tensor_construct", + "tensor_dimensions", + "tensor_elements", + "times", + "vector_plus", + "vector_scale", + "zero", +] diff --git a/bindings/python/_hmath_native/algorithm_values.py b/bindings/python/_hmath_native/algorithm_values.py new file mode 100644 index 0000000..457dc63 --- /dev/null +++ b/bindings/python/_hmath_native/algorithm_values.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_foundation_bindings.py. +"""Original HMath.Algorithms public functions and immutable values.""" + +from ._foundation_base import _invoke + + +def binary_search(argument1, argument2, *, prototype=None): + "Given target and ascending list, return Just the first matching zero-based index or Nothing if absent. Reject unsorted input. Example: binarySearch 2 [1,2,2] == Right (Just 1)." + return _invoke( + "hmath_foundation_algorithms_binary_search", + [["a"], ["list", ["a"]]], + [argument1, argument2], + "ordered", + prototype=prototype, + ) + + +def interpolation_search(argument1, argument2): + "Search ascending Integer values using value-based interpolation, returning the first matching index or Nothing. Reject unsorted input. Example: interpolationSearch 20 [10,20,30] == Right (Just 1)." + return _invoke( + "hmath_foundation_algorithms_interpolation_search", + [["Integer"], ["list", ["Integer"]]], + [argument1, argument2], + "value", + ) + + +def exponential_search(argument1, argument2, *, prototype=None): + "Given a target and ascending finite list, grow a search range then find a matching index or Nothing. Reject unsorted input. The implementation returns a matching index without a general first-duplicate guarantee." + return _invoke( + "hmath_foundation_algorithms_exponential_search", + [["a"], ["list", ["a"]]], + [argument1, argument2], + "ordered", + prototype=prototype, + ) + + +def ternary_search(argument1, argument2, argument3, argument4): + "Fixed-iteration minimization of a unimodal finite function on [lo,hi]. Returns the final bracket; unimodality is a caller precondition." + return _invoke( + "hmath_foundation_algorithms_ternary_search", + [["Int"], ["function", ["Double"], ["Double"]], ["Double"], ["Double"]], + [argument1, argument2, argument3, argument4], + "value", + ) + + +def numeric_groups(argument1, *, prototype=None): + "Sort ascending and return each distinct value paired with its frequency. Example: numericGroups [2,1,2] == [(1,1),(2,2)]." + return _invoke( + "hmath_foundation_algorithms_numeric_groups", + [["list", ["a"]]], + [argument1], + "ordered", + prototype=prototype, + ) + + +def run_length_encode(argument1): + "Encode adjacent equal runs as (value,count), preserving run order without sorting. Example: runLengthEncode [1,1,2,1] == [(1,2),(2,1),(1,1)]." + return _invoke( + "hmath_foundation_algorithms_run_length_encode", + [["list", ["a"]]], + [argument1], + "equality", + ) + + +def run_length_decode(argument1, argument2): + "Given maximum output length then (value,count) runs, expand runs. Negative budget/count fails; output beyond the budget returns NonConvergence before allocation. Zero-length runs are allowed." + return _invoke( + "hmath_foundation_algorithms_run_length_decode", + [["Int"], ["list", ["tuple", ["a"], ["Int"]]]], + [argument1, argument2], + "value", + ) + + +def coordinate_compression(argument1, *, prototype=None): + "Return sorted unique keys and zero-based ranks for the original input order. Example: coordinateCompression [8,2,8] == ([2,8],[1,0,1])." + return _invoke( + "hmath_foundation_algorithms_coordinate_compression", + [["list", ["a"]]], + [argument1], + "ordered", + prototype=prototype, + ) + + +def interval_sweep(argument1): + "Half-open interval union length and peak overlap; zero-length intervals contribute neither. End events precede starts at the same coordinate." + return _invoke( + "hmath_foundation_algorithms_interval_sweep", + [["list", ["tuple", ["Integer"], ["Integer"]]]], + [argument1], + "value", + ) + + +def divide_conquer_dp(argument1, argument2): + "One DP layer `next[j] = min_{0<=k128, or negative exponent." + return _invoke( + "hmath_foundation_algorithms_integer_matrix_power", + [["list", ["list", ["Integer"]]], ["Integer"]], + [argument1, argument2], + "value", + ) + + +__all__ = [ + "binary_search", + "coordinate_compression", + "divide_conquer_dp", + "exponential_search", + "integer_matrix_power", + "interpolation_search", + "interval_sweep", + "memoized_dp", + "numeric_groups", + "run_length_decode", + "run_length_encode", + "tabulate_dp", + "ternary_search", +] diff --git a/bindings/python/_hmath_native/algorithms.py b/bindings/python/_hmath_native/algorithms.py new file mode 100644 index 0000000..e9f4222 --- /dev/null +++ b/bindings/python/_hmath_native/algorithms.py @@ -0,0 +1,286 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def lower_bound(x, xs, *, dtype='float64'): + """Call HMath.Algorithms.lowerBound; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_lower_bound', + ['f', 'fs'], + 'i', + [x, xs], + dtype, + 0, + ) + + +def upper_bound(x, xs, *, dtype='float64'): + """Call HMath.Algorithms.upperBound; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_upper_bound', + ['f', 'fs'], + 'i', + [x, xs], + dtype, + 0, + ) + + +def quickselect(k, xs, *, dtype='float64'): + """Call HMath.Algorithms.quickselect; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_quickselect', + ['i', 'fs'], + 'f', + [k, xs], + dtype, + 0, + ) + + +def introselect(k, xs, *, dtype='float64'): + """Call HMath.Algorithms.introselect; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_introselect', + ['i', 'fs'], + 'f', + [k, xs], + dtype, + 0, + ) + + +def partial_sort(argument1, argument2, *, dtype='float64'): + """Call HMath.Algorithms.partialSort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_partial_sort', + ['i', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def merge_sort(argument1, *, dtype='float64'): + """Call HMath.Algorithms.mergeSort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_merge_sort', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def quicksort(argument1, *, dtype='float64'): + """Call HMath.Algorithms.quicksort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_quicksort', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def heapsort(argument1, *, dtype='float64'): + """Call HMath.Algorithms.heapsort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_heapsort', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def introsort(argument1, *, dtype='float64'): + """Call HMath.Algorithms.introsort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_introsort', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def counting_sort(budget, xs): + """Call HMath.Algorithms.countingSort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_counting_sort', + ['i', 'is'], + 'id', + [budget, xs], + None, + 0, + ) + + +def radix_sort(argument1): + """Call HMath.Algorithms.radixSort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_radix_sort', + ['zs'], + 'zd', + [argument1], + None, + 0, + ) + + +def bucket_sort(buckets, xs, *, dtype='float64'): + """Call HMath.Algorithms.bucketSort; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_algorithms_bucket_sort', + ['i', 'fs'], + 'fd', + [buckets, xs], + dtype, + 0, + ) + + +def argsort(argument1, *, dtype='float64'): + """Call HMath.Algorithms.argsort; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_argsort', + ['fs'], + 'id', + [argument1], + dtype, + 0, + ) + + +def top_k(argument1, argument2, *, dtype='float64'): + """Call HMath.Algorithms.topK; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_top_k', + ['i', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def quantile_select(q, xs, *, dtype='float64'): + """Call HMath.Algorithms.quantileSelect; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_algorithms_quantile_select', + ['f', 'fs'], + 'f', + [q, xs], + dtype, + 0, + ) + + +def deduplicate(argument1, *, dtype='float64'): + """Call HMath.Algorithms.deduplicate; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_deduplicate', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def prefix_sums(argument1, *, dtype='float64'): + """Call HMath.Algorithms.prefixSums; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_prefix_sums', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def suffix_sums(argument1, *, dtype='float64'): + """Call HMath.Algorithms.suffixSums; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_suffix_sums', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def difference_array(argument1, *, dtype='float64'): + """Call HMath.Algorithms.differenceArray; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_difference_array', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def apply_differences(argument1, *, dtype='float64'): + """Call HMath.Algorithms.applyDifferences; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_apply_differences', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def binary_lift(next, steps, start): + """Call HMath.Algorithms.binaryLift; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_binary_lift', + ['is', 'z', 'i'], + 'i', + [next, steps, start], + None, + 0, + ) + + +def polynomial_hash(base, modulus, xs): + """Call HMath.Algorithms.polynomialHash; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_polynomial_hash', + ['z', 'z', 'zs'], + 'z', + [base, modulus, xs], + None, + 0, + ) + + +def rolling_hashes(base, modulus, width, xs): + """Call HMath.Algorithms.rollingHashes; preserve its argument order, result and errors.""" + return _call( + 'hmath_algorithms_rolling_hashes', + ['z', 'z', 'i', 'zs'], + 'zd', + [base, modulus, width, xs], + None, + 0, + ) + + +from .algorithm_values import * diff --git a/bindings/python/_hmath_native/api_algebra.py b/bindings/python/_hmath_native/api_algebra.py new file mode 100644 index 0000000..472c854 --- /dev/null +++ b/bindings/python/_hmath_native/api_algebra.py @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def inner_product(argument1, argument2, *, dtype='float64'): + """Call HMath.API.Algebra.innerProduct; preserve its argument order, result and errors.""" + return _call( + 'hmath_api_algebra_inner_product', + ['fs', 'fs'], + 'f', + [argument1, argument2], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/autodiff.py b/bindings/python/_hmath_native/autodiff.py new file mode 100644 index 0000000..02f614e --- /dev/null +++ b/bindings/python/_hmath_native/autodiff.py @@ -0,0 +1,1125 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Native Haskell AD graphs, dual arithmetic and explicit gradient state. + +Builders/rules are pure functions of their inputs. Handles are immutable; close +retained objects explicitly. Callbacks are retained transitively by graph owners. +""" + +import ctypes as C +import math +import threading +import weakref +from contextlib import ExitStack, contextmanager +from fractions import Fraction + +from ._callback_error import fill as _fill_callback_error +from ._math_error import Wire as _ErrorWire +from ._numeric import _decimal, _int, _integer + +P, Z, D, I = C.c_void_p, C.c_size_t, C.c_double, C.c_ssize_t +_callback_errors = threading.local() + + +def _api(name, *types, result=C.c_int): + import hmath + + return C.CFUNCTYPE(result, *types)(("hmath_ad_" + name, hmath._lib)) + + +def _check(code): + import hmath + + if code and getattr(_callback_errors, "error", None) is not None: + error = _callback_errors.error + del _callback_errors.error + raise error + hmath._check(code) + + +def _real(value): + try: + return float(value) + except OverflowError: + return math.inf if value >= 0 else -math.inf + + +def _owners(*values): + keepers = {id(keeper): keeper for value in values for keeper in value._keepers} + return tuple(keepers.values()) + + +@contextmanager +def _locked(*objects): + with ExitStack() as stack: + objects = sorted({id(value): value for value in objects}.values(), key=id) + for value in objects: + stack.enter_context(value._lock) + if not value._ptr: + raise ValueError("AD object is closed") + # Independent native refs and callback snapshots survive reentrant close. + snapshots = [(value._ptr, value._keepers) for value in objects] + for pointer, _ in snapshots: + _api("retain", P, result=None)(pointer) + try: + yield + finally: + for pointer, _ in snapshots: + _api("release", P, result=None)(pointer) + + +def _new(cls, name, types, args, parents=(), keepers=()): + import hmath + + hmath.initialize() + result = cls._adopt(P()) + result._keepers = _owners(*parents) + tuple(keepers) + with _locked(*parents): + _check(_api(name, P, *types, C.POINTER(P))(None, *args, C.byref(result._ptr))) + return result + + +class _Handle: + @classmethod + def _adopt(cls, pointer, keepers=()): + value = object.__new__(cls) + value._ptr, value._lock, value._keepers = ( + pointer, + threading.RLock(), + tuple(keepers), + ) + return value + + def close(self): + with self._lock: + if self._ptr: + _api("release", P, result=None)(self._ptr) + self._ptr = P() + self._keepers = () + + def __enter__(self): + with _locked(self): + return self + + def __exit__(self, *_): + self.close() + + def __del__(self): + if getattr(self, "_ptr", None): + self.close() + + def _metadata(self): + count, rank = Z(), Z() + with _locked(self): + _check( + _api("metadata", P, C.POINTER(Z), C.POINTER(Z))( + self._ptr, C.byref(count), C.byref(rank) + ) + ) + return count.value, rank.value + + +class _Arithmetic(_Handle): + def _coerce(self, value): + if isinstance(value, type(self)): + return value + if isinstance(value, _Handle): + raise TypeError("cannot mix AD handle kinds") + return constant(value) if isinstance(self, Expr) else Dual(value, 0) + + def _binary(self, other, operation, reverse=False): + other = self._coerce(other) + left, right = (other, self) if reverse else (self, other) + return _new( + type(self), + "binary", + [C.c_int, P, P], + [operation, left._ptr, right._ptr], + parents=[left, right], + ) + + def _unary(self, operation): + return _new( + type(self), "unary", [C.c_int, P], [operation, self._ptr], parents=[self] + ) + + def __add__(self, other): + return self._binary(other, 0) + + def __radd__(self, other): + return self._binary(other, 0, True) + + def __sub__(self, other): + return self._binary(other, 1) + + def __rsub__(self, other): + return self._binary(other, 1, True) + + def __mul__(self, other): + return self._binary(other, 2) + + def __rmul__(self, other): + return self._binary(other, 2, True) + + def __truediv__(self, other): + return self._binary(other, 3) + + def __rtruediv__(self, other): + return self._binary(other, 3, True) + + def __pow__(self, other): + return self._binary(other, 4) + + def __rpow__(self, other): + return self._binary(other, 4, True) + + def __neg__(self): + return self._unary(0) + + def __abs__(self): + return self._unary(1) + + +class Expr(_Arithmetic): + """Immutable scalar expression using the original Haskell Expr instances.""" + + +class Dual(_Arithmetic): + """Original nested Dual instances over explicitly typed coefficient leaves.""" + + def __init__(self, value, tangent, *, dtype=None): + import hmath + + self._ptr, self._lock, self._keepers = P(), threading.RLock(), () + hmath.initialize() + template = ( + value + if isinstance(value, Dual) + else tangent + if isinstance(tangent, Dual) + else None + ) + owned_prototype = None + if dtype is None: + if template is not None: + dtype = template.dtype + if dtype.startswith("numeric."): + owned_prototype = template.element_type + dtype = owned_prototype + else: + from ._value import Value + + if isinstance(value, Value): + dtype = value + elif isinstance(tangent, Value): + dtype = tangent + else: + dtype = ( + "complex128" + if isinstance(value, complex) or isinstance(tangent, complex) + else "float64" + ) + try: + self._initialize_pair(value, tangent, dtype, template) + finally: + if owned_prototype is not None: + owned_prototype.close() + + def _initialize_pair(self, value, tangent, dtype, template): + from . import _value as v + + if not isinstance(dtype, v.Value) and dtype not in v.DTYPES: + raise ValueError( + "Dual dtype must name a supported coefficient or provide a typed coefficient prototype" + ) + if template is not None: + value = _dual_number(value, template.depth, dtype) + tangent = _dual_number(tangent, template.depth, dtype) + self._keepers = _owners(value, tangent) + with _locked(value, tangent): + _check( + _api("dual_nested", P, P, P, C.POINTER(P))( + None, value._ptr, tangent._ptr, C.byref(self._ptr) + ) + ) + elif dtype in ("float64", "float32"): + real = D if dtype == "float64" else C.c_float + name = "dual_create" if dtype == "float64" else "dual_create_f32" + _check( + _api(name, P, real, real, C.POINTER(P))( + None, _real(value), _real(tangent), C.byref(self._ptr) + ) + ) + elif dtype == "integer": + _check( + _api("dual_create_integer", P, C.c_char_p, C.c_char_p, C.POINTER(P))( + None, _decimal(value), _decimal(tangent), C.byref(self._ptr) + ) + ) + elif dtype == "rational": + value, tangent = Fraction(value), Fraction(tangent) + _check( + _api( + "dual_create_rational", + P, + C.c_char_p, + C.c_char_p, + C.c_char_p, + C.c_char_p, + C.POINTER(P), + )( + None, + _decimal(value.numerator), + _decimal(value.denominator), + _decimal(tangent.numerator), + _decimal(tangent.denominator), + C.byref(self._ptr), + ) + ) + + else: + from ._autodiff_value import export_value + + with ( + _coefficient_leaf(value, dtype) as primal_value, + _coefficient_leaf(tangent, dtype) as tangent_value, + export_value(primal_value) as primal_handle, + export_value(tangent_value) as tangent_handle, + ): + self._keepers = _owners(primal_handle, tangent_handle) + with _locked(primal_handle, tangent_handle): + _check( + _api("dual_nested", P, P, P, C.POINTER(P))( + None, + primal_handle._ptr, + tangent_handle._ptr, + C.byref(self._ptr), + ) + ) + + @property + def depth(self): + out = Z() + with _locked(self): + _check(_api("dual_depth", P, C.POINTER(Z))(self._ptr, C.byref(out))) + return out.value + + @property + def dtype(self): + kind = C.c_int() + with _locked(self): + _check(_api("dual_kind", P, C.POINTER(C.c_int))(self._ptr, C.byref(kind))) + from ._value import DTYPE_NAMES + + return DTYPE_NAMES.get( + kind.value, + {20: "numeric.dual", 21: "numeric.quaternion"}.get( + kind.value, "unsupported" + ), + ) + + @property + def element_type(self): + """Owned exact source coefficient prototype, including numeric towers.""" + from ._autodiff_value import import_value + + current, owned = self, [] + try: + while current.depth: + first, second = Dual._adopt(P()), Dual._adopt(P()) + with _locked(current): + _check( + _api("dual_parts", P, C.POINTER(P), C.POINTER(P))( + current._ptr, C.byref(first._ptr), C.byref(second._ptr) + ) + ) + second.close() + current = first + owned.append(first) + return import_value(current) + finally: + for value in owned: + value.close() + + def _coerce(self, value): + dtype = self.dtype + if dtype.startswith("numeric."): + with self.element_type as prototype: + return _dual_number(value, self.depth, prototype) + return _dual_number(value, self.depth, dtype) + + def _part(self, index): + if self.depth == 1 and self.dtype in ("float64", "float32"): + return _copy_values(self)[index] + primal_part, tangent_part = Dual._adopt(P()), Dual._adopt(P()) + with _locked(self): + _check( + _api("dual_parts", P, C.POINTER(P), C.POINTER(P))( + self._ptr, C.byref(primal_part._ptr), C.byref(tangent_part._ptr) + ) + ) + parts = [primal_part, tangent_part] + parts[1 - index].close() + result = parts[index] + if result.depth == 0: + try: + from ._autodiff_value import import_value + + return import_value(result).decode() + finally: + result.close() + return result + + def _relation(self, other, operation): + other = self._coerce(other) + out = C.c_int() + with _locked(self, other): + _check( + _api("dual_relation", P, C.c_int, P, P, C.POINTER(C.c_int))( + None, operation, self._ptr, other._ptr, C.byref(out) + ) + ) + return bool(out.value) + + def __eq__(self, other): + try: + return self._relation(other, 0) + except TypeError: + return NotImplemented + + def __lt__(self, other): + return self._relation(other, 1) + + def __le__(self, other): + return self._relation(other, 2) + + def __gt__(self, other): + return self._relation(other, 3) + + def __ge__(self, other): + return self._relation(other, 4) + + @property + def primal(self): + return self._part(0) + + @property + def tangent(self): + return self._part(1) + + +def _coefficient_leaf(value, dtype): + from . import _value as v + + if isinstance(value, v.Value): + return value.clone() + if isinstance(dtype, v.Value): + from ._numeric_types_runtime import _literal + + return _literal(value, dtype) + return v.scalar(value, dtype) + + +def _dual_number(value, depth, dtype): + if isinstance(value, Dual): + if value.depth != depth or (isinstance(dtype, str) and value.dtype != dtype): + raise TypeError("mismatched Dual scalar types") + return value + if isinstance(value, _Handle): + raise TypeError("cannot mix AD handle kinds") + result = value + for _ in range(depth): + result = Dual(result, 0, dtype=dtype) + return result + + +def _exact_scalar(value): + numerator, denominator = P(), P() + try: + with _locked(value): + _check( + _api("scalar_text", P, C.POINTER(P), C.POINTER(P))( + value._ptr, C.byref(numerator), C.byref(denominator) + ) + ) + n, d = _integer(C.string_at(numerator)), _integer(C.string_at(denominator)) + return n if value.dtype == "integer" else Fraction(n, d) + finally: + _api("string_free", P, result=None)(numerator) + _api("string_free", P, result=None)(denominator) + + +class CompiledGraph(_Handle): + """Immutable compiled graph; evaluate it repeatedly at new input values.""" + + def evaluate(self, values): + return evaluate_graph(self, values) + + +class GradientState(_Handle): + """Explicit original accumulation state; constructor adds no finite check.""" + + def __init__(self, values): + import hmath + + self._ptr, self._lock, self._keepers = P(), threading.RLock(), () + values = _doubles(values) + hmath.initialize() + _check( + _api("gradient_state_create", P, C.POINTER(D), Z, C.POINTER(P))( + None, values, len(values), C.byref(self._ptr) + ) + ) + + @property + def accumulated_gradient(self): + return _copy_values(self) + + +class ADTensor(_Handle): + """Original row-major symbolic tensor and checked broadcast operations.""" + + def __init__(self, shape, values): + import hmath + + self._ptr, self._lock, self._keepers = P(), threading.RLock(), () + shape = _indices(shape) + values = [_expression(value) for value in values] + self._keepers = _owners(*values) + hmath.initialize() + with _locked(*values): + pointers = (P * len(values))(*(value._ptr for value in values)) + _check( + _api( + "tensor_create", P, C.POINTER(I), Z, C.POINTER(P), Z, C.POINTER(P) + )(None, shape, len(shape), pointers, len(values), C.byref(self._ptr)) + ) + + @property + def shape(self): + _, rank = self._metadata() + shape = (I * rank)() + with _locked(self): + _check(_api("shape_copy", P, C.POINTER(I), Z)(self._ptr, shape, rank)) + return tuple(shape) + + @property + def values(self): + count, _ = self._metadata() + pointers = (P * count)() + adopted = [] + with _locked(self): + _check( + _api("tensor_values", P, C.POINTER(P), Z)(self._ptr, pointers, count) + ) + try: + for pointer in pointers: + adopted.append(Expr._adopt(P(pointer), self._keepers)) + except BaseException: + for pointer in list(pointers)[len(adopted) :]: + _api("release", P, result=None)(pointer) + raise + return adopted + + def __add__(self, other): + return ad_add(self, other) + + def __mul__(self, other): + return ad_multiply(self, other) + + def __matmul__(self, other): + return ad_matmul(self, other) + + +def _doubles(values): + values = tuple(_real(value) for value in values) + return (D * len(values))(*values) + + +def _indices(values): + values = tuple(_int(value) for value in values) + return (I * len(values))(*values) + + +def _expression(value): + if isinstance(value, Expr): + return value + if isinstance(value, _Handle): + raise TypeError("expected an AD expression") + return constant(value) + + +def _copy_values(value): + count, _ = value._metadata() + out = (D * count)() + with _locked(value): + _check(_api("values_copy", P, C.POINTER(D), Z)(value._ptr, out, count)) + return list(out) + + +def variable(index): + return _new(Expr, "variable", [I], [_int(index)]) + + +def constant(value): + return _new(Expr, "constant", [D], [_real(value)]) + + +def compile_graph(input_count, expression): + expression = _expression(expression) + return _new( + CompiledGraph, + "compile_graph", + [I, P], + [_int(input_count), expression._ptr], + parents=[expression], + ) + + +def differentiate(index, expression): + expression = _expression(expression) + return _new( + Expr, + "differentiate", + [I, P], + [_int(index), expression._ptr], + parents=[expression], + ) + + +def _build(function, n, vector=False): + value = ( + function([variable(index) for index in range(n)]) + if callable(function) + else function + ) + return [_expression(item) for item in value] if vector else [_expression(value)] + + +def _run( + name, expressions, values, required, direction=None, scalar=None, vector=False +): + values = _doubles(values) + out = (D * required)() + types, args = [P], [None] + with _locked(*expressions): + if vector: + pointers = (P * len(expressions))(*(value._ptr for value in expressions)) + types.extend([C.POINTER(P), Z]) + args.extend([pointers, len(expressions)]) + else: + types.append(P) + args.append(expressions[0]._ptr) + types.extend([C.POINTER(D), Z]) + args.extend([values, len(values)]) + if direction is not None: + direction = _doubles(direction) + types.extend([C.POINTER(D), Z]) + args.extend([direction, len(direction)]) + if scalar is not None: + types.append(D) + args.append(_real(scalar)) + types.extend([C.POINTER(D), Z]) + args.extend([out, required]) + _check(_api(name, *types)(*args)) + return list(out) + + +def evaluate_graph(graph, values): + if not isinstance(graph, CompiledGraph): + raise TypeError("expected CompiledGraph") + return _run("evaluate_graph", [graph], values, 1)[0] + + +def value_and_gradient(function, values): + values = tuple(values) + out = _run( + "value_and_gradient", _build(function, len(values)), values, len(values) + 1 + ) + return out[0], out[1:] + + +def gradient(function, values): + values = tuple(values) + return _run("gradient", _build(function, len(values)), values, len(values)) + + +def hessian(function, values): + values = tuple(values) + n = len(values) + out = _run("hessian", _build(function, n), values, n * n) + return [out[row * n : (row + 1) * n] for row in range(n)] + + +def jacobian(function, values): + values = tuple(values) + n = len(values) + expressions = _build(function, n, True) + out = _run("jacobian", expressions, values, len(expressions) * n, vector=True) + return [out[row * n : (row + 1) * n] for row in range(len(expressions))] + + +def jvp(function, values, direction): + values = tuple(values) + expressions = _build(function, len(values), True) + return _run( + "jvp", expressions, values, len(expressions), direction=direction, vector=True + ) + + +def vjp(function, values, direction): + values = tuple(values) + expressions = _build(function, len(values), True) + return _run( + "vjp", expressions, values, len(values), direction=direction, vector=True + ) + + +def hvp(function, values, direction): + values = tuple(values) + return _run( + "hvp", _build(function, len(values)), values, len(values), direction=direction + ) + + +def gradient_check(step, function, values): + values = tuple(values) + return _run( + "gradient_check", _build(function, len(values)), values, 1, scalar=step + )[0] + + +def complex_gradient(function, value): + return complex( + *_run("complex_gradient", _build(function, 2), [value.real, value.imag], 2) + ) + + +def primal(value): + return value.primal + + +def tangent(value): + return value.tangent + + +def forward(function, value, *, dtype=None): + seed = Dual(value, 1, dtype=dtype) + result = function(seed) + if not isinstance(result, Dual): + result = seed._coerce(result) + return primal(result), tangent(result) + + +def forward_jvp(function, values, direction): + values, direction = tuple(values), tuple(direction) + _run("forward_jvp_result", [], values, 0, direction=direction, vector=True) + outputs = [ + value if isinstance(value, Dual) else Dual(value, 0) + for value in function( + [Dual(value, seed) for value, seed in zip(values, direction)] + ) + ] + result = _run( + "forward_jvp_result", + outputs, + values, + 2 * len(outputs), + direction=direction, + vector=True, + ) + return result[: len(outputs)], result[len(outputs) :] + + +def zero_gradients(count): + return _new(GradientState, "zero_gradients", [I], [_int(count)]) + + +def accumulate_gradients(state, values): + values = _doubles(values) + return _new( + GradientState, + "accumulate_gradients", + [P, C.POINTER(D), Z], + [state._ptr, values, len(values)], + parents=[state], + ) + + +def reset_gradients(state): + return _new(GradientState, "reset_gradients", [P], [state._ptr], parents=[state]) + + +def gradient_hook(function, state): + values = _doubles(function(state.accumulated_gradient)) + return _new( + GradientState, + "gradient_hook_result", + [P, C.POINTER(D), Z], + [state._ptr, values, len(values)], + parents=[state], + ) + + +def clip_gradient(limit, values): + values = _doubles(values) + with _new( + GradientState, + "clip_gradient", + [D, C.POINTER(D), Z], + [_real(limit), values, len(values)], + ) as result: + return result.accumulated_gradient + + +def ad_tensor(shape, values): + return ADTensor(shape, values) + + +def ad_values(tensor): + return tensor.values + + +def ad_shape(tensor): + return tensor.shape + + +def ad_broadcast(shape, tensor): + shape = _indices(shape) + return _new( + ADTensor, + "broadcast", + [C.POINTER(I), Z, P], + [shape, len(shape), tensor._ptr], + parents=[tensor], + ) + + +def _tensor_binary(name, left, right): + if not isinstance(left, ADTensor) or not isinstance(right, ADTensor): + raise TypeError("expected ADTensor operands") + return _new(ADTensor, name, [P, P], [left._ptr, right._ptr], parents=[left, right]) + + +def ad_add(left, right): + return _tensor_binary("tensor_add", left, right) + + +def ad_multiply(left, right): + return _tensor_binary("tensor_multiply", left, right) + + +def ad_matmul(left, right): + return _tensor_binary("matmul", left, right) + + +def ad_contract(left_axes, right_axes, left, right): + left_axes, right_axes = _indices(left_axes), _indices(right_axes) + return _new( + ADTensor, + "contract", + [C.POINTER(I), Z, C.POINTER(I), Z, P, P], + [left_axes, len(left_axes), right_axes, len(right_axes), left._ptr, right._ptr], + parents=[left, right], + ) + + +def ad_sum(tensor): + return _new(Expr, "sum", [P], [tensor._ptr], parents=[tensor]) + + +def differentiable_step(rate, function, expressions): + points = [_expression(value) for value in expressions] + objective = _build(function, len(points))[0] + with _locked(objective, *points): + pointers = (P * len(points))(*(value._ptr for value in points)) + with _new( + ADTensor, + "differentiable_step", + [D, P, C.POINTER(P), Z], + [_real(rate), objective._ptr, pointers, len(points)], + parents=[objective, *points], + ) as result: + return result.values + + +class _CallbackOwner: + def __init__(self): + self.callbacks = [] + self.buffers = [] + self.derived = {} + self.results = [] + + +def _callback_error(owner, error, message): + _callback_errors.error = error + try: + encoded = str(error).encode("utf-8", "backslashreplace") + except BaseException: # noqa: BLE001 - even exception formatting stays inside C + encoded = b"AD callback failed" + owner.buffers.append(encoded) + message[0] = encoded + try: + status = getattr(error, "status", 6) + return status if isinstance(status, int) and 1 <= status <= 11 else 6 + except BaseException: # noqa: BLE001 - contain arbitrary exception properties + return 6 + + +_RULE = C.CFUNCTYPE( + C.c_int, + C.POINTER(D), + Z, + P, + C.POINTER(D), + C.POINTER(D), + Z, + C.POINTER(Z), + C.POINTER(C.c_char_p), +) +_UNARY = C.CFUNCTYPE(C.c_int, D, P, C.POINTER(D), C.POINTER(C.c_char_p)) +_BUILDER = C.CFUNCTYPE(C.c_int, C.POINTER(P), Z, P, C.POINTER(P), C.POINTER(C.c_char_p)) +_RULE_CHECKED = C.CFUNCTYPE( + C.c_int, + C.POINTER(D), + Z, + P, + C.POINTER(D), + C.POINTER(D), + Z, + C.POINTER(Z), + C.POINTER(_ErrorWire), +) +_UNARY_CHECKED = C.CFUNCTYPE(C.c_int, D, P, C.POINTER(D), C.POINTER(_ErrorWire)) +_BUILDER_CHECKED = C.CFUNCTYPE( + C.c_int, C.POINTER(P), Z, P, C.POINTER(P), C.POINTER(_ErrorWire) +) + + +def _has_checked_callback(name): + import hmath + + return hasattr(hmath._lib, "hmath_ad_" + name + "_checked") + + +def _checked_callback_error(owner, exception, error): + buffers = [] + owner.buffers.append(buffers) + try: + status = _fill_callback_error(error, exception, buffers) + except BaseException as invalid_payload: # noqa: BLE001 - contain malformed payloads + _callback_errors.error = invalid_payload + return 6 + if status: + return status + _callback_errors.error = exception + try: + message = str(exception).encode("utf-8", "surrogatepass") + buffer = C.create_string_buffer(message) + buffers.append(buffer) + error.contents.kind = 0 + error.contents.message = C.cast(buffer, P) + error.contents.message_length = len(message) + except BaseException: # noqa: BLE001 - even formatting/allocation stays inside C + error.contents.kind = 0 + error.contents.message = None + error.contents.message_length = 0 + return 6 + + +def custom_operation(function, expressions): + expressions = [_expression(value) for value in expressions] + owner = _CallbackOwner() + reference = weakref.proxy(owner) + checked = _has_checked_callback("custom_operation") + callback_type = _RULE_CHECKED if checked else _RULE + + @callback_type + def callback(values, count, userdata, out, partials, capacity, written, error): + try: + value, derivatives = function([values[index] for index in range(count)]) + derivatives = tuple(derivatives) + out[0] = _real(value) + written[0] = len(derivatives) + for index in range(min(capacity, len(derivatives))): + partials[index] = _real(derivatives[index]) + return 0 + except BaseException as exception: # noqa: BLE001 - C callback exception boundary + return (_checked_callback_error if checked else _callback_error)( + reference, exception, error + ) + + owner.callbacks.append(callback) + with _locked(*expressions): + pointers = (P * len(expressions))(*(value._ptr for value in expressions)) + return _new( + Expr, + "custom_operation_checked" if checked else "custom_operation", + [callback_type, P, C.POINTER(P), Z], + [callback, None, pointers, len(expressions)], + parents=expressions, + keepers=[owner], + ) + + +def custom_unary(function, derivative, expression): + expression = _expression(expression) + owner = _CallbackOwner() + reference = weakref.proxy(owner) + checked = _has_checked_callback("custom_unary") + callback_type = _UNARY_CHECKED if checked else _UNARY + + def wrap(function): + @callback_type + def callback(value, userdata, out, error): + try: + out[0] = _real(function(value)) + return 0 + except BaseException as exception: # noqa: BLE001 - C callback exception boundary + return (_checked_callback_error if checked else _callback_error)( + reference, exception, error + ) + + owner.callbacks.append(callback) + return callback + + value_callback, derivative_callback = wrap(function), wrap(derivative) + return _new( + Expr, + "custom_unary_checked" if checked else "custom_unary", + [callback_type, callback_type, P, P], + [value_callback, derivative_callback, None, expression._ptr], + parents=[expression], + keepers=[owner], + ) + + +def checkpoint(function, expressions): + expressions = [_expression(value) for value in expressions] + owner = _CallbackOwner() + reference = weakref.proxy(owner) + input_keepers = _owners(*expressions) + checked = _has_checked_callback("checkpoint") + callback_type = _BUILDER_CHECKED if checked else _BUILDER + + @callback_type + def callback(pointers, count, userdata, out, error): + inputs = [] + try: + for index in range(count): + pointer = P(pointers[index]) + _api("retain", P, result=None)(pointer) + inputs.append(Expr._adopt(pointer, input_keepers)) + result = _expression(function(inputs)) + reference.results.append(result) + for keeper in result._keepers: + reference.derived[id(keeper)] = keeper + with _locked(result): + _api("retain", P, result=None)(result._ptr) + out[0] = result._ptr + return 0 + except BaseException as exception: # noqa: BLE001 - C callback exception boundary + for value in inputs: + value.close() + return (_checked_callback_error if checked else _callback_error)( + reference, exception, error + ) + + owner.callbacks.append(callback) + with _locked(*expressions): + pointers = (P * len(expressions))(*(value._ptr for value in expressions)) + return _new( + Expr, + "checkpoint_checked" if checked else "checkpoint", + [callback_type, P, C.POINTER(P), Z], + [callback, None, pointers, len(expressions)], + parents=expressions, + keepers=[owner], + ) + + +def negate(value): + return value._unary(0) + + +def absolute(value): + return value._unary(1) + + +def sign(value): + return value._unary(2) + + +def reciprocal(value): + return value._unary(3) + + +def exp(value): + return value._unary(4) + + +def log(value): + return value._unary(5) + + +def sqrt(value): + return value._unary(6) + + +def sin(value): + return value._unary(7) + + +def cos(value): + return value._unary(8) + + +def tan(value): + return value._unary(9) + + +def asin(value): + return value._unary(10) + + +def acos(value): + return value._unary(11) + + +def atan(value): + return value._unary(12) + + +def sinh(value): + return value._unary(13) + + +def cosh(value): + return value._unary(14) + + +def tanh(value): + return value._unary(15) + + +def asinh(value): + return value._unary(16) + + +def acosh(value): + return value._unary(17) + + +def atanh(value): + return value._unary(18) + + +def detach(value): + return value._unary(19) + + +def stop_gradient(value): + return value._unary(20) + + +# Register exact shared-Value interoperability after all legacy owner classes. +from . import _autodiff_value as _value_interop # noqa: F401 diff --git a/bindings/python/_hmath_native/backend.py b/bindings/python/_hmath_native/backend.py new file mode 100644 index 0000000..6f8542d --- /dev/null +++ b/bindings/python/_hmath_native/backend.py @@ -0,0 +1,599 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Backend public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class Provider(LinearValue): + """Original HMath.Backend.Provider immutable owner.""" + + _source_type = "HMath.Backend.Provider" + + +register("HMath.Backend.Provider", Provider) + + +class IntegerABI(LinearValue): + """Original HMath.Backend.IntegerABI immutable owner.""" + + _source_type = "HMath.Backend.IntegerABI" + + +register("HMath.Backend.IntegerABI", IntegerABI) + + +class BackendRequest(LinearValue): + """Original HMath.Backend.BackendRequest immutable owner.""" + + _source_type = "HMath.Backend.BackendRequest" + + +register("HMath.Backend.BackendRequest", BackendRequest) + + +class BackendInfo(LinearValue): + """Original HMath.Backend.BackendInfo immutable owner.""" + + _source_type = "HMath.Backend.BackendInfo" + + def __init__(self, selected_provider, selected_integer_abi): + self._initialize( + "hmath_linear_backend_new_backend_info", + False, + [["Provider"], ["IntegerABI"]], + [selected_provider, selected_integer_abi], + ) + + @property + def selected_provider(self): + return _invoke( + "hmath_linear_backend_selected_provider", False, [["BackendInfo"]], [self] + ) + + @property + def selected_integer_abi(self): + return _invoke( + "hmath_linear_backend_selected_integer_abi", + False, + [["BackendInfo"]], + [self], + ) + + +register("HMath.Backend.BackendInfo", BackendInfo) + + +class Backend(LinearValue): + """Original HMath.Backend.Backend immutable owner.""" + + _source_type = "HMath.Backend.Backend" + + +register("HMath.Backend.Backend", Backend) + + +class BackendLayout(LinearValue): + """Original HMath.Backend.BackendLayout immutable owner.""" + + _source_type = "HMath.Backend.BackendLayout" + + +register("HMath.Backend.BackendLayout", BackendLayout) + + +class Transpose(LinearValue): + """Original HMath.Backend.Transpose immutable owner.""" + + _source_type = "HMath.Backend.Transpose" + + def __init__( + self, + ): + self._initialize("hmath_linear_backend_new_transpose", False, [], []) + + +register("HMath.Backend.Transpose", Transpose) + + +def backend_info(backend1): + "Provider identity is immutable for the lifetime of a handle. Call original HMath.Backend.backendInfo :: Backend -> BackendInfo" + return _invoke( + "hmath_linear_backend_backend_info", False, [["Backend"]], [backend1] + ) + + +def pure_backend(): + "Construct the deterministic reference backend without dynamically loading BLAS. Its lifetime is garbage-collected; selected numeric reference decomposition limits still apply. Call original HMath.Backend.pureBackend :: Backend" + return _invoke("hmath_linear_backend_pure_backend", False, [], []) + + +def lapack_available(): + "Availability of the once-initialized independent LAPACKE loader. Call original HMath.Backend.lapackAvailable :: IO Bool" + return _invoke("hmath_linear_backend_lapack_available", False, [], []) + + +def select_backend(backend_request1): + "Given AutoBackend or explicit provider/integer-ABI/library request, select a reference or native BLAS backend in IO. Auto honors HMATH_BACKEND, HMATH_BLAS_PROVIDER, HMATH_BLAS_INTEGER_BITS and HMATH_BLAS_LIBRARY; unknown settings or unavailable explicit providers fail. Keep the Backend alive while calling it. Call original HMath.Backend.selectBackend :: BackendRequest -> IO (Either MathError Backend)" + return _invoke( + "hmath_linear_backend_select_backend", + False, + [["BackendRequest"]], + [backend_request1], + ) + + +def set_backend_threads(backend1, index2): + "Positive thread count; Pure supports one thread. Accelerate has no supported runtime setter and returns an explicit error. No implicit global restoration. Call original HMath.Backend.setBackendThreads :: Backend -> Int -> IO (Either MathError ())" + return _invoke( + "hmath_linear_backend_set_backend_threads", + False, + [["Backend"], ["Int"]], + [backend1, index2], + ) + + +def lapack_status(text1, index2): + "Convert the LAPACK convention without losing the distinction between an invalid argument and failed numerical convergence. For factorization pivots callers may instead map a positive code to SingularMatrix (info - 1). Call original HMath.Backend.lapackStatus :: String -> Int -> Either MathError ()" + return _invoke( + "hmath_linear_backend_lapack_status", + False, + [["String"], ["Int"]], + [text1, index2], + ) + + +def matrix_from_layout(backend_layout1, index2, index3, values4, *, dtype=None): + "Layout conversion is a checked, explicit copy; zero shapes retain rank. Call original HMath.Backend.matrixFromLayout :: BackendLayout -> Int -> Int -> [a] -> Either MathError (M.Matrix a)" + return _invoke( + "hmath_linear_backend_matrix_from_layout", + True, + [["BackendLayout"], ["Int"], ["Int"], ["list", ["a"]]], + [backend_layout1, index2, index3, values4], + dtype=dtype, + ) + + +def matrix_to_layout(backend_layout1, matrix2, *, dtype=None): + "Given RowMajor/ColumnMajor layout then Matrix, return values in that physical order without changing the logical matrix. Call original HMath.Backend.matrixToLayout :: BackendLayout -> M.Matrix a -> [a]" + return _invoke( + "hmath_linear_backend_matrix_to_layout", + True, + [["BackendLayout"], ["Matrix", ["a"]]], + [backend_layout1, matrix2], + dtype=dtype, + ) + + +def axpy(backend1, double2, values3, values4): + "Given backend,alpha,x,y, return alpha*x+y as a new Double list. Require equal lengths, finite inputs/result and provider-supported integer extents; validation/provider failures return Left MathError in IO. Call original HMath.Backend.axpy :: Backend -> Double -> [Double] -> [Double] -> IO (Either MathError [Double])" + return _invoke( + "hmath_linear_backend_axpy", + False, + [["Backend"], ["Double"], ["list", ["Double"]], ["list", ["Double"]]], + [backend1, double2, values3, values4], + ) + + +def dot(backend1, values2, values3): + "Real inner product. Finite input and output; accumulation can overflow even when exact cancellation would produce a finite mathematical result. Call original HMath.Backend.dot :: Backend -> [Double] -> [Double] -> IO (Either MathError Double)" + return _invoke( + "hmath_linear_backend_dot", + False, + [["Backend"], ["list", ["Double"]], ["list", ["Double"]]], + [backend1, values2, values3], + ) + + +def nrm2(backend1, values2): + "Given backend then finite Double vector, return Euclidean norm through the selected provider or reference path. Empty input gives zero; invalid/non-finite output or provider bounds fail in IO. Call original HMath.Backend.nrm2 :: Backend -> [Double] -> IO (Either MathError Double)" + return _invoke( + "hmath_linear_backend_nrm2", + False, + [["Backend"], ["list", ["Double"]]], + [backend1, values2], + ) + + +def gemv(backend1, transpose2, double3, matrix4, values5, double6, values7): + "y := alpha op(A) x + beta y. Finite inputs are checked even for zero alpha. Call original HMath.Backend.gemv :: Backend -> Transpose -> Double -> M.Matrix Double -> [Double] -> Double -> [Double] -> IO (Either MathError [Double])" + return _invoke( + "hmath_linear_backend_gemv", + False, + [ + ["Backend"], + ["Transpose"], + ["Double"], + ["Matrix", ["Double"]], + ["list", ["Double"]], + ["Double"], + ["list", ["Double"]], + ], + [backend1, transpose2, double3, matrix4, values5, double6, values7], + ) + + +def gemm(backend1, transpose2, transpose3, double4, matrix5, matrix6, double7, matrix8): + "C := alpha op(A) op(B) + beta C. Matrices and output must have compatible shapes; all zero-dimensional cases use the reference arithmetic. Call original HMath.Backend.gemm :: Backend -> Transpose -> Transpose -> Double -> M.Matrix Double -> M.Matrix Double -> Double -> M.Matrix Double -> IO (Either MathError (M.Matrix Double))" + return _invoke( + "hmath_linear_backend_gemm", + False, + [ + ["Backend"], + ["Transpose"], + ["Transpose"], + ["Double"], + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["Double"], + ["Matrix", ["Double"]], + ], + [backend1, transpose2, transpose3, double4, matrix5, matrix6, double7, matrix8], + ) + + +def complex_gemm( + backend1, transpose2, transpose3, complex4, matrix5, matrix6, complex7, matrix8 +): + "Given backend,transpose A,transpose B,alpha,A,B,beta,C, return alpha*op(A)*op(B)+beta*C as a new complex matrix. Validate compatible dimensions, finite components and provider integer/allocation bounds. Call original HMath.Backend.complexGemm :: Backend -> Transpose -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> M.Matrix (Complex Double) -> Complex Double -> M.Matrix (Complex Double) -> IO (Either MathError (M.Matrix (Complex Double)))" + return _invoke( + "hmath_linear_backend_complex_gemm", + False, + [ + ["Backend"], + ["Transpose"], + ["Transpose"], + ["Complex", ["Double"]], + ["Matrix", ["Complex", ["Double"]]], + ["Matrix", ["Complex", ["Double"]]], + ["Complex", ["Double"]], + ["Matrix", ["Complex", ["Double"]]], + ], + [ + backend1, + transpose2, + transpose3, + complex4, + matrix5, + matrix6, + complex7, + matrix8, + ], + ) + + +def complex_axpy(backend1, complex2, values3, values4): + "Given backend,complex alpha,x,y, compute alpha*x+y, requiring equal lengths and finite real/imaginary components. Return a new list or checked shape/provider/numeric error in IO. Call original HMath.Backend.complexAxpy :: Backend -> Complex Double -> [Complex Double] -> [Complex Double] -> IO (Either MathError [Complex Double])" + return _invoke( + "hmath_linear_backend_complex_axpy", + False, + [ + ["Backend"], + ["Complex", ["Double"]], + ["list", ["Complex", ["Double"]]], + ["list", ["Complex", ["Double"]]], + ], + [backend1, complex2, values3, values4], + ) + + +def complex_dot(backend1, flag2, values3, values4): + "Set the Boolean to True for the Hermitian dot product (conjugate x). Call original HMath.Backend.complexDot :: Backend -> Bool -> [Complex Double] -> [Complex Double] -> IO (Either MathError (Complex Double))" + return _invoke( + "hmath_linear_backend_complex_dot", + False, + [ + ["Backend"], + ["Bool"], + ["list", ["Complex", ["Double"]]], + ["list", ["Complex", ["Double"]]], + ], + [backend1, flag2, values3, values4], + ) + + +def complex_nrm2(backend1, values2): + "Given backend then complex vector, return real Euclidean norm of all real/imaginary components. Non-finite input/output or provider extent errors return Left MathError in IO. Call original HMath.Backend.complexNrm2 :: Backend -> [Complex Double] -> IO (Either MathError Double)" + return _invoke( + "hmath_linear_backend_complex_nrm2", + False, + [["Backend"], ["list", ["Complex", ["Double"]]]], + [backend1, values2], + ) + + +def complex_gemv(backend1, transpose2, complex3, matrix4, values5, complex6, values7): + "Given backend,transpose selector,alpha,A,x,beta,y, return alpha*op(A)*x+beta*y as a new complex list. ConjugateTranspose conjugates matrix values; dimensions, finite values and provider bounds are checked. Call original HMath.Backend.complexGemv :: Backend -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> [Complex Double] -> Complex Double -> [Complex Double] -> IO (Either MathError [Complex Double])" + return _invoke( + "hmath_linear_backend_complex_gemv", + False, + [ + ["Backend"], + ["Transpose"], + ["Complex", ["Double"]], + ["Matrix", ["Complex", ["Double"]]], + ["list", ["Complex", ["Double"]]], + ["Complex", ["Double"]], + ["list", ["Complex", ["Double"]]], + ], + [backend1, transpose2, complex3, matrix4, values5, complex6, values7], + ) + + +def batched_gemm(backend1, transpose2, transpose3, double4, double5, values6): + "Uniform scalar/transpose options, independently checked matrix triples. Earlier calls may execute before a later invalid item; no input is mutated. Call original HMath.Backend.batchedGemm :: Backend -> Transpose -> Transpose -> Double -> Double -> [(M.Matrix Double, M.Matrix Double, M.Matrix Double)] -> IO (Either MathError [M.Matrix Double])" + return _invoke( + "hmath_linear_backend_batched_gemm", + False, + [ + ["Backend"], + ["Transpose"], + ["Transpose"], + ["Double"], + ["Double"], + [ + "list", + [ + "tuple", + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ], + ], + ], + [backend1, transpose2, transpose3, double4, double5, values6], + ) + + +def strided_batched_gemm( + backend1, index2, index3, index4, index5, index6, values7, index8, values9 +): + "Row-major batches of A(m,k) and B(k,n). Strides count elements, may include padding, and may be zero for broadcast. Extents are checked with Integer before slicing; output batches are contiguous m*n matrices. No implicit transposes. Call original HMath.Backend.stridedBatchedGemm :: Backend -> Int -> Int -> Int -> Int -> Int -> [Double] -> Int -> [Double] -> IO (Either MathError [M.Matrix Double])" + return _invoke( + "hmath_linear_backend_strided_batched_gemm", + False, + [ + ["Backend"], + ["Int"], + ["Int"], + ["Int"], + ["Int"], + ["Int"], + ["list", ["Double"]], + ["Int"], + ["list", ["Double"]], + ], + [backend1, index2, index3, index4, index5, index6, values7, index8, values9], + ) + + +def backend_lu(backend1, matrix2): + "Given backend then real matrix, compute checked column-independent LU using the reference pivoted LU implementation. The backend argument does not change this routine's provider. Shape/pivot/numeric failures propagate. Call original HMath.Backend.backendLU :: Backend -> M.Matrix Double -> Either MathError (LU.LU Double)" + return _invoke( + "hmath_linear_backend_backend_lu", + False, + [["Backend"], ["Matrix", ["Double"]]], + [backend1, matrix2], + ) + + +def backend_qr(backend1, matrix2): + "Given backend then real matrix, compute reference column-pivoted Householder QR; selection does not change this routine's provider. Validation/numeric errors propagate. Call original HMath.Backend.backendQR :: Backend -> M.Matrix Double -> Either MathError (QR.QR Double)" + return _invoke( + "hmath_linear_backend_backend_qr", + False, + [["Backend"], ["Matrix", ["Double"]]], + [backend1, matrix2], + ) + + +def backend_solve(backend1, matrix2, values3): + "Given backend,square real matrix,then RHS list, solve via reference LU for Pure or the independent LAPACKE solve bridge for a native backend. Invalid dimensions, unavailable solver, singularity or non-finite arithmetic returns Left MathError. Call original HMath.Backend.backendSolve :: Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]" + return _invoke( + "hmath_linear_backend_backend_solve", + False, + [["Backend"], ["Matrix", ["Double"]], ["list", ["Double"]]], + [backend1, matrix2, values3], + ) + + +def backend_cholesky(backend1, matrix2): + "Given backend then finite symmetric positive-definite matrix, return reference lower Cholesky factor. Invalid shape/symmetry/pivots/numeric results fail; provider selection is not used by this wrapper. Call original HMath.Backend.backendCholesky :: Backend -> M.Matrix Double -> Either MathError (M.Matrix Double)" + return _invoke( + "hmath_linear_backend_backend_cholesky", + False, + [["Backend"], ["Matrix", ["Double"]]], + [backend1, matrix2], + ) + + +def backend_least_squares(backend1, matrix2, values3): + "Given backend,design matrix,then RHS list, solve using reference pivoted QR. Require compatible overdetermined/full-rank input; shape/rank/numeric failures propagate. Call original HMath.Backend.backendLeastSquares :: Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]" + return _invoke( + "hmath_linear_backend_backend_least_squares", + False, + [["Backend"], ["Matrix", ["Double"]], ["list", ["Double"]]], + [backend1, matrix2, values3], + ) + + +def backend_svd(backend1, matrix2): + "Given backend then finite real matrix, use bounded pure reference SVD for Pure or LAPACK thin SVD for native selection. Return factors or checked shape/budget/provider/convergence errors. Call original HMath.Backend.backendSVD :: Backend -> M.Matrix Double -> Either MathError L.SVD" + return _invoke( + "hmath_linear_backend_backend_svd", + False, + [["Backend"], ["Matrix", ["Double"]]], + [backend1, matrix2], + ) + + +def backend_symmetric_eigen(backend1, matrix2): + "Given backend then finite symmetric square matrix, use bounded cyclic-Jacobi reference solver for Pure or LAPACK otherwise. Return eigenvalues/vectors or input/provider/convergence errors. Call original HMath.Backend.backendSymmetricEigen :: Backend -> M.Matrix Double -> Either MathError L.Eigen" + return _invoke( + "hmath_linear_backend_backend_symmetric_eigen", + False, + [["Backend"], ["Matrix", ["Double"]]], + [backend1, matrix2], + ) + + +def pure_symmetric_eigen(matrix1): + "Cyclic Jacobi symmetric eigensolver, at most 100 sweeps, ascending eigenvalues. Scaled input avoids squared-norm overflow. This reference path is limited to order 128 and reports nonconvergence rather than returning an unchecked factor. Call original HMath.Backend.pureSymmetricEigen :: M.Matrix Double -> Either MathError L.Eigen" + return _invoke( + "hmath_linear_backend_pure_symmetric_eigen", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def pure_svd(matrix1): + "Thin real SVD by one-sided Jacobi orthogonalization, at most 100 sweeps, dimensions <=128. Unlike a normal-equation SVD it does not form A^T A. A deterministic orthogonal completion supplies zero-singular-value columns. Call original HMath.Backend.pureSVD :: M.Matrix Double -> Either MathError L.SVD" + return _invoke( + "hmath_linear_backend_pure_svd", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def pure(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.Pure :: constructor" + return _invoke("hmath_linear_backend_new_pure", False, [], []) + + +def open_blas(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.OpenBLAS :: constructor" + return _invoke("hmath_linear_backend_new_open_blas", False, [], []) + + +def blis(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.BLIS :: constructor" + return _invoke("hmath_linear_backend_new_blis", False, [], []) + + +def one_mkl(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.OneMKL :: constructor" + return _invoke("hmath_linear_backend_new_one_mkl", False, [], []) + + +def accelerate(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.Accelerate :: constructor" + return _invoke("hmath_linear_backend_new_accelerate", False, [], []) + + +def lp64(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.LP64 :: constructor" + return _invoke("hmath_linear_backend_new_lp64", False, [], []) + + +def ilp64(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.ILP64 :: constructor" + return _invoke("hmath_linear_backend_new_ilp64", False, [], []) + + +def auto_backend(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.AutoBackend :: constructor" + return _invoke("hmath_linear_backend_new_auto_backend", False, [], []) + + +def require_backend(provider1, integer_abi2, maybe3): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.RequireBackend :: constructor" + return _invoke( + "hmath_linear_backend_new_require_backend", + False, + [["Provider"], ["IntegerABI"], ["Maybe", ["String"]]], + [provider1, integer_abi2, maybe3], + ) + + +def selected_provider(backend_info1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Backend.selectedProvider :: BackendInfo -> field" + return _invoke( + "hmath_linear_backend_selected_provider", + False, + [["BackendInfo"]], + [backend_info1], + ) + + +def selected_integer_abi(backend_info1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Backend.selectedIntegerABI :: BackendInfo -> field" + return _invoke( + "hmath_linear_backend_selected_integer_abi", + False, + [["BackendInfo"]], + [backend_info1], + ) + + +def row_major(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.RowMajor :: constructor" + return _invoke("hmath_linear_backend_new_row_major", False, [], []) + + +def column_major(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.ColumnMajor :: constructor" + return _invoke("hmath_linear_backend_new_column_major", False, [], []) + + +def no_transpose(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.NoTranspose :: constructor" + return _invoke("hmath_linear_backend_new_no_transpose", False, [], []) + + +def conjugate_transpose(): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Backend.ConjugateTranspose :: constructor" + return _invoke("hmath_linear_backend_new_conjugate_transpose", False, [], []) + + +__all__ = [ + "Backend", + "BackendInfo", + "BackendLayout", + "BackendRequest", + "IntegerABI", + "Provider", + "Transpose", + "accelerate", + "auto_backend", + "axpy", + "backend_cholesky", + "backend_info", + "backend_least_squares", + "backend_lu", + "backend_qr", + "backend_solve", + "backend_svd", + "backend_symmetric_eigen", + "batched_gemm", + "blis", + "column_major", + "complex_axpy", + "complex_dot", + "complex_gemm", + "complex_gemv", + "complex_nrm2", + "conjugate_transpose", + "dot", + "gemm", + "gemv", + "ilp64", + "lapack_available", + "lapack_status", + "lp64", + "matrix_from_layout", + "matrix_to_layout", + "no_transpose", + "nrm2", + "one_mkl", + "open_blas", + "pure", + "pure_backend", + "pure_svd", + "pure_symmetric_eigen", + "require_backend", + "row_major", + "select_backend", + "selected_integer_abi", + "selected_provider", + "set_backend_threads", + "strided_batched_gemm", +] diff --git a/bindings/python/_hmath_native/basic.py b/bindings/python/_hmath_native/basic.py new file mode 100644 index 0000000..b2eedb6 --- /dev/null +++ b/bindings/python/_hmath_native/basic.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call +from ._numeric_objects import _call_value, _uses_value + + +def factorial(n): + """Call HMath.Basic.factorial; preserve its argument order, result and errors.""" + return _call( + 'hmath_basic_factorial', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def fibonacci(n): + """Call HMath.Basic.fibonacci; preserve its argument order, result and errors.""" + return _call( + 'hmath_basic_fibonacci', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def is_prime(n): + """Call HMath.Basic.isPrime; preserve its argument order, result and errors.""" + return _call( + 'hmath_basic_is_prime', + ['z'], + 'b', + [n], + None, + 0, + ) + + +def clamp(low, high, value, *, dtype='float64'): + """Call HMath.Basic.clamp; preserve its argument order, result and errors.""" + if _uses_value([low, high, value], dtype, ordered=True): + return _call_value('hmath_basic_clamp', ['f', 'f', 'f'], [low, high, value], dtype) + variants = { + 'float32': (['f', 'f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_basic_clamp', kinds, result, [low, high, value], precision, 0, symbol_suffix=suffix) + + +def lerp(a, b, t, *, dtype='float64'): + """Call HMath.Basic.lerp; preserve its argument order, result and errors.""" + if _uses_value([a, b, t], dtype, ordered=False): + return _call_value('hmath_basic_lerp', ['f', 'f', 'f'], [a, b, t], dtype) + variants = { + 'float32': (['f', 'f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q', 'q'], 'q', None, '_rational'), + 'complex64': (['c', 'c', 'c'], 'c', 'float32', '_c64'), + 'complex128': (['c', 'c', 'c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_basic_lerp', kinds, result, [a, b, t], precision, 0, symbol_suffix=suffix) diff --git a/bindings/python/_hmath_native/buffer_values.py b/bindings/python/_hmath_native/buffer_values.py new file mode 100644 index 0000000..5fea0b6 --- /dev/null +++ b/bindings/python/_hmath_native/buffer_values.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_buffer_bindings.py. +from ._buffer_base import ( + BorrowedPointer, + Boxed, + IOBuffer, + STBuffer, + UnboxedDouble, + _boxed, + _call, + _new_io, + _thaw_io, +) + + +def lazy_boxed(values, *, dtype=None): + """Finite lists only. The list spine is consumed; elements remain lazy.""" + return _boxed('lazy_boxed', values, dtype) + + +def strict_boxed(values, *, dtype=None): + """ Construct a boxed container from a finite list, forcing every element to weak head normal form (not deep normal form). Preserve order; element evaluation exceptions propagate. """ + return _boxed('strict_boxed', values, dtype) + + +def boxed_values(value): + """ Return boxed elements in zero-based array order as a list. Elements retain the laziness/strictness chosen at construction. """ + return _call('boxed_values', [value]) + + +def boxed_length(value): + """Return the number of elements in a boxed container; empty storage has length zero.""" + return _call('boxed_length', [value]) + + +def map_strict(function, value): + """ Given element transformation then boxed input, return a boxed result with every mapped element forced to WHNF. Preserve length/order; evaluation exceptions propagate. """ + return _call('map_strict', [function, value], 0) + + +def unboxed_double(values): + """ Copy a finite Double list into an immutable unboxed array in list order. Values are evaluated by unboxing; no finiteness validation is added. """ + return UnboxedDouble(values) + + +def unboxed_values(value): + """Copy/expand unboxed Doubles into a list in array order, preserving length.""" + return _call('unboxed_values', [value]) + + +def run_st_buffer(value, callback): + """The rank-2 state parameter prevents a mutable region from escaping.""" + return _call('run_st_buffer', [value, callback], 1) + + +def thaw_st_buffer(region, value): + """ Copy immutable boxed values into new mutable storage in the current ST region. The input remains unchanged; storage cannot escape the region. """ + return _call('thaw_st_buffer', [region, value]) + + +def freeze_st_buffer(value): + """ Copy current mutable ST values into an immutable boxed container; later writes do not modify the frozen result. """ + return _call('freeze_st_buffer', [value]) + + +def read_st_buffer(value, index): + """ Given ST buffer then zero-based index, read the element. Negative/out-of-range indices return Left InvalidArgument within ST, rather than indexing the array. """ + return _call('read_st_buffer', [value, index]) + + +def write_st_buffer(value, index, element): + """ Given ST buffer, zero-based index, then value, update one element and return Right (). Invalid index returns Left InvalidArgument without writing. """ + return _call('write_st_buffer', [value, index, element]) + + +def new_io_buffer(count, initial, *, dtype=None): + """ Allocation overflow is checked before allocation. Allocation/OS exceptions remain IO exceptions; MathError describes input and numeric contract failures. """ + return _new_io(count, initial, dtype) + + +def thaw_io_buffer(value, *, dtype=None, prototype=None): + """ Copy boxed Storable values into new pinned IO storage. Return Left InvalidArgument for byte-size overflow; allocation/OS/evaluation failures remain IO exceptions. """ + return _thaw_io(value, dtype, prototype) + + +def freeze_io_buffer(value): + """ Lock and copy pinned IO values to a strict immutable boxed container. The result is independent of later buffer writes; allocation/IO exceptions propagate. """ + return _call('freeze_io_buffer', [value]) + + +def io_buffer_length(value): + """ Return the immutable element count of a pinned IO buffer. This query neither borrows its pointer nor takes ownership. """ + return _call('io_buffer_length', [value]) + + +def read_io_buffer(value, index): + """ Given IO buffer then zero-based index, read under the buffer lock. Invalid index returns Left InvalidArgument; IO exceptions propagate. """ + return _call('read_io_buffer', [value, index]) + + +def write_io_buffer(value, index, element): + """ Given IO buffer, zero-based index, then value, write under its lock and return Right (). Invalid index returns Left InvalidArgument without modification. """ + return value.write(index, element) + + +def with_io_buffer(value, callback): + """ Given IO buffer then callback, hold its lock and lend a Ptr plus element count for the callback duration. Do not retain the pointer or reenter locking operations on this same buffer. Callback exceptions propagate while releasing the lock. """ + return _call('with_io_buffer', [value, callback], 1) + + +def unboxed_to_boxed(value): + """ Convert unboxed Double storage to a new strict boxed container, preserving order and values. """ + return _call('unboxed_to_boxed', [value]) + + +def boxed_to_unboxed(value): + """ Convert boxed Double values to a new unboxed array, forcing values during copying. Preserve order and length. """ + return _call('boxed_to_unboxed', [value]) + + +__all__ = [ + "BorrowedPointer", + "Boxed", + "IOBuffer", + "STBuffer", + "UnboxedDouble", + "boxed_length", + "boxed_to_unboxed", + "boxed_values", + "freeze_io_buffer", + "freeze_st_buffer", + "io_buffer_length", + "lazy_boxed", + "map_strict", + "new_io_buffer", + "read_io_buffer", + "read_st_buffer", + "run_st_buffer", + "strict_boxed", + "thaw_io_buffer", + "thaw_st_buffer", + "unboxed_double", + "unboxed_to_boxed", + "unboxed_values", + "with_io_buffer", + "write_io_buffer", + "write_st_buffer" +] diff --git a/bindings/python/_hmath_native/calculus.py b/bindings/python/_hmath_native/calculus.py new file mode 100644 index 0000000..c1de30d --- /dev/null +++ b/bindings/python/_hmath_native/calculus.py @@ -0,0 +1,292 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numerical_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Estimate(Value): + """Owned immutable original HMath.Calculus.Estimate.""" + + +register(200, Estimate) + + +class Tolerance(Value): + """Owned immutable original HMath.Calculus.Tolerance.""" + + +register(201, Tolerance) + + +class Difference(Value): + """Owned immutable original HMath.Calculus.Difference.""" + + +register(202, Difference) + + +class Quadrature(Value): + """Owned immutable original HMath.Calculus.Quadrature.""" + + +register(203, Quadrature) + + +def estimate(value, error, evaluations): + """HMath.Calculus.Estimate :: a -> Double -> Int -> Estimate a.""" + return _invoke('hmath_calculus_estimate', [['Value'], ['Double'], ['Int']], [value, error, evaluations]) + + +def estimate_value(value): + """HMath.Calculus.estimateValue :: Estimate a -> a.""" + return _invoke('hmath_calculus_estimate_value', [['EstimateValue']], [value]) + + +def estimate_error(value): + """HMath.Calculus.estimateError :: Estimate a -> Double.""" + return _invoke('hmath_calculus_estimate_error', [['EstimateValue']], [value]) + + +def evaluations(value): + """HMath.Calculus.evaluations :: Estimate a -> Int.""" + return _invoke('hmath_calculus_evaluations', [['EstimateValue']], [value]) + + +def tolerance(absolute_tolerance, relative_tolerance, maximum_evaluations): + """HMath.Calculus.Tolerance :: Double -> Double -> Int -> Tolerance.""" + return _invoke('hmath_calculus_tolerance', [['Double'], ['Double'], ['Int']], [absolute_tolerance, relative_tolerance, maximum_evaluations]) + + +def absolute_tolerance(value): + """HMath.Calculus.absoluteTolerance :: Tolerance -> Double.""" + return _invoke('hmath_calculus_absolute_tolerance', [['Tolerance']], [value]) + + +def relative_tolerance(value): + """HMath.Calculus.relativeTolerance :: Tolerance -> Double.""" + return _invoke('hmath_calculus_relative_tolerance', [['Tolerance']], [value]) + + +def maximum_evaluations(value): + """HMath.Calculus.maximumEvaluations :: Tolerance -> Int.""" + return _invoke('hmath_calculus_maximum_evaluations', [['Tolerance']], [value]) + + +def default_tolerance(): + """HMath.Calculus.defaultTolerance :: Tolerance.""" + return _invoke('hmath_calculus_default_tolerance', [], []) + + +def forward(): + """HMath.Calculus.Forward :: Difference.""" + return _invoke('hmath_calculus_forward', [], []) + + +def backward(): + """HMath.Calculus.Backward :: Difference.""" + return _invoke('hmath_calculus_backward', [], []) + + +def central(): + """HMath.Calculus.Central :: Difference.""" + return _invoke('hmath_calculus_central', [], []) + + +def trapezoidal(): + """HMath.Calculus.Trapezoidal :: Quadrature.""" + return _invoke('hmath_calculus_trapezoidal', [], []) + + +def simpson(): + """HMath.Calculus.Simpson :: Quadrature.""" + return _invoke('hmath_calculus_simpson', [], []) + + +def three_eighths(): + """HMath.Calculus.ThreeEighths :: Quadrature.""" + return _invoke('hmath_calculus_three_eighths', [], []) + + +def derivative(method, h, f, x): + """HMath.Calculus.derivative :: Difference -> Double -> (Double -> Double) -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_derivative', [['Difference'], ['Double'], ['function', ['Double'], ['Double']], ['Double']], [method, h, f, x]) + + +def derivative_n(order, h, f, x): + """HMath.Calculus.derivativeN :: Int -> Double -> (Double -> Double) -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_derivative_n', [['Int'], ['Double'], ['function', ['Double'], ['Double']], ['Double']], [order, h, f, x]) + + +def complex_derivative(h, f, x): + """HMath.Calculus.complexDerivative :: Double -> (Complex Double -> Complex Double) -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_complex_derivative', [['Double'], ['function', ['ComplexDouble'], ['ComplexDouble']], ['Double']], [h, f, x]) + + +def richardson(tol, initial, f, x): + """HMath.Calculus.richardson :: Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_richardson', [['Tolerance'], ['Double'], ['function', ['Double'], ['Double']], ['Double']], [tol, initial, f, x]) + + +def ridders(tol, initial, f, x): + """HMath.Calculus.ridders :: Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_ridders', [['Tolerance'], ['Double'], ['function', ['Double'], ['Double']], ['Double']], [tol, initial, f, x]) + + +def limit(side, tol, initial, f, x): + """HMath.Calculus.limit :: Difference -> Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_limit', [['Difference'], ['Tolerance'], ['Double'], ['function', ['Double'], ['Double']], ['Double']], [side, tol, initial, f, x]) + + +def partial_derivative(i, h, f, xs): + """HMath.Calculus.partialDerivative :: Int -> Double -> ([Double] -> Double) -> [Double] -> Either MathError Double.""" + return _invoke('hmath_calculus_partial_derivative', [['Int'], ['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']]], [i, h, f, xs]) + + +def gradient(h, f, xs): + """HMath.Calculus.gradient :: Double -> ([Double] -> Double) -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_calculus_gradient', [['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']]], [h, f, xs]) + + +def jacobian(h, f, xs): + """HMath.Calculus.jacobian :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError (Matrix Double).""" + return _invoke('hmath_calculus_jacobian', [['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']]], [h, f, xs]) + + +def hessian(h, f, xs): + """HMath.Calculus.hessian :: Double -> ([Double] -> Double) -> [Double] -> Either MathError (Matrix Double).""" + return _invoke('hmath_calculus_hessian', [['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']]], [h, f, xs]) + + +def directional_derivative(h, f, x, v): + """HMath.Calculus.directionalDerivative :: Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_calculus_directional_derivative', [['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']], ['list', ['Double']]], [h, f, x, v]) + + +def jvp(h, f, x, v): + """HMath.Calculus.jvp :: Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_calculus_jvp', [['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [h, f, x, v]) + + +def vjp(h, f, x, v): + """HMath.Calculus.vjp :: Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_calculus_vjp', [['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [h, f, x, v]) + + +def hvp(h, f, x, v): + """HMath.Calculus.hvp :: Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_calculus_hvp', [['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']], ['list', ['Double']]], [h, f, x, v]) + + +def divergence(h, f, x): + """HMath.Calculus.divergence :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError Double.""" + return _invoke('hmath_calculus_divergence', [['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']]], [h, f, x]) + + +def curl(h, f, x): + """HMath.Calculus.curl :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_calculus_curl', [['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']]], [h, f, x]) + + +def laplacian(h, f, x): + """HMath.Calculus.laplacian :: Double -> ([Double] -> Double) -> [Double] -> Either MathError Double.""" + return _invoke('hmath_calculus_laplacian', [['Double'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']]], [h, f, x]) + + +def integrate_composite(method, n, f, a, b): + """HMath.Calculus.integrateComposite :: Quadrature -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_integrate_composite', [['Quadrature'], ['Int'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [method, n, f, a, b]) + + +def romberg(tol, f, a, b): + """HMath.Calculus.romberg :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_romberg', [['Tolerance'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [tol, f, a, b]) + + +def gauss_legendre(n, f, a, b): + """HMath.Calculus.gaussLegendre :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_gauss_legendre', [['Int'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [n, f, a, b]) + + +def gauss_hermite(value, value2): + """HMath.Calculus.gaussHermite :: Int -> (Double -> Double) -> Either MathError Double.""" + return _invoke('hmath_calculus_gauss_hermite', [['Int'], ['function', ['Double'], ['Double']]], [value, value2]) + + +def gauss_laguerre(value, value2): + """HMath.Calculus.gaussLaguerre :: Int -> (Double -> Double) -> Either MathError Double.""" + return _invoke('hmath_calculus_gauss_laguerre', [['Int'], ['function', ['Double'], ['Double']]], [value, value2]) + + +def gauss_chebyshev(n, f): + """HMath.Calculus.gaussChebyshev :: Int -> (Double -> Double) -> Either MathError Double.""" + return _invoke('hmath_calculus_gauss_chebyshev', [['Int'], ['function', ['Double'], ['Double']]], [n, f]) + + +def gauss_kronrod(f, a, b): + """HMath.Calculus.gaussKronrod :: (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_gauss_kronrod', [['function', ['Double'], ['Double']], ['Double'], ['Double']], [f, a, b]) + + +def adaptive_integrate(tol, f, a, b): + """HMath.Calculus.adaptiveIntegrate :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_adaptive_integrate', [['Tolerance'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [tol, f, a, b]) + + +def clenshaw_curtis(n, f, a, b): + """HMath.Calculus.clenshawCurtis :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Double.""" + return _invoke('hmath_calculus_clenshaw_curtis', [['Int'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [n, f, a, b]) + + +def tanh_sinh(tol, f, a, b): + """HMath.Calculus.tanhSinh :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_tanh_sinh', [['Tolerance'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [tol, f, a, b]) + + +def integrate_infinite(tol, f, a, b): + """HMath.Calculus.integrateInfinite :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_integrate_infinite', [['Tolerance'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [tol, f, a, b]) + + +def integrate_oscillatory(sine, omega, tol, f, a, b): + """HMath.Calculus.integrateOscillatory :: Bool -> Double -> Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_integrate_oscillatory', [['Bool'], ['Double'], ['Tolerance'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [sine, omega, tol, f, a, b]) + + +def integrate_nd(panels, budget, f, bounds): + """HMath.Calculus.integrateND :: Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double.""" + return _invoke('hmath_calculus_integrate_nd', [['Int'], ['Int'], ['function', ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [panels, budget, f, bounds]) + + +def monte_carlo(seed, n, f, bounds): + """HMath.Calculus.monteCarlo :: Integer -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_monte_carlo', [['Integer'], ['Int'], ['function', ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [seed, n, f, bounds]) + + +def quasi_monte_carlo(n, f, bounds): + """HMath.Calculus.quasiMonteCarlo :: Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_quasi_monte_carlo', [['Int'], ['function', ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [n, f, bounds]) + + +def cumulative_integral(value): + """HMath.Calculus.cumulativeIntegral :: [(Double, Double)] -> Either MathError [Double].""" + return _invoke('hmath_calculus_cumulative_integral', [['list', ['tuple', ['Double'], ['Double']]]], [value]) + + +def path_integral(tol, curve, tangent, f, a, b): + """HMath.Calculus.pathIntegral :: Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> Double) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_path_integral', [['Tolerance'], ['function', ['Double'], ['list', ['Double']]], ['function', ['Double'], ['list', ['Double']]], ['function', ['list', ['Double']], ['Double']], ['Double'], ['Double']], [tol, curve, tangent, f, a, b]) + + +def line_integral(tol, curve, tangent, field, a, b): + """HMath.Calculus.lineIntegral :: Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> Either MathError (Estimate Double).""" + return _invoke('hmath_calculus_line_integral', [['Tolerance'], ['function', ['Double'], ['list', ['Double']]], ['function', ['Double'], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double']], [tol, curve, tangent, field, a, b]) + + +def surface_integral(panels, budget, surface, du, dv, f, bounds): + """HMath.Calculus.surfaceIntegral :: Int -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double.""" + return _invoke('hmath_calculus_surface_integral', [['Int'], ['Int'], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [panels, budget, surface, du, dv, f, bounds]) + + +def volume_integral(panels, budget, f, bounds): + """HMath.Calculus.volumeIntegral :: Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double.""" + return _invoke('hmath_calculus_volume_integral', [['Int'], ['Int'], ['function', ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [panels, budget, f, bounds]) diff --git a/bindings/python/_hmath_native/combinatorics.py b/bindings/python/_hmath_native/combinatorics.py new file mode 100644 index 0000000..91ece74 --- /dev/null +++ b/bindings/python/_hmath_native/combinatorics.py @@ -0,0 +1,258 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def permutations_count(n, k): + """Call HMath.Combinatorics.permutationsCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_permutations_count', + ['i', 'i'], + 'z', + [n, k], + None, + 0, + ) + + +def combinations_count(n, k): + """Call HMath.Combinatorics.combinationsCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_combinations_count', + ['i', 'i'], + 'z', + [n, k], + None, + 0, + ) + + +def multinomial(argument1): + """Call HMath.Combinatorics.multinomial; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_multinomial', + ['is'], + 'z', + [argument1], + None, + 0, + ) + + +def rank_permutation(p): + """Call HMath.Combinatorics.rankPermutation; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_rank_permutation', + ['is'], + 'z', + [p], + None, + 0, + ) + + +def unrank_permutation(n, r): + """Call HMath.Combinatorics.unrankPermutation; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_unrank_permutation', + ['i', 'z'], + 'id', + [n, r], + None, + 0, + ) + + +def rank_combination(n, xs): + """Call HMath.Combinatorics.rankCombination; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_rank_combination', + ['i', 'is'], + 'z', + [n, xs], + None, + 0, + ) + + +def unrank_combination(n, k, r): + """Call HMath.Combinatorics.unrankCombination; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_unrank_combination', + ['i', 'i', 'z'], + 'id', + [n, k, r], + None, + 0, + ) + + +def derangement_count(n): + """Call HMath.Combinatorics.derangementCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_derangement_count', + ['i'], + 'z', + [n], + None, + 0, + ) + + +def stirling_first(argument1, argument2): + """Call HMath.Combinatorics.stirlingFirst; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_stirling_first', + ['i', 'i'], + 'z', + [argument1, argument2], + None, + 0, + ) + + +def stirling_second(argument1, argument2): + """Call HMath.Combinatorics.stirlingSecond; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_stirling_second', + ['i', 'i'], + 'z', + [argument1, argument2], + None, + 0, + ) + + +def bell_number(n): + """Call HMath.Combinatorics.bellNumber; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_bell_number', + ['i'], + 'z', + [n], + None, + 0, + ) + + +def eulerian_number(argument1, argument2): + """Call HMath.Combinatorics.eulerianNumber; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_eulerian_number', + ['i', 'i'], + 'z', + [argument1, argument2], + None, + 0, + ) + + +def lah_number(n, k): + """Call HMath.Combinatorics.lahNumber; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_lah_number', + ['i', 'i'], + 'z', + [n, k], + None, + 0, + ) + + +def catalan_number(argument1): + """Call HMath.Combinatorics.catalanNumber; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_catalan_number', + ['i'], + 'z', + [argument1], + None, + 0, + ) + + +def fibonacci(n): + """Call HMath.Combinatorics.fibonacci; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_fibonacci', + ['i'], + 'z', + [n], + None, + 0, + ) + + +def lucas(n): + """Call HMath.Combinatorics.lucas; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_lucas', + ['i'], + 'z', + [n], + None, + 0, + ) + + +def inclusion_exclusion(n, sizes): + """Call HMath.Combinatorics.inclusionExclusion; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_inclusion_exclusion', + ['i', 'zs'], + 'z', + [n, sizes], + None, + 0, + ) + + +def multiset_count(argument1, *, dtype='float64'): + """Call HMath.Combinatorics.multisetCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_multiset_count', + ['fs'], + 'z', + [argument1], + dtype, + 0, + ) + + +def linear_recurrence(n, cs, initial): + """Call HMath.Combinatorics.linearRecurrence; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_linear_recurrence', + ['i', 'zs', 'zs'], + 'zd', + [n, cs, initial], + None, + 0, + ) + + +def convolve_series(n, a, b): + """Call HMath.Combinatorics.convolveSeries; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_convolve_series', + ['i', 'zs', 'zs'], + 'zd', + [n, a, b], + None, + 0, + ) + + +def finite_sum(argument1, *, dtype='float64'): + """Call HMath.Combinatorics.finiteSum; preserve its argument order, result and errors.""" + return _call( + 'hmath_combinatorics_finite_sum', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +from .combinatorics_values import * diff --git a/bindings/python/_hmath_native/combinatorics_values.py b/bindings/python/_hmath_native/combinatorics_values.py new file mode 100644 index 0000000..a59a258 --- /dev/null +++ b/bindings/python/_hmath_native/combinatorics_values.py @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_foundation_bindings.py. +"""Original HMath.Combinatorics public functions and immutable values.""" + +from ._foundation_base import _invoke + + +def permutations_of(argument1, argument2, argument3): + "Distinct positions, including when values compare equal." + return _invoke( + "hmath_foundation_combinatorics_permutations_of", + [["Int"], ["Int"], ["list", ["a"]]], + [argument1, argument2, argument3], + "value", + ) + + +def combinations_of(argument1, argument2, argument3): + "Given output budget, selection length k, then list, enumerate position-distinct k-element combinations in source order. Invalid order or insufficient budget fails before output construction." + return _invoke( + "hmath_foundation_combinatorics_combinations_of", + [["Int"], ["Int"], ["list", ["a"]]], + [argument1, argument2, argument3], + "value", + ) + + +def derangements(argument1, argument2): + "Enumeration uses the factorial upper bound, so a request may be rejected even if its filtered derangement output would fit." + return _invoke( + "hmath_foundation_combinatorics_derangements", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def integer_partitions(argument1, argument2): + "Nonincreasing positive parts. The budget counts search nodes as well as outputs, preventing long searches with a tiny output limit." + return _invoke( + "hmath_foundation_combinatorics_integer_partitions", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def set_partitions(argument1, argument2): + "Set partitions of `[0,n)`, using restricted-growth order of block labels." + return _invoke( + "hmath_foundation_combinatorics_set_partitions", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def pascal_triangle(argument1): + "Return Pascal rows zero through n inclusive, starting [[1]]. n must lie in [0,512]; invalid orders fail." + return _invoke( + "hmath_foundation_combinatorics_pascal_triangle", + [["Int"]], + [argument1], + "value", + ) + + +def subsets(argument1, argument2): + "Given maximum output count then list, enumerate its position-based powerset. Reject input order >4096 or a budget smaller than 2^length. Equal input values can yield equal-valued subsets." + return _invoke( + "hmath_foundation_combinatorics_subsets", + [["Int"], ["list", ["a"]]], + [argument1, argument2], + "value", + ) + + +def cartesian_product(argument1, argument2): + "Given output budget then a list of lists, return all ordered choices using sequence. Reject negative/insufficient budget before constructing results. Empty outer list yields one empty choice." + return _invoke( + "hmath_foundation_combinatorics_cartesian_product", + [["Int"], ["list", ["list", ["a"]]]], + [argument1, argument2], + "value", + ) + + +def multiset_permutations(argument1, argument2, *, prototype=None): + "Given budget then ordered values, enumerate distinct multiset permutations in ascending lexicographic order. Invalid size or insufficient output budget fails before enumeration." + return _invoke( + "hmath_foundation_combinatorics_multiset_permutations", + [["Int"], ["list", ["a"]]], + [argument1, argument2], + "ordered", + prototype=prototype, + ) + + +def generating_coefficients(argument1, argument2, argument3): + "Formal power-series division `P(x)/Q(x)` around zero, exact rationals. The denominator constant must be nonzero; no analytic convergence is claimed." + return _invoke( + "hmath_foundation_combinatorics_generating_coefficients", + [["Int"], ["list", ["Rational"]], ["list", ["Rational"]]], + [argument1, argument2, argument3], + "value", + ) + + +def finite_differences(argument1, *, dtype=None): + "Return successive forward-difference rows beginning with the original list and ending at the last singleton. Empty input yields no rows. Example: finiteDifferences [1,4,9] == [[1,4,9],[3,5],[2]]." + return _invoke( + "hmath_foundation_combinatorics_finite_differences", + [["list", ["a"]]], + [argument1], + "numeric", + dtype, + ) + + +__all__ = [ + "cartesian_product", + "combinations_of", + "derangements", + "finite_differences", + "generating_coefficients", + "integer_partitions", + "multiset_permutations", + "pascal_triangle", + "permutations_of", + "set_partitions", + "subsets", +] diff --git a/bindings/python/_hmath_native/complex.py b/bindings/python/_hmath_native/complex.py new file mode 100644 index 0000000..07d03d8 --- /dev/null +++ b/bindings/python/_hmath_native/complex.py @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def to_polar(z, *, dtype='float64'): + """Call HMath.Complex.toPolar; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_to_polar', + ['c'], + 'ff', + [z], + dtype, + 0, + ) + + +def complex(real, imaginary, *, dtype='float64'): + """Call HMath.Complex.complex; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_complex', + ['f', 'f'], + 'c', + [real, imaginary], + dtype, + 0, + ) + + +def reciprocal(z, *, dtype='float64'): + """Call HMath.Complex.reciprocal; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_reciprocal', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def add(a, b, *, dtype='float64'): + """Call HMath.Complex.add; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_add', + ['c', 'c'], + 'c', + [a, b], + dtype, + 0, + ) + + +def subtract_complex(a, b, *, dtype='float64'): + """Call HMath.Complex.subtractComplex; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_subtract_complex', + ['c', 'c'], + 'c', + [a, b], + dtype, + 0, + ) + + +def multiply(a, b, *, dtype='float64'): + """Call HMath.Complex.multiply; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_multiply', + ['c', 'c'], + 'c', + [a, b], + dtype, + 0, + ) + + +def divide(a, b, *, dtype='float64'): + """Call HMath.Complex.divide; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_divide', + ['c', 'c'], + 'c', + [a, b], + dtype, + 0, + ) + + +def power(a, b, *, dtype='float64'): + """Call HMath.Complex.power; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_power', + ['c', 'c'], + 'c', + [a, b], + dtype, + 0, + ) + + +def from_polar(radius, angle, *, dtype='float64'): + """Call HMath.Complex.fromPolar; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_from_polar', + ['f', 'f'], + 'c', + [radius, angle], + dtype, + 0, + ) + + +def rotate(angle, z, *, dtype='float64'): + """Call HMath.Complex.rotate; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_complex_rotate', + ['f', 'c'], + 'c', + [angle, z], + dtype, + 0, + ) + + +from .complex_extras import * diff --git a/bindings/python/_hmath_native/complex_extras.py b/bindings/python/_hmath_native/complex_extras.py new file mode 100644 index 0000000..7c9200d --- /dev/null +++ b/bindings/python/_hmath_native/complex_extras.py @@ -0,0 +1,134 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_scalar_extras.py; do not edit. +from ._scalar_extras_base import Elementary, _invoke + + +def exp(): + """HMath.Complex.Exp :: Elementary.""" + return _invoke('hmath_complex_exp', [], [], 'Elementary') + + +def log(): + """HMath.Complex.Log :: Elementary.""" + return _invoke('hmath_complex_log', [], [], 'Elementary') + + +def sqrt(): + """HMath.Complex.Sqrt :: Elementary.""" + return _invoke('hmath_complex_sqrt', [], [], 'Elementary') + + +def sin(): + """HMath.Complex.Sin :: Elementary.""" + return _invoke('hmath_complex_sin', [], [], 'Elementary') + + +def cos(): + """HMath.Complex.Cos :: Elementary.""" + return _invoke('hmath_complex_cos', [], [], 'Elementary') + + +def tan(): + """HMath.Complex.Tan :: Elementary.""" + return _invoke('hmath_complex_tan', [], [], 'Elementary') + + +def sinh(): + """HMath.Complex.Sinh :: Elementary.""" + return _invoke('hmath_complex_sinh', [], [], 'Elementary') + + +def cosh(): + """HMath.Complex.Cosh :: Elementary.""" + return _invoke('hmath_complex_cosh', [], [], 'Elementary') + + +def tanh(): + """HMath.Complex.Tanh :: Elementary.""" + return _invoke('hmath_complex_tanh', [], [], 'Elementary') + + +def asin(): + """HMath.Complex.Asin :: Elementary.""" + return _invoke('hmath_complex_asin', [], [], 'Elementary') + + +def acos(): + """HMath.Complex.Acos :: Elementary.""" + return _invoke('hmath_complex_acos', [], [], 'Elementary') + + +def atan(): + """HMath.Complex.Atan :: Elementary.""" + return _invoke('hmath_complex_atan', [], [], 'Elementary') + + +def asinh(): + """HMath.Complex.Asinh :: Elementary.""" + return _invoke('hmath_complex_asinh', [], [], 'Elementary') + + +def acosh(): + """HMath.Complex.Acosh :: Elementary.""" + return _invoke('hmath_complex_acosh', [], [], 'Elementary') + + +def atanh(): + """HMath.Complex.Atanh :: Elementary.""" + return _invoke('hmath_complex_atanh', [], [], 'Elementary') + + +def elementary(operation, value): + """HMath.Complex.elementary :: Elementary -> Complex Double -> Either MathError (Complex Double).""" + return _invoke('hmath_complex_elementary', ['Elementary', 'ComplexDouble'], [operation, value], 'ComplexDouble') + + +def complex_matrix(rows, columns, values): + """HMath.Complex.complexMatrix :: Int -> Int -> [Complex Double] -> Either MathError (Matrix (Complex Double)).""" + return _invoke('hmath_complex_complex_matrix', ['Int', 'Int', '[ComplexDouble]'], [rows, columns, values], 'ComplexMatrix') + + +def multiply_matrices(a, b): + """HMath.Complex.multiplyMatrices :: Matrix (Complex Double) -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)).""" + return _invoke('hmath_complex_multiply_matrices', ['ComplexMatrix', 'ComplexMatrix'], [a, b], 'ComplexMatrix') + + +def conjugate_transpose(value): + """HMath.Complex.conjugateTranspose :: Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)).""" + return _invoke('hmath_complex_conjugate_transpose', ['ComplexMatrix'], [value], 'ComplexMatrix') + + +def complex_fft(values): + """HMath.Complex.complexFFT :: [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_complex_complex_fft', ['[ComplexDouble]'], [values], '[ComplexDouble]') + + +def complex_ifft(values): + """HMath.Complex.complexIFFT :: [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_complex_complex_ifft', ['[ComplexDouble]'], [values], '[ComplexDouble]') + + +__all__ = [ + "Elementary", + "acos", + "acosh", + "asin", + "asinh", + "atan", + "atanh", + "complex_fft", + "complex_ifft", + "complex_matrix", + "conjugate_transpose", + "cos", + "cosh", + "elementary", + "exp", + "log", + "multiply_matrices", + "sin", + "sinh", + "sqrt", + "tan", + "tanh" +] diff --git a/bindings/python/_hmath_native/constants.py b/bindings/python/_hmath_native/constants.py new file mode 100644 index 0000000..63c629a --- /dev/null +++ b/bindings/python/_hmath_native/constants.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def pi_constant(*, dtype='float64'): + """Call HMath.Constants.piConstant; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_pi_constant', + [], + 'f', + [], + dtype, + 0, + ) + + +def e_constant(*, dtype='float64'): + """Call HMath.Constants.eConstant; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_e_constant', + [], + 'f', + [], + dtype, + 0, + ) + + +def tau(*, dtype='float64'): + """Call HMath.Constants.tau; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_tau', + [], + 'f', + [], + dtype, + 0, + ) + + +def golden_ratio(*, dtype='float64'): + """Call HMath.Constants.goldenRatio; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_golden_ratio', + [], + 'f', + [], + dtype, + 0, + ) + + +def euler_mascheroni(*, dtype='float64'): + """Call HMath.Constants.eulerMascheroni; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_euler_mascheroni', + [], + 'f', + [], + dtype, + 0, + ) + + +def catalan_constant(*, dtype='float64'): + """Call HMath.Constants.catalanConstant; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_catalan_constant', + [], + 'f', + [], + dtype, + 0, + ) + + +def apery_constant(*, dtype='float64'): + """Call HMath.Constants.aperyConstant; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_apery_constant', + [], + 'f', + [], + dtype, + 0, + ) + + +def sqrt2(*, dtype='float64'): + """Call HMath.Constants.sqrt2; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_sqrt2', + [], + 'f', + [], + dtype, + 0, + ) + + +def sqrt3(*, dtype='float64'): + """Call HMath.Constants.sqrt3; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_sqrt3', + [], + 'f', + [], + dtype, + 0, + ) + + +def ln2(*, dtype='float64'): + """Call HMath.Constants.ln2; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_ln2', + [], + 'f', + [], + dtype, + 0, + ) + + +def ln10(*, dtype='float64'): + """Call HMath.Constants.ln10; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_ln10', + [], + 'f', + [], + dtype, + 0, + ) + + +def infinity(*, dtype='float64'): + """Call HMath.Constants.infinity; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_infinity', + [], + 'f', + [], + dtype, + 0, + ) + + +def nan(*, dtype='float64'): + """Call HMath.Constants.nan; preserve its argument order, result and errors.""" + return _call( + 'hmath_constants_nan', + [], + 'f', + [], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/convergence_values.py b/bindings/python/_hmath_native/convergence_values.py new file mode 100644 index 0000000..3984690 --- /dev/null +++ b/bindings/python/_hmath_native/convergence_values.py @@ -0,0 +1,305 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_foundation_bindings.py. +"""Original HMath.API.Convergence public functions and immutable values.""" + +from ._foundation_base import FoundationValue, _invoke, register + + +class StopReason(FoundationValue): + """Original HMath.API.Convergence.StopReason immutable owner.""" + + _source_type = "HMath.API.Convergence.StopReason" + + +register("HMath.API.Convergence.StopReason", StopReason) + + +class Convergence(FoundationValue): + """Original HMath.API.Convergence.Convergence immutable owner.""" + + _source_type = "HMath.API.Convergence.Convergence" + + def __init__(self, estimate, iteration_count, final_residual, stop_reason): + self._initialize( + "hmath_foundation_convergence_new_convergence", + [["a"], ["Int"], ["Double"], ["StopReason"]], + [estimate, iteration_count, final_residual, stop_reason], + "equality", + ) + + @property + def estimate(self): + return _invoke( + "hmath_foundation_convergence_estimate", + [["Convergence", ["a"]]], + [self], + "equality", + ) + + @property + def iteration_count(self): + return _invoke( + "hmath_foundation_convergence_iteration_count", + [["Convergence", ["a"]]], + [self], + "equality", + ) + + @property + def final_residual(self): + return _invoke( + "hmath_foundation_convergence_final_residual", + [["Convergence", ["a"]]], + [self], + "equality", + ) + + @property + def stop_reason(self): + return _invoke( + "hmath_foundation_convergence_stop_reason", + [["Convergence", ["a"]]], + [self], + "equality", + ) + + +register("HMath.API.Convergence.Convergence", Convergence) + + +class IterationOptions(FoundationValue): + """Original HMath.API.Convergence.IterationOptions immutable owner.""" + + _source_type = "HMath.API.Convergence.IterationOptions" + + def __init__(self, maximum_iterations, absolute_tolerance, relative_tolerance): + self._initialize( + "hmath_foundation_convergence_new_iteration_options", + [["Int"], ["Double"], ["Double"]], + [maximum_iterations, absolute_tolerance, relative_tolerance], + "equality", + ) + + @property + def maximum_iterations(self): + return _invoke( + "hmath_foundation_convergence_maximum_iterations", + [["IterationOptions"]], + [self], + "equality", + ) + + @property + def absolute_tolerance(self): + return _invoke( + "hmath_foundation_convergence_absolute_tolerance", + [["IterationOptions"]], + [self], + "equality", + ) + + @property + def relative_tolerance(self): + return _invoke( + "hmath_foundation_convergence_relative_tolerance", + [["IterationOptions"]], + [self], + "equality", + ) + + +register("HMath.API.Convergence.IterationOptions", IterationOptions) + + +def default_iteration_options(): + "Default iteration budget 1000, absolute tolerance 1e-12, relative tolerance 1e-10. Use record updates to configure a solver; iterateUntil validates nonnegative finite tolerances." + return _invoke( + "hmath_foundation_convergence_default_iteration_options", [], [], "equality" + ) + + +def iterate_until(argument1, argument2, argument3, argument4, argument5): + "Stop at residual <= atol + rtol * initialResidual. Comparisons are scaled to avoid overflow in that sum. The initial value is tested at iteration zero." + return _invoke( + "hmath_foundation_convergence_iterate_until", + [ + ["IterationOptions"], + ["function", ["a"], ["Either", ["MathError"], ["a"]]], + ["function", ["a"], ["Either", ["MathError"], ["Double"]]], + ["function", ["a"], ["a"], ["Bool"]], + ["a"], + ], + [argument1, argument2, argument3, argument4, argument5], + "equality", + ) + + +def require_convergence(argument1, argument2): + "Given operation name then convergence report, return its estimate only for ResidualSatisfied. IterationLimit or Stagnation becomes Left (NonConvergence name iterationCount), preserving the distinction between execution and convergence." + return _invoke( + "hmath_foundation_convergence_require_convergence", + [["String"], ["Convergence", ["a"]]], + [argument1, argument2], + "equality", + ) + + +def result_maybe(argument1): + "Explicitly discard error details for callers retaining a Maybe interface." + return _invoke( + "hmath_foundation_convergence_result_maybe", + [["Either", ["e"], ["a"]]], + [argument1], + "value", + ) + + +def from_maybe_error(argument1, argument2): + 'Given error value then Maybe result, convert Nothing to Left error and Just x to Right x. Example: fromMaybeError "missing" (Just 3) == Right 3.' + return _invoke( + "hmath_foundation_convergence_from_maybe_error", + [["e"], ["Maybe", ["a"]]], + [argument1, argument2], + "value", + ) + + +def residual_satisfied(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_convergence_new_residual_satisfied", [], [], "equality" + ) + + +def iteration_limit(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_convergence_new_iteration_limit", [], [], "equality" + ) + + +def stagnation(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_foundation_convergence_new_stagnation", [], [], "equality") + + +def estimate(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_estimate", + [["Convergence", ["a"]]], + [argument1], + "equality", + ) + + +def iteration_count(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_iteration_count", + [["Convergence", ["a"]]], + [argument1], + "equality", + ) + + +def final_residual(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_final_residual", + [["Convergence", ["a"]]], + [argument1], + "equality", + ) + + +def stop_reason(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_stop_reason", + [["Convergence", ["a"]]], + [argument1], + "equality", + ) + + +def maximum_iterations(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_maximum_iterations", + [["IterationOptions"]], + [argument1], + "equality", + ) + + +def absolute_tolerance(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_absolute_tolerance", + [["IterationOptions"]], + [argument1], + "equality", + ) + + +def relative_tolerance(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_convergence_relative_tolerance", + [["IterationOptions"]], + [argument1], + "equality", + ) + + +def converged(argument1): + "Read-only successful view. The report still retains its residual and count." + return _invoke( + "hmath_foundation_convergence_converged", + [["Convergence", ["a"]]], + [argument1], + "equality", + ) + + +from ._foundation_base import ( + Either, + Just, + OrderedType, + just, + left, + optional_type, + ordered_type, + right, +) + +__all__ = [ + "Convergence", + "Either", + "IterationOptions", + "Just", + "OrderedType", + "StopReason", + "absolute_tolerance", + "converged", + "default_iteration_options", + "estimate", + "final_residual", + "from_maybe_error", + "iterate_until", + "iteration_count", + "iteration_limit", + "just", + "left", + "maximum_iterations", + "optional_type", + "ordered_type", + "relative_tolerance", + "require_convergence", + "residual_satisfied", + "result_maybe", + "right", + "stagnation", + "stop_reason", +] diff --git a/bindings/python/_hmath_native/data_structures.py b/bindings/python/_hmath_native/data_structures.py new file mode 100644 index 0000000..f819c09 --- /dev/null +++ b/bindings/python/_hmath_native/data_structures.py @@ -0,0 +1,706 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_foundation_bindings.py. +"""Original HMath.DataStructure public functions and immutable values.""" + +from ._foundation_base import FoundationValue, _invoke, register + + +class Fenwick(FoundationValue): + """Original HMath.DataStructure.Fenwick immutable owner.""" + + _source_type = "HMath.DataStructure.Fenwick" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_fenwick", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.Fenwick", Fenwick) + + +class SegmentTree(FoundationValue): + """Original HMath.DataStructure.SegmentTree immutable owner.""" + + _source_type = "HMath.DataStructure.SegmentTree" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_segment_tree", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.SegmentTree", SegmentTree) + + +class SparseTable(FoundationValue): + """Original HMath.DataStructure.SparseTable immutable owner.""" + + _source_type = "HMath.DataStructure.SparseTable" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_sparse_table", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.SparseTable", SparseTable) + + +class DisjointSparseTable(FoundationValue): + """Original HMath.DataStructure.DisjointSparseTable immutable owner.""" + + _source_type = "HMath.DataStructure.DisjointSparseTable" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_disjoint_sparse_table", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.DisjointSparseTable", DisjointSparseTable) + + +class Heap(FoundationValue): + """Original HMath.DataStructure.Heap immutable owner.""" + + _source_type = "HMath.DataStructure.Heap" + + def __init__(self, argument1, *, prototype=None): + self._initialize( + "hmath_foundation_datastructure_heap_from_list", + [["list", ["a"]]], + [argument1], + "value", + prototype=prototype, + ) + + +register("HMath.DataStructure.Heap", Heap) + + +class BinaryHeap(FoundationValue): + """Original HMath.DataStructure.BinaryHeap immutable owner.""" + + _source_type = "HMath.DataStructure.BinaryHeap" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_binary_heap", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.BinaryHeap", BinaryHeap) + + +class IndexedHeap(FoundationValue): + """Original HMath.DataStructure.IndexedHeap immutable owner.""" + + _source_type = "HMath.DataStructure.IndexedHeap" + + def __init__(self): + self._initialize("hmath_foundation_datastructure_indexed_heap", [], [], "value") + + +register("HMath.DataStructure.IndexedHeap", IndexedHeap) + + +class UnionFind(FoundationValue): + """Original HMath.DataStructure.UnionFind immutable owner.""" + + _source_type = "HMath.DataStructure.UnionFind" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_union_find", [["Int"]], [argument1], "value" + ) + + +register("HMath.DataStructure.UnionFind", UnionFind) + + +class Bloom(FoundationValue): + """Original HMath.DataStructure.Bloom immutable owner.""" + + _source_type = "HMath.DataStructure.Bloom" + + def __init__(self, argument1, argument2): + self._initialize( + "hmath_foundation_datastructure_bloom", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +register("HMath.DataStructure.Bloom", Bloom) + + +class CountMin(FoundationValue): + """Original HMath.DataStructure.CountMin immutable owner.""" + + _source_type = "HMath.DataStructure.CountMin" + + def __init__(self, argument1, argument2): + self._initialize( + "hmath_foundation_datastructure_count_min", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +register("HMath.DataStructure.CountMin", CountMin) + + +class HyperLogLog(FoundationValue): + """Original HMath.DataStructure.HyperLogLog immutable owner.""" + + _source_type = "HMath.DataStructure.HyperLogLog" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_hyper_log_log", + [["Int"]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.HyperLogLog", HyperLogLog) + + +class Reservoir(FoundationValue): + """Original HMath.DataStructure.Reservoir immutable owner.""" + + _source_type = "HMath.DataStructure.Reservoir" + + def __init__(self, argument1, argument2): + self._initialize( + "hmath_foundation_datastructure_reservoir", + [["Int"], ["Word64"]], + [argument1, argument2], + "equality", + ) + + +register("HMath.DataStructure.Reservoir", Reservoir) + + +class OnlineQuantiles(FoundationValue): + """Original HMath.DataStructure.OnlineQuantiles immutable owner.""" + + _source_type = "HMath.DataStructure.OnlineQuantiles" + + def __init__(self, argument1): + self._initialize( + "hmath_foundation_datastructure_online_quantiles", + [["Int"]], + [argument1], + "value", + ) + + +register("HMath.DataStructure.OnlineQuantiles", OnlineQuantiles) + + +def fenwick(argument1): + "Build an immutable Fenwick prefix-sum tree from at most 1048576 Integers. Oversized input fails; indices in public operations are zero based." + return _invoke( + "hmath_foundation_datastructure_fenwick", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +def fenwick_add(argument1, argument2, argument3): + "Given zero-based index,delta,then Fenwick tree, return a new tree with that value incremented. Invalid index returns Left InvalidArgument." + return _invoke( + "hmath_foundation_datastructure_fenwick_add", + [["Int"], ["Integer"], ["Fenwick"]], + [argument1, argument2, argument3], + "value", + ) + + +def fenwick_prefix(argument1, argument2): + "Given exclusive end then tree, return exact sum over [0,end). Require 0\\<=end\\<=length; invalid bounds fail." + return _invoke( + "hmath_foundation_datastructure_fenwick_prefix", + [["Int"], ["Fenwick"]], + [argument1, argument2], + "value", + ) + + +def fenwick_range(argument1, argument2, argument3): + "Given lo,hi,then tree, return exact half-open sum over [lo,hi). Invalid/reversed bounds fail; empty range gives zero." + return _invoke( + "hmath_foundation_datastructure_fenwick_range", + [["Int"], ["Int"], ["Fenwick"]], + [argument1, argument2, argument3], + "value", + ) + + +def segment_tree(argument1): + "Build an immutable Integer sum segment tree from at most 1048576 values. Invalid size fails; later queries use half-open bounds." + return _invoke( + "hmath_foundation_datastructure_segment_tree", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +def segment_set(argument1, argument2, argument3): + "Given zero-based index,new Integer,then segment tree, return an updated tree. Invalid index fails; the original remains unchanged." + return _invoke( + "hmath_foundation_datastructure_segment_set", + [["Int"], ["Integer"], ["SegmentTree"]], + [argument1, argument2, argument3], + "value", + ) + + +def segment_range(argument1, argument2, argument3): + "Given lo,hi,then segment tree, return Integer sum over [lo,hi). Invalid bounds fail; an empty range gives zero." + return _invoke( + "hmath_foundation_datastructure_segment_range", + [["Int"], ["Int"], ["SegmentTree"]], + [argument1, argument2, argument3], + "value", + ) + + +def sparse_table(argument1): + "Precompute range minima for at most 1048576 Integers. Return immutable sparse table; oversized input fails." + return _invoke( + "hmath_foundation_datastructure_sparse_table", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +def sparse_minimum(argument1, argument2, argument3): + "Given lo,hi,then sparse table, return minimum over nonempty [lo,hi). Out-of-range/reversed or empty bounds fail." + return _invoke( + "hmath_foundation_datastructure_sparse_minimum", + [["Int"], ["Int"], ["SparseTable"]], + [argument1, argument2, argument3], + "value", + ) + + +def disjoint_sparse_table(argument1): + "Suffix/prefix blocks for associative integer addition, O(n log n) build and O(1) arithmetic for nonempty queries. Also handles an empty range as zero." + return _invoke( + "hmath_foundation_datastructure_disjoint_sparse_table", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +def disjoint_range(argument1, argument2, argument3): + "Given lo,hi,then disjoint sparse sum table, return exact sum over [lo,hi). Invalid bounds fail; empty range yields zero." + return _invoke( + "hmath_foundation_datastructure_disjoint_range", + [["Int"], ["Int"], ["DisjointSparseTable"]], + [argument1, argument2, argument3], + "value", + ) + + +def next_greater(argument1, *, prototype=None): + "For each list position, return Maybe index of its first strictly greater element to the right, using a monotone stack. Preserve input length; absent successors yield Nothing." + return _invoke( + "hmath_foundation_datastructure_next_greater", + [["list", ["a"]]], + [argument1], + "ordered", + prototype=prototype, + ) + + +def empty_heap(): + "Construct an empty persistent leftist min-heap. heapPop returns Nothing until values are inserted." + return _invoke("hmath_foundation_datastructure_empty_heap", [], [], "value") + + +def heap_insert(argument1, argument2): + "Given value then persistent min-heap, return a new heap containing it. Duplicate values are retained; original heap remains valid." + return _invoke( + "hmath_foundation_datastructure_heap_insert", + [["a"], ["Heap", ["a"]]], + [argument1, argument2], + "value", + ) + + +def heap_pop(argument1): + "Return Nothing for empty heap, otherwise Just (smallest value,remaining heap). Ties follow lawful Ord without discarding duplicates." + return _invoke( + "hmath_foundation_datastructure_heap_pop", + [["Heap", ["a"]]], + [argument1], + "value", + ) + + +def heap_from_list(argument1, *, prototype=None): + "Build a persistent min-heap from a finite list, retaining all elements including duplicates." + return _invoke( + "hmath_foundation_datastructure_heap_from_list", + [["list", ["a"]]], + [argument1], + "value", + prototype=prototype, + ) + + +def binary_heap(argument1): + "Build an array-backed Integer min-heap from at most 1048576 values. Oversized input fails." + return _invoke( + "hmath_foundation_datastructure_binary_heap", + [["list", ["Integer"]]], + [argument1], + "value", + ) + + +def binary_insert(argument1, argument2): + "Given Integer then binary heap, return a persistent updated min-heap. The insert operation itself has no Either size check." + return _invoke( + "hmath_foundation_datastructure_binary_insert", + [["Integer"], ["BinaryHeap"]], + [argument1, argument2], + "value", + ) + + +def binary_pop(argument1): + "Return Nothing if empty, otherwise the smallest Integer and a new binary heap containing the remaining values." + return _invoke( + "hmath_foundation_datastructure_binary_pop", + [["BinaryHeap"]], + [argument1], + "value", + ) + + +def indexed_heap(): + "Construct an empty indexed priority queue. Each Int key has at most one Integer priority." + return _invoke("hmath_foundation_datastructure_indexed_heap", [], [], "value") + + +def indexed_set(argument1, argument2, argument3): + "Given Int key,Integer priority,then indexed heap, set or replace that key's priority. Return a new queue; an existing key is updated, not duplicated." + return _invoke( + "hmath_foundation_datastructure_indexed_set", + [["Int"], ["Integer"], ["IndexedHeap"]], + [argument1, argument2, argument3], + "value", + ) + + +def indexed_pop(argument1): + "Return Just ((key,priority),remaining queue) for the minimum (priority,key) pair, or Nothing if empty." + return _invoke( + "hmath_foundation_datastructure_indexed_pop", + [["IndexedHeap"]], + [argument1], + "value", + ) + + +def union_find(argument1): + "Construct disjoint singleton sets for n zero-based elements, requiring n in [0,1048576]. Invalid size fails." + return _invoke( + "hmath_foundation_datastructure_union_find", [["Int"]], [argument1], "value" + ) + + +def find_root(argument1, argument2): + "Given element index then union-find structure, return representative root. Invalid index fails; this pure query does not mutate/compress the stored structure." + return _invoke( + "hmath_foundation_datastructure_find_root", + [["Int"], ["UnionFind"]], + [argument1, argument2], + "value", + ) + + +def union(argument1, argument2, argument3): + "Given two valid indices then union-find, return a new structure merging their components by size. Invalid indices fail; already connected inputs leave connectivity unchanged." + return _invoke( + "hmath_foundation_datastructure_union", + [["Int"], ["Int"], ["UnionFind"]], + [argument1, argument2, argument3], + "value", + ) + + +def connected(argument1, argument2, argument3): + "Given two indices then union-find, return whether their roots match. Invalid indices return Left InvalidArgument." + return _invoke( + "hmath_foundation_datastructure_connected", + [["Int"], ["Int"], ["UnionFind"]], + [argument1, argument2, argument3], + "value", + ) + + +def components(argument1): + "Return all disjoint components as lists of zero-based element indices, including singleton sets." + return _invoke( + "hmath_foundation_datastructure_components", + [["UnionFind"]], + [argument1], + "value", + ) + + +def bloom(argument1, argument2): + "Given bit count m in [1,1048576] then hash count k in [1,64], construct an empty Bloom filter. Invalid dimensions fail." + return _invoke( + "hmath_foundation_datastructure_bloom", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def bloom_insert(argument1, argument2): + "Given Word64 key then Bloom filter, set its k hash positions and return updated filter. Reinsertions are permitted; false positives remain possible." + return _invoke( + "hmath_foundation_datastructure_bloom_insert", + [["Word64"], ["Bloom"]], + [argument1, argument2], + "value", + ) + + +def bloom_member(argument1, argument2): + "Test a Word64 key against all Bloom hash positions. False means definitely absent; True may be a false positive under the documented hash model." + return _invoke( + "hmath_foundation_datastructure_bloom_member", + [["Word64"], ["Bloom"]], + [argument1, argument2], + "value", + ) + + +def bloom_false_positive_bound(argument1): + "Conservative union bound `min(1,k*n/m)^k` under independent uniform query hashes, since at most k*n bits can be occupied. This is a bound rather than the common exponential occupancy approximation." + return _invoke( + "hmath_foundation_datastructure_bloom_false_positive_bound", + [["Bloom"]], + [argument1], + "value", + ) + + +def count_min(argument1, argument2): + "Given positive width and depth with product\\<=1048576, construct an empty count-min sketch. Invalid dimensions fail." + return _invoke( + "hmath_foundation_datastructure_count_min", + [["Int"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def count_min_add(argument1, argument2, argument3): + "Given Word64 key,nonnegative Integer increment,then sketch, increment its hash counters. Negative updates fail; return a persistent updated sketch." + return _invoke( + "hmath_foundation_datastructure_count_min_add", + [["Word64"], ["Integer"], ["CountMin"]], + [argument1, argument2, argument3], + "value", + ) + + +def count_min_estimate(argument1, argument2): + "Given Word64 key then sketch, return minimum associated counter as an Integer frequency estimate. It may overestimate through collisions; use countMinErrorBound for the documented model." + return _invoke( + "hmath_foundation_datastructure_count_min_estimate", + [["Word64"], ["CountMin"]], + [argument1, argument2], + "value", + ) + + +def count_min_error_bound(argument1): + "`(additive error, failure probability)` under the uniform-hash model." + return _invoke( + "hmath_foundation_datastructure_count_min_error_bound", + [["CountMin"]], + [argument1], + "value", + ) + + +def hyper_log_log(argument1): + "Construct an empty cardinality sketch from precision p in [4,16], using 2^p registers. Invalid precision fails; hllEstimate returns its probabilistic estimate." + return _invoke( + "hmath_foundation_datastructure_hyper_log_log", [["Int"]], [argument1], "value" + ) + + +def hll_add(argument1, argument2): + "Given Word64 item then HyperLogLog sketch, hash and update its register maximum. Return persistent updated sketch; repeated items do not add a new exact count." + return _invoke( + "hmath_foundation_datastructure_hll_add", + [["Word64"], ["HyperLogLog"]], + [argument1, argument2], + "value", + ) + + +def hll_estimate(argument1): + "HyperLogLog with linear-counting small-range correction. Typical relative standard error is approximately `1.04/sqrt(2^p)` under uniform hashing." + return _invoke( + "hmath_foundation_datastructure_hll_estimate", + [["HyperLogLog"]], + [argument1], + "value", + ) + + +def reservoir(argument1, argument2): + "Given sample capacity in [0,1048576] then Word64 seed, construct an empty deterministic Algorithm-R reservoir. Invalid capacity fails." + return _invoke( + "hmath_foundation_datastructure_reservoir", + [["Int"], ["Word64"]], + [argument1, argument2], + "equality", + ) + + +def reservoir_add(argument1, argument2): + "Algorithm R with rejection sampling (no modulo bias). The 64-bit stream index is bounded; uniform sampling assumes the pseudorandom stream model." + return _invoke( + "hmath_foundation_datastructure_reservoir_add", + [["a"], ["Reservoir", ["a"]]], + [argument1, argument2], + "equality", + ) + + +def reservoir_values(argument1): + "Return retained reservoir sample values. Their count never exceeds capacity; output order is storage order, not a sorted or arrival-order guarantee." + return _invoke( + "hmath_foundation_datastructure_reservoir_values", + [["Reservoir", ["a"]]], + [argument1], + "equality", + ) + + +def online_quantiles(argument1): + "Given exact-storage cap in [0,1048576], create an empty online order-statistics container. Invalid capacity fails; this retains exact values rather than a bounded-memory approximate sketch." + return _invoke( + "hmath_foundation_datastructure_online_quantiles", + [["Int"]], + [argument1], + "value", + ) + + +def quantile_add(argument1, argument2): + "Given finite Double then quantile container, insert in sorted order. Non-finite values or a full cap fail without eviction; original container is unchanged." + return _invoke( + "hmath_foundation_datastructure_quantile_add", + [["Double"], ["OnlineQuantiles"]], + [argument1, argument2], + "value", + ) + + +def online_quantile(argument1, argument2): + "Given finite q in [0,1] then nonempty quantile container, linearly interpolate order statistics at q*(n-1). Invalid q or empty state returns Left InvalidArgument." + return _invoke( + "hmath_foundation_datastructure_online_quantile", + [["Double"], ["OnlineQuantiles"]], + [argument1, argument2], + "value", + ) + + +__all__ = [ + "BinaryHeap", + "Bloom", + "CountMin", + "DisjointSparseTable", + "Fenwick", + "Heap", + "HyperLogLog", + "IndexedHeap", + "OnlineQuantiles", + "Reservoir", + "SegmentTree", + "SparseTable", + "UnionFind", + "binary_heap", + "binary_insert", + "binary_pop", + "bloom", + "bloom_false_positive_bound", + "bloom_insert", + "bloom_member", + "components", + "connected", + "count_min", + "count_min_add", + "count_min_error_bound", + "count_min_estimate", + "disjoint_range", + "disjoint_sparse_table", + "empty_heap", + "fenwick", + "fenwick_add", + "fenwick_prefix", + "fenwick_range", + "find_root", + "heap_from_list", + "heap_insert", + "heap_pop", + "hll_add", + "hll_estimate", + "hyper_log_log", + "indexed_heap", + "indexed_pop", + "indexed_set", + "next_greater", + "online_quantile", + "online_quantiles", + "quantile_add", + "reservoir", + "reservoir_add", + "reservoir_values", + "segment_range", + "segment_set", + "segment_tree", + "sparse_minimum", + "sparse_table", + "union", + "union_find", +] diff --git a/bindings/python/_hmath_native/datastructure.py b/bindings/python/_hmath_native/datastructure.py new file mode 100644 index 0000000..f59e137 --- /dev/null +++ b/bindings/python/_hmath_native/datastructure.py @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def monotonic_minima(argument1, argument2, *, dtype='float64'): + """Call HMath.DataStructure.monotonicMinima; preserve its argument order, result and errors.""" + return _call( + 'hmath_datastructure_monotonic_minima', + ['i', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +from .data_structures import * diff --git a/bindings/python/_hmath_native/decomposition.py b/bindings/python/_hmath_native/decomposition.py new file mode 100644 index 0000000..0b29011 --- /dev/null +++ b/bindings/python/_hmath_native/decomposition.py @@ -0,0 +1,445 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Matrix.Decomposition public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class Bidiagonal(LinearValue): + """Original HMath.Matrix.Decomposition.Bidiagonal immutable owner.""" + + _source_type = "HMath.Matrix.Decomposition.Bidiagonal" + + def __init__(self, bidiagonal_u, bidiagonal_b, bidiagonal_v, *, dtype=None): + self._initialize( + "hmath_linear_decomposition_new_bidiagonal", + True, + [["Matrix", ["a"]], ["Matrix", ["a"]], ["Matrix", ["a"]]], + [bidiagonal_u, bidiagonal_b, bidiagonal_v], + dtype, + ) + + @property + def bidiagonal_u(self): + return _invoke( + "hmath_linear_decomposition_bidiagonal_u", + True, + [["Bidiagonal", ["a"]]], + [self], + ) + + @property + def bidiagonal_b(self): + return _invoke( + "hmath_linear_decomposition_bidiagonal_b", + True, + [["Bidiagonal", ["a"]]], + [self], + ) + + @property + def bidiagonal_v(self): + return _invoke( + "hmath_linear_decomposition_bidiagonal_v", + True, + [["Bidiagonal", ["a"]]], + [self], + ) + + +register("HMath.Matrix.Decomposition.Bidiagonal", Bidiagonal) + + +class Iteration(LinearValue): + """Original HMath.Matrix.Decomposition.Iteration immutable owner.""" + + _source_type = "HMath.Matrix.Decomposition.Iteration" + + def __init__( + self, + iteration_value, + iteration_vector, + iteration_residual, + iteration_count, + *, + dtype=None, + ): + self._initialize( + "hmath_linear_decomposition_new_iteration", + True, + [["a"], ["list", ["a"]], ["a"], ["Int"]], + [iteration_value, iteration_vector, iteration_residual, iteration_count], + dtype, + ) + + @property + def iteration_value(self): + return _invoke( + "hmath_linear_decomposition_iteration_value", + True, + [["Iteration", ["a"]]], + [self], + ) + + @property + def iteration_vector(self): + return _invoke( + "hmath_linear_decomposition_iteration_vector", + True, + [["Iteration", ["a"]]], + [self], + ) + + @property + def iteration_residual(self): + return _invoke( + "hmath_linear_decomposition_iteration_residual", + True, + [["Iteration", ["a"]]], + [self], + ) + + @property + def iteration_count(self): + return _invoke( + "hmath_linear_decomposition_iteration_count", + True, + [["Iteration", ["a"]]], + [self], + ) + + +register("HMath.Matrix.Decomposition.Iteration", Iteration) + + +class Arnoldi(LinearValue): + """Original HMath.Matrix.Decomposition.Arnoldi immutable owner.""" + + _source_type = "HMath.Matrix.Decomposition.Arnoldi" + + def __init__(self, arnoldi_basis, arnoldi_hessenberg, *, dtype=None): + self._initialize( + "hmath_linear_decomposition_new_arnoldi", + True, + [["Matrix", ["a"]], ["Matrix", ["a"]]], + [arnoldi_basis, arnoldi_hessenberg], + dtype, + ) + + @property + def arnoldi_basis(self): + return _invoke( + "hmath_linear_decomposition_arnoldi_basis", + True, + [["Arnoldi", ["a"]]], + [self], + ) + + @property + def arnoldi_hessenberg(self): + return _invoke( + "hmath_linear_decomposition_arnoldi_hessenberg", + True, + [["Arnoldi", ["a"]]], + [self], + ) + + +register("HMath.Matrix.Decomposition.Arnoldi", Arnoldi) + + +def gaussian_elimination(scalar1, matrix2, *, dtype=None): + "Given finite nonnegative relative tolerance then finite matrix, return normalized row-echelon form and zero-based pivot columns. Partial row pivoting skips pivots below tolerance times the global entry scale. Invalid tolerance/non-finite arithmetic fails. Call original HMath.Matrix.Decomposition.gaussianElimination :: a -> Matrix a -> Either MathError (Matrix a, [Int])" + return _invoke( + "hmath_linear_decomposition_gaussian_elimination", + True, + [["a"], ["Matrix", ["a"]]], + [scalar1, matrix2], + dtype=dtype, + ) + + +def gauss_jordan(scalar1, matrix2, *, dtype=None): + "Given relative tolerance then finite matrix, return reduced row-echelon form and zero-based pivot columns using row pivoting. Invalid tolerance/non-finite arithmetic fails. Call original HMath.Matrix.Decomposition.gaussJordan :: a -> Matrix a -> Either MathError (Matrix a, [Int])" + return _invoke( + "hmath_linear_decomposition_gauss_jordan", + True, + [["a"], ["Matrix", ["a"]]], + [scalar1, matrix2], + dtype=dtype, + ) + + +def cholesky(matrix1, *, dtype=None): + "Factor a finite symmetric positive-definite matrix as L*transpose(L), returning lower-triangular L. Non-square/asymmetric/non-finite input or a nonpositive diagonal pivot returns Left MathError. Call original HMath.Matrix.Decomposition.cholesky :: Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_decomposition_cholesky", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def ldlt(matrix1, *, dtype=None): + "Factor a finite symmetric matrix as L*diag(d)*transpose(L), returning unit lower L and diagonal list d. This unpivoted method requires nonzero scalar pivots; it can reject invertible indefinite matrices needing block pivots. Call original HMath.Matrix.Decomposition.ldlt :: Matrix a -> Either MathError (Matrix a, [a])" + return _invoke( + "hmath_linear_decomposition_ldlt", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def givens_qr(matrix1, *, dtype=None): + "Factor finite m-by-n matrix as Q*R using Givens rotations, returning square m-by-m Q and m-by-n R without column pivoting. Non-finite input/intermediate results fail. Call original HMath.Matrix.Decomposition.givensQR :: Matrix a -> Either MathError (Matrix a, Matrix a)" + return _invoke( + "hmath_linear_decomposition_givens_qr", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def bidiagonalize(matrix1, *, dtype=None): + "Reduce a finite rectangular matrix to bidiagonal form with orthogonal factors, returning Bidiagonal fields. Input/numeric validation errors propagate; inspect the factor types and module reconstruction example. Call original HMath.Matrix.Decomposition.bidiagonalize :: Matrix a -> Either MathError (Bidiagonal a)" + return _invoke( + "hmath_linear_decomposition_bidiagonalize", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def tridiagonalize(matrix1): + "Reduce a symmetric finite square matrix to `(Q,T)`, satisfying `A = Q * T * transpose Q` with tridiagonal `T`. Non-square/asymmetric input or numerical failure returns Left MathError. Call original HMath.Matrix.Decomposition.tridiagonalize :: Matrix Double -> Either MathError (Matrix Double, Matrix Double)" + return _invoke( + "hmath_linear_decomposition_tridiagonalize", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def power_iteration(scalar1, index2, matrix3, values4, *, dtype=None): + "Given positive finite tolerance,positive budget,square finite matrix,then nonzero starting vector, estimate a dominant eigenpair. Return Iteration with value/vector/residual/count; invalid dimensions/options, non-finite arithmetic or exhausted budget fails. Call original HMath.Matrix.Decomposition.powerIteration :: a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)" + return _invoke( + "hmath_linear_decomposition_power_iteration", + True, + [["a"], ["Int"], ["Matrix", ["a"]], ["list", ["a"]]], + [scalar1, index2, matrix3, values4], + dtype=dtype, + ) + + +def inverse_iteration(scalar1, index2, scalar3, matrix4, values5, *, dtype=None): + "Given tolerance,budget,shift,square matrix,then starting vector, estimate an eigenpair near shift by repeated shifted solves. Require valid finite inputs and nonzero start; singular shifted systems or convergence/numerical failures return Left MathError. Call original HMath.Matrix.Decomposition.inverseIteration :: a -> Int -> a -> Matrix a -> [a] -> Either MathError (Iteration a)" + return _invoke( + "hmath_linear_decomposition_inverse_iteration", + True, + [["a"], ["Int"], ["a"], ["Matrix", ["a"]], ["list", ["a"]]], + [scalar1, index2, scalar3, matrix4, values5], + dtype=dtype, + ) + + +def rayleigh_iteration(scalar1, index2, matrix3, values4, *, dtype=None): + "Given tolerance,budget,square matrix,then nonzero initial vector, refine an eigenpair with Rayleigh-quotient shifts. Shape/options, singular shifted solves or convergence/numerical failures return Left MathError. Call original HMath.Matrix.Decomposition.rayleighIteration :: a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)" + return _invoke( + "hmath_linear_decomposition_rayleigh_iteration", + True, + [["a"], ["Int"], ["Matrix", ["a"]], ["list", ["a"]]], + [scalar1, index2, matrix3, values4], + dtype=dtype, + ) + + +def arnoldi(scalar1, index2, matrix3, values4, *, dtype=None): + "Given positive finite tolerance,requested basis size,square matrix,then nonzero initial vector, build Arnoldi basis/projection. Require 1\\<=requested\\<=matrix order. Invalid input or numerical failures return Left MathError; exact Krylov breakdown terminates the basis. Call original HMath.Matrix.Decomposition.arnoldi :: a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)" + return _invoke( + "hmath_linear_decomposition_arnoldi", + True, + [["a"], ["Int"], ["Matrix", ["a"]], ["list", ["a"]]], + [scalar1, index2, matrix3, values4], + dtype=dtype, + ) + + +def lanczos(scalar1, index2, matrix3, values4, *, dtype=None): + "Symmetric Lanczos with the three-term recurrence and two full reorthogonalization passes. Small correction coefficients are retained in H so the projection residual remains meaningful after floating-point rounding. Call original HMath.Matrix.Decomposition.lanczos :: a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)" + return _invoke( + "hmath_linear_decomposition_lanczos", + True, + [["a"], ["Int"], ["Matrix", ["a"]], ["list", ["a"]]], + [scalar1, index2, matrix3, values4], + dtype=dtype, + ) + + +def qr_iteration(scalar1, index2, matrix3, *, dtype=None): + "Given positive finite tolerance,positive budget,then finite square matrix, iterate QR to return `(Q,T)`: accumulated orthogonal vectors and the resulting iterate. Invalid options/shape or failure to converge within budget returns Left MathError. Call original HMath.Matrix.Decomposition.qrIteration :: a -> Int -> Matrix a -> Either MathError (Matrix a, Matrix a)" + return _invoke( + "hmath_linear_decomposition_qr_iteration", + True, + [["a"], ["Int"], ["Matrix", ["a"]]], + [scalar1, index2, matrix3], + dtype=dtype, + ) + + +def jordan_chains(scalar1, matrix2, values3, *, dtype=None): + "Verify supplied Jordan chains against A and lambda and construct J and P. Computing a Jordan structure from floating input is ill posed; the caller supplies chain vectors ordered eigenvector first. A P = P J is checked. This API never pretends a Schur form is a Jordan form. Call original HMath.Matrix.Decomposition.jordanChains :: a -> Matrix a -> [(a, [[a]])] -> Either MathError (Matrix a, Matrix a)" + return _invoke( + "hmath_linear_decomposition_jordan_chains", + True, + [ + ["a"], + ["Matrix", ["a"]], + ["list", ["tuple", ["a"], ["list", ["list", ["a"]]]]], + ], + [scalar1, matrix2, values3], + dtype=dtype, + ) + + +def jordan_form(matrix1, values2): + "Exact Jordan construction over Rational with a caller-provided complete set of distinct rational eigenvalues (multiplicities are inferred). Unlike floating Jordan algorithms this never uses a tolerance to decide structure. Nullspaces of successive (A-lambda I) powers construct generalized chains. An incomplete/nonrational spectrum is rejected rather than approximated. Call original HMath.Matrix.Decomposition.jordanForm :: Matrix Rational -> [Rational] -> Either MathError (Matrix Rational, Matrix Rational)" + return _invoke( + "hmath_linear_decomposition_jordan_form", + False, + [["Matrix", ["Rational"]], ["list", ["Rational"]]], + [matrix1, values2], + ) + + +def bidiagonal_u(bidiagonal1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.bidiagonalU :: Bidiagonal -> field" + return _invoke( + "hmath_linear_decomposition_bidiagonal_u", + True, + [["Bidiagonal", ["a"]]], + [bidiagonal1], + dtype=dtype, + ) + + +def bidiagonal_b(bidiagonal1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.bidiagonalB :: Bidiagonal -> field" + return _invoke( + "hmath_linear_decomposition_bidiagonal_b", + True, + [["Bidiagonal", ["a"]]], + [bidiagonal1], + dtype=dtype, + ) + + +def bidiagonal_v(bidiagonal1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.bidiagonalV :: Bidiagonal -> field" + return _invoke( + "hmath_linear_decomposition_bidiagonal_v", + True, + [["Bidiagonal", ["a"]]], + [bidiagonal1], + dtype=dtype, + ) + + +def iteration_value(iteration1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.iterationValue :: Iteration -> field" + return _invoke( + "hmath_linear_decomposition_iteration_value", + True, + [["Iteration", ["a"]]], + [iteration1], + dtype=dtype, + ) + + +def iteration_vector(iteration1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.iterationVector :: Iteration -> field" + return _invoke( + "hmath_linear_decomposition_iteration_vector", + True, + [["Iteration", ["a"]]], + [iteration1], + dtype=dtype, + ) + + +def iteration_residual(iteration1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.iterationResidual :: Iteration -> field" + return _invoke( + "hmath_linear_decomposition_iteration_residual", + True, + [["Iteration", ["a"]]], + [iteration1], + dtype=dtype, + ) + + +def iteration_count(iteration1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.iterationCount :: Iteration -> field" + return _invoke( + "hmath_linear_decomposition_iteration_count", + True, + [["Iteration", ["a"]]], + [iteration1], + dtype=dtype, + ) + + +def arnoldi_basis(arnoldi1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.arnoldiBasis :: Arnoldi -> field" + return _invoke( + "hmath_linear_decomposition_arnoldi_basis", + True, + [["Arnoldi", ["a"]]], + [arnoldi1], + dtype=dtype, + ) + + +def arnoldi_hessenberg(arnoldi1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Decomposition.arnoldiHessenberg :: Arnoldi -> field" + return _invoke( + "hmath_linear_decomposition_arnoldi_hessenberg", + True, + [["Arnoldi", ["a"]]], + [arnoldi1], + dtype=dtype, + ) + + +__all__ = [ + "Arnoldi", + "Bidiagonal", + "Iteration", + "arnoldi", + "arnoldi_basis", + "arnoldi_hessenberg", + "bidiagonal_b", + "bidiagonal_u", + "bidiagonal_v", + "bidiagonalize", + "cholesky", + "gauss_jordan", + "gaussian_elimination", + "givens_qr", + "inverse_iteration", + "iteration_count", + "iteration_residual", + "iteration_value", + "iteration_vector", + "jordan_chains", + "jordan_form", + "lanczos", + "ldlt", + "power_iteration", + "qr_iteration", + "rayleigh_iteration", + "tridiagonalize", +] diff --git a/bindings/python/_hmath_native/deeplearning_core.py b/bindings/python/_hmath_native/deeplearning_core.py new file mode 100644 index 0000000..65a7ace --- /dev/null +++ b/bindings/python/_hmath_native/deeplearning_core.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def log_softmax(argument1, *, dtype='float64'): + """Call HMath.DeepLearning.Core.logSoftmax; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_log_softmax', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def softmax(xs, *, dtype='float64'): + """Call HMath.DeepLearning.Core.softmax; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_softmax', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def sparsemax(argument1, *, dtype='float64'): + """Call HMath.DeepLearning.Core.sparsemax; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_sparsemax', + ['fs'], + 'fd', + [argument1], + dtype, + 0, + ) + + +def gated_linear_unit(values, gate, *, dtype='float64'): + """Call HMath.DeepLearning.Core.gatedLinearUnit; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_gated_linear_unit', + ['fs', 'fs'], + 'fd', + [values, gate], + dtype, + 0, + ) + + +def categorical_cross_entropy_logits(target, logits, *, dtype='float64'): + """Call HMath.DeepLearning.Core.categoricalCrossEntropyLogits; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_categorical_cross_entropy_logits', + ['fs', 'fs'], + 'f', + [target, logits], + dtype, + 0, + ) + + +def regularization(l1, l2, weights, *, dtype='float64'): + """Call HMath.DeepLearning.Core.regularization; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_regularization', + ['f', 'f', 'fs'], + 'f', + [l1, l2, weights], + dtype, + 0, + ) + + +def contrastive_loss(margin, similar, a, b, *, dtype='float64'): + """Call HMath.DeepLearning.Core.contrastiveLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_contrastive_loss', + ['f', 'b', 'fs', 'fs'], + 'f', + [margin, similar, a, b], + dtype, + 0, + ) + + +def triplet_loss(margin, anchor, positive, negative, *, dtype='float64'): + """Call HMath.DeepLearning.Core.tripletLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_triplet_loss', + ['f', 'fs', 'fs', 'fs'], + 'f', + [margin, anchor, positive, negative], + dtype, + 0, + ) + + +def focal_loss(alpha, gamma, target, prediction, *, dtype='float64'): + """Call HMath.DeepLearning.Core.focalLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_focal_loss', + ['f', 'f', 'fs', 'fs'], + 'f', + [alpha, gamma, target, prediction], + dtype, + 0, + ) + + +def dice_loss(smooth, target, prediction, *, dtype='float64'): + """Call HMath.DeepLearning.Core.diceLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_dice_loss', + ['f', 'fs', 'fs'], + 'f', + [smooth, target, prediction], + dtype, + 0, + ) + + +def iou_loss(smooth, target, prediction, *, dtype='float64'): + """Call HMath.DeepLearning.Core.iouLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_core_iou_loss', + ['f', 'fs', 'fs'], + 'f', + [smooth, target, prediction], + dtype, + 0, + ) + + +from ._neural_core import * diff --git a/bindings/python/_hmath_native/deeplearning_layers.py b/bindings/python/_hmath_native/deeplearning_layers.py new file mode 100644 index 0000000..38cec33 --- /dev/null +++ b/bindings/python/_hmath_native/deeplearning_layers.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.DeepLearning.Layers complete typed adapters.""" + +from ._neural_base import ( + AveragePool, + BatchNormState, + ConvOptions, + Inference, + Initializer, + KaimingNormal, + KaimingUniform, + KVCache, + MaxPool, + Orthogonal, + PoolMode, + Training, + TruncatedNormal, + XavierNormal, + XavierUniform, + adaptive_pooling, + alibi_bias, + append_cache, + batch_norm, + batches_seen, + cache_values, + causal_mask, + convolution, + convolution_ad, + convolution_dilation, + convolution_groups, + convolution_padding, + convolution_stride, + dense, + dense_ad, + depthwise_convolution, + dropout, + embedding, + empty_cache, + global_pooling, + group_norm, + initialize_weights, + instance_norm, + layer_norm, + layer_norm_ad, + multihead_attention, + pooling, + rms_norm, + rms_norm_ad, + rotary_embedding, + running_mean, + running_variance, + scaled_dot_product_attention, + scaled_dot_product_attention_ad, + sinusoidal_encoding, + spatial_dropout, + transformer_feed_forward, + transposed_convolution, + weight_norm, +) + +__all__ = [ + "AveragePool", + "BatchNormState", + "ConvOptions", + "Inference", + "Initializer", + "KVCache", + "KaimingNormal", + "KaimingUniform", + "MaxPool", + "Orthogonal", + "PoolMode", + "Training", + "TruncatedNormal", + "XavierNormal", + "XavierUniform", + "adaptive_pooling", + "alibi_bias", + "append_cache", + "batch_norm", + "batches_seen", + "cache_values", + "causal_mask", + "convolution", + "convolution_ad", + "convolution_dilation", + "convolution_groups", + "convolution_padding", + "convolution_stride", + "dense", + "dense_ad", + "depthwise_convolution", + "dropout", + "embedding", + "empty_cache", + "global_pooling", + "group_norm", + "initialize_weights", + "instance_norm", + "layer_norm", + "layer_norm_ad", + "multihead_attention", + "pooling", + "rms_norm", + "rms_norm_ad", + "rotary_embedding", + "running_mean", + "running_variance", + "scaled_dot_product_attention", + "scaled_dot_product_attention_ad", + "sinusoidal_encoding", + "spatial_dropout", + "transformer_feed_forward", + "transposed_convolution", + "weight_norm", +] diff --git a/bindings/python/_hmath_native/deeplearning_metrics.py b/bindings/python/_hmath_native/deeplearning_metrics.py new file mode 100644 index 0000000..8e8bec2 --- /dev/null +++ b/bindings/python/_hmath_native/deeplearning_metrics.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def perplexity(logs, *, dtype='float64'): + """Call HMath.DeepLearning.Metrics.perplexity; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_metrics_perplexity', + ['fs'], + 'f', + [logs], + dtype, + 0, + ) + + +def margin_ranking_loss(margin, labels, left, right, *, dtype='float64'): + """Call HMath.DeepLearning.Metrics.marginRankingLoss; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_metrics_margin_ranking_loss', + ['f', 'fs', 'fs', 'fs'], + 'f', + [margin, labels, left, right], + dtype, + 0, + ) + + +from ._neural_metrics import * diff --git a/bindings/python/_hmath_native/deeplearning_precision.py b/bindings/python/_hmath_native/deeplearning_precision.py new file mode 100644 index 0000000..87bdaca --- /dev/null +++ b/bindings/python/_hmath_native/deeplearning_precision.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def gradient_norm(xs, *, dtype='float64'): + """Call HMath.DeepLearning.Precision.gradientNorm; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_precision_gradient_norm', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def clip_gradients(argument1, argument2, *, dtype='float64'): + """Call HMath.DeepLearning.Precision.clipGradients; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_deeplearning_precision_clip_gradients', + ['f', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +from ._neural_precision import * diff --git a/bindings/python/_hmath_native/discrete.py b/bindings/python/_hmath_native/discrete.py new file mode 100644 index 0000000..d8e8784 --- /dev/null +++ b/bindings/python/_hmath_native/discrete.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def set_union(a, b, *, dtype='float64'): + """Call HMath.Discrete.setUnion; preserve its argument order, result and errors.""" + return _call( + 'hmath_discrete_set_union', + ['fs', 'fs'], + 'fd', + [a, b], + dtype, + 0, + ) + + +def set_intersection(a, b, *, dtype='float64'): + """Call HMath.Discrete.setIntersection; preserve its argument order, result and errors.""" + return _call( + 'hmath_discrete_set_intersection', + ['fs', 'fs'], + 'fd', + [a, b], + dtype, + 0, + ) + + +def set_difference(a, b, *, dtype='float64'): + """Call HMath.Discrete.setDifference; preserve its argument order, result and errors.""" + return _call( + 'hmath_discrete_set_difference', + ['fs', 'fs'], + 'fd', + [a, b], + dtype, + 0, + ) + + +def symmetric_difference(a, b, *, dtype='float64'): + """Call HMath.Discrete.symmetricDifference; preserve its argument order, result and errors.""" + return _call( + 'hmath_discrete_symmetric_difference', + ['fs', 'fs'], + 'fd', + [a, b], + dtype, + 0, + ) + + +from .discrete_values import * diff --git a/bindings/python/_hmath_native/discrete_values.py b/bindings/python/_hmath_native/discrete_values.py new file mode 100644 index 0000000..a8928be --- /dev/null +++ b/bindings/python/_hmath_native/discrete_values.py @@ -0,0 +1,541 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_foundation_bindings.py. +"""Original HMath.Discrete public functions and immutable values.""" + +from ._foundation_base import FoundationValue, _invoke, register + + +class MultiSet(FoundationValue): + """Original HMath.Discrete.MultiSet immutable owner.""" + + _source_type = "HMath.Discrete.MultiSet" + + def __init__(self, argument1, *, prototype=None): + self._initialize( + "hmath_foundation_discrete_multiset", + [["list", ["a"]]], + [argument1], + "value", + prototype=prototype, + ) + + +register("HMath.Discrete.MultiSet", MultiSet) + + +class BitSet(FoundationValue): + """Original HMath.Discrete.BitSet immutable owner.""" + + _source_type = "HMath.Discrete.BitSet" + + def __init__(self, argument1, argument2): + self._initialize( + "hmath_foundation_discrete_bit_set", + [["Int"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +register("HMath.Discrete.BitSet", BitSet) + + +class Prop(FoundationValue): + """Original HMath.Discrete.Prop immutable owner.""" + + _source_type = "HMath.Discrete.Prop" + + +register("HMath.Discrete.Prop", Prop) + + +class Implicant(FoundationValue): + """Original HMath.Discrete.Implicant immutable owner.""" + + _source_type = "HMath.Discrete.Implicant" + + def __init__(self, implicant_value, implicant_mask): + self._initialize( + "hmath_foundation_discrete_new_implicant", + [["Integer"], ["Integer"]], + [implicant_value, implicant_mask], + "value", + ) + + @property + def implicant_value(self): + return _invoke( + "hmath_foundation_discrete_implicant_value", + [["Implicant"]], + [self], + "value", + ) + + @property + def implicant_mask(self): + return _invoke( + "hmath_foundation_discrete_implicant_mask", [["Implicant"]], [self], "value" + ) + + +register("HMath.Discrete.Implicant", Implicant) + + +def multiset(argument1, *, prototype=None): + "Construct a finite multiset by counting equal ordered values with exact nonnegative Integer multiplicities." + return _invoke( + "hmath_foundation_discrete_multiset", + [["list", ["a"]]], + [argument1], + "value", + prototype=prototype, + ) + + +def multiplicity(argument1, argument2): + "Given value then multiset, return its Integer frequency, or zero when absent." + return _invoke( + "hmath_foundation_discrete_multiplicity", + [["a"], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def multiset_entries(argument1): + "Return (value,positive multiplicity) pairs in ascending value order." + return _invoke( + "hmath_foundation_discrete_multiset_entries", + [["MultiSet", ["a"]]], + [argument1], + "value", + ) + + +def multiset_insert(argument1, argument2): + "Given value then multiset, increment its multiplicity by one and return a new multiset." + return _invoke( + "hmath_foundation_discrete_multiset_insert", + [["a"], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def multiset_delete(argument1, argument2): + "Given value then multiset, remove one occurrence, deleting its entry at zero. Absent values are a no-op." + return _invoke( + "hmath_foundation_discrete_multiset_delete", + [["a"], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def multiset_union(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_multiset_union", + [["MultiSet", ["a"]], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def multiset_intersection(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_multiset_intersection", + [["MultiSet", ["a"]], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def multiset_difference(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_multiset_difference", + [["MultiSet", ["a"]], ["MultiSet", ["a"]]], + [argument1, argument2], + "value", + ) + + +def bit_set(argument1, argument2): + "Given width in [0,1048576] then nonnegative Integer less than 2^width, construct an opaque bitset. Invalid width/value fails; bit zero is least significant." + return _invoke( + "hmath_foundation_discrete_bit_set", + [["Int"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def bit_width(argument1): + "Return declared number of bits, including leading zeros." + return _invoke( + "hmath_foundation_discrete_bit_width", [["BitSet"]], [argument1], "value" + ) + + +def bit_value(argument1): + "Return unsigned Integer value of all bits within the declared width." + return _invoke( + "hmath_foundation_discrete_bit_value", [["BitSet"]], [argument1], "value" + ) + + +def bit_member(argument1, argument2): + "Given bitset then zero-based bit index, return membership. Out-of-width or negative indices return Left InvalidArgument." + return _invoke( + "hmath_foundation_discrete_bit_member", + [["BitSet"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def bit_insert(argument1, argument2): + "Given bitset then valid bit index, return a new bitset with that bit set. Invalid index fails." + return _invoke( + "hmath_foundation_discrete_bit_insert", + [["BitSet"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def bit_delete(argument1, argument2): + "Given bitset then valid bit index, return a new bitset with that bit cleared. Invalid index fails." + return _invoke( + "hmath_foundation_discrete_bit_delete", + [["BitSet"], ["Int"]], + [argument1, argument2], + "value", + ) + + +def bit_union(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_bit_union", + [["BitSet"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def bit_intersection(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_bit_intersection", + [["BitSet"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def bit_difference(argument1, argument2): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_bit_difference", + [["BitSet"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def resize_bit_set(argument1, argument2): + "Shrinking explicitly discards high bits." + return _invoke( + "hmath_foundation_discrete_resize_bit_set", + [["Int"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def population_count(argument1): + "Count set bits within declared width, returning Int." + return _invoke( + "hmath_foundation_discrete_population_count", [["BitSet"]], [argument1], "value" + ) + + +def leading_zeros(argument1): + "Count high-end zero bits within declared width. All-zero bitset returns its full width." + return _invoke( + "hmath_foundation_discrete_leading_zeros", [["BitSet"]], [argument1], "value" + ) + + +def trailing_zeros(argument1): + "Count low-end zero bits; an all-zero bitset returns its declared width." + return _invoke( + "hmath_foundation_discrete_trailing_zeros", [["BitSet"]], [argument1], "value" + ) + + +def rotate_bits(argument1, argument2): + "Given signed rotation count then bitset, rotate left modulo width (negative counts rotate right). Width-zero input is unchanged." + return _invoke( + "hmath_foundation_discrete_rotate_bits", + [["Int"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def reverse_bits(argument1): + "Reverse exactly the declared width of bits, preserving width and leading/trailing zero positions." + return _invoke( + "hmath_foundation_discrete_reverse_bits", [["BitSet"]], [argument1], "value" + ) + + +def gray_encode(argument1): + "Return width-preserving reflected Gray code v xor (v shifted right one)." + return _invoke( + "hmath_foundation_discrete_gray_encode", [["BitSet"]], [argument1], "value" + ) + + +def gray_decode(argument1): + "Decode reflected Gray bits to the corresponding width-preserving binary value." + return _invoke( + "hmath_foundation_discrete_gray_decode", [["BitSet"]], [argument1], "value" + ) + + +def hamming_distance(argument1, argument2): + "Count differing bit positions between equal-width bitsets. Different widths return Left InvalidArgument." + return _invoke( + "hmath_foundation_discrete_hamming_distance", + [["BitSet"], ["BitSet"]], + [argument1, argument2], + "value", + ) + + +def transitive_closure(argument1): + "Warshall closure. Paths must have positive length; use 'equivalenceClosure' when a reflexive closure is wanted." + return _invoke( + "hmath_foundation_discrete_transitive_closure", + [["list", ["list", ["Bool"]]]], + [argument1], + "value", + ) + + +def equivalence_closure(argument1): + "Given square Bool relation matrix, add reflexivity and symmetry then compute transitive closure. Reject nonsquare or oversized (>512) relations." + return _invoke( + "hmath_foundation_discrete_equivalence_closure", + [["list", ["list", ["Bool"]]]], + [argument1], + "value", + ) + + +def is_equivalence(argument1): + "Return whether a bounded square Bool relation is already reflexive, symmetric and transitive. Invalid matrix shape/size fails." + return _invoke( + "hmath_foundation_discrete_is_equivalence", + [["list", ["list", ["Bool"]]]], + [argument1], + "value", + ) + + +def boolean_multiply(argument1, argument2): + "Multiply compatible square Bool relation matrices over OR/AND, representing relational composition. Invalid dimensions or size bounds fail." + return _invoke( + "hmath_foundation_discrete_boolean_multiply", + [["list", ["list", ["Bool"]]], ["list", ["list", ["Bool"]]]], + [argument1, argument2], + "value", + ) + + +def evaluate_prop(argument1, argument2): + "Given variable Bool assignment list then proposition, evaluate literals/variables/connectives. Invalid variable index or excessive expression depth returns Left MathError." + return _invoke( + "hmath_foundation_discrete_evaluate_prop", + [["list", ["Bool"]], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def truth_table(argument1, argument2): + "Assignments in binary order, variable zero the least-significant bit." + return _invoke( + "hmath_foundation_discrete_truth_table", + [["Int"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def implicant_covers(argument1, argument2): + "Given implicant then Integer minterm, compare bits where implicantMask is clear. True means this Boolean cube covers the minterm." + return _invoke( + "hmath_foundation_discrete_implicant_covers", + [["Implicant"], ["Integer"]], + [argument1, argument2], + "value", + ) + + +def quine_mc_cluskey(argument1, argument2, argument3, argument4): + "Exact Quine--McCluskey prime generation followed by branch-and-bound cover selection. Objective is fewest terms, then literals, then lexical order. The explicit budget counts prime comparisons and covering-search nodes." + return _invoke( + "hmath_foundation_discrete_quine_mc_cluskey", + [["Int"], ["Int"], ["list", ["Integer"]], ["list", ["Integer"]]], + [argument1, argument2, argument3, argument4], + "value", + ) + + +def literal(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_literal", [["Bool"]], [argument1], "value" + ) + + +def variable(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_variable", [["Int"]], [argument1], "value" + ) + + +def logical_not(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_not", [["Prop"]], [argument1], "value" + ) + + +def logical_and(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_and", + [["Prop"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def logical_or(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_or", + [["Prop"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def xor(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_xor", + [["Prop"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def implies(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_implies", + [["Prop"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def iff(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_foundation_discrete_new_iff", + [["Prop"], ["Prop"]], + [argument1, argument2], + "value", + ) + + +def implicant_value(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_implicant_value", + [["Implicant"]], + [argument1], + "value", + ) + + +def implicant_mask(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_foundation_discrete_implicant_mask", + [["Implicant"]], + [argument1], + "value", + ) + + +__all__ = [ + "BitSet", + "Implicant", + "MultiSet", + "Prop", + "bit_delete", + "bit_difference", + "bit_insert", + "bit_intersection", + "bit_member", + "bit_set", + "bit_union", + "bit_value", + "bit_width", + "boolean_multiply", + "equivalence_closure", + "evaluate_prop", + "gray_decode", + "gray_encode", + "hamming_distance", + "iff", + "implicant_covers", + "implicant_mask", + "implicant_value", + "implies", + "is_equivalence", + "leading_zeros", + "literal", + "logical_and", + "logical_not", + "logical_or", + "multiplicity", + "multiset", + "multiset_delete", + "multiset_difference", + "multiset_entries", + "multiset_insert", + "multiset_intersection", + "multiset_union", + "population_count", + "quine_mc_cluskey", + "resize_bit_set", + "reverse_bits", + "rotate_bits", + "trailing_zeros", + "transitive_closure", + "truth_table", + "variable", + "xor", +] diff --git a/bindings/python/_hmath_native/errors.py b/bindings/python/_hmath_native/errors.py new file mode 100644 index 0000000..86004ed --- /dev/null +++ b/bindings/python/_hmath_native/errors.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Haskell MathError constructors for checked callbacks.""" + +from ._math_error import MathError, MathErrorKind + +__all__ = [ + "DomainError", + "ElementCountMismatch", + "ElementCountOverflow", + "IndexOutOfBounds", + "InnerDimensionMismatch", + "InvalidArgument", + "InvalidTolerance", + "MathError", + "MathErrorKind", + "NearSingularMatrix", + "NegativeDimensions", + "NonConvergence", + "NonFiniteMatrixEntry", + "NonFiniteResult", + "NonFiniteVectorEntry", + "NonSquareMatrix", + "NotPositiveDefinite", + "RankDeficient", + "RightHandSideMismatch", + "ShapeMismatch", + "SingularMatrix", + "SliceOutOfBounds", + "VectorLengthMismatch", +] + + +def NegativeDimensions(shape): + return MathError(MathErrorKind.NEGATIVE_DIMENSIONS, shape) + + +def ElementCountOverflow(shape): + return MathError(MathErrorKind.ELEMENT_COUNT_OVERFLOW, shape) + + +def ElementCountMismatch(expected, actual): + return MathError(MathErrorKind.ELEMENT_COUNT_MISMATCH, (expected, actual)) + + +def ShapeMismatch(left, right): + return MathError(MathErrorKind.SHAPE_MISMATCH, (*left, *right)) + + +def InnerDimensionMismatch(left_columns, right_rows): + return MathError(MathErrorKind.INNER_DIMENSION_MISMATCH, (left_columns, right_rows)) + + +def IndexOutOfBounds(shape, index): + return MathError(MathErrorKind.INDEX_OUT_OF_BOUNDS, (*shape, *index)) + + +def SliceOutOfBounds(shape, start, extent): + return MathError(MathErrorKind.SLICE_OUT_OF_BOUNDS, (*shape, *start, *extent)) + + +def VectorLengthMismatch(expected, actual): + return MathError(MathErrorKind.VECTOR_LENGTH_MISMATCH, (expected, actual)) + + +def NonSquareMatrix(shape): + return MathError(MathErrorKind.NON_SQUARE_MATRIX, shape) + + +def InvalidTolerance(): + return MathError(MathErrorKind.INVALID_TOLERANCE) + + +def SingularMatrix(index): + return MathError(MathErrorKind.SINGULAR_MATRIX, (index,)) + + +def NearSingularMatrix(index): + return MathError(MathErrorKind.NEAR_SINGULAR_MATRIX, (index,)) + + +def NonFiniteMatrixEntry(index): + return MathError(MathErrorKind.NON_FINITE_MATRIX_ENTRY, index) + + +def NonFiniteVectorEntry(index): + return MathError(MathErrorKind.NON_FINITE_VECTOR_ENTRY, (index,)) + + +def NonFiniteResult(): + return MathError(MathErrorKind.NON_FINITE_RESULT) + + +def RightHandSideMismatch(expected, actual): + return MathError(MathErrorKind.RIGHT_HAND_SIDE_MISMATCH, (expected, actual)) + + +def DomainError(message): + return MathError(MathErrorKind.DOMAIN_ERROR, message=message) + + +def InvalidArgument(message): + return MathError(MathErrorKind.INVALID_ARGUMENT, message=message) + + +def NonConvergence(algorithm, iterations): + return MathError(MathErrorKind.NON_CONVERGENCE, (iterations,), algorithm) + + +def RankDeficient(rank): + return MathError(MathErrorKind.RANK_DEFICIENT, (rank,)) + + +def NotPositiveDefinite(index): + return MathError(MathErrorKind.NOT_POSITIVE_DEFINITE, (index,)) diff --git a/bindings/python/_hmath_native/execution.py b/bindings/python/_hmath_native/execution.py new file mode 100644 index 0000000..6396532 --- /dev/null +++ b/bindings/python/_hmath_native/execution.py @@ -0,0 +1,196 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Explicit row-major buffer GEMM with optional BLAS and no dtype conversion.""" + +import ctypes as C +import operator +import os +import threading +from enum import IntEnum + + +class Provider(IntEnum): + REFERENCE = 0 + OPENBLAS = 1 + BLIS = 2 + MKL = 3 + ACCELERATE = 4 + + +class _Options(C.Structure): + _fields_ = [ + ("provider", C.c_int), + ("integer_bits", C.c_uint), + ("library_path", C.c_char_p), + ("max_elements", C.c_size_t), + ("max_multiply_adds", C.c_size_t), + ] + + +class _View(C.Structure): + _fields_ = [ + ("data", C.c_void_p), + ("storage_count", C.c_size_t), + ("rows", C.c_size_t), + ("columns", C.c_size_t), + ("leading_dimension", C.c_size_t), + ] + + +def _api(name, result, *types): + import hmath + + return C.CFUNCTYPE(result, *types)((name, hmath._lib)) + + +def _size(value): + value = operator.index(value) + if value < 0 or value > C.c_size_t(-1).value: + raise ValueError("resource limit must be a nonnegative size_t") + return value + + +def _view(array, writable=False): + import numpy as np + + if not isinstance(array, np.ndarray) or array.ndim != 2: + raise TypeError("execution requires two-dimensional NumPy arrays") + if ( + array.dtype not in (np.dtype("float32"), np.dtype("float64")) + or not array.dtype.isnative + ): + raise TypeError("execution requires native-endian float32 or float64 arrays") + if not array.flags.aligned or (writable and not array.flags.writeable): + raise ValueError( + "execution storage must be aligned and output must be writable" + ) + rows, columns = array.shape + item = array.dtype.itemsize + if any(stride < 0 or stride % item for stride in array.strides): + raise ValueError("execution requires nonnegative element-aligned strides") + if columns > 1 and rows and array.strides[1] != item: + raise ValueError("execution requires consecutive columns") + leading = array.strides[0] // item + if rows > 1 and columns and leading < columns: + raise ValueError("execution rows must not overlap") + # Row stride is irrelevant for a single row or an empty view. Canonicalize + # it to the required leading dimension without changing any data address. + if rows <= 1 or not columns: + leading = max(columns, leading) + span = (rows - 1) * leading + columns if rows and columns else 0 + return _View(array.ctypes.data, span, rows, columns, leading) + + +class Execution: + """Immutable provider/resource selection; buffers are borrowed per call. + + Provider selection never silently falls back. Limits of zero mean no + artificial cap; overflow, allocation, shape and alias checks remain active. + A live Execution owns its provider library but does not pin the GHC runtime. + """ + + def __init__( + self, + provider=Provider.REFERENCE, + *, + integer_bits=32, + library_path=None, + max_elements=0, + max_multiply_adds=0, + ): + import hmath + + self._lock, self._ptr = threading.RLock(), C.c_void_p() + if isinstance(provider, str): + provider = Provider[provider.upper()] + provider = Provider(provider) + integer_bits = operator.index(integer_bits) + if integer_bits not in (0, 32, 64): + raise ValueError("integer_bits must be 32 (LP64) or 64 (ILP64)") + path = None if library_path is None else os.fsencode(library_path) + options = _Options( + provider, integer_bits, path, _size(max_elements), _size(max_multiply_adds) + ) + hmath._check( + _api( + "hmath_execution_create", + C.c_int, + C.POINTER(_Options), + C.POINTER(C.c_void_p), + )(C.byref(options), C.byref(self._ptr)) + ) + + def close(self): + with self._lock: + if self._ptr: + _api("hmath_execution_release", None, C.c_void_p)(self._ptr) + self._ptr = C.c_void_p() + + def __enter__(self): + with self._lock: + if not self._ptr: + raise ValueError("execution is closed") + return self + + def __exit__(self, *_): + self.close() + + def __del__(self): + if getattr(self, "_ptr", None): + self.close() + + def gemm(self, a, b, out, *, alpha=1, beta=0): + """Write alpha*A*B + beta*out into the supplied NumPy output. + + Arrays retain their original float32/float64 storage; padded rows are + accepted, strided columns/negative strides and overlapping outputs are + rejected. A/B may share storage. All logical elements (including initial + output when beta=0) must be finite. Padding is untouched. Validation + errors leave output unchanged. Once execution starts, cancellation or + numeric failure may leave output modified. Inputs and their aliases must + not be mutated concurrently; concurrent calls need separate outputs. + """ + import hmath + + av, bv, cv = _view(a), _view(b), _view(out, writable=True) + if a.dtype != b.dtype or a.dtype != out.dtype: + raise TypeError("GEMM arrays must have exactly the same dtype") + real = C.c_float if a.dtype.itemsize == 4 else C.c_double + call = _api( + "hmath_execution_gemm_f32" + if real is C.c_float + else "hmath_execution_gemm_f64", + C.c_int, + C.c_void_p, + C.c_void_p, + real, + C.POINTER(_View), + C.POINTER(_View), + real, + C.POINTER(_View), + ) + retain = _api("hmath_execution_retain", None, C.c_void_p) + release = _api("hmath_execution_release", None, C.c_void_p) + hmath.initialize() + with self._lock: + if not self._ptr: + raise ValueError("execution is closed") + pointer = C.c_void_p(self._ptr.value) + retain(pointer) + try: + hmath._check( + call(pointer, None, alpha, C.byref(av), C.byref(bv), beta, C.byref(cv)) + ) + finally: + release(pointer) + return out + + def matmul(self, a, b): + """Allocate a zeroed output of the same dtype, then execute GEMM.""" + import numpy as np + + _view(a) + _view(b) + if a.dtype != b.dtype: + raise TypeError("GEMM arrays must have exactly the same dtype") + out = np.zeros((a.shape[0], b.shape[1]), dtype=a.dtype) + return self.gemm(a, b, out) diff --git a/bindings/python/_hmath_native/expression.py b/bindings/python/_hmath_native/expression.py new file mode 100644 index 0000000..37af363 --- /dev/null +++ b/bindings/python/_hmath_native/expression.py @@ -0,0 +1,230 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.Expression public API.""" + +from ._expression_base import ( + Abs, + Acos, + Add, + Asin, + Atan, + Binary, + BinaryOp, + Bindings, + Builtin, + Call, + Ceiling, + Compiled, + Constant, + Cos, + Cosh, + DepthLimit, + Divide, + DomainFailure, + ErrorKind, + Euler, + ExactRational, + ExactValue, + Exp, + Expr, + ExprError, + ExpressionCache, + ExprNode, + Float64, + FloatValue, + Floor, + InvalidLimits, + Let, + Limits, + Literal, + Log, + Max, + MemoryLimit, + Min, + Multiply, + NamedConstant, + Negate, + NonFinite, + Pi, + Power, + Precision, + Registry, + Signum, + Sin, + Sinh, + SourcePos, + Sqrt, + StepLimit, + Subtract, + SyntaxError, + Tan, + Tanh, + Tau, + TypeMismatch, + Unary, + UnaryOp, + UnknownName, + Unsupported, + Value, + Variable, + allowed_functions, + binary, + cache_size, + cached_expression, + call, + compile_expression, + compiled_node_count, + constant, + default_limits, + default_registry, + deserialize_expression, + empty_expression_cache, + empty_registry, + error_kind, + error_message, + error_position, + evaluate_compiled, + evaluate_expression, + evaluate_text, + expression_hash, + expression_node, + expression_position, + format_radix, + format_scientific, + free_variables, + let_in, + literal, + maximum_cache_entries, + maximum_depth, + maximum_input_chars, + maximum_integer_bits, + maximum_nodes, + maximum_steps, + optimize_expression, + parse_expression, + pretty_expression, + register_function, + serialize_expression, + source_column, + source_line, + source_offset, + type_check_expression, + unary, + unknown_position, + validate_expression, + validate_limits, + variable, +) + +__all__ = [ + "Abs", + "Acos", + "Add", + "Asin", + "Atan", + "Binary", + "BinaryOp", + "Bindings", + "Builtin", + "Call", + "Ceiling", + "Compiled", + "Constant", + "Cos", + "Cosh", + "DepthLimit", + "Divide", + "DomainFailure", + "ErrorKind", + "Euler", + "ExactRational", + "ExactValue", + "Exp", + "Expr", + "ExprError", + "ExprNode", + "ExpressionCache", + "Float64", + "FloatValue", + "Floor", + "InvalidLimits", + "Let", + "Limits", + "Literal", + "Log", + "Max", + "MemoryLimit", + "Min", + "Multiply", + "NamedConstant", + "Negate", + "NonFinite", + "Pi", + "Power", + "Precision", + "Registry", + "Signum", + "Sin", + "Sinh", + "SourcePos", + "Sqrt", + "StepLimit", + "Subtract", + "SyntaxError", + "Tan", + "Tanh", + "Tau", + "TypeMismatch", + "Unary", + "UnaryOp", + "UnknownName", + "Unsupported", + "Value", + "Variable", + "allowed_functions", + "binary", + "cache_size", + "cached_expression", + "call", + "compile_expression", + "compiled_node_count", + "constant", + "default_limits", + "default_registry", + "deserialize_expression", + "empty_expression_cache", + "empty_registry", + "error_kind", + "error_message", + "error_position", + "evaluate_compiled", + "evaluate_expression", + "evaluate_text", + "expression_hash", + "expression_node", + "expression_position", + "format_radix", + "format_scientific", + "free_variables", + "let_in", + "literal", + "maximum_cache_entries", + "maximum_depth", + "maximum_input_chars", + "maximum_integer_bits", + "maximum_nodes", + "maximum_steps", + "optimize_expression", + "parse_expression", + "pretty_expression", + "register_function", + "serialize_expression", + "source_column", + "source_line", + "source_offset", + "type_check_expression", + "unary", + "unknown_position", + "validate_expression", + "validate_limits", + "variable", +] diff --git a/bindings/python/_hmath_native/fourier.py b/bindings/python/_hmath_native/fourier.py new file mode 100644 index 0000000..4899330 --- /dev/null +++ b/bindings/python/_hmath_native/fourier.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def frequencies(n, spacing, *, dtype='float64'): + """Call HMath.Fourier.frequencies; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_frequencies', + ['i', 'f'], + 'fd', + [n, spacing], + dtype, + 0, + ) + + +def fft_shift(xs, *, dtype='float64'): + """Call HMath.Fourier.fftShift; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_fft_shift', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def ifft_shift(xs, *, dtype='float64'): + """Call HMath.Fourier.ifftShift; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_ifft_shift', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def hartley(xs, *, dtype='float64'): + """Call HMath.Fourier.hartley; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_hartley', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def periodogram(rate, window, xs, *, dtype='float64'): + """Call HMath.Fourier.periodogram; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_periodogram', + ['f', 'fs', 'fs'], + 'fd', + [rate, window, xs], + dtype, + 0, + ) + + +def welch(rate, window, hop, xs, *, dtype='float64'): + """Call HMath.Fourier.welch; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_welch', + ['f', 'fs', 'i', 'fs'], + 'fd', + [rate, window, hop, xs], + dtype, + 0, + ) + + +def cepstrum(floorValue, xs, *, dtype='float64'): + """Call HMath.Fourier.cepstrum; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_cepstrum', + ['f', 'fs'], + 'fd', + [floorValue, xs], + dtype, + 0, + ) + + +def hilbert(xs, *, dtype='float64'): + """Call HMath.Fourier.hilbert; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_fourier_hilbert', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +from .fourier_values import * diff --git a/bindings/python/_hmath_native/fourier_values.py b/bindings/python/_hmath_native/fourier_values.py new file mode 100644 index 0000000..d272b0a --- /dev/null +++ b/bindings/python/_hmath_native/fourier_values.py @@ -0,0 +1,261 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_spectral_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Direction(Value): + """Owned immutable original HMath.Fourier.Direction.""" + + +register(377, Direction) + + +class FFTAlgorithm(Value): + """Owned immutable original HMath.Fourier.FFTAlgorithm.""" + + +register(378, FFTAlgorithm) + + +class FFTPlan(Value): + """Owned immutable original HMath.Fourier.FFTPlan.""" + + +register(379, FFTPlan) + + +class TransformType(Value): + """Owned immutable original HMath.Fourier.TransformType.""" + + +register(380, TransformType) + + +class STFT(Value): + """Owned immutable original HMath.Fourier.STFT.""" + + +register(381, STFT) + + +def forward(): + """HMath.Fourier.Forward :: Direction.""" + return _invoke('hmath_fourier_value_forward', [], []) + + +def inverse(): + """HMath.Fourier.Inverse :: Direction.""" + return _invoke('hmath_fourier_value_inverse', [], []) + + +def automatic(): + """HMath.Fourier.Automatic :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_automatic', [], []) + + +def direct(): + """HMath.Fourier.Direct :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_direct', [], []) + + +def radix2(): + """HMath.Fourier.Radix2 :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_radix2', [], []) + + +def radix4(): + """HMath.Fourier.Radix4 :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_radix4', [], []) + + +def mixed_radix(): + """HMath.Fourier.MixedRadix :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_mixed_radix', [], []) + + +def split_radix(): + """HMath.Fourier.SplitRadix :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_split_radix', [], []) + + +def bluestein(): + """HMath.Fourier.Bluestein :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_bluestein', [], []) + + +def rader(): + """HMath.Fourier.Rader :: FFTAlgorithm.""" + return _invoke('hmath_fourier_value_rader', [], []) + + +def type_i(): + """HMath.Fourier.TypeI :: TransformType.""" + return _invoke('hmath_fourier_value_type_i', [], []) + + +def type_ii(): + """HMath.Fourier.TypeII :: TransformType.""" + return _invoke('hmath_fourier_value_type_ii', [], []) + + +def type_iii(): + """HMath.Fourier.TypeIII :: TransformType.""" + return _invoke('hmath_fourier_value_type_iii', [], []) + + +def type_iv(): + """HMath.Fourier.TypeIV :: TransformType.""" + return _invoke('hmath_fourier_value_type_iv', [], []) + + +def plan_fft(direction, method, n): + """HMath.Fourier.planFFT :: Direction -> FFTAlgorithm -> Int -> Either MathError FFTPlan.""" + return _invoke('hmath_fourier_value_plan_fft', [['Direction'], ['FFTAlgorithm'], ['Int']], [direction, method, n]) + + +def execute_fft(value, value2): + """HMath.Fourier.executeFFT :: FFTPlan -> [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_execute_fft', [['FFTPlan'], ['list', ['ComplexDouble']]], [value, value2]) + + +def fft(xs): + """HMath.Fourier.fft :: [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_fft', [['list', ['ComplexDouble']]], [xs]) + + +def ifft(xs): + """HMath.Fourier.ifft :: [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_ifft', [['list', ['ComplexDouble']]], [xs]) + + +def dft(xs): + """HMath.Fourier.dft :: [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_dft', [['list', ['ComplexDouble']]], [xs]) + + +def real_fft(value): + """HMath.Fourier.realFFT :: [Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_real_fft', [['list', ['Double']]], [value]) + + +def inverse_real_fft(tolerance, xs): + """HMath.Fourier.inverseRealFFT :: Double -> [Complex Double] -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_inverse_real_fft', [['Double'], ['list', ['ComplexDouble']]], [tolerance, xs]) + + +def fft_batch(value, value2): + """HMath.Fourier.fftBatch :: FFTPlan -> [[Complex Double]] -> Either MathError [[Complex Double]].""" + return _invoke('hmath_fourier_value_fft_batch', [['FFTPlan'], ['list', ['list', ['ComplexDouble']]]], [value, value2]) + + +def fft_nd(direction, dims, xs): + """HMath.Fourier.fftND :: Direction -> [Int] -> [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_fft_nd', [['Direction'], ['list', ['Int']], ['list', ['ComplexDouble']]], [direction, dims, xs]) + + +def dct(value, value2): + """HMath.Fourier.dct :: TransformType -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_dct', [['TransformType'], ['list', ['Double']]], [value, value2]) + + +def idct(value, value2): + """HMath.Fourier.idct :: TransformType -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_idct', [['TransformType'], ['list', ['Double']]], [value, value2]) + + +def dst(value, value2): + """HMath.Fourier.dst :: TransformType -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_dst', [['TransformType'], ['list', ['Double']]], [value, value2]) + + +def idst(value, value2): + """HMath.Fourier.idst :: TransformType -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_idst', [['TransformType'], ['list', ['Double']]], [value, value2]) + + +def stft_frames(value): + """HMath.Fourier.stftFrames :: STFT -> [[Complex Double]].""" + return _invoke('hmath_fourier_value_stft_frames', [['STFT']], [value]) + + +def stft(window, hop, xs): + """HMath.Fourier.stft :: [Double] -> Int -> [Double] -> Either MathError STFT.""" + return _invoke('hmath_fourier_value_stft', [['list', ['Double']], ['Int'], ['list', ['Double']]], [window, hop, xs]) + + +def istft(value): + """HMath.Fourier.istft :: STFT -> Either MathError [Double].""" + return _invoke('hmath_fourier_value_istft', [['STFT']], [value]) + + +def magnitude_spectrum(value): + """HMath.Fourier.magnitudeSpectrum :: [Complex Double] -> [Double].""" + return _invoke('hmath_fourier_value_magnitude_spectrum', [['list', ['ComplexDouble']]], [value]) + + +def phase_spectrum(value): + """HMath.Fourier.phaseSpectrum :: [Complex Double] -> [Double].""" + return _invoke('hmath_fourier_value_phase_spectrum', [['list', ['ComplexDouble']]], [value]) + + +def power_spectrum(value): + """HMath.Fourier.powerSpectrum :: [Complex Double] -> [Double].""" + return _invoke('hmath_fourier_value_power_spectrum', [['list', ['ComplexDouble']]], [value]) + + +def cross_spectrum(rate, window, x, y): + """HMath.Fourier.crossSpectrum :: Double -> [Double] -> [Double] -> [Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_cross_spectrum', [['Double'], ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], [rate, window, x, y]) + + +def spectrogram(w, h, xs): + """HMath.Fourier.spectrogram :: [Double] -> Int -> [Double] -> Either MathError [[Double]].""" + return _invoke('hmath_fourier_value_spectrogram', [['list', ['Double']], ['Int'], ['list', ['Double']]], [w, h, xs]) + + +def analytic_signal(xs): + """HMath.Fourier.analyticSignal :: [Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_analytic_signal', [['list', ['Double']]], [xs]) + + +def chirp_z(count, a, w, xs): + """HMath.Fourier.chirpZ :: Int -> Complex Double -> Complex Double -> [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_chirp_z', [['Int'], ['ComplexDouble'], ['ComplexDouble'], ['list', ['ComplexDouble']]], [count, a, w, xs]) + + +def goertzel(omega, xs): + """HMath.Fourier.goertzel :: Double -> [Double] -> Either MathError (Complex Double).""" + return _invoke('hmath_fourier_value_goertzel', [['Double'], ['list', ['Double']]], [omega, xs]) + + +def fft_convolve(a, b): + """HMath.Fourier.fftConvolve :: [Complex Double] -> [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_fft_convolve', [['list', ['ComplexDouble']], ['list', ['ComplexDouble']]], [a, b]) + + +def fft_correlate(a, b): + """HMath.Fourier.fftCorrelate :: [Complex Double] -> [Complex Double] -> Either MathError [Complex Double].""" + return _invoke('hmath_fourier_value_fft_correlate', [['list', ['ComplexDouble']], ['list', ['ComplexDouble']]], [a, b]) + + +def fft_shift(xs, *, dtype=None): + if dtype not in (None, "float64"): + raise ValueError("legacy dtype must be float64; generic elements retain their own types") + """HMath.Fourier.fftShift :: [a] -> [a].""" + return _invoke('hmath_fourier_value_fft_shift', [['list', ['Value']]], [xs]) + + +def ifft_shift(xs, *, dtype=None): + if dtype not in (None, "float64"): + raise ValueError("legacy dtype must be float64; generic elements retain their own types") + """HMath.Fourier.ifftShift :: [a] -> [a].""" + return _invoke('hmath_fourier_value_ifft_shift', [['list', ['Value']]], [xs]) + + +from ._spectral_base import fft_in_place as fft_in_place + + +def describe(value): + """Return the original Haskell Show representation of a spectral object.""" + return _invoke("hmath_spectral_describe", [["Value"]], [value]) diff --git a/bindings/python/_hmath_native/geometry.py b/bindings/python/_hmath_native/geometry.py new file mode 100644 index 0000000..0793138 --- /dev/null +++ b/bindings/python/_hmath_native/geometry.py @@ -0,0 +1,1158 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_geometry_bindings.py; do not edit. +"""Original checked geometry, topology, intersections and spatial search.""" +from ._geometry_base import GeometryValue, Ordering, _invoke +from ._value import register +from .geometry_primitives import hamming_distance, jaccard_distance + +IndexedTriangle = tuple + + +class Point2(GeometryValue): + """Actual immutable HMath.Geometry.Point2 native owner.""" + + +register(169, Point2) + + +class Point3(GeometryValue): + """Actual immutable HMath.Geometry.Point3 native owner.""" + + +register(170, Point3) + + +class PointND(GeometryValue): + """Actual immutable HMath.Geometry.PointND native owner.""" + + +register(171, PointND) + + +class Line(GeometryValue): + """Actual immutable HMath.Geometry.Line native owner.""" + + +register(172, Line) + + +class Ray(GeometryValue): + """Actual immutable HMath.Geometry.Ray native owner.""" + + +register(173, Ray) + + +class Segment(GeometryValue): + """Actual immutable HMath.Geometry.Segment native owner.""" + + +register(174, Segment) + + +class Plane(GeometryValue): + """Actual immutable HMath.Geometry.Plane native owner.""" + + +register(175, Plane) + + +class Triangle(GeometryValue): + """Actual immutable HMath.Geometry.Triangle native owner.""" + + +register(176, Triangle) + + +class Rectangle(GeometryValue): + """Actual immutable HMath.Geometry.Rectangle native owner.""" + + +register(177, Rectangle) + + +class Circle(GeometryValue): + """Actual immutable HMath.Geometry.Circle native owner.""" + + +register(178, Circle) + + +class Ellipse(GeometryValue): + """Actual immutable HMath.Geometry.Ellipse native owner.""" + + +register(179, Ellipse) + + +class Polygon(GeometryValue): + """Actual immutable HMath.Geometry.Polygon native owner.""" + + +register(180, Polygon) + + +class Sphere(GeometryValue): + """Actual immutable HMath.Geometry.Sphere native owner.""" + + +register(181, Sphere) + + +class AABB(GeometryValue): + """Actual immutable HMath.Geometry.AABB native owner.""" + + +register(182, AABB) + + +class OBB(GeometryValue): + """Actual immutable HMath.Geometry.OBB native owner.""" + + +register(183, OBB) + + +class Capsule(GeometryValue): + """Actual immutable HMath.Geometry.Capsule native owner.""" + + +register(184, Capsule) + + +class Cylinder(GeometryValue): + """Actual immutable HMath.Geometry.Cylinder native owner.""" + + +register(185, Cylinder) + + +class Cone(GeometryValue): + """Actual immutable HMath.Geometry.Cone native owner.""" + + +register(186, Cone) + + +class Frustum(GeometryValue): + """Actual immutable HMath.Geometry.Frustum native owner.""" + + +register(187, Frustum) + + +class Orientation(GeometryValue): + """Actual immutable HMath.Geometry.Orientation native owner.""" + + +register(188, Orientation) + + +class Location(GeometryValue): + """Actual immutable HMath.Geometry.Location native owner.""" + + +register(189, Location) + + +class Penetration(GeometryValue): + """Actual immutable HMath.Geometry.Penetration native owner.""" + + +register(190, Penetration) + + +class HullAlgorithm(GeometryValue): + """Actual immutable HMath.Geometry.HullAlgorithm native owner.""" + + +register(191, HullAlgorithm) + + +class BooleanOperation(GeometryValue): + """Actual immutable HMath.Geometry.BooleanOperation native owner.""" + + +register(192, BooleanOperation) + + +class Metric(GeometryValue): + """Actual immutable HMath.Geometry.Metric native owner.""" + + +register(193, Metric) + + +class Intersection2(GeometryValue): + """Actual immutable HMath.Geometry.Intersection2 native owner.""" + + +register(194, Intersection2) + + +class CircleIntersection(GeometryValue): + """Actual immutable HMath.Geometry.CircleIntersection native owner.""" + + +register(195, CircleIntersection) + + +class SpatialKind(GeometryValue): + """Actual immutable HMath.Geometry.SpatialKind native owner.""" + + +register(196, SpatialKind) + + +class PointCloud(GeometryValue): + """Actual immutable HMath.Geometry.PointCloud native owner.""" + + +register(197, PointCloud) + + +class SpatialIndex(GeometryValue): + """Actual immutable HMath.Geometry.SpatialIndex native owner.""" + + +register(198, SpatialIndex) + + +class NeighborQuery(GeometryValue): + """Actual immutable HMath.Geometry.NeighborQuery native owner.""" + + +register(199, NeighborQuery) + + +def parts(value): + """Return the actual public constructor and typed fields.""" + return _invoke("hmath_geometry_parts", [["GeometryObject"]], [value]) + + +def describe(value): + """Return the original Show representation, never evaluated as code.""" + return _invoke("hmath_geometry_describe", [["GeometryObject"]], [value]) + + +def penetration(number, point2, number2, count): + """HMath.Geometry.Collision.Penetration :: Double -> Point2 -> Double -> Int -> Penetration.""" + result = _invoke('hmath_geometry_penetration', [['Double'], ['Point2'], ['Double'], ['Int']], [number, point2, number2, count]) + return result + + +def epa(count, number, values, values2): + """HMath.Geometry.Collision.epa :: Int -> Double -> [Point2] -> [Point2] -> Either MathError (Maybe Penetration).""" + result = _invoke('hmath_geometry_epa', [['Int'], ['Double'], ['list', ['Point2']], ['list', ['Point2']]], [count, number, values, values2]) + return result + + +def gjk(count, values, values2): + """HMath.Geometry.Collision.gjk :: Int -> [Point2] -> [Point2] -> Either MathError Bool.""" + result = _invoke('hmath_geometry_gjk', [['Int'], ['list', ['Point2']], ['list', ['Point2']]], [count, values, values2]) + return result + + +def penetration_depth(penetration): + """HMath.Geometry.Collision.penetrationDepth :: Penetration -> Double.""" + result = _invoke('hmath_geometry_penetration_depth', [['Penetration']], [penetration]) + return result + + +def penetration_error(penetration): + """HMath.Geometry.Collision.penetrationError :: Penetration -> Double.""" + result = _invoke('hmath_geometry_penetration_error', [['Penetration']], [penetration]) + return result + + +def penetration_iterations(penetration): + """HMath.Geometry.Collision.penetrationIterations :: Penetration -> Int.""" + result = _invoke('hmath_geometry_penetration_iterations', [['Penetration']], [penetration]) + return result + + +def penetration_normal(penetration): + """HMath.Geometry.Collision.penetrationNormal :: Penetration -> Point2.""" + result = _invoke('hmath_geometry_penetration_normal', [['Penetration']], [penetration]) + return result + + +def separating_axis(values, values2): + """HMath.Geometry.Collision.separatingAxis :: [Point2] -> [Point2] -> Either MathError (Maybe Penetration).""" + result = _invoke('hmath_geometry_separating_axis', [['list', ['Point2']], ['list', ['Point2']]], [values, values2]) + return result + + +def aabb(point_nd, point_nd2): + """HMath.Geometry.Internal.AABB :: PointND -> PointND -> AABB.""" + result = _invoke('hmath_geometry_aabb', [['PointND'], ['PointND']], [point_nd, point_nd2]) + return result + + +def boundary(): + """HMath.Geometry.Internal.Boundary :: Location.""" + result = _invoke('hmath_geometry_boundary', [], []) + return result + + +def capsule(point3, point32, number): + """HMath.Geometry.Internal.Capsule :: Point3 -> Point3 -> Double -> Capsule.""" + result = _invoke('hmath_geometry_capsule', [['Point3'], ['Point3'], ['Double']], [point3, point32, number]) + return result + + +def circle(point2, number): + """HMath.Geometry.Internal.Circle :: Point2 -> Double -> Circle.""" + result = _invoke('hmath_geometry_circle', [['Point2'], ['Double']], [point2, number]) + return result + + +def clockwise(): + """HMath.Geometry.Internal.Clockwise :: Orientation.""" + result = _invoke('hmath_geometry_clockwise', [], []) + return result + + +def collinear(): + """HMath.Geometry.Internal.Collinear :: Orientation.""" + result = _invoke('hmath_geometry_collinear', [], []) + return result + + +def cone(point3, point32, number): + """HMath.Geometry.Internal.Cone :: Point3 -> Point3 -> Double -> Cone.""" + result = _invoke('hmath_geometry_cone', [['Point3'], ['Point3'], ['Double']], [point3, point32, number]) + return result + + +def counterclockwise(): + """HMath.Geometry.Internal.Counterclockwise :: Orientation.""" + result = _invoke('hmath_geometry_counterclockwise', [], []) + return result + + +def cylinder(point3, point32, number): + """HMath.Geometry.Internal.Cylinder :: Point3 -> Point3 -> Double -> Cylinder.""" + result = _invoke('hmath_geometry_cylinder', [['Point3'], ['Point3'], ['Double']], [point3, point32, number]) + return result + + +def ellipse(point2, number, number2, number3): + """HMath.Geometry.Internal.Ellipse :: Point2 -> Double -> Double -> Double -> Ellipse.""" + result = _invoke('hmath_geometry_ellipse', [['Point2'], ['Double'], ['Double'], ['Double']], [point2, number, number2, number3]) + return result + + +def frustum(values): + """HMath.Geometry.Internal.Frustum :: [Plane] -> Frustum.""" + result = _invoke('hmath_geometry_frustum', [['list', ['Plane']]], [values]) + return result + + +def inside(): + """HMath.Geometry.Internal.Inside :: Location.""" + result = _invoke('hmath_geometry_inside', [], []) + return result + + +def line(point_nd, point_nd2): + """HMath.Geometry.Internal.Line :: PointND -> PointND -> Line.""" + result = _invoke('hmath_geometry_line', [['PointND'], ['PointND']], [point_nd, point_nd2]) + return result + + +def obb(point3, values, point32): + """HMath.Geometry.Internal.OBB :: Point3 -> [Point3] -> Point3 -> OBB.""" + result = _invoke('hmath_geometry_obb', [['Point3'], ['list', ['Point3']], ['Point3']], [point3, values, point32]) + return result + + +def outside(): + """HMath.Geometry.Internal.Outside :: Location.""" + result = _invoke('hmath_geometry_outside', [], []) + return result + + +def p2(number, number2): + """HMath.Geometry.Internal.P2 :: Double -> Double -> Point2.""" + result = _invoke('hmath_geometry_p2', [['Double'], ['Double']], [number, number2]) + return result + + +def p3(number, number2, number3): + """HMath.Geometry.Internal.P3 :: Double -> Double -> Double -> Point3.""" + result = _invoke('hmath_geometry_p3', [['Double'], ['Double'], ['Double']], [number, number2, number3]) + return result + + +def plane(point3, number): + """HMath.Geometry.Internal.Plane :: Point3 -> Double -> Plane.""" + result = _invoke('hmath_geometry_plane', [['Point3'], ['Double']], [point3, number]) + return result + + +def point_nd_raw(values): + """HMath.Geometry.Internal.PointND :: [Double] -> PointND.""" + result = _invoke('hmath_geometry_point_nd_raw', [['list', ['Double']]], [values]) + return result + + +def polygon(values): + """HMath.Geometry.Internal.Polygon :: [Point2] -> Polygon.""" + result = _invoke('hmath_geometry_polygon', [['list', ['Point2']]], [values]) + return result + + +def ray(point3, point32): + """HMath.Geometry.Internal.Ray :: Point3 -> Point3 -> Ray.""" + result = _invoke('hmath_geometry_ray', [['Point3'], ['Point3']], [point3, point32]) + return result + + +def rectangle(point2, point22): + """HMath.Geometry.Internal.Rectangle :: Point2 -> Point2 -> Rectangle.""" + result = _invoke('hmath_geometry_rectangle', [['Point2'], ['Point2']], [point2, point22]) + return result + + +def segment(point_nd, point_nd2): + """HMath.Geometry.Internal.Segment :: PointND -> PointND -> Segment.""" + result = _invoke('hmath_geometry_segment', [['PointND'], ['PointND']], [point_nd, point_nd2]) + return result + + +def sphere(point3, number): + """HMath.Geometry.Internal.Sphere :: Point3 -> Double -> Sphere.""" + result = _invoke('hmath_geometry_sphere', [['Point3'], ['Double']], [point3, number]) + return result + + +def triangle(point2, point22, point23): + """HMath.Geometry.Internal.Triangle :: Point2 -> Point2 -> Point2 -> Triangle.""" + result = _invoke('hmath_geometry_triangle', [['Point2'], ['Point2'], ['Point2']], [point2, point22, point23]) + return result + + +def point2(number, number2): + """HMath.Geometry.Internal.point2 :: Double -> Double -> Either MathError Point2.""" + result = _invoke('hmath_geometry_point2', [['Double'], ['Double']], [number, number2]) + return result + + +def point3(number, number2, number3): + """HMath.Geometry.Internal.point3 :: Double -> Double -> Double -> Either MathError Point3.""" + result = _invoke('hmath_geometry_point3', [['Double'], ['Double'], ['Double']], [number, number2, number3]) + return result + + +def point_nd(values): + """HMath.Geometry.Internal.pointND :: [Double] -> Either MathError PointND.""" + result = _invoke('hmath_geometry_point_nd', [['list', ['Double']]], [values]) + return result + + +def difference(): + """HMath.Geometry.Polygon.Difference :: BooleanOperation.""" + result = _invoke('hmath_geometry_difference', [], []) + return result + + +def gift_wrapping(): + """HMath.Geometry.Polygon.GiftWrapping :: HullAlgorithm.""" + result = _invoke('hmath_geometry_gift_wrapping', [], []) + return result + + +def graham_scan(): + """HMath.Geometry.Polygon.GrahamScan :: HullAlgorithm.""" + result = _invoke('hmath_geometry_graham_scan', [], []) + return result + + +def intersection(): + """HMath.Geometry.Polygon.Intersection :: BooleanOperation.""" + result = _invoke('hmath_geometry_intersection', [], []) + return result + + +def monotone_chain(): + """HMath.Geometry.Polygon.MonotoneChain :: HullAlgorithm.""" + result = _invoke('hmath_geometry_monotone_chain', [], []) + return result + + +def quickhull(): + """HMath.Geometry.Polygon.Quickhull :: HullAlgorithm.""" + result = _invoke('hmath_geometry_quickhull', [], []) + return result + + +def union(): + """HMath.Geometry.Polygon.Union :: BooleanOperation.""" + result = _invoke('hmath_geometry_union', [], []) + return result + + +def clip_polygon(polygon, polygon2): + """HMath.Geometry.Polygon.clipPolygon :: Polygon -> Polygon -> Either MathError [Point2].""" + result = _invoke('hmath_geometry_clip_polygon', [['Polygon'], ['Polygon']], [polygon, polygon2]) + return result + + +def convex_hull(hull_algorithm, values): + """HMath.Geometry.Polygon.convexHull :: HullAlgorithm -> [Point2] -> Either MathError [Point2].""" + result = _invoke('hmath_geometry_convex_hull', [['HullAlgorithm'], ['list', ['Point2']]], [hull_algorithm, values]) + return result + + +def minimum_bounding_circle(values): + """HMath.Geometry.Polygon.minimumBoundingCircle :: [Point2] -> Either MathError Circle.""" + result = _invoke('hmath_geometry_minimum_bounding_circle', [['list', ['Point2']]], [values]) + return result + + +def minimum_bounding_rectangle(values): + """HMath.Geometry.Polygon.minimumBoundingRectangle :: [Point2] -> Either MathError [Point2].""" + result = _invoke('hmath_geometry_minimum_bounding_rectangle', [['list', ['Point2']]], [values]) + return result + + +def minkowski_sum(values, values2): + """HMath.Geometry.Polygon.minkowskiSum :: [Point2] -> [Point2] -> Either MathError [Point2].""" + result = _invoke('hmath_geometry_minkowski_sum', [['list', ['Point2']], ['list', ['Point2']]], [values, values2]) + return result + + +def polygon_area(polygon): + """HMath.Geometry.Polygon.polygonArea :: Polygon -> Either MathError Double.""" + result = _invoke('hmath_geometry_polygon_area', [['Polygon']], [polygon]) + return result + + +def polygon_boolean(boolean_operation, polygon, polygon2): + """HMath.Geometry.Polygon.polygonBoolean :: BooleanOperation -> Polygon -> Polygon -> Either MathError [Polygon].""" + result = _invoke('hmath_geometry_polygon_boolean', [['BooleanOperation'], ['Polygon'], ['Polygon']], [boolean_operation, polygon, polygon2]) + return result + + +def polygon_centroid(polygon): + """HMath.Geometry.Polygon.polygonCentroid :: Polygon -> Either MathError Point2.""" + result = _invoke('hmath_geometry_polygon_centroid', [['Polygon']], [polygon]) + return result + + +def shoelace(polygon): + """HMath.Geometry.Polygon.shoelace :: Polygon -> Either MathError Double.""" + result = _invoke('hmath_geometry_shoelace', [['Polygon']], [polygon]) + return result + + +def chebyshev(): + """HMath.Geometry.Primitives.Chebyshev :: Metric.""" + result = _invoke('hmath_geometry_chebyshev', [], []) + return result + + +def circle_points(values): + """HMath.Geometry.Primitives.CirclePoints :: [Point2] -> CircleIntersection.""" + result = _invoke('hmath_geometry_circle_points', [['list', ['Point2']]], [values]) + return result + + +def coincident_circles(): + """HMath.Geometry.Primitives.CoincidentCircles :: CircleIntersection.""" + result = _invoke('hmath_geometry_coincident_circles', [], []) + return result + + +def coincident_line(): + """HMath.Geometry.Primitives.CoincidentLine :: Intersection2.""" + result = _invoke('hmath_geometry_coincident_line', [], []) + return result + + +def disjoint_circles(): + """HMath.Geometry.Primitives.DisjointCircles :: CircleIntersection.""" + result = _invoke('hmath_geometry_disjoint_circles', [], []) + return result + + +def euclidean(): + """HMath.Geometry.Primitives.Euclidean :: Metric.""" + result = _invoke('hmath_geometry_euclidean', [], []) + return result + + +def intersection_point(point2): + """HMath.Geometry.Primitives.IntersectionPoint :: Point2 -> Intersection2.""" + result = _invoke('hmath_geometry_intersection_point', [['Point2']], [point2]) + return result + + +def manhattan(): + """HMath.Geometry.Primitives.Manhattan :: Metric.""" + result = _invoke('hmath_geometry_manhattan', [], []) + return result + + +def minkowski(number): + """HMath.Geometry.Primitives.Minkowski :: Double -> Metric.""" + result = _invoke('hmath_geometry_minkowski', [['Double']], [number]) + return result + + +def no_intersection(): + """HMath.Geometry.Primitives.NoIntersection :: Intersection2.""" + result = _invoke('hmath_geometry_no_intersection', [], []) + return result + + +def overlap_segment(point2, point22): + """HMath.Geometry.Primitives.OverlapSegment :: Point2 -> Point2 -> Intersection2.""" + result = _invoke('hmath_geometry_overlap_segment', [['Point2'], ['Point2']], [point2, point22]) + return result + + +def box_contains(aabb, point_nd): + """HMath.Geometry.Primitives.boxContains :: AABB -> PointND -> Either MathError Bool.""" + result = _invoke('hmath_geometry_box_contains', [['AABB'], ['PointND']], [aabb, point_nd]) + return result + + +def box_sdf(aabb, point_nd): + """HMath.Geometry.Primitives.boxSDF :: AABB -> PointND -> Either MathError Double.""" + result = _invoke('hmath_geometry_box_sdf', [['AABB'], ['PointND']], [aabb, point_nd]) + return result + + +def capsule_sdf(capsule, point3): + """HMath.Geometry.Primitives.capsuleSDF :: Capsule -> Point3 -> Either MathError Double.""" + result = _invoke('hmath_geometry_capsule_sdf', [['Capsule'], ['Point3']], [capsule, point3]) + return result + + +def circle_intersection(circle, circle2): + """HMath.Geometry.Primitives.circleIntersection :: Circle -> Circle -> Either MathError CircleIntersection.""" + result = _invoke('hmath_geometry_circle_intersection', [['Circle'], ['Circle']], [circle, circle2]) + return result + + +def circumcenter(triangle): + """HMath.Geometry.Primitives.circumcenter :: Triangle -> Either MathError Point2.""" + result = _invoke('hmath_geometry_circumcenter', [['Triangle']], [triangle]) + return result + + +def cone_sdf(cone, point3): + """HMath.Geometry.Primitives.coneSDF :: Cone -> Point3 -> Either MathError Double.""" + result = _invoke('hmath_geometry_cone_sdf', [['Cone'], ['Point3']], [cone, point3]) + return result + + +def cosine_distance(point_nd, point_nd2): + """HMath.Geometry.Primitives.cosineDistance :: PointND -> PointND -> Either MathError Double.""" + result = _invoke('hmath_geometry_cosine_distance', [['PointND'], ['PointND']], [point_nd, point_nd2]) + return result + + +def cylinder_sdf(cylinder, point3): + """HMath.Geometry.Primitives.cylinderSDF :: Cylinder -> Point3 -> Either MathError Double.""" + result = _invoke('hmath_geometry_cylinder_sdf', [['Cylinder'], ['Point3']], [cylinder, point3]) + return result + + +def distance(metric, point_nd, point_nd2): + """HMath.Geometry.Primitives.distance :: Metric -> PointND -> PointND -> Either MathError Double.""" + result = _invoke('hmath_geometry_distance', [['Metric'], ['PointND'], ['PointND']], [metric, point_nd, point_nd2]) + return result + + +def ellipse_contains(ellipse, point2): + """HMath.Geometry.Primitives.ellipseContains :: Ellipse -> Point2 -> Either MathError Bool.""" + result = _invoke('hmath_geometry_ellipse_contains', [['Ellipse'], ['Point2']], [ellipse, point2]) + return result + + +def hausdorff_distance(values, values2): + """HMath.Geometry.Primitives.hausdorffDistance :: [PointND] -> [PointND] -> Either MathError Double.""" + result = _invoke('hmath_geometry_hausdorff_distance', [['list', ['PointND']], ['list', ['PointND']]], [values, values2]) + return result + + +def incenter(triangle): + """HMath.Geometry.Primitives.incenter :: Triangle -> Either MathError Point2.""" + result = _invoke('hmath_geometry_incenter', [['Triangle']], [triangle]) + return result + + +def incircle(point2, point22, point23, point24): + """HMath.Geometry.Primitives.incircle :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Ordering.""" + result = _invoke('hmath_geometry_incircle', [['Point2'], ['Point2'], ['Point2'], ['Point2']], [point2, point22, point23, point24]) + return Ordering(result) + + +def line_intersection(point2, point22, point23, point24): + """HMath.Geometry.Primitives.lineIntersection :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2.""" + result = _invoke('hmath_geometry_line_intersection', [['Point2'], ['Point2'], ['Point2'], ['Point2']], [point2, point22, point23, point24]) + return result + + +def line_plane_intersection(line, plane): + """HMath.Geometry.Primitives.linePlaneIntersection :: Line -> Plane -> Either MathError (Maybe (Maybe Point3)).""" + result = _invoke('hmath_geometry_line_plane_intersection', [['Line'], ['Plane']], [line, plane]) + return result + + +def mahalanobis_distance(values, point_nd, point_nd2): + """HMath.Geometry.Primitives.mahalanobisDistance :: [[Double]] -> PointND -> PointND -> Either MathError Double.""" + result = _invoke('hmath_geometry_mahalanobis_distance', [['list', ['list', ['Double']]], ['PointND'], ['PointND']], [values, point_nd, point_nd2]) + return result + + +def obb_sdf(obb, point3): + """HMath.Geometry.Primitives.obbSDF :: OBB -> Point3 -> Either MathError Double.""" + result = _invoke('hmath_geometry_obb_sdf', [['OBB'], ['Point3']], [obb, point3]) + return result + + +def orientation(point2, point22, point23): + """HMath.Geometry.Primitives.orientation :: Point2 -> Point2 -> Point2 -> Either MathError Orientation.""" + result = _invoke('hmath_geometry_orientation', [['Point2'], ['Point2'], ['Point2']], [point2, point22, point23]) + return result + + +def plane_intersection(plane, plane2): + """HMath.Geometry.Primitives.planeIntersection :: Plane -> Plane -> Either MathError (Maybe (Maybe Line)).""" + result = _invoke('hmath_geometry_plane_intersection', [['Plane'], ['Plane']], [plane, plane2]) + return result + + +def point_line_distance(point_nd, line): + """HMath.Geometry.Primitives.pointLineDistance :: PointND -> Line -> Either MathError Double.""" + result = _invoke('hmath_geometry_point_line_distance', [['PointND'], ['Line']], [point_nd, line]) + return result + + +def point_plane_distance(point3, plane): + """HMath.Geometry.Primitives.pointPlaneDistance :: Point3 -> Plane -> Either MathError Double.""" + result = _invoke('hmath_geometry_point_plane_distance', [['Point3'], ['Plane']], [point3, plane]) + return result + + +def point_segment_distance(point_nd, segment): + """HMath.Geometry.Primitives.pointSegmentDistance :: PointND -> Segment -> Either MathError Double.""" + result = _invoke('hmath_geometry_point_segment_distance', [['PointND'], ['Segment']], [point_nd, segment]) + return result + + +def polygon_location(polygon, point2): + """HMath.Geometry.Primitives.polygonLocation :: Polygon -> Point2 -> Either MathError Location.""" + result = _invoke('hmath_geometry_polygon_location', [['Polygon'], ['Point2']], [polygon, point2]) + return result + + +def ray_box(ray, aabb): + """HMath.Geometry.Primitives.rayBox :: Ray -> AABB -> Either MathError (Maybe (Double, Double)).""" + result = _invoke('hmath_geometry_ray_box', [['Ray'], ['AABB']], [ray, aabb]) + return result + + +def ray_sphere(ray, sphere): + """HMath.Geometry.Primitives.raySphere :: Ray -> Sphere -> Either MathError (Maybe (Double, Double)).""" + result = _invoke('hmath_geometry_ray_sphere', [['Ray'], ['Sphere']], [ray, sphere]) + return result + + +def ray_triangle(ray, tuple_value): + """HMath.Geometry.Primitives.rayTriangle :: Ray -> (Point3, Point3, Point3) -> Either MathError (Maybe Double).""" + result = _invoke('hmath_geometry_ray_triangle', [['Ray'], ['tuple', ['Point3'], ['Point3'], ['Point3']]], [ray, tuple_value]) + return result + + +def segment_intersection(point2, point22, point23, point24): + """HMath.Geometry.Primitives.segmentIntersection :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2.""" + result = _invoke('hmath_geometry_segment_intersection', [['Point2'], ['Point2'], ['Point2'], ['Point2']], [point2, point22, point23, point24]) + return result + + +def sphere_contains(sphere, point3): + """HMath.Geometry.Primitives.sphereContains :: Sphere -> Point3 -> Either MathError Bool.""" + result = _invoke('hmath_geometry_sphere_contains', [['Sphere'], ['Point3']], [sphere, point3]) + return result + + +def sphere_sdf(sphere, point3): + """HMath.Geometry.Primitives.sphereSDF :: Sphere -> Point3 -> Either MathError Double.""" + result = _invoke('hmath_geometry_sphere_sdf', [['Sphere'], ['Point3']], [sphere, point3]) + return result + + +def triangle_barycentric(triangle, point2): + """HMath.Geometry.Primitives.triangleBarycentric :: Triangle -> Point2 -> Either MathError [Double].""" + result = _invoke('hmath_geometry_triangle_barycentric', [['Triangle'], ['Point2']], [triangle, point2]) + return result + + +def triangle_intersection(triangle, triangle2): + """HMath.Geometry.Primitives.triangleIntersection :: Triangle -> Triangle -> Either MathError [Point2].""" + result = _invoke('hmath_geometry_triangle_intersection', [['Triangle'], ['Triangle']], [triangle, triangle2]) + return result + + +def triangle_location(triangle, point2): + """HMath.Geometry.Primitives.triangleLocation :: Triangle -> Point2 -> Either MathError Location.""" + result = _invoke('hmath_geometry_triangle_location', [['Triangle'], ['Point2']], [triangle, point2]) + return result + + +def bvh(): + """HMath.Geometry.Spatial.BVH :: SpatialKind.""" + result = _invoke('hmath_geometry_bvh', [], []) + return result + + +def ball_tree(): + """HMath.Geometry.Spatial.BallTree :: SpatialKind.""" + result = _invoke('hmath_geometry_ball_tree', [], []) + return result + + +def kd_tree(): + """HMath.Geometry.Spatial.KDTree :: SpatialKind.""" + result = _invoke('hmath_geometry_kd_tree', [], []) + return result + + +def neighbor_query(values, count, flag): + """HMath.Geometry.Spatial.NeighborQuery :: [(Int, Double)] -> Int -> Bool -> NeighborQuery.""" + result = _invoke('hmath_geometry_neighbor_query', [['list', ['tuple', ['Int'], ['Double']]], ['Int'], ['Bool']], [values, count, flag]) + return result + + +def octree(): + """HMath.Geometry.Spatial.Octree :: SpatialKind.""" + result = _invoke('hmath_geometry_octree', [], []) + return result + + +def quadtree(): + """HMath.Geometry.Spatial.Quadtree :: SpatialKind.""" + result = _invoke('hmath_geometry_quadtree', [], []) + return result + + +def r_tree(): + """HMath.Geometry.Spatial.RTree :: SpatialKind.""" + result = _invoke('hmath_geometry_r_tree', [], []) + return result + + +def spatial_hash(number): + """HMath.Geometry.Spatial.SpatialHash :: Double -> SpatialKind.""" + result = _invoke('hmath_geometry_spatial_hash', [['Double']], [number]) + return result + + +def build_spatial_index(spatial_kind, point_cloud): + """HMath.Geometry.Spatial.buildSpatialIndex :: SpatialKind -> PointCloud -> Either MathError SpatialIndex.""" + result = _invoke('hmath_geometry_build_spatial_index', [['SpatialKind'], ['PointCloud']], [spatial_kind, point_cloud]) + return result + + +def cloud_points(point_cloud): + """HMath.Geometry.Spatial.cloudPoints :: PointCloud -> [PointND].""" + result = _invoke('hmath_geometry_cloud_points', [['PointCloud']], [point_cloud]) + return result + + +def nearest_query(count, count2, spatial_index, point_nd): + """HMath.Geometry.Spatial.nearestQuery :: Int -> Int -> SpatialIndex -> PointND -> Either MathError NeighborQuery.""" + result = _invoke('hmath_geometry_nearest_query', [['Int'], ['Int'], ['SpatialIndex'], ['PointND']], [count, count2, spatial_index, point_nd]) + return result + + +def point_cloud(values): + """HMath.Geometry.Spatial.pointCloud :: [PointND] -> Either MathError PointCloud.""" + result = _invoke('hmath_geometry_point_cloud', [['list', ['PointND']]], [values]) + return result + + +def query_exhaustive(neighbor_query): + """HMath.Geometry.Spatial.queryExhaustive :: NeighborQuery -> Bool.""" + result = _invoke('hmath_geometry_query_exhaustive', [['NeighborQuery']], [neighbor_query]) + return result + + +def query_leaves(neighbor_query): + """HMath.Geometry.Spatial.queryLeaves :: NeighborQuery -> Int.""" + result = _invoke('hmath_geometry_query_leaves', [['NeighborQuery']], [neighbor_query]) + return result + + +def query_neighbors(neighbor_query): + """HMath.Geometry.Spatial.queryNeighbors :: NeighborQuery -> [(Int, Double)].""" + result = _invoke('hmath_geometry_query_neighbors', [['NeighborQuery']], [neighbor_query]) + return result + + +def radius_query(spatial_index, point_nd, number): + """HMath.Geometry.Spatial.radiusQuery :: SpatialIndex -> PointND -> Double -> Either MathError [Int].""" + result = _invoke('hmath_geometry_radius_query', [['SpatialIndex'], ['PointND'], ['Double']], [spatial_index, point_nd, number]) + return result + + +def range_query(spatial_index, aabb): + """HMath.Geometry.Spatial.rangeQuery :: SpatialIndex -> AABB -> Either MathError [Int].""" + result = _invoke('hmath_geometry_range_query', [['SpatialIndex'], ['AABB']], [spatial_index, aabb]) + return result + + +def affine_transform(matrix, point_nd): + """HMath.Geometry.Transform.affineTransform :: Matrix Double -> PointND -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_affine_transform', [['Matrix Double'], ['PointND']], [matrix, point_nd]) + return result + + +def apply_transform(matrix, point_nd): + """HMath.Geometry.Transform.applyTransform :: Matrix Double -> PointND -> Either MathError PointND.""" + result = _invoke('hmath_geometry_apply_transform', [['Matrix Double'], ['PointND']], [matrix, point_nd]) + return result + + +def compose_transforms(matrix, matrix2): + """HMath.Geometry.Transform.composeTransforms :: Matrix Double -> Matrix Double -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_compose_transforms', [['Matrix Double'], ['Matrix Double']], [matrix, matrix2]) + return result + + +def cull_box(frustum, aabb): + """HMath.Geometry.Transform.cullBox :: Frustum -> AABB -> Either MathError Bool.""" + result = _invoke('hmath_geometry_cull_box', [['Frustum'], ['AABB']], [frustum, aabb]) + return result + + +def cull_sphere(frustum, sphere): + """HMath.Geometry.Transform.cullSphere :: Frustum -> Sphere -> Either MathError Bool.""" + result = _invoke('hmath_geometry_cull_sphere', [['Frustum'], ['Sphere']], [frustum, sphere]) + return result + + +def extract_frustum(matrix): + """HMath.Geometry.Transform.extractFrustum :: Matrix Double -> Either MathError Frustum.""" + result = _invoke('hmath_geometry_extract_frustum', [['Matrix Double']], [matrix]) + return result + + +def inverse_transform(matrix): + """HMath.Geometry.Transform.inverseTransform :: Matrix Double -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_inverse_transform', [['Matrix Double']], [matrix]) + return result + + +def look_at(point3, point32, point33): + """HMath.Geometry.Transform.lookAt :: Point3 -> Point3 -> Point3 -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_look_at', [['Point3'], ['Point3'], ['Point3']], [point3, point32, point33]) + return result + + +def orthographic(number, number2, number3, number4, number5, number6): + """HMath.Geometry.Transform.orthographic :: Double -> Double -> Double -> Double -> Double -> Double -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_orthographic', [['Double'], ['Double'], ['Double'], ['Double'], ['Double'], ['Double']], [number, number2, number3, number4, number5, number6]) + return result + + +def perspective(number, number2, number3, number4): + """HMath.Geometry.Transform.perspective :: Double -> Double -> Double -> Double -> Either MathError (Matrix Double).""" + result = _invoke('hmath_geometry_perspective', [['Double'], ['Double'], ['Double'], ['Double']], [number, number2, number3, number4]) + return result + + +def constrained_delaunay(values, values2): + """HMath.Geometry.Triangulation.constrainedDelaunay :: [Point2] -> [(Int, Int)] -> Either MathError [IndexedTriangle].""" + result = _invoke('hmath_geometry_constrained_delaunay', [['list', ['Point2']], ['list', ['tuple', ['Int'], ['Int']]]], [values, values2]) + return result + + +def delaunay(values): + """HMath.Geometry.Triangulation.delaunay :: [Point2] -> Either MathError [IndexedTriangle].""" + result = _invoke('hmath_geometry_delaunay', [['list', ['Point2']]], [values]) + return result + + +def ear_clip(polygon): + """HMath.Geometry.Triangulation.earClip :: Polygon -> Either MathError [IndexedTriangle].""" + result = _invoke('hmath_geometry_ear_clip', [['Polygon']], [polygon]) + return result + + +def voronoi(rectangle, values): + """HMath.Geometry.Triangulation.voronoi :: Rectangle -> [Point2] -> Either MathError [[Point2]].""" + result = _invoke('hmath_geometry_voronoi', [['Rectangle'], ['list', ['Point2']]], [rectangle, values]) + return result + + +__all__ = [ + "AABB", + "OBB", + "BooleanOperation", + "Capsule", + "Circle", + "CircleIntersection", + "Cone", + "Cylinder", + "Ellipse", + "Frustum", + "HullAlgorithm", + "IndexedTriangle", + "Intersection2", + "Line", + "Location", + "Metric", + "NeighborQuery", + "Ordering", + "Orientation", + "Penetration", + "Plane", + "Point2", + "Point3", + "PointCloud", + "PointND", + "Polygon", + "Ray", + "Rectangle", + "Segment", + "SpatialIndex", + "SpatialKind", + "Sphere", + "Triangle", + "aabb", + "affine_transform", + "apply_transform", + "ball_tree", + "boundary", + "box_contains", + "box_sdf", + "build_spatial_index", + "bvh", + "capsule", + "capsule_sdf", + "chebyshev", + "circle", + "circle_intersection", + "circle_points", + "circumcenter", + "clip_polygon", + "clockwise", + "cloud_points", + "coincident_circles", + "coincident_line", + "collinear", + "compose_transforms", + "cone", + "cone_sdf", + "constrained_delaunay", + "convex_hull", + "cosine_distance", + "counterclockwise", + "cull_box", + "cull_sphere", + "cylinder", + "cylinder_sdf", + "delaunay", + "describe", + "difference", + "disjoint_circles", + "distance", + "ear_clip", + "ellipse", + "ellipse_contains", + "epa", + "euclidean", + "extract_frustum", + "frustum", + "gift_wrapping", + "gjk", + "graham_scan", + "hamming_distance", + "hausdorff_distance", + "incenter", + "incircle", + "inside", + "intersection", + "intersection_point", + "inverse_transform", + "jaccard_distance", + "kd_tree", + "line", + "line_intersection", + "line_plane_intersection", + "look_at", + "mahalanobis_distance", + "manhattan", + "minimum_bounding_circle", + "minimum_bounding_rectangle", + "minkowski", + "minkowski_sum", + "monotone_chain", + "nearest_query", + "neighbor_query", + "no_intersection", + "obb", + "obb_sdf", + "octree", + "orientation", + "orthographic", + "outside", + "overlap_segment", + "p2", + "p3", + "parts", + "penetration", + "penetration_depth", + "penetration_error", + "penetration_iterations", + "penetration_normal", + "perspective", + "plane", + "plane_intersection", + "point2", + "point3", + "point_cloud", + "point_line_distance", + "point_nd", + "point_nd_raw", + "point_plane_distance", + "point_segment_distance", + "polygon", + "polygon_area", + "polygon_boolean", + "polygon_centroid", + "polygon_location", + "quadtree", + "query_exhaustive", + "query_leaves", + "query_neighbors", + "quickhull", + "r_tree", + "radius_query", + "range_query", + "ray", + "ray_box", + "ray_sphere", + "ray_triangle", + "rectangle", + "segment", + "segment_intersection", + "separating_axis", + "shoelace", + "spatial_hash", + "sphere", + "sphere_contains", + "sphere_sdf", + "triangle", + "triangle_barycentric", + "triangle_intersection", + "triangle_location", + "union", + "voronoi" +] diff --git a/bindings/python/_hmath_native/geometry_primitives.py b/bindings/python/_hmath_native/geometry_primitives.py new file mode 100644 index 0000000..7e38a75 --- /dev/null +++ b/bindings/python/_hmath_native/geometry_primitives.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call +from ._numeric_objects import _call_value, _uses_equality_value + + +def hamming_distance(argument1, argument2, *, dtype='float64'): + """Call HMath.Geometry.Primitives.hammingDistance; preserve its argument order, result and errors.""" + if _uses_equality_value([argument1, argument2], dtype): + return _call_value('hmath_geometry_primitives_hamming_distance', ['fs', 'fs'], [argument1, argument2], dtype) + return _call( + 'hmath_geometry_primitives_hamming_distance', + ['fs', 'fs'], + 'i', + [argument1, argument2], + dtype, + 0, + ) + + +def jaccard_distance(argument1, argument2, *, dtype='float64'): + """Call HMath.Geometry.Primitives.jaccardDistance; preserve its argument order, result and errors.""" + if _uses_equality_value([argument1, argument2], dtype): + return _call_value('hmath_geometry_primitives_jaccard_distance', ['fs', 'fs'], [argument1, argument2], dtype) + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_geometry_primitives_jaccard_distance', + ['fs', 'fs'], + 'f', + [argument1, argument2], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/graph.py b/bindings/python/_hmath_native/graph.py new file mode 100644 index 0000000..0b50d4e --- /dev/null +++ b/bindings/python/_hmath_native/graph.py @@ -0,0 +1,595 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_graph_bindings.py. +from ._graph_base import _invoke, _astar +from ._value import Value, register + + +class Graph(Value): + """Owned immutable original HMath.Graph.Core.Graph.""" + + +register(60, Graph) + + +class Edge(Value): + """Owned immutable original HMath.Graph.Core.Edge.""" + + +register(61, Edge) + + +class CSR(Value): + """Owned immutable original HMath.Graph.Core.CSR.""" + + +register(62, CSR) + + +class BipartiteGraph(Value): + """Owned immutable original HMath.Graph.Core.BipartiteGraph.""" + + +register(63, BipartiteGraph) + + +class Hypergraph(Value): + """Owned immutable original HMath.Graph.Core.Hypergraph.""" + + +register(64, Hypergraph) + + +class Network(Value): + """Owned immutable original HMath.Graph.Flow.Network.""" + + +register(65, Network) + + +class NetworkEdge(Value): + """Owned immutable original HMath.Graph.Flow.NetworkEdge.""" + + +register(66, NetworkEdge) + + +class FlowResult(Value): + """Owned immutable original HMath.Graph.Flow.FlowResult.""" + + +register(67, FlowResult) + + +def betweenness_centrality(graph): + """HMath.Graph.Analysis.betweennessCentrality :: Graph -> [Double].""" + return _invoke('hmath_graph_betweenness_centrality', [['Graph']], [graph]) + + +def bipartite_colors(graph): + """HMath.Graph.Analysis.bipartiteColors :: Graph -> Maybe [Bool].""" + return _invoke('hmath_graph_bipartite_colors', [['Graph']], [graph]) + + +def closeness_centrality(graph): + """HMath.Graph.Analysis.closenessCentrality :: Graph -> [Double].""" + return _invoke('hmath_graph_closeness_centrality', [['Graph']], [graph]) + + +def clustering_coefficients(graph): + """HMath.Graph.Analysis.clusteringCoefficients :: Graph -> Either MathError [Double].""" + return _invoke('hmath_graph_clustering_coefficients', [['Graph']], [graph]) + + +def degree_centrality(graph): + """HMath.Graph.Analysis.degreeCentrality :: Graph -> [Double].""" + return _invoke('hmath_graph_degree_centrality', [['Graph']], [graph]) + + +def density(graph): + """HMath.Graph.Analysis.density :: Graph -> Double.""" + return _invoke('hmath_graph_density', [['Graph']], [graph]) + + +def diameter_radius(graph): + """HMath.Graph.Analysis.diameterRadius :: Graph -> Maybe (Int, Int).""" + return _invoke('hmath_graph_diameter_radius', [['Graph']], [graph]) + + +def eigenvector_centrality(iterations, tolerance, graph): + """HMath.Graph.Analysis.eigenvectorCentrality :: Int -> Double -> Graph -> Either MathError [Double].""" + return _invoke('hmath_graph_eigenvector_centrality', [['Int'], ['Double'], ['Graph']], [iterations, tolerance, graph]) + + +def eulerian_path(graph): + """HMath.Graph.Analysis.eulerianPath :: Graph -> Either MathError (Maybe ([Int], [Int])).""" + return _invoke('hmath_graph_eulerian_path', [['Graph']], [graph]) + + +def exact_coloring(fuel, graph): + """HMath.Graph.Analysis.exactColoring :: Int -> Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_exact_coloring', [['Int'], ['Graph']], [fuel, graph]) + + +def graph_edit_distance(budget, left, right): + """HMath.Graph.Analysis.graphEditDistance :: Int -> Graph -> Graph -> Either MathError Int.""" + return _invoke('hmath_graph_graph_edit_distance', [['Int'], ['Graph'], ['Graph']], [budget, left, right]) + + +def graph_laplacian(normalized, graph): + """HMath.Graph.Analysis.graphLaplacian :: Bool -> Graph -> Either MathError [[Double]].""" + return _invoke('hmath_graph_graph_laplacian', [['Bool'], ['Graph']], [normalized, graph]) + + +def graph_similarity(left, right): + """HMath.Graph.Analysis.graphSimilarity :: Graph -> Graph -> Either MathError Double.""" + return _invoke('hmath_graph_graph_similarity', [['Graph'], ['Graph']], [left, right]) + + +def greedy_coloring(graph): + """HMath.Graph.Analysis.greedyColoring :: Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_greedy_coloring', [['Graph']], [graph]) + + +def hamiltonian_path(fuel, graph): + """HMath.Graph.Analysis.hamiltonianPath :: Int -> Graph -> Either MathError (Maybe [Int]).""" + return _invoke('hmath_graph_hamiltonian_path', [['Int'], ['Graph']], [fuel, graph]) + + +def katz_centrality(iterations, tolerance, alpha, beta, graph): + """HMath.Graph.Analysis.katzCentrality :: Int -> Double -> Double -> Double -> Graph -> Either MathError [Double].""" + return _invoke('hmath_graph_katz_centrality', [['Int'], ['Double'], ['Double'], ['Double'], ['Graph']], [iterations, tolerance, alpha, beta, graph]) + + +def label_propagation(iterations, graph): + """HMath.Graph.Analysis.labelPropagation :: Int -> Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_label_propagation', [['Int'], ['Graph']], [iterations, graph]) + + +def laplacian_spectrum(iterations, tolerance, normalized, graph): + """HMath.Graph.Analysis.laplacianSpectrum :: Int -> Double -> Bool -> Graph -> Either MathError [Double].""" + return _invoke('hmath_graph_laplacian_spectrum', [['Int'], ['Double'], ['Bool'], ['Graph']], [iterations, tolerance, normalized, graph]) + + +def louvain(budget, graph): + """HMath.Graph.Analysis.louvain :: Int -> Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_louvain', [['Int'], ['Graph']], [budget, graph]) + + +def modularity(graph, labels): + """HMath.Graph.Analysis.modularity :: Graph -> [Int] -> Either MathError Double.""" + return _invoke('hmath_graph_modularity', [['Graph'], ['list', ['Int']]], [graph, labels]) + + +def nearest_neighbor_tour(graph, start): + """HMath.Graph.Analysis.nearestNeighborTour :: Graph -> Int -> Either MathError (Maybe (Double, [Int])).""" + return _invoke('hmath_graph_nearest_neighbor_tour', [['Graph'], ['Int']], [graph, start]) + + +def page_rank(iterations, tolerance, damping, graph): + """HMath.Graph.Analysis.pageRank :: Int -> Double -> Double -> Graph -> Either MathError [Double].""" + return _invoke('hmath_graph_page_rank', [['Int'], ['Double'], ['Double'], ['Graph']], [iterations, tolerance, damping, graph]) + + +def random_walk(count, seed, graph, start): + """HMath.Graph.Analysis.randomWalk :: Int -> Word64 -> Graph -> Int -> Either MathError [Int].""" + return _invoke('hmath_graph_random_walk', [['Int'], ['Word64'], ['Graph'], ['Int']], [count, seed, graph, start]) + + +def two_opt_tour(iterations, graph, tour): + """HMath.Graph.Analysis.twoOptTour :: Int -> Graph -> [Int] -> Either MathError (Double, [Int]).""" + return _invoke('hmath_graph_two_opt_tour', [['Int'], ['Graph'], ['list', ['Int']]], [iterations, graph, tour]) + + +def csr(directed, vertex_count, offsets, targets, weights, edge_ids, orientations): + """HMath.Graph.Core.CSR :: Bool -> Int -> [Int] -> [Int] -> [Double] -> [Int] -> [(Int, Int)] -> CSR.""" + return _invoke('hmath_graph_csr', [['Bool'], ['Int'], ['list', ['Int']], ['list', ['Int']], ['list', ['Double']], ['list', ['Int']], ['list', ['tuple', ['Int'], ['Int']]]], [directed, vertex_count, offsets, targets, weights, edge_ids, orientations]) + + +def edge(edge_id, source, target, weight): + """HMath.Graph.Core.Edge :: Int -> Int -> Int -> Double -> Edge.""" + return _invoke('hmath_graph_edge', [['Int'], ['Int'], ['Int'], ['Double']], [edge_id, source, target, weight]) + + +def adjacency_list(graph): + """HMath.Graph.Core.adjacencyList :: Graph -> [[(Int, Double, Int)]].""" + return _invoke('hmath_graph_adjacency_list', [['Graph']], [graph]) + + +def adjacency_matrix(graph): + """HMath.Graph.Core.adjacencyMatrix :: Graph -> [[[(Int, Double)]]].""" + return _invoke('hmath_graph_adjacency_matrix', [['Graph']], [graph]) + + +def arcs(graph): + """HMath.Graph.Core.arcs :: Graph -> [Edge].""" + return _invoke('hmath_graph_arcs', [['Graph']], [graph]) + + +def articulation_points(graph): + """HMath.Graph.Core.articulationPoints :: Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_articulation_points', [['Graph']], [graph]) + + +def bfs(graph, start): + """HMath.Graph.Core.bfs :: Graph -> Int -> Either MathError [Int].""" + return _invoke('hmath_graph_bfs', [['Graph'], ['Int']], [graph, start]) + + +def bipartite_base(bipartite_graph): + """HMath.Graph.Core.bipartiteBase :: BipartiteGraph -> Graph.""" + return _invoke('hmath_graph_bipartite_base', [['BipartiteGraph']], [bipartite_graph]) + + +def bipartite_graph(left_vertices, right_vertices, edges): + """HMath.Graph.Core.bipartiteGraph :: Int -> Int -> [(Int, Int, Double)] -> Either MathError BipartiteGraph.""" + return _invoke('hmath_graph_bipartite_graph', [['Int'], ['Int'], ['list', ['tuple', ['Int'], ['Int'], ['Double']]]], [left_vertices, right_vertices, edges]) + + +def bipartite_parts(bipartite_graph): + """HMath.Graph.Core.bipartiteParts :: BipartiteGraph -> (Int, Int).""" + return _invoke('hmath_graph_bipartite_parts', [['BipartiteGraph']], [bipartite_graph]) + + +def boruvka(graph): + """HMath.Graph.Core.boruvka :: Graph -> Either MathError [Edge].""" + return _invoke('hmath_graph_boruvka', [['Graph']], [graph]) + + +def bridges(graph): + """HMath.Graph.Core.bridges :: Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_bridges', [['Graph']], [graph]) + + +def check_vertex(graph, vertex): + """HMath.Graph.Core.checkVertex :: Graph -> Int -> Either MathError ().""" + return _invoke('hmath_graph_check_vertex', [['Graph'], ['Int']], [graph, vertex]) + + +def connected_components(graph): + """HMath.Graph.Core.connectedComponents :: Graph -> [[Int]].""" + return _invoke('hmath_graph_connected_components', [['Graph']], [graph]) + + +def csr_directed(csr): + """HMath.Graph.Core.csrDirected :: CSR -> Bool.""" + return _invoke('hmath_graph_csr_directed', [['CSR']], [csr]) + + +def csr_ids(csr): + """HMath.Graph.Core.csrIds :: CSR -> [Int].""" + return _invoke('hmath_graph_csr_ids', [['CSR']], [csr]) + + +def csr_offsets(csr): + """HMath.Graph.Core.csrOffsets :: CSR -> [Int].""" + return _invoke('hmath_graph_csr_offsets', [['CSR']], [csr]) + + +def csr_orientations(csr): + """HMath.Graph.Core.csrOrientations :: CSR -> [(Int, Int)].""" + return _invoke('hmath_graph_csr_orientations', [['CSR']], [csr]) + + +def csr_targets(csr): + """HMath.Graph.Core.csrTargets :: CSR -> [Int].""" + return _invoke('hmath_graph_csr_targets', [['CSR']], [csr]) + + +def csr_vertices(csr): + """HMath.Graph.Core.csrVertices :: CSR -> Int.""" + return _invoke('hmath_graph_csr_vertices', [['CSR']], [csr]) + + +def csr_weights(csr): + """HMath.Graph.Core.csrWeights :: CSR -> [Double].""" + return _invoke('hmath_graph_csr_weights', [['CSR']], [csr]) + + +def deserialize_bipartite_graph(text): + """HMath.Graph.Core.deserializeBipartiteGraph :: String -> Either MathError BipartiteGraph.""" + return _invoke('hmath_graph_deserialize_bipartite_graph', [['String']], [text]) + + +def deserialize_graph(text): + """HMath.Graph.Core.deserializeGraph :: String -> Either MathError Graph.""" + return _invoke('hmath_graph_deserialize_graph', [['String']], [text]) + + +def deserialize_hypergraph(text): + """HMath.Graph.Core.deserializeHypergraph :: String -> Either MathError Hypergraph.""" + return _invoke('hmath_graph_deserialize_hypergraph', [['String']], [text]) + + +def dfs(graph, start): + """HMath.Graph.Core.dfs :: Graph -> Int -> Either MathError [Int].""" + return _invoke('hmath_graph_dfs', [['Graph'], ['Int']], [graph, start]) + + +def directed(graph): + """HMath.Graph.Core.directed :: Graph -> Bool.""" + return _invoke('hmath_graph_directed', [['Graph']], [graph]) + + +def edge_from(edge): + """HMath.Graph.Core.edgeFrom :: Edge -> Int.""" + return _invoke('hmath_graph_edge_from', [['Edge']], [edge]) + + +def edge_id(edge): + """HMath.Graph.Core.edgeId :: Edge -> Int.""" + return _invoke('hmath_graph_edge_id', [['Edge']], [edge]) + + +def edge_to(edge): + """HMath.Graph.Core.edgeTo :: Edge -> Int.""" + return _invoke('hmath_graph_edge_to', [['Edge']], [edge]) + + +def edge_weight(edge): + """HMath.Graph.Core.edgeWeight :: Edge -> Double.""" + return _invoke('hmath_graph_edge_weight', [['Edge']], [edge]) + + +def edges(graph): + """HMath.Graph.Core.edges :: Graph -> [Edge].""" + return _invoke('hmath_graph_edges', [['Graph']], [graph]) + + +def finite(x): + """HMath.Graph.Core.finite :: Double -> Bool.""" + return _invoke('hmath_graph_finite', [['Double']], [x]) + + +def from_adjacency_list(directed, rows, orientations): + """HMath.Graph.Core.fromAdjacencyList :: Bool -> [[(Int, Double, Int)]] -> [(Int, Int)] -> Either MathError Graph.""" + return _invoke('hmath_graph_from_adjacency_list', [['Bool'], ['list', ['list', ['tuple', ['Int'], ['Double'], ['Int']]]], ['list', ['tuple', ['Int'], ['Int']]]], [directed, rows, orientations]) + + +def from_adjacency_matrix(directed, cells): + """HMath.Graph.Core.fromAdjacencyMatrix :: Bool -> [[[Double]]] -> Either MathError Graph.""" + return _invoke('hmath_graph_from_adjacency_matrix', [['Bool'], ['list', ['list', ['list', ['Double']]]]], [directed, cells]) + + +def from_csr(csr): + """HMath.Graph.Core.fromCSR :: CSR -> Either MathError Graph.""" + return _invoke('hmath_graph_from_csr', [['CSR']], [csr]) + + +def from_labeled_adjacency_matrix(directed, cells, orientations): + """HMath.Graph.Core.fromLabeledAdjacencyMatrix :: Bool -> [[[(Int, Double)]]] -> [(Int, Int)] -> Either MathError Graph.""" + return _invoke('hmath_graph_from_labeled_adjacency_matrix', [['Bool'], ['list', ['list', ['list', ['tuple', ['Int'], ['Double']]]]], ['list', ['tuple', ['Int'], ['Int']]]], [directed, cells, orientations]) + + +def graph(directed, vertex_count, edges): + """HMath.Graph.Core.graph :: Bool -> Int -> [(Int, Int, Double)] -> Either MathError Graph.""" + return _invoke('hmath_graph_graph', [['Bool'], ['Int'], ['list', ['tuple', ['Int'], ['Int'], ['Double']]]], [directed, vertex_count, edges]) + + +def has_cycle(graph): + """HMath.Graph.Core.hasCycle :: Graph -> Bool.""" + return _invoke('hmath_graph_has_cycle', [['Graph']], [graph]) + + +def hyper_vertices(hypergraph): + """HMath.Graph.Core.hyperVertices :: Hypergraph -> Int.""" + return _invoke('hmath_graph_hyper_vertices', [['Hypergraph']], [hypergraph]) + + +def hyperedges(hypergraph): + """HMath.Graph.Core.hyperedges :: Hypergraph -> [[Int]].""" + return _invoke('hmath_graph_hyperedges', [['Hypergraph']], [hypergraph]) + + +def hypergraph(vertex_count, hyperedges): + """HMath.Graph.Core.hypergraph :: Int -> [[Int]] -> Either MathError Hypergraph.""" + return _invoke('hmath_graph_hypergraph', [['Int'], ['list', ['list', ['Int']]]], [vertex_count, hyperedges]) + + +def iterative_deepening(budget, graph, source, target): + """HMath.Graph.Core.iterativeDeepening :: Int -> Graph -> Int -> Int -> Either MathError (Maybe [Int]).""" + return _invoke('hmath_graph_iterative_deepening', [['Int'], ['Graph'], ['Int'], ['Int']], [budget, graph, source, target]) + + +def kosaraju_scc(graph): + """HMath.Graph.Core.kosarajuSCC :: Graph -> [[Int]].""" + return _invoke('hmath_graph_kosaraju_scc', [['Graph']], [graph]) + + +def kruskal(graph): + """HMath.Graph.Core.kruskal :: Graph -> Either MathError [Edge].""" + return _invoke('hmath_graph_kruskal', [['Graph']], [graph]) + + +def neighbors(graph, vertex): + """HMath.Graph.Core.neighbors :: Graph -> Int -> [(Int, Double, Int)].""" + return _invoke('hmath_graph_neighbors', [['Graph'], ['Int']], [graph, vertex]) + + +def prim(graph): + """HMath.Graph.Core.prim :: Graph -> Either MathError [Edge].""" + return _invoke('hmath_graph_prim', [['Graph']], [graph]) + + +def require_undirected(graph): + """HMath.Graph.Core.requireUndirected :: Graph -> Either MathError ().""" + return _invoke('hmath_graph_require_undirected', [['Graph']], [graph]) + + +def serialize_bipartite_graph(bipartite): + """HMath.Graph.Core.serializeBipartiteGraph :: BipartiteGraph -> String.""" + return _invoke('hmath_graph_serialize_bipartite_graph', [['BipartiteGraph']], [bipartite]) + + +def serialize_graph(graph): + """HMath.Graph.Core.serializeGraph :: Graph -> String.""" + return _invoke('hmath_graph_serialize_graph', [['Graph']], [graph]) + + +def serialize_hypergraph(hypergraph): + """HMath.Graph.Core.serializeHypergraph :: Hypergraph -> String.""" + return _invoke('hmath_graph_serialize_hypergraph', [['Hypergraph']], [hypergraph]) + + +def tarjan_scc(graph): + """HMath.Graph.Core.tarjanSCC :: Graph -> [[Int]].""" + return _invoke('hmath_graph_tarjan_scc', [['Graph']], [graph]) + + +def to_csr(graph): + """HMath.Graph.Core.toCSR :: Graph -> CSR.""" + return _invoke('hmath_graph_to_csr', [['Graph']], [graph]) + + +def topological_sort(graph): + """HMath.Graph.Core.topologicalSort :: Graph -> Either MathError [Int].""" + return _invoke('hmath_graph_topological_sort', [['Graph']], [graph]) + + +def vertex_count(graph): + """HMath.Graph.Core.vertexCount :: Graph -> Int.""" + return _invoke('hmath_graph_vertex_count', [['Graph']], [graph]) + + +def flow_result(value, edge_flows, cost): + """HMath.Graph.Flow.FlowResult :: Integer -> [Integer] -> Integer -> FlowResult.""" + return _invoke('hmath_graph_flow_result', [['Integer'], ['list', ['Integer']], ['Integer']], [value, edge_flows, cost]) + + +def network_edge(edge_id, source, target, capacity, cost): + """HMath.Graph.Flow.NetworkEdge :: Int -> Int -> Int -> Integer -> Integer -> NetworkEdge.""" + return _invoke('hmath_graph_network_edge', [['Int'], ['Int'], ['Int'], ['Integer'], ['Integer']], [edge_id, source, target, capacity, cost]) + + +def dinic(budget, network, source, target): + """HMath.Graph.Flow.dinic :: Int -> Network -> Int -> Int -> Either MathError FlowResult.""" + return _invoke('hmath_graph_dinic', [['Int'], ['Network'], ['Int'], ['Int']], [budget, network, source, target]) + + +def edge_flows(flow_result): + """HMath.Graph.Flow.edgeFlows :: FlowResult -> [Integer].""" + return _invoke('hmath_graph_edge_flows', [['FlowResult']], [flow_result]) + + +def edmonds_karp(value, network, value3, value4): + """HMath.Graph.Flow.edmondsKarp :: Int -> Network -> Int -> Int -> Either MathError FlowResult.""" + return _invoke('hmath_graph_edmonds_karp', [['Int'], ['Network'], ['Int'], ['Int']], [value, network, value3, value4]) + + +def flow_cost(flow_result): + """HMath.Graph.Flow.flowCost :: FlowResult -> Integer.""" + return _invoke('hmath_graph_flow_cost', [['FlowResult']], [flow_result]) + + +def flow_value(flow_result): + """HMath.Graph.Flow.flowValue :: FlowResult -> Integer.""" + return _invoke('hmath_graph_flow_value', [['FlowResult']], [flow_result]) + + +def ford_fulkerson(value, network, value3, value4): + """HMath.Graph.Flow.fordFulkerson :: Int -> Network -> Int -> Int -> Either MathError FlowResult.""" + return _invoke('hmath_graph_ford_fulkerson', [['Int'], ['Network'], ['Int'], ['Int']], [value, network, value3, value4]) + + +def hopcroft_karp(bipartite): + """HMath.Graph.Flow.hopcroftKarp :: BipartiteGraph -> [(Int, Int)].""" + return _invoke('hmath_graph_hopcroft_karp', [['BipartiteGraph']], [bipartite]) + + +def hungarian(costs): + """HMath.Graph.Flow.hungarian :: [[Integer]] -> Either MathError (Integer, [(Int, Int)]).""" + return _invoke('hmath_graph_hungarian', [['list', ['list', ['Integer']]]], [costs]) + + +def minimum_cost_maximum_flow(value, network, value3, value4): + """HMath.Graph.Flow.minimumCostMaximumFlow :: Int -> Network -> Int -> Int -> Either MathError FlowResult.""" + return _invoke('hmath_graph_minimum_cost_maximum_flow', [['Int'], ['Network'], ['Int'], ['Int']], [value, network, value3, value4]) + + +def minimum_cut(value, network, value3, value4): + """HMath.Graph.Flow.minimumCut :: Int -> Network -> Int -> Int -> Either MathError ([Int], Integer).""" + return _invoke('hmath_graph_minimum_cut', [['Int'], ['Network'], ['Int'], ['Int']], [value, network, value3, value4]) + + +def network(vertex_count, edges): + """HMath.Graph.Flow.network :: Int -> [(Int, Int, Integer, Integer)] -> Either MathError Network.""" + return _invoke('hmath_graph_network', [['Int'], ['list', ['tuple', ['Int'], ['Int'], ['Integer'], ['Integer']]]], [vertex_count, edges]) + + +def network_capacity(network_edge): + """HMath.Graph.Flow.networkCapacity :: NetworkEdge -> Integer.""" + return _invoke('hmath_graph_network_capacity', [['NetworkEdge']], [network_edge]) + + +def network_cost(network_edge): + """HMath.Graph.Flow.networkCost :: NetworkEdge -> Integer.""" + return _invoke('hmath_graph_network_cost', [['NetworkEdge']], [network_edge]) + + +def network_edge_id(network_edge): + """HMath.Graph.Flow.networkEdgeId :: NetworkEdge -> Int.""" + return _invoke('hmath_graph_network_edge_id', [['NetworkEdge']], [network_edge]) + + +def network_edges(network): + """HMath.Graph.Flow.networkEdges :: Network -> [NetworkEdge].""" + return _invoke('hmath_graph_network_edges', [['Network']], [network]) + + +def network_from(network_edge): + """HMath.Graph.Flow.networkFrom :: NetworkEdge -> Int.""" + return _invoke('hmath_graph_network_from', [['NetworkEdge']], [network_edge]) + + +def network_to(network_edge): + """HMath.Graph.Flow.networkTo :: NetworkEdge -> Int.""" + return _invoke('hmath_graph_network_to', [['NetworkEdge']], [network_edge]) + + +def push_relabel(value, network, value3, value4): + """HMath.Graph.Flow.pushRelabel :: Int -> Network -> Int -> Int -> Either MathError FlowResult.""" + return _invoke('hmath_graph_push_relabel', [['Int'], ['Network'], ['Int'], ['Int']], [value, network, value3, value4]) + + +def a_star(graph, heuristic, source, target): + """HMath.Graph.Paths.aStar :: Graph -> (Int -> Double) -> Int -> Int -> Either MathError (Maybe (Double, [Int])).""" + return _astar(graph, heuristic, source, target) + + +def bellman_ford(graph, source): + """HMath.Graph.Paths.bellmanFord :: Graph -> Int -> Either MathError [Maybe Double].""" + return _invoke('hmath_graph_bellman_ford', [['Graph'], ['Int']], [graph, source]) + + +def bidirectional_dijkstra(graph, source, target): + """HMath.Graph.Paths.bidirectionalDijkstra :: Graph -> Int -> Int -> Either MathError (Maybe Double).""" + return _invoke('hmath_graph_bidirectional_dijkstra', [['Graph'], ['Int'], ['Int']], [graph, source, target]) + + +def dijkstra(graph, source): + """HMath.Graph.Paths.dijkstra :: Graph -> Int -> Either MathError [Maybe Double].""" + return _invoke('hmath_graph_dijkstra', [['Graph'], ['Int']], [graph, source]) + + +def floyd_warshall(graph): + """HMath.Graph.Paths.floydWarshall :: Graph -> Either MathError [[Maybe Double]].""" + return _invoke('hmath_graph_floyd_warshall', [['Graph']], [graph]) + + +def johnson(graph): + """HMath.Graph.Paths.johnson :: Graph -> Either MathError [[Maybe Double]].""" + return _invoke('hmath_graph_johnson', [['Graph']], [graph]) + + +def k_shortest_paths(budget, count, graph, source, target): + """HMath.Graph.Paths.kShortestPaths :: Int -> Int -> Graph -> Int -> Int -> Either MathError [(Double, [Int], [Int])].""" + return _invoke('hmath_graph_k_shortest_paths', [['Int'], ['Int'], ['Graph'], ['Int'], ['Int']], [budget, count, graph, source, target]) + + +def longest_dag_paths(graph, source): + """HMath.Graph.Paths.longestDAGPaths :: Graph -> Int -> Either MathError [Maybe Double].""" + return _invoke('hmath_graph_longest_dag_paths', [['Graph'], ['Int']], [graph, source]) + + +def multi_source_dijkstra(graph, sources): + """HMath.Graph.Paths.multiSourceDijkstra :: Graph -> [Int] -> Either MathError [Maybe Double].""" + return _invoke('hmath_graph_multi_source_dijkstra', [['Graph'], ['list', ['Int']]], [graph, sources]) diff --git a/bindings/python/_hmath_native/graph_core.py b/bindings/python/_hmath_native/graph_core.py new file mode 100644 index 0000000..d809374 --- /dev/null +++ b/bindings/python/_hmath_native/graph_core.py @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def finite(x, *, dtype='float64'): + """Call HMath.Graph.Core.finite; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_graph_core_finite', + ['f'], + 'b', + [x], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/image.py b/bindings/python/_hmath_native/image.py new file mode 100644 index 0000000..3025ef6 --- /dev/null +++ b/bindings/python/_hmath_native/image.py @@ -0,0 +1,570 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_image_bindings.py; do not edit. +"""Original Image operations and typed Tensor Double interchange.""" +from ._image_base import _invoke +from ._tensor_object import TensorDouble +from ._value import Value, register +from .image_color import linear_to_srgb, srgb_to_linear + + +class Image(Value): + """Actual immutable HMath.Image.Core.Image native owner.""" + + +register(160, Image) + + +class Boundary(Value): + """Actual immutable HMath.Image.Core.Boundary native owner.""" + + +register(162, Boundary) + + +class GradientOperator(Value): + """Actual immutable HMath.Image.Filter.GradientOperator native owner.""" + + +register(163, GradientOperator) + + +class Morphology(Value): + """Actual immutable HMath.Image.Filter.Morphology native owner.""" + + +register(164, Morphology) + + +class TemplateMetric(Value): + """Actual immutable HMath.Image.Measure.TemplateMetric native owner.""" + + +register(165, TemplateMetric) + + +class Interpolation(Value): + """Actual immutable HMath.Image.Spatial.Interpolation native owner.""" + + +register(166, Interpolation) + + +class Connectivity(Value): + """Actual immutable HMath.Image.Spatial.Connectivity native owner.""" + + +register(167, Connectivity) + + +class ColorSpace(Value): + """Actual immutable HMath.Image.Color.ColorSpace native owner.""" + + +register(168, ColorSpace) + + +def image(shape, channels, values): + """HMath.Image.Core.image :: [Int] -> Int -> [Double] -> Either MathError Image.""" + return _invoke('hmath_image_image', [['list', ['Int']], ['Int'], ['list', ['Double']]], [shape, channels, values]) + + +def from_tensor(tensor): + """HMath.Image.Core.fromTensor :: Tensor Double -> Either MathError Image.""" + return _invoke('hmath_image_from_tensor', [['Tensor Double']], [tensor]) + + +def to_tensor(image): + """HMath.Image.Core.toTensor :: Image -> Either MathError Tensor Double.""" + return _invoke('hmath_image_to_tensor', [['Image']], [image]) + + +def image_shape(image): + """HMath.Image.Core.imageShape :: Image -> [Int].""" + return _invoke('hmath_image_image_shape', [['Image']], [image]) + + +def image_channels(image): + """HMath.Image.Core.imageChannels :: Image -> Int.""" + return _invoke('hmath_image_image_channels', [['Image']], [image]) + + +def image_values(image): + """HMath.Image.Core.imageValues :: Image -> [Double].""" + return _invoke('hmath_image_image_values', [['Image']], [image]) + + +def pixel(image, coordinates): + """HMath.Image.Core.pixel :: Image -> [Int] -> Either MathError [Double].""" + return _invoke('hmath_image_pixel', [['Image'], ['list', ['Int']]], [image, coordinates]) + + +def channel(index, image): + """HMath.Image.Core.channel :: Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_channel', [['Int'], ['Image']], [index, image]) + + +def combine_channels(images): + """HMath.Image.Core.combineChannels :: [Image] -> Either MathError Image.""" + return _invoke('hmath_image_combine_channels', [['list', ['Image']]], [images]) + + +def map_image(function, image): + """HMath.Image.Core.mapImage :: (Double -> Double) -> Image -> Either MathError Image.""" + return _invoke('hmath_image_map_image', [['function', ['Double'], ['Double']], ['Image']], [function, image]) + + +def zip_image(function, a, b): + """HMath.Image.Core.zipImage :: (Double -> Double -> Double) -> Image -> Image -> Either MathError Image.""" + return _invoke('hmath_image_zip_image', [['function', ['Double'], ['Double'], ['Double']], ['Image'], ['Image']], [function, a, b]) + + +def normalize(low, high, image): + """HMath.Image.Core.normalize :: Double -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_normalize', [['Double'], ['Double'], ['Image']], [low, high, image]) + + +def brightness(offset, image): + """HMath.Image.Core.brightness :: Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_brightness', [['Double'], ['Image']], [offset, image]) + + +def contrast(factor, pivot, image): + """HMath.Image.Core.contrast :: Double -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_contrast', [['Double'], ['Double'], ['Image']], [factor, pivot, image]) + + +def gamma(power, image): + """HMath.Image.Core.gamma :: Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_gamma', [['Double'], ['Image']], [power, image]) + + +def constant(fill): + """HMath.Image.Core.Constant :: Double -> Boundary.""" + return _invoke('hmath_image_constant', [['Double']], [fill]) + + +def clamp(): + """HMath.Image.Core.Clamp :: Boundary.""" + return _invoke('hmath_image_clamp', [], []) + + +def reflect(): + """HMath.Image.Core.Reflect :: Boundary.""" + return _invoke('hmath_image_reflect', [], []) + + +def wrap(): + """HMath.Image.Core.Wrap :: Boundary.""" + return _invoke('hmath_image_wrap', [], []) + + +def convolve(boundary, shape, weights, image): + """HMath.Image.Filter.convolve :: Boundary -> [Int] -> [Double] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_convolve', [['Boundary'], ['list', ['Int']], ['list', ['Double']], ['Image']], [boundary, shape, weights, image]) + + +def correlate(boundary, shape, weights, image): + """HMath.Image.Filter.correlate :: Boundary -> [Int] -> [Double] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_correlate', [['Boundary'], ['list', ['Int']], ['list', ['Double']], ['Image']], [boundary, shape, weights, image]) + + +def gaussian_blur(boundary, sigma, radius, image): + """HMath.Image.Filter.gaussianBlur :: Boundary -> Double -> Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_gaussian_blur', [['Boundary'], ['Double'], ['Int'], ['Image']], [boundary, sigma, radius, image]) + + +def box_blur(boundary, radius, image): + """HMath.Image.Filter.boxBlur :: Boundary -> Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_box_blur', [['Boundary'], ['Int'], ['Image']], [boundary, radius, image]) + + +def median_blur(boundary, radius, image): + """HMath.Image.Filter.medianBlur :: Boundary -> Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_median_blur', [['Boundary'], ['Int'], ['Image']], [boundary, radius, image]) + + +def bilateral_blur(boundary, sigma_space, sigma_range, radius, image): + """HMath.Image.Filter.bilateralBlur :: Boundary -> Double -> Double -> Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_bilateral_blur', [['Boundary'], ['Double'], ['Double'], ['Int'], ['Image']], [boundary, sigma_space, sigma_range, radius, image]) + + +def sharpen(boundary, amount, sigma, radius, image): + """HMath.Image.Filter.sharpen :: Boundary -> Double -> Double -> Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_sharpen', [['Boundary'], ['Double'], ['Double'], ['Int'], ['Image']], [boundary, amount, sigma, radius, image]) + + +def gradient(method, boundary, image): + """HMath.Image.Filter.gradient :: GradientOperator -> Boundary -> Image -> Either MathError (Image, Image, Image, Image).""" + return _invoke('hmath_image_gradient', [['GradientOperator'], ['Boundary'], ['Image']], [method, boundary, image]) + + +def laplacian(boundary, image): + """HMath.Image.Filter.laplacian :: Boundary -> Image -> Either MathError Image.""" + return _invoke('hmath_image_laplacian', [['Boundary'], ['Image']], [boundary, image]) + + +def canny(boundary, sigma, radius, low, high, image): + """HMath.Image.Filter.canny :: Boundary -> Double -> Int -> Double -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_canny', [['Boundary'], ['Double'], ['Int'], ['Double'], ['Double'], ['Image']], [boundary, sigma, radius, low, high, image]) + + +def morphology(operation, boundary, shape, mask, image): + """HMath.Image.Filter.morphology :: Morphology -> Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_morphology', [['Morphology'], ['Boundary'], ['list', ['Int']], ['list', ['Bool']], ['Image']], [operation, boundary, shape, mask, image]) + + +def morphological_gradient(boundary, shape, mask, image): + """HMath.Image.Filter.morphologicalGradient :: Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_morphological_gradient', [['Boundary'], ['list', ['Int']], ['list', ['Bool']], ['Image']], [boundary, shape, mask, image]) + + +def validate_boundary(boundary): + """HMath.Image.Filter.validateBoundary :: Boundary -> Either MathError ().""" + return _invoke('hmath_image_validate_boundary', [['Boundary']], [boundary]) + + +def scalar2_d(image): + """HMath.Image.Filter.scalar2D :: Image -> Either MathError (Int, Int).""" + return _invoke('hmath_image_scalar2_d', [['Image']], [image]) + + +def window_offsets(radius, image): + """HMath.Image.Filter.windowOffsets :: Int -> Image -> Either MathError [[Int]].""" + return _invoke('hmath_image_window_offsets', [['Int'], ['Image']], [radius, image]) + + +def sobel(): + """HMath.Image.Filter.Sobel :: GradientOperator.""" + return _invoke('hmath_image_sobel', [], []) + + +def prewitt(): + """HMath.Image.Filter.Prewitt :: GradientOperator.""" + return _invoke('hmath_image_prewitt', [], []) + + +def scharr(): + """HMath.Image.Filter.Scharr :: GradientOperator.""" + return _invoke('hmath_image_scharr', [], []) + + +def erosion(): + """HMath.Image.Filter.Erosion :: Morphology.""" + return _invoke('hmath_image_erosion', [], []) + + +def dilation(): + """HMath.Image.Filter.Dilation :: Morphology.""" + return _invoke('hmath_image_dilation', [], []) + + +def opening(): + """HMath.Image.Filter.Opening :: Morphology.""" + return _invoke('hmath_image_opening', [], []) + + +def closing(): + """HMath.Image.Filter.Closing :: Morphology.""" + return _invoke('hmath_image_closing', [], []) + + +def histogram(bins, image): + """HMath.Image.Histogram.histogram :: Int -> Image -> Either MathError [[Int]].""" + return _invoke('hmath_image_histogram', [['Int'], ['Image']], [bins, image]) + + +def equalize_histogram(bins, image): + """HMath.Image.Histogram.equalizeHistogram :: Int -> Image -> Either MathError Image.""" + return _invoke('hmath_image_equalize_histogram', [['Int'], ['Image']], [bins, image]) + + +def clahe(bins, tiles, clip_limit, image): + """HMath.Image.Histogram.clahe :: Int -> (Int, Int) -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_clahe', [['Int'], ['tuple', ['Int'], ['Int']], ['Double'], ['Image']], [bins, tiles, clip_limit, image]) + + +def threshold(level, image): + """HMath.Image.Histogram.threshold :: Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_threshold', [['Double'], ['Image']], [level, image]) + + +def otsu(bins, image): + """HMath.Image.Histogram.otsu :: Int -> Image -> Either MathError ([Double], Image).""" + return _invoke('hmath_image_otsu', [['Int'], ['Image']], [bins, image]) + + +def adaptive_threshold(gaussian, boundary, radius, offset, image): + """HMath.Image.Histogram.adaptiveThreshold :: Bool -> Boundary -> Int -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_adaptive_threshold', [['Bool'], ['Boundary'], ['Int'], ['Double'], ['Image']], [gaussian, boundary, radius, offset, image]) + + +def template_match(metric, needle, haystack): + """HMath.Image.Measure.templateMatch :: TemplateMetric -> Image -> Image -> Either MathError Image.""" + return _invoke('hmath_image_template_match', [['TemplateMetric'], ['Image'], ['Image']], [metric, needle, haystack]) + + +def raw_moment(row_order, column_order, image): + """HMath.Image.Measure.rawMoment :: Int -> Int -> Image -> Either MathError Double.""" + return _invoke('hmath_image_raw_moment', [['Int'], ['Int'], ['Image']], [row_order, column_order, image]) + + +def central_moment(row_order, column_order, image): + """HMath.Image.Measure.centralMoment :: Int -> Int -> Image -> Either MathError Double.""" + return _invoke('hmath_image_central_moment', [['Int'], ['Int'], ['Image']], [row_order, column_order, image]) + + +def image_centroid(image): + """HMath.Image.Measure.imageCentroid :: Image -> Either MathError (Double, Double).""" + return _invoke('hmath_image_image_centroid', [['Image']], [image]) + + +def integral_image(image): + """HMath.Image.Measure.integralImage :: Image -> Either MathError Image.""" + return _invoke('hmath_image_integral_image', [['Image']], [image]) + + +def rectangle_sum(origin, extent, image): + """HMath.Image.Measure.rectangleSum :: (Int, Int) -> (Int, Int) -> Image -> Either MathError [Double].""" + return _invoke('hmath_image_rectangle_sum', [['tuple', ['Int'], ['Int']], ['tuple', ['Int'], ['Int']], ['Image']], [origin, extent, image]) + + +def mean_squared_error(a, b): + """HMath.Image.Measure.meanSquaredError :: Image -> Image -> Either MathError Double.""" + return _invoke('hmath_image_mean_squared_error', [['Image'], ['Image']], [a, b]) + + +def peak_signal_to_noise(data_range, a, b): + """HMath.Image.Measure.peakSignalToNoise :: Double -> Image -> Image -> Either MathError Double.""" + return _invoke('hmath_image_peak_signal_to_noise', [['Double'], ['Image'], ['Image']], [data_range, a, b]) + + +def structural_similarity(data_range, window, a, b): + """HMath.Image.Measure.structuralSimilarity :: Double -> Int -> Image -> Image -> Either MathError Double.""" + return _invoke('hmath_image_structural_similarity', [['Double'], ['Int'], ['Image'], ['Image']], [data_range, window, a, b]) + + +def squared_difference(): + """HMath.Image.Measure.SquaredDifference :: TemplateMetric.""" + return _invoke('hmath_image_squared_difference', [], []) + + +def normalized_correlation(): + """HMath.Image.Measure.NormalizedCorrelation :: TemplateMetric.""" + return _invoke('hmath_image_normalized_correlation', [], []) + + +def resize(interpolation, boundary, shape, image): + """HMath.Image.Spatial.resize :: Interpolation -> Boundary -> (Int, Int) -> Image -> Either MathError Image.""" + return _invoke('hmath_image_resize', [['Interpolation'], ['Boundary'], ['tuple', ['Int'], ['Int']], ['Image']], [interpolation, boundary, shape, image]) + + +def warp(interpolation, boundary, shape, matrix, image): + """HMath.Image.Spatial.warp :: Interpolation -> Boundary -> (Int, Int) -> [[Double]] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_warp', [['Interpolation'], ['Boundary'], ['tuple', ['Int'], ['Int']], ['list', ['list', ['Double']]], ['Image']], [interpolation, boundary, shape, matrix, image]) + + +def translate(interpolation, boundary, row_shift, column_shift, image): + """HMath.Image.Spatial.translate :: Interpolation -> Boundary -> Double -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_translate', [['Interpolation'], ['Boundary'], ['Double'], ['Double'], ['Image']], [interpolation, boundary, row_shift, column_shift, image]) + + +def rotate(interpolation, boundary, angle, image): + """HMath.Image.Spatial.rotate :: Interpolation -> Boundary -> Double -> Image -> Either MathError Image.""" + return _invoke('hmath_image_rotate', [['Interpolation'], ['Boundary'], ['Double'], ['Image']], [interpolation, boundary, angle, image]) + + +def connected_components(connectivity, image): + """HMath.Image.Spatial.connectedComponents :: Connectivity -> Image -> Either MathError (Image, [Int]).""" + return _invoke('hmath_image_connected_components', [['Connectivity'], ['Image']], [connectivity, image]) + + +def distance_transform(spacing, image): + """HMath.Image.Spatial.distanceTransform :: [Double] -> Image -> Either MathError Image.""" + return _invoke('hmath_image_distance_transform', [['list', ['Double']], ['Image']], [spacing, image]) + + +def nearest(): + """HMath.Image.Spatial.Nearest :: Interpolation.""" + return _invoke('hmath_image_nearest', [], []) + + +def bilinear(): + """HMath.Image.Spatial.Bilinear :: Interpolation.""" + return _invoke('hmath_image_bilinear', [], []) + + +def bicubic(): + """HMath.Image.Spatial.Bicubic :: Interpolation.""" + return _invoke('hmath_image_bicubic', [], []) + + +def lanczos(): + """HMath.Image.Spatial.Lanczos :: Interpolation.""" + return _invoke('hmath_image_lanczos', [], []) + + +def axis_connected(): + """HMath.Image.Spatial.AxisConnected :: Connectivity.""" + return _invoke('hmath_image_axis_connected', [], []) + + +def fully_connected(): + """HMath.Image.Spatial.FullyConnected :: Connectivity.""" + return _invoke('hmath_image_fully_connected', [], []) + + +def convert_color(source, destination, image): + """HMath.Image.Color.convertColor :: ColorSpace -> ColorSpace -> Image -> Either MathError Image.""" + return _invoke('hmath_image_convert_color', [['ColorSpace'], ['ColorSpace'], ['Image']], [source, destination, image]) + + +def grayscale(source, image): + """HMath.Image.Color.grayscale :: ColorSpace -> Image -> Either MathError Image.""" + return _invoke('hmath_image_grayscale', [['ColorSpace'], ['Image']], [source, image]) + + +def srgb(): + """HMath.Image.Color.SRGB :: ColorSpace.""" + return _invoke('hmath_image_srgb', [], []) + + +def linear_rgb(): + """HMath.Image.Color.LinearRGB :: ColorSpace.""" + return _invoke('hmath_image_linear_rgb', [], []) + + +def hsv(): + """HMath.Image.Color.HSV :: ColorSpace.""" + return _invoke('hmath_image_hsv', [], []) + + +def hsl(): + """HMath.Image.Color.HSL :: ColorSpace.""" + return _invoke('hmath_image_hsl', [], []) + + +def xyz(): + """HMath.Image.Color.XYZ :: ColorSpace.""" + return _invoke('hmath_image_xyz', [], []) + + +def lab(): + """HMath.Image.Color.Lab :: ColorSpace.""" + return _invoke('hmath_image_lab', [], []) + + +def y_cb_cr(): + """HMath.Image.Color.YCbCr :: ColorSpace.""" + return _invoke('hmath_image_y_cb_cr', [], []) + + +def tensor(shape, values): + """HMath.Tensor.tensor :: [Int] -> [Double] -> Either MathError Tensor Double.""" + return _invoke('hmath_image_tensor', [['list', ['Int']], ['list', ['Double']]], [shape, values]) + + +def tensor_shape(tensor): + """HMath.Tensor.tensorShape :: Tensor Double -> [Int].""" + return _invoke('hmath_image_tensor_shape', [['Tensor Double']], [tensor]) + + +def tensor_values(tensor): + """HMath.Tensor.tensorValues :: Tensor Double -> [Double].""" + return _invoke('hmath_image_tensor_values', [['Tensor Double']], [tensor]) + + +__all__ = [ + "Boundary", + "ColorSpace", + "Connectivity", + "GradientOperator", + "Image", + "Interpolation", + "Morphology", + "TemplateMetric", + "TensorDouble", + "adaptive_threshold", + "axis_connected", + "bicubic", + "bilateral_blur", + "bilinear", + "box_blur", + "brightness", + "canny", + "central_moment", + "channel", + "clahe", + "clamp", + "closing", + "combine_channels", + "connected_components", + "constant", + "contrast", + "convert_color", + "convolve", + "correlate", + "dilation", + "distance_transform", + "equalize_histogram", + "erosion", + "from_tensor", + "fully_connected", + "gamma", + "gaussian_blur", + "gradient", + "grayscale", + "histogram", + "hsl", + "hsv", + "image", + "image_centroid", + "image_channels", + "image_shape", + "image_values", + "integral_image", + "lab", + "lanczos", + "laplacian", + "linear_rgb", + "linear_to_srgb", + "map_image", + "mean_squared_error", + "median_blur", + "morphological_gradient", + "morphology", + "nearest", + "normalize", + "normalized_correlation", + "opening", + "otsu", + "peak_signal_to_noise", + "pixel", + "prewitt", + "raw_moment", + "rectangle_sum", + "reflect", + "resize", + "rotate", + "scalar2_d", + "scharr", + "sharpen", + "sobel", + "squared_difference", + "srgb", + "srgb_to_linear", + "structural_similarity", + "template_match", + "tensor", + "tensor_shape", + "tensor_values", + "threshold", + "to_tensor", + "translate", + "validate_boundary", + "warp", + "window_offsets", + "wrap", + "xyz", + "y_cb_cr", + "zip_image" +] diff --git a/bindings/python/_hmath_native/image_color.py b/bindings/python/_hmath_native/image_color.py new file mode 100644 index 0000000..3ba96ed --- /dev/null +++ b/bindings/python/_hmath_native/image_color.py @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def srgb_to_linear(x, *, dtype='float64'): + """Call HMath.Image.Color.srgbToLinear; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_image_color_srgb_to_linear', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def linear_to_srgb(x, *, dtype='float64'): + """Call HMath.Image.Color.linearToSrgb; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_image_color_linear_to_srgb', + ['f'], + 'f', + [x], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/interchange.py b/bindings/python/_hmath_native/interchange.py new file mode 100644 index 0000000..18c9ff5 --- /dev/null +++ b/bindings/python/_hmath_native/interchange.py @@ -0,0 +1,469 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_interchange_bindings.py. +from ._interchange_base import (Array,InterchangeError,Limits,DType,Endian,Order,Compression,RawSpec,MappedArray,GetProgram,PutProgram,BinaryHandle,Bytes,_invoke,_element_type,_get_element,_put_element,_from_values,_to_values,_mapped_value) + + +def big_endian(): + """HMath.Interchange.Array.BigEndian :: Endian.""" + return _invoke('hmath_interchange_value_big_endian',[],[]) + + +def bool8(): + """HMath.Interchange.Array.Bool8 :: DType.""" + return _invoke('hmath_interchange_value_bool8',[],[]) + + +def c128(): + """HMath.Interchange.Array.C128 :: DType.""" + return _invoke('hmath_interchange_value_c128',[],[]) + + +def c64(): + """HMath.Interchange.Array.C64 :: DType.""" + return _invoke('hmath_interchange_value_c64',[],[]) + + +def c_order(): + """HMath.Interchange.Array.COrder :: Order.""" + return _invoke('hmath_interchange_value_c_order',[],[]) + + +def f32(): + """HMath.Interchange.Array.F32 :: DType.""" + return _invoke('hmath_interchange_value_f32',[],[]) + + +def f64(): + """HMath.Interchange.Array.F64 :: DType.""" + return _invoke('hmath_interchange_value_f64',[],[]) + + +def f_order(): + """HMath.Interchange.Array.FOrder :: Order.""" + return _invoke('hmath_interchange_value_f_order',[],[]) + + +def i16(): + """HMath.Interchange.Array.I16 :: DType.""" + return _invoke('hmath_interchange_value_i16',[],[]) + + +def i32(): + """HMath.Interchange.Array.I32 :: DType.""" + return _invoke('hmath_interchange_value_i32',[],[]) + + +def i64(): + """HMath.Interchange.Array.I64 :: DType.""" + return _invoke('hmath_interchange_value_i64',[],[]) + + +def i8(): + """HMath.Interchange.Array.I8 :: DType.""" + return _invoke('hmath_interchange_value_i8',[],[]) + + +def interchange_io_error(message): + """HMath.Interchange.Array.InterchangeIOError :: String -> InterchangeError.""" + return _invoke('hmath_interchange_value_interchange_io_error',[['String']],[message]) + + +def invalid_data(message): + """HMath.Interchange.Array.InvalidData :: String -> InterchangeError.""" + return _invoke('hmath_interchange_value_invalid_data',[['String']],[message]) + + +def limit_exceeded(message): + """HMath.Interchange.Array.LimitExceeded :: String -> InterchangeError.""" + return _invoke('hmath_interchange_value_limit_exceeded',[['String']],[message]) + + +def limits(max_bytes, max_elements, max_rank, max_metadata, max_archive_entries): + """HMath.Interchange.Array.Limits :: Int -> Int -> Int -> Int -> Int -> Limits.""" + return _invoke('hmath_interchange_value_limits',[['Int'], ['Int'], ['Int'], ['Int'], ['Int']],[max_bytes, max_elements, max_rank, max_metadata, max_archive_entries]) + + +def little_endian(): + """HMath.Interchange.Array.LittleEndian :: Endian.""" + return _invoke('hmath_interchange_value_little_endian',[],[]) + + +def u16(): + """HMath.Interchange.Array.U16 :: DType.""" + return _invoke('hmath_interchange_value_u16',[],[]) + + +def u32(): + """HMath.Interchange.Array.U32 :: DType.""" + return _invoke('hmath_interchange_value_u32',[],[]) + + +def u64(): + """HMath.Interchange.Array.U64 :: DType.""" + return _invoke('hmath_interchange_value_u64',[],[]) + + +def u8(): + """HMath.Interchange.Array.U8 :: DType.""" + return _invoke('hmath_interchange_value_u8',[],[]) + + +def unsupported(message): + """HMath.Interchange.Array.Unsupported :: String -> InterchangeError.""" + return _invoke('hmath_interchange_value_unsupported',[['String']],[message]) + + +def array(lim, dt, en, sh, st, off, bs): + """HMath.Interchange.Array.array :: Limits -> DType -> Endian -> [Int] -> [Int] -> Int -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_array',[['Limits'], ['DType'], ['Endian'], ['list', ['Int']], ['list', ['Int']], ['Int'], ['ByteString']],[lim, dt, en, sh, st, off, bs]) + + +def array_bytes(value): + """HMath.Interchange.Array.arrayBytes :: Array -> ByteString.""" + return _invoke('hmath_interchange_value_array_bytes',[['Array']],[value]) + + +def array_d_type(value): + """HMath.Interchange.Array.arrayDType :: Array -> DType.""" + return _invoke('hmath_interchange_value_array_d_type',[['Array']],[value]) + + +def array_endian(value): + """HMath.Interchange.Array.arrayEndian :: Array -> Endian.""" + return _invoke('hmath_interchange_value_array_endian',[['Array']],[value]) + + +def array_metadata(value): + """HMath.Interchange.Array.arrayMetadata :: Array -> [(String, String)].""" + return _invoke('hmath_interchange_value_array_metadata',[['Array']],[value]) + + +def array_offset(value): + """HMath.Interchange.Array.arrayOffset :: Array -> Int.""" + return _invoke('hmath_interchange_value_array_offset',[['Array']],[value]) + + +def array_shape(value): + """HMath.Interchange.Array.arrayShape :: Array -> [Int].""" + return _invoke('hmath_interchange_value_array_shape',[['Array']],[value]) + + +def array_strides(value): + """HMath.Interchange.Array.arrayStrides :: Array -> [Int].""" + return _invoke('hmath_interchange_value_array_strides',[['Array']],[value]) + + +def contiguous_array(lim, dt, en, order, sh, bs): + """HMath.Interchange.Array.contiguousArray :: Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_contiguous_array',[['Limits'], ['DType'], ['Endian'], ['Order'], ['list', ['Int']], ['ByteString']],[lim, dt, en, order, sh, bs]) + + +def default_limits(): + """HMath.Interchange.Array.defaultLimits :: Limits.""" + return _invoke('hmath_interchange_value_default_limits',[],[]) + + +def dense_strides(c_order, w, sh): + """HMath.Interchange.Array.denseStrides :: Order -> Int -> [Int] -> [Int].""" + return _invoke('hmath_interchange_value_dense_strides',[['Order'], ['Int'], ['list', ['Int']]],[c_order, w, sh]) + + +def element_bytes(dt): + """HMath.Interchange.Array.elementBytes :: DType -> Int.""" + return _invoke('hmath_interchange_value_element_bytes',[['DType']],[dt]) + + +def element_count(value): + """HMath.Interchange.Array.elementCount :: Array -> Int.""" + return _invoke('hmath_interchange_value_element_count',[['Array']],[value]) + + +def element_type(*, dtype="float64"): + return _element_type(dtype) + + +def from_matrix(value, value2, value3): + """HMath.Interchange.Array.fromMatrix :: Element a => Limits -> Endian -> HMath.Matrix.Matrix a -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_from_matrix',[['Limits'], ['Endian'], ['Value']],[value, value2, value3]) + + +def from_tensor(value, value2, value3): + """HMath.Interchange.Array.fromTensor :: Element a => Limits -> Endian -> HMath.Tensor.Tensor a -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_from_tensor',[['Limits'], ['Endian'], ['Value']],[value, value2, value3]) + + +def from_values(limits,endian,shape,values, *, dtype="float64"): + return _from_values(limits,endian,shape,values,dtype) + + +def get_element(endian, *, dtype="float64"): + return _get_element(endian,dtype) + + +def max_archive_entries(value): + """HMath.Interchange.Array.maxArchiveEntries :: Limits -> Int.""" + return _invoke('hmath_interchange_value_max_archive_entries',[['Limits']],[value]) + + +def max_bytes(value): + """HMath.Interchange.Array.maxBytes :: Limits -> Int.""" + return _invoke('hmath_interchange_value_max_bytes',[['Limits']],[value]) + + +def max_elements(value): + """HMath.Interchange.Array.maxElements :: Limits -> Int.""" + return _invoke('hmath_interchange_value_max_elements',[['Limits']],[value]) + + +def max_metadata(value): + """HMath.Interchange.Array.maxMetadata :: Limits -> Int.""" + return _invoke('hmath_interchange_value_max_metadata',[['Limits']],[value]) + + +def max_rank(value): + """HMath.Interchange.Array.maxRank :: Limits -> Int.""" + return _invoke('hmath_interchange_value_max_rank',[['Limits']],[value]) + + +def put_element(endian,value, *, dtype="float64"): + return _put_element(endian,value,dtype) + + +def raw_decode(value, value2, value3, value4, value5, value6): + """HMath.Interchange.Array.rawDecode :: Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_raw_decode',[['Limits'], ['DType'], ['Endian'], ['Order'], ['list', ['Int']], ['ByteString']],[value, value2, value3, value4, value5, value6]) + + +def raw_encode(value, value2, value3, value4): + """HMath.Interchange.Array.rawEncode :: Limits -> Endian -> Order -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_raw_encode',[['Limits'], ['Endian'], ['Order'], ['Array']],[value, value2, value3, value4]) + + +def repack(lim, en, order, a): + """HMath.Interchange.Array.repack :: Limits -> Endian -> Order -> Array -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_repack',[['Limits'], ['Endian'], ['Order'], ['Array']],[lim, en, order, a]) + + +def to_matrix(array, *, dtype=None): + return _to_values("to_matrix",array,dtype,False) + + +def to_tensor(array, *, dtype=None): + return _to_values("to_tensor",array,dtype,False) + + +def to_values(array, *, dtype=None, boxed=False): + return _to_values("to_values",array,dtype,boxed) + + +def validate_shape(lim, sh): + """HMath.Interchange.Array.validateShape :: Limits -> [Int] -> Either InterchangeError Int.""" + return _invoke('hmath_interchange_value_validate_shape',[['Limits'], ['list', ['Int']]],[lim, sh]) + + +def with_metadata(value, value2, value3): + """HMath.Interchange.Array.withMetadata :: Limits -> [(String, String)] -> Array -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_with_metadata',[['Limits'], ['list', ['tuple', ['String'], ['String']]], ['Array']],[value, value2, value3]) + + +def crc32(value): + """HMath.Interchange.Binary.crc32 :: ByteString -> Word32.""" + return _invoke('hmath_interchange_value_crc32',[['ByteString']],[value]) + + +def decode_binary(lim, input): + """HMath.Interchange.Binary.decodeBinary :: Limits -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_decode_binary',[['Limits'], ['ByteString']],[lim, input]) + + +def encode_binary(lim, a): + """HMath.Interchange.Binary.encodeBinary :: Limits -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_encode_binary',[['Limits'], ['Array']],[lim, a]) + + +def gzip(): + """HMath.Interchange.Compression.Gzip :: Compression.""" + return _invoke('hmath_interchange_value_gzip',[],[]) + + +def raw_deflate(): + """HMath.Interchange.Compression.RawDeflate :: Compression.""" + return _invoke('hmath_interchange_value_raw_deflate',[],[]) + + +def zlib(): + """HMath.Interchange.Compression.Zlib :: Compression.""" + return _invoke('hmath_interchange_value_zlib',[],[]) + + +def compress(lim, wrapper, input): + """HMath.Interchange.Compression.compress :: Limits -> Compression -> ByteString -> IO (Either InterchangeError ByteString).""" + return _invoke('hmath_interchange_value_compress',[['Limits'], ['Compression'], ['ByteString']],[lim, wrapper, input]) + + +def compression_available(): + """HMath.Interchange.Compression.compressionAvailable :: IO Bool.""" + return _invoke('hmath_interchange_value_compression_available',[],[]) + + +def decompress(value, value2, value3, value4): + """HMath.Interchange.Compression.decompress :: Limits -> Compression -> Int -> ByteString -> IO (Either InterchangeError ByteString).""" + return _invoke('hmath_interchange_value_decompress',[['Limits'], ['Compression'], ['Int'], ['ByteString']],[value, value2, value3, value4]) + + +def raw_spec(dtype, endian, order, shape): + """HMath.Interchange.IO.RawSpec :: DType -> Endian -> Order -> [Int] -> RawSpec.""" + return _invoke('hmath_interchange_value_raw_spec',[['DType'], ['Endian'], ['Order'], ['list', ['Int']]],[dtype, endian, order, shape]) + + +def mapped_read_bytes(mapping, offset, count): + """HMath.Interchange.IO.mappedReadBytes :: forall {k} (s :: k). MappedArray s -> Int -> Int -> IO (Either InterchangeError ByteString).""" + return _invoke('hmath_interchange_value_mapped_read_bytes',[['MappedArray'], ['Int'], ['Int']],[mapping, offset, count]) + + +def mapped_shape(mapping): + """HMath.Interchange.IO.mappedShape :: forall {k} (s :: k). MappedArray s -> [Int].""" + return _invoke('hmath_interchange_value_mapped_shape',[['MappedArray']],[mapping]) + + +def mapped_value(mapping,indices, *, dtype="float64",boxed=False): + return _mapped_value(mapping,indices,dtype,boxed) + + +def read_array_file(lim, decode, path): + """HMath.Interchange.IO.readArrayFile :: Limits -> (ByteString -> Either InterchangeError Array) -> FilePath -> IO (Either InterchangeError Array).""" + return _invoke('hmath_interchange_value_read_array_file',[['Limits'], ['function', ['ByteString'], ['either', ['Array']]], ['String']],[lim, decode, path]) + + +def read_raw_chunks(value, value2, value3, value4, value5): + """HMath.Interchange.IO.readRawChunks :: Limits -> RawSpec -> Int -> Handle -> (Array -> IO (Either InterchangeError Bool)) -> IO (Either InterchangeError ()).""" + return _invoke('hmath_interchange_value_read_raw_chunks',[['Limits'], ['RawSpec'], ['Int'], ['Handle'], ['function', ['Array'], ['io', ['either', ['Bool']]]]],[value, value2, value3, value4, value5]) + + +def with_mapped_array(limits, specification, path, callback): + """HMath.Interchange.IO.withMappedArray :: Limits -> RawSpec -> FilePath -> (forall (s :: k). MappedArray s -> IO a) -> IO (Either InterchangeError a).""" + return _invoke('hmath_interchange_value_with_mapped_array',[['Limits'], ['RawSpec'], ['String'], ['function', ['MappedArray'], ['io', ['Value']]]],[limits, specification, path, callback]) + + +def write_array_file(lim, encode, path, a): + """HMath.Interchange.IO.writeArrayFile :: Limits -> (Limits -> Array -> Either InterchangeError ByteString) -> FilePath -> Array -> IO (Either InterchangeError ()).""" + return _invoke('hmath_interchange_value_write_array_file',[['Limits'], ['function', ['Limits'], ['Array'], ['either', ['ByteString']]], ['String'], ['Array']],[lim, encode, path, a]) + + +def write_raw_chunks(value, value2, value3, value4, value5): + """HMath.Interchange.IO.writeRawChunks :: Limits -> RawSpec -> Int -> Handle -> (Int -> IO (Either InterchangeError (Maybe ByteString))) -> IO (Either InterchangeError ()).""" + return _invoke('hmath_interchange_value_write_raw_chunks',[['Limits'], ['RawSpec'], ['Int'], ['Handle'], ['function', ['Int'], ['io', ['either', ['maybe', ['ByteString']]]]]],[value, value2, value3, value4, value5]) + + +def decode_npy(lim, input): + """HMath.Interchange.Numpy.decodeNpy :: Limits -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_decode_npy',[['Limits'], ['ByteString']],[lim, input]) + + +def decode_npz(lim, input): + """HMath.Interchange.Numpy.decodeNpz :: Limits -> ByteString -> IO (Either InterchangeError [(String, Array)]).""" + return _invoke('hmath_interchange_value_decode_npz',[['Limits'], ['ByteString']],[lim, input]) + + +def encode_npy(lim, order, a): + """HMath.Interchange.Numpy.encodeNpy :: Limits -> Order -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_encode_npy',[['Limits'], ['Order'], ['Array']],[lim, order, a]) + + +def encode_npz(lim, compressed, arrays): + """HMath.Interchange.Numpy.encodeNpz :: Limits -> Bool -> [(String, Array)] -> IO (Either InterchangeError ByteString).""" + return _invoke('hmath_interchange_value_encode_npz',[['Limits'], ['Bool'], ['list', ['tuple', ['String'], ['Array']]]],[lim, compressed, arrays]) + + +def decode_delimited(lim, separator, dt, bs): + """HMath.Interchange.Text.decodeDelimited :: Limits -> Char -> DType -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_decode_delimited',[['Limits'], ['Char'], ['DType'], ['ByteString']],[lim, separator, dt, bs]) + + +def decode_matrix_market(lim, bs): + """HMath.Interchange.Text.decodeMatrixMarket :: Limits -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_decode_matrix_market',[['Limits'], ['ByteString']],[lim, bs]) + + +def decode_text(lim, bs): + """HMath.Interchange.Text.decodeText :: Limits -> ByteString -> Either InterchangeError Array.""" + return _invoke('hmath_interchange_value_decode_text',[['Limits'], ['ByteString']],[lim, bs]) + + +def encode_delimited(lim, separator, a): + """HMath.Interchange.Text.encodeDelimited :: Limits -> Char -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_encode_delimited',[['Limits'], ['Char'], ['Array']],[lim, separator, a]) + + +def encode_matrix_market(lim, a): + """HMath.Interchange.Text.encodeMatrixMarket :: Limits -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_encode_matrix_market',[['Limits'], ['Array']],[lim, a]) + + +def encode_text(lim, a): + """HMath.Interchange.Text.encodeText :: Limits -> Array -> Either InterchangeError ByteString.""" + return _invoke('hmath_interchange_value_encode_text',[['Limits'], ['Array']],[lim, a]) + + +def bounded_int(name, upper, x): + """HMath.Interchange.Array.boundedInt :: String -> Integer -> Integer -> Either InterchangeError Int.""" + return _invoke('hmath_interchange_value_bounded_int',[['String'], ['Integer'], ['Integer']],[name, upper, x]) + + +def byte_offsets(a): + """HMath.Interchange.Array.byteOffsets :: Array -> [Int].""" + return _invoke('hmath_interchange_value_byte_offsets',[['Array']],[a]) + + +def check_limits(lim): + """HMath.Interchange.Array.checkLimits :: Limits -> Either InterchangeError ().""" + return _invoke('hmath_interchange_value_check_limits',[['Limits']],[lim]) + + +def guard_i(p, e): + """HMath.Interchange.Array.guardI :: Bool -> InterchangeError -> Either InterchangeError ().""" + return _invoke('hmath_interchange_value_guard_i',[['Bool'], ['InterchangeError']],[p, e]) + + +def run_decoder(parser, data, *, boxed=False): + """HMath.Interchange.Binary.runDecoder :: Get a -> ByteString -> Either InterchangeError a.""" + return _invoke('hmath_interchange_value_run_decoder',[['GetProgram'], ['ByteString']],[parser, data],boxed=boxed) + + +def dtype_code(dtype): + return _invoke('hmath_interchange_value_dtype_code',[['Value']],[dtype]) + + +def error_fields(error): + return _invoke('hmath_interchange_value_error_fields',[['Value']],[error]) + + +def put_bytes(program): + return _invoke('hmath_interchange_value_put_bytes',[['Value']],[program]) + + +def open_handle(path, mode): + return _invoke('hmath_interchange_value_open_handle',[['String'], ['String']],[path, mode]) + + +def close_handle(handle): + return _invoke('hmath_interchange_value_close_handle',[['Value']],[handle]) + + +def seek_handle(handle, whence, offset): + return _invoke('hmath_interchange_value_seek_handle',[['Value'], ['Value'], ['Value']],[handle, whence, offset]) + + +def tell_handle(handle): + return _invoke('hmath_interchange_value_tell_handle',[['Value']],[handle]) + + +def flush_handle(handle): + return _invoke('hmath_interchange_value_flush_handle',[['Value']],[handle]) + + +def equal_array(left, right): + return _invoke('hmath_interchange_value_equal_array',[['Value'], ['Value']],[left, right]) + + +Element = DType diff --git a/bindings/python/_hmath_native/interpolation.py b/bindings/python/_hmath_native/interpolation.py new file mode 100644 index 0000000..a6b8e8c --- /dev/null +++ b/bindings/python/_hmath_native/interpolation.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def evaluate_chebyshev(cs, a, b, x, *, dtype='float64'): + """Call HMath.Interpolation.evaluateChebyshev; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_interpolation_evaluate_chebyshev', + ['fs', 'f', 'f', 'f'], + 'f', + [cs, a, b, x], + dtype, + 0, + ) + + +from .interpolation_values import * diff --git a/bindings/python/_hmath_native/interpolation_values.py b/bindings/python/_hmath_native/interpolation_values.py new file mode 100644 index 0000000..409eac8 --- /dev/null +++ b/bindings/python/_hmath_native/interpolation_values.py @@ -0,0 +1,345 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_spectral_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Extrapolation(Value): + """Owned immutable original HMath.Interpolation.Extrapolation.""" + + +register(369, Extrapolation) + + +class InterpolationMethod(Value): + """Owned immutable original HMath.Interpolation.InterpolationMethod.""" + + +register(370, InterpolationMethod) + + +class SplineBoundary(Value): + """Owned immutable original HMath.Interpolation.SplineBoundary.""" + + +register(371, SplineBoundary) + + +class PiecewisePolynomial(Value): + """Owned immutable original HMath.Interpolation.PiecewisePolynomial.""" + + +register(372, PiecewisePolynomial) + + +class BSpline(Value): + """Owned immutable original HMath.Interpolation.BSpline.""" + + +register(373, BSpline) + + +class RadialKernel(Value): + """Owned immutable original HMath.Interpolation.RadialKernel.""" + + +register(374, RadialKernel) + + +class RBF(Value): + """Owned immutable original HMath.Interpolation.RBF.""" + + +register(375, RBF) + + +class Approximation(Value): + """Owned immutable original HMath.Interpolation.Approximation.""" + + +register(376, Approximation) + + +def reject(): + """HMath.Interpolation.Reject :: Extrapolation.""" + return _invoke('hmath_interpolation_value_reject', [], []) + + +def clamp(): + """HMath.Interpolation.Clamp :: Extrapolation.""" + return _invoke('hmath_interpolation_value_clamp', [], []) + + +def extrapolate(): + """HMath.Interpolation.Extrapolate :: Extrapolation.""" + return _invoke('hmath_interpolation_value_extrapolate', [], []) + + +def nearest(): + """HMath.Interpolation.Nearest :: InterpolationMethod.""" + return _invoke('hmath_interpolation_value_nearest', [], []) + + +def linear(): + """HMath.Interpolation.Linear :: InterpolationMethod.""" + return _invoke('hmath_interpolation_value_linear', [], []) + + +def lagrange(): + """HMath.Interpolation.Lagrange :: InterpolationMethod.""" + return _invoke('hmath_interpolation_value_lagrange', [], []) + + +def newton(): + """HMath.Interpolation.Newton :: InterpolationMethod.""" + return _invoke('hmath_interpolation_value_newton', [], []) + + +def barycentric(): + """HMath.Interpolation.Barycentric :: InterpolationMethod.""" + return _invoke('hmath_interpolation_value_barycentric', [], []) + + +def natural(): + """HMath.Interpolation.Natural :: SplineBoundary.""" + return _invoke('hmath_interpolation_value_natural', [], []) + + +def clamped(value, value2): + """HMath.Interpolation.Clamped :: Double -> Double -> SplineBoundary.""" + return _invoke('hmath_interpolation_value_clamped', [['Double'], ['Double']], [value, value2]) + + +def periodic(): + """HMath.Interpolation.Periodic :: SplineBoundary.""" + return _invoke('hmath_interpolation_value_periodic', [], []) + + +def gaussian(value): + """HMath.Interpolation.Gaussian :: Double -> RadialKernel.""" + return _invoke('hmath_interpolation_value_gaussian', [['Double']], [value]) + + +def multiquadric(value): + """HMath.Interpolation.Multiquadric :: Double -> RadialKernel.""" + return _invoke('hmath_interpolation_value_multiquadric', [['Double']], [value]) + + +def inverse_multiquadric(value): + """HMath.Interpolation.InverseMultiquadric :: Double -> RadialKernel.""" + return _invoke('hmath_interpolation_value_inverse_multiquadric', [['Double']], [value]) + + +def thin_plate(): + """HMath.Interpolation.ThinPlate :: RadialKernel.""" + return _invoke('hmath_interpolation_value_thin_plate', [], []) + + +def cubic(): + """HMath.Interpolation.Cubic :: RadialKernel.""" + return _invoke('hmath_interpolation_value_cubic', [], []) + + +def approximation(approximation_coefficients, approximation_error, approximation_iterations): + """HMath.Interpolation.Approximation :: [Double] -> Double -> Int -> Approximation.""" + return _invoke('hmath_interpolation_value_approximation', [['list', ['Double']], ['Double'], ['Int']], [approximation_coefficients, approximation_error, approximation_iterations]) + + +def approximation_coefficients(value): + """HMath.Interpolation.approximationCoefficients :: Approximation -> [Double].""" + return _invoke('hmath_interpolation_value_approximation_coefficients', [['Approximation']], [value]) + + +def approximation_error(value): + """HMath.Interpolation.approximationError :: Approximation -> Double.""" + return _invoke('hmath_interpolation_value_approximation_error', [['Approximation']], [value]) + + +def approximation_iterations(value): + """HMath.Interpolation.approximationIterations :: Approximation -> Int.""" + return _invoke('hmath_interpolation_value_approximation_iterations', [['Approximation']], [value]) + + +def interpolate(method, policy, points, x0): + """HMath.Interpolation.interpolate :: InterpolationMethod -> Extrapolation -> [(Double, Double)] -> Double -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_interpolate', [['InterpolationMethod'], ['Extrapolation'], ['list', ['tuple', ['Double'], ['Double']]], ['Double']], [method, policy, points, x0]) + + +def hermite(triples, x): + """HMath.Interpolation.hermite :: [(Double, Double, Double)] -> Double -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_hermite', [['list', ['tuple', ['Double'], ['Double'], ['Double']]], ['Double']], [triples, x]) + + +def piecewise_polynomial(knots, coefficients): + """HMath.Interpolation.piecewisePolynomial :: [Double] -> [[Double]] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_piecewise_polynomial', [['list', ['Double']], ['list', ['list', ['Double']]]], [knots, coefficients]) + + +def piecewise_knots(value): + """HMath.Interpolation.piecewiseKnots :: PiecewisePolynomial -> [Double].""" + return _invoke('hmath_interpolation_value_piecewise_knots', [['PiecewisePolynomial']], [value]) + + +def evaluate_piecewise(value, value2, value3): + """HMath.Interpolation.evaluatePiecewise :: Extrapolation -> PiecewisePolynomial -> Double -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_evaluate_piecewise', [['Extrapolation'], ['PiecewisePolynomial'], ['Double']], [value, value2, value3]) + + +def differentiate_piecewise(value): + """HMath.Interpolation.differentiatePiecewise :: PiecewisePolynomial -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_differentiate_piecewise', [['PiecewisePolynomial']], [value]) + + +def integrate_piecewise(value, value2, value3): + """HMath.Interpolation.integratePiecewise :: PiecewisePolynomial -> Double -> Double -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_integrate_piecewise', [['PiecewisePolynomial'], ['Double'], ['Double']], [value, value2, value3]) + + +def cubic_hermite(triples): + """HMath.Interpolation.cubicHermite :: [(Double, Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_cubic_hermite', [['list', ['tuple', ['Double'], ['Double'], ['Double']]]], [triples]) + + +def cubic_spline(boundary, points): + """HMath.Interpolation.cubicSpline :: SplineBoundary -> [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_cubic_spline', [['SplineBoundary'], ['list', ['tuple', ['Double'], ['Double']]]], [boundary, points]) + + +def pchip(points): + """HMath.Interpolation.pchip :: [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_pchip', [['list', ['tuple', ['Double'], ['Double']]]], [points]) + + +def akima(points): + """HMath.Interpolation.akima :: [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_akima', [['list', ['tuple', ['Double'], ['Double']]]], [points]) + + +def smoothing_spline(lambda_, points): + """HMath.Interpolation.smoothingSpline :: Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_smoothing_spline', [['Double'], ['list', ['tuple', ['Double'], ['Double']]]], [lambda_, points]) + + +def b_spline(degree, knots, controls, weights): + """HMath.Interpolation.bSpline :: Int -> [Double] -> [[Double]] -> [Double] -> Either MathError BSpline.""" + return _invoke('hmath_interpolation_value_b_spline', [['Int'], ['list', ['Double']], ['list', ['list', ['Double']]], ['list', ['Double']]], [degree, knots, controls, weights]) + + +def evaluate_b_spline(s, x): + """HMath.Interpolation.evaluateBSpline :: BSpline -> Double -> Either MathError [Double].""" + return _invoke('hmath_interpolation_value_evaluate_b_spline', [['BSpline'], ['Double']], [s, x]) + + +def derivative_b_spline(s, x): + """HMath.Interpolation.derivativeBSpline :: BSpline -> Double -> Either MathError [Double].""" + return _invoke('hmath_interpolation_value_derivative_b_spline', [['BSpline'], ['Double']], [s, x]) + + +def insert_knot(value, value2): + """HMath.Interpolation.insertKnot :: BSpline -> Double -> Either MathError BSpline.""" + return _invoke('hmath_interpolation_value_insert_knot', [['BSpline'], ['Double']], [value, value2]) + + +def rational_bezier(controls, ws, t): + """HMath.Interpolation.rationalBezier :: [[Double]] -> [Double] -> Double -> Either MathError [Double].""" + return _invoke('hmath_interpolation_value_rational_bezier', [['list', ['list', ['Double']]], ['list', ['Double']], ['Double']], [controls, ws, t]) + + +def bezier(value, value2): + """HMath.Interpolation.bezier :: [[Double]] -> Double -> Either MathError [Double].""" + return _invoke('hmath_interpolation_value_bezier', [['list', ['list', ['Double']]], ['Double']], [value, value2]) + + +def kochanek_bartels(tension, continuity, bias, points): + """HMath.Interpolation.kochanekBartels :: Double -> Double -> Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_kochanek_bartels', [['Double'], ['Double'], ['Double'], ['list', ['tuple', ['Double'], ['Double']]]], [tension, continuity, bias, points]) + + +def cardinal_spline(value, value2): + """HMath.Interpolation.cardinalSpline :: Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_cardinal_spline', [['Double'], ['list', ['tuple', ['Double'], ['Double']]]], [value, value2]) + + +def catmull_rom(value): + """HMath.Interpolation.catmullRom :: [(Double, Double)] -> Either MathError PiecewisePolynomial.""" + return _invoke('hmath_interpolation_value_catmull_rom', [['list', ['tuple', ['Double'], ['Double']]]], [value]) + + +def curve_integral(value, value2, value3, value4): + """HMath.Interpolation.curveIntegral :: C.Tolerance -> BSpline -> Double -> Double -> Either MathError [C.Estimate Double].""" + return _invoke('hmath_interpolation_value_curve_integral', [['Tolerance'], ['BSpline'], ['Double'], ['Double']], [value, value2, value3, value4]) + + +def arc_length(tolerance, spline, a, b): + """HMath.Interpolation.arcLength :: C.Tolerance -> BSpline -> Double -> Double -> Either MathError (C.Estimate Double).""" + return _invoke('hmath_interpolation_value_arc_length', [['Tolerance'], ['BSpline'], ['Double'], ['Double']], [tolerance, spline, a, b]) + + +def grid_interpolate(method, policy, axes, values, point): + """HMath.Interpolation.gridInterpolate :: InterpolationMethod -> Extrapolation -> [[Double]] -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_grid_interpolate', [['InterpolationMethod'], ['Extrapolation'], ['list', ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [method, policy, axes, values, point]) + + +def fit_rbf(method, smoothing, nodes, ys): + """HMath.Interpolation.fitRBF :: RadialKernel -> Double -> [[Double]] -> [Double] -> Either MathError RBF.""" + return _invoke('hmath_interpolation_value_fit_rbf', [['RadialKernel'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [method, smoothing, nodes, ys]) + + +def evaluate_rbf(value, value2): + """HMath.Interpolation.evaluateRBF :: RBF -> [Double] -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_evaluate_rbf', [['RBF'], ['list', ['Double']]], [value, value2]) + + +def inverse_distance(power, nodes, ys, point): + """HMath.Interpolation.inverseDistance :: Double -> [[Double]] -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_inverse_distance', [['Double'], ['list', ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [power, nodes, ys, point]) + + +def shepard(value, value2, value3): + """HMath.Interpolation.shepard :: [[Double]] -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_shepard', [['list', ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [value, value2, value3]) + + +def kriging(range, nugget, nodes, ys, point): + """HMath.Interpolation.kriging :: Double -> Double -> [[Double]] -> [Double] -> [Double] -> Either MathError (Double, Double).""" + return _invoke('hmath_interpolation_value_kriging', [['Double'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [range, nugget, nodes, ys, point]) + + +def polynomial_fit(degree, points): + """HMath.Interpolation.polynomialFit :: Int -> [(Double, Double)] -> Either MathError Approximation.""" + return _invoke('hmath_interpolation_value_polynomial_fit', [['Int'], ['list', ['tuple', ['Double'], ['Double']]]], [degree, points]) + + +def chebyshev_approximate(degree, f, a, b): + """HMath.Interpolation.chebyshevApproximate :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation.""" + return _invoke('hmath_interpolation_value_chebyshev_approximate', [['Int'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [degree, f, a, b]) + + +def pade(m, n, series): + """HMath.Interpolation.pade :: Int -> Int -> [Double] -> Either MathError ([Double], [Double]).""" + return _invoke('hmath_interpolation_value_pade', [['Int'], ['Int'], ['list', ['Double']]], [m, n, series]) + + +def rational_fit(m, n, points): + """HMath.Interpolation.rationalFit :: Int -> Int -> [(Double, Double)] -> Either MathError ([Double], [Double], Double).""" + return _invoke('hmath_interpolation_value_rational_fit', [['Int'], ['Int'], ['list', ['tuple', ['Double'], ['Double']]]], [m, n, points]) + + +def remez(degree, grid_count, tolerance, budget, f, a, b): + """HMath.Interpolation.remez :: Int -> Int -> Double -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation.""" + return _invoke('hmath_interpolation_value_remez', [['Int'], ['Int'], ['Double'], ['Int'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [degree, grid_count, tolerance, budget, f, a, b]) + + +def nonlinear_fit(budget, tolerance, model, points, initial): + """HMath.Interpolation.nonlinearFit :: Int -> Double -> (Double -> [Double] -> Double) -> [(Double, Double)] -> [Double] -> Either MathError Approximation.""" + return _invoke('hmath_interpolation_value_nonlinear_fit', [['Int'], ['Double'], ['function', ['Double'], ['list', ['Double']], ['Double']], ['list', ['tuple', ['Double'], ['Double']]], ['list', ['Double']]], [budget, tolerance, model, points, initial]) + + +def interpolation_error(f, points): + """HMath.Interpolation.interpolationError :: (Double -> Double) -> [(Double, Double)] -> Either MathError Double.""" + return _invoke('hmath_interpolation_value_interpolation_error', [['function', ['Double'], ['Double']], ['list', ['tuple', ['Double'], ['Double']]]], [f, points]) + + +def describe(value): + """Return the original Haskell Show representation of a spectral object.""" + return _invoke("hmath_spectral_describe", [["Value"]], [value]) diff --git a/bindings/python/_hmath_native/iterative.py b/bindings/python/_hmath_native/iterative.py new file mode 100644 index 0000000..c6318c7 --- /dev/null +++ b/bindings/python/_hmath_native/iterative.py @@ -0,0 +1,508 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Matrix.Iterative public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class IterativeOptions(LinearValue): + """Original HMath.Matrix.Iterative.IterativeOptions immutable owner.""" + + _source_type = "HMath.Matrix.Iterative.IterativeOptions" + + def __init__( + self, absolute_tolerance, relative_tolerance, maximum_iterations, *, dtype=None + ): + self._initialize( + "hmath_linear_iterative_new_iterative_options", + True, + [["a"], ["a"], ["Int"]], + [absolute_tolerance, relative_tolerance, maximum_iterations], + dtype, + ) + + @property + def absolute_tolerance(self): + return _invoke( + "hmath_linear_iterative_absolute_tolerance", + True, + [["IterativeOptions", ["a"]]], + [self], + ) + + @property + def relative_tolerance(self): + return _invoke( + "hmath_linear_iterative_relative_tolerance", + True, + [["IterativeOptions", ["a"]]], + [self], + ) + + @property + def maximum_iterations(self): + return _invoke( + "hmath_linear_iterative_maximum_iterations", + True, + [["IterativeOptions", ["a"]]], + [self], + ) + + +register("HMath.Matrix.Iterative.IterativeOptions", IterativeOptions) + + +class IterativeResult(LinearValue): + """Original HMath.Matrix.Iterative.IterativeResult immutable owner.""" + + _source_type = "HMath.Matrix.Iterative.IterativeResult" + + def __init__( + self, + iterative_solution, + iterative_iterations, + iterative_residual_norm, + iterative_normal_residual_norm, + *, + dtype=None, + ): + self._initialize( + "hmath_linear_iterative_new_iterative_result", + True, + [["list", ["a"]], ["Int"], ["a"], ["a"]], + [ + iterative_solution, + iterative_iterations, + iterative_residual_norm, + iterative_normal_residual_norm, + ], + dtype, + ) + + @property + def iterative_solution(self): + return _invoke( + "hmath_linear_iterative_iterative_solution", + True, + [["IterativeResult", ["a"]]], + [self], + ) + + @property + def iterative_iterations(self): + return _invoke( + "hmath_linear_iterative_iterative_iterations", + True, + [["IterativeResult", ["a"]]], + [self], + ) + + @property + def iterative_residual_norm(self): + return _invoke( + "hmath_linear_iterative_iterative_residual_norm", + True, + [["IterativeResult", ["a"]]], + [self], + ) + + @property + def iterative_normal_residual_norm(self): + return _invoke( + "hmath_linear_iterative_iterative_normal_residual_norm", + True, + [["IterativeResult", ["a"]]], + [self], + ) + + +register("HMath.Matrix.Iterative.IterativeResult", IterativeResult) + + +class Preconditioner(LinearValue): + """Original HMath.Matrix.Iterative.Preconditioner immutable owner.""" + + _source_type = "HMath.Matrix.Iterative.Preconditioner" + + +register("HMath.Matrix.Iterative.Preconditioner", Preconditioner) + + +def default_iterative_options(*, dtype=None): + "1000 iterations, zero absolute tolerance and relative tolerance 1e-10. Call original HMath.Matrix.Iterative.defaultIterativeOptions :: IterativeOptions a" + return _invoke( + "hmath_linear_iterative_default_iterative_options", True, [], [], dtype=dtype + ) + + +def apply_preconditioner(preconditioner1, values2, *, dtype=None): + "Apply an inverse action; wrong vector lengths and nonfinite values fail. Call original HMath.Matrix.Iterative.applyPreconditioner :: Preconditioner a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_iterative_apply_preconditioner", + True, + [["Preconditioner", ["a"]], ["list", ["a"]]], + [preconditioner1, values2], + dtype=dtype, + ) + + +def identity_preconditioner(index1, *, dtype=None): + "Identity inverse action in a nonnegative dimension. Call original HMath.Matrix.Iterative.identityPreconditioner :: Int -> Either MathError (Preconditioner a)" + return _invoke( + "hmath_linear_iterative_identity_preconditioner", + True, + [["Int"]], + [index1], + dtype=dtype, + ) + + +def jacobi_preconditioner(matrix1, *, dtype=None): + "Inverse diagonal preconditioner. Every diagonal entry must be nonzero. Call original HMath.Matrix.Iterative.jacobiPreconditioner :: Matrix a -> Either MathError (Preconditioner a)" + return _invoke( + "hmath_linear_iterative_jacobi_preconditioner", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def block_jacobi_preconditioner(values1, matrix2, *, dtype=None): + "Block Jacobi from contiguous positive block sizes summing to the dimension. Each diagonal block is factored with pivoted LU; off-block entries are ignored. Call original HMath.Matrix.Iterative.blockJacobiPreconditioner :: [Int] -> Matrix a -> Either MathError (Preconditioner a)" + return _invoke( + "hmath_linear_iterative_block_jacobi_preconditioner", + True, + [["list", ["Int"]], ["Matrix", ["a"]]], + [values1, matrix2], + dtype=dtype, + ) + + +def ilu0_preconditioner(matrix1, *, dtype=None): + "Incomplete LU with zero fill and no pivoting. The exact nonzero pattern of A is retained, diagonal pivots are mandatory, and zero pivots fail explicitly. Call original HMath.Matrix.Iterative.ilu0Preconditioner :: Matrix a -> Either MathError (Preconditioner a)" + return _invoke( + "hmath_linear_iterative_ilu0_preconditioner", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def ic0_preconditioner(matrix1, *, dtype=None): + "Incomplete Cholesky with zero fill for a symmetric positive-definite input. Dropping can itself cause a nonpositive pivot; that reports NotPositiveDefinite. Call original HMath.Matrix.Iterative.ic0Preconditioner :: Matrix a -> Either MathError (Preconditioner a)" + return _invoke( + "hmath_linear_iterative_ic0_preconditioner", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def conjugate_gradient(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Conjugate gradient for symmetric positive-definite matrices. Symmetry is checked; nonpositive Krylov curvature rejects indefinite matrices encountered. Call original HMath.Matrix.Iterative.conjugateGradient :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_conjugate_gradient", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def preconditioned_cg( + iterative_options1, preconditioner2, matrix3, values4, values5, *, dtype=None +): + "Preconditioned conjugate gradient. The inverse action must be SPD; a nonpositive r^T M^-1 r or search curvature is reported as a domain error. Call original HMath.Matrix.Iterative.preconditionedCG :: IterativeOptions a -> Preconditioner a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_preconditioned_cg", + True, + [ + ["IterativeOptions", ["a"]], + ["Preconditioner", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, preconditioner2, matrix3, values4, values5], + dtype=dtype, + ) + + +def gmres(iterative_options1, index2, matrix3, values4, values5, *, dtype=None): + "Restarted GMRES with modified Gram--Schmidt Arnoldi and a second orthogonalization pass. Restart length must be positive; total iterations are bounded by options. Each projected least-squares problem is solved by QR. Call original HMath.Matrix.Iterative.gmres :: IterativeOptions a -> Int -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_gmres", + True, + [ + ["IterativeOptions", ["a"]], + ["Int"], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, index2, matrix3, values4, values5], + dtype=dtype, + ) + + +def minres(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Minimum residual on the symmetric Lanczos Krylov space, including indefinite systems. A full tridiagonal projected least-squares problem is solved by QR each iteration (the mathematical MINRES objective, without short recurrences). Call original HMath.Matrix.Iterative.minres :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_minres", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def bicg(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Bi-conjugate gradient for nonsymmetric square matrices; the initial shadow residual equals the initial residual. Biorthogonality breakdown fails explicitly. Call original HMath.Matrix.Iterative.bicg :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_bicg", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def bicgstab(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Stabilized BiCG with a fixed initial shadow residual and a minimal-residual omega step. Zero projection/omega denominators return explicit breakdown errors. Call original HMath.Matrix.Iterative.bicgstab :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_bicgstab", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def lsqr(iterative_options1, matrix2, values3, values4, *, dtype=None): + "LSQR by Golub--Kahan bidiagonalization and plane-rotation recurrences. Rectangular and rank-deficient systems are supported. The least-squares stopping test uses the original normal residual as well as the true residual. Call original HMath.Matrix.Iterative.lsqr :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_lsqr", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def lsmr(iterative_options1, matrix2, values3, values4, *, dtype=None): + "LSMR's minimum-normal-residual Krylov objective using explicit Golub--Kahan bases and QR on the projected tridiagonal normal operator. A^T A is never formed. This full-basis reference version uses more storage than short-recurrence implementations; it minimizes ||A^T(b-Ax)|| over the generated Krylov space. Call original HMath.Matrix.Iterative.lsmr :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_lsmr", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def jacobi_solve(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Simultaneous Jacobi stationary iteration. Convergence requires an appropriate splitting (for example strict diagonal dominance); it is not assumed. Call original HMath.Matrix.Iterative.jacobiSolve :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_jacobi_solve", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def gauss_seidel_solve(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Forward Gauss--Seidel stationary iteration. Call original HMath.Matrix.Iterative.gaussSeidelSolve :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_gauss_seidel_solve", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def sor_solve(iterative_options1, scalar2, matrix3, values4, values5, *, dtype=None): + "Successive over-relaxation, requiring a finite relaxation 0 a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_sor_solve", + True, + [ + ["IterativeOptions", ["a"]], + ["a"], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, scalar2, matrix3, values4, values5], + dtype=dtype, + ) + + +def iterative_refinement(iterative_options1, matrix2, values3, values4, *, dtype=None): + "Residual-correction refinement using a reusable partial-pivoted LU. Residuals and corrections use the scalar type's precision. This does not claim mixed-precision accuracy; callers may provide an initial guess from any solver. Call original HMath.Matrix.Iterative.iterativeRefinement :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)" + return _invoke( + "hmath_linear_iterative_iterative_refinement", + True, + [ + ["IterativeOptions", ["a"]], + ["Matrix", ["a"]], + ["list", ["a"]], + ["list", ["a"]], + ], + [iterative_options1, matrix2, values3, values4], + dtype=dtype, + ) + + +def absolute_tolerance(iterative_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.absoluteTolerance :: IterativeOptions -> field" + return _invoke( + "hmath_linear_iterative_absolute_tolerance", + True, + [["IterativeOptions", ["a"]]], + [iterative_options1], + dtype=dtype, + ) + + +def relative_tolerance(iterative_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.relativeTolerance :: IterativeOptions -> field" + return _invoke( + "hmath_linear_iterative_relative_tolerance", + True, + [["IterativeOptions", ["a"]]], + [iterative_options1], + dtype=dtype, + ) + + +def maximum_iterations(iterative_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.maximumIterations :: IterativeOptions -> field" + return _invoke( + "hmath_linear_iterative_maximum_iterations", + True, + [["IterativeOptions", ["a"]]], + [iterative_options1], + dtype=dtype, + ) + + +def iterative_solution(iterative_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.iterativeSolution :: IterativeResult -> field" + return _invoke( + "hmath_linear_iterative_iterative_solution", + True, + [["IterativeResult", ["a"]]], + [iterative_result1], + dtype=dtype, + ) + + +def iterative_iterations(iterative_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.iterativeIterations :: IterativeResult -> field" + return _invoke( + "hmath_linear_iterative_iterative_iterations", + True, + [["IterativeResult", ["a"]]], + [iterative_result1], + dtype=dtype, + ) + + +def iterative_residual_norm(iterative_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.iterativeResidualNorm :: IterativeResult -> field" + return _invoke( + "hmath_linear_iterative_iterative_residual_norm", + True, + [["IterativeResult", ["a"]]], + [iterative_result1], + dtype=dtype, + ) + + +def iterative_normal_residual_norm(iterative_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.Iterative.iterativeNormalResidualNorm :: IterativeResult -> field" + return _invoke( + "hmath_linear_iterative_iterative_normal_residual_norm", + True, + [["IterativeResult", ["a"]]], + [iterative_result1], + dtype=dtype, + ) + + +__all__ = [ + "IterativeOptions", + "IterativeResult", + "Preconditioner", + "absolute_tolerance", + "apply_preconditioner", + "bicg", + "bicgstab", + "block_jacobi_preconditioner", + "conjugate_gradient", + "default_iterative_options", + "gauss_seidel_solve", + "gmres", + "ic0_preconditioner", + "identity_preconditioner", + "ilu0_preconditioner", + "iterative_iterations", + "iterative_normal_residual_norm", + "iterative_refinement", + "iterative_residual_norm", + "iterative_solution", + "jacobi_preconditioner", + "jacobi_solve", + "lsmr", + "lsqr", + "maximum_iterations", + "minres", + "preconditioned_cg", + "relative_tolerance", + "sor_solve", +] diff --git a/bindings/python/_hmath_native/lapack.py b/bindings/python/_hmath_native/lapack.py new file mode 100644 index 0000000..6909fd2 --- /dev/null +++ b/bindings/python/_hmath_native/lapack.py @@ -0,0 +1,597 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Matrix.LAPACK public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class SVD(LinearValue): + """Original HMath.Matrix.LAPACK.SVD immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.SVD" + + def __init__(self, svd_u, singular_values, svd_vt): + self._initialize( + "hmath_linear_lapack_new_svd", + False, + [["Matrix", ["Double"]], ["list", ["Double"]], ["Matrix", ["Double"]]], + [svd_u, singular_values, svd_vt], + ) + + @property + def svd_u(self): + return _invoke("hmath_linear_lapack_svd_u", False, [["SVD"]], [self]) + + @property + def singular_values(self): + return _invoke("hmath_linear_lapack_singular_values", False, [["SVD"]], [self]) + + @property + def svd_vt(self): + return _invoke("hmath_linear_lapack_svd_vt", False, [["SVD"]], [self]) + + +register("HMath.Matrix.LAPACK.SVD", SVD) + + +class Eigen(LinearValue): + """Original HMath.Matrix.LAPACK.Eigen immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.Eigen" + + def __init__(self, eigenvalues, eigenvectors): + self._initialize( + "hmath_linear_lapack_new_eigen", + False, + [["list", ["Complex", ["Double"]]], ["Matrix", ["Complex", ["Double"]]]], + [eigenvalues, eigenvectors], + ) + + @property + def eigenvalues(self): + return _invoke("hmath_linear_lapack_eigenvalues", False, [["Eigen"]], [self]) + + @property + def eigenvectors(self): + return _invoke("hmath_linear_lapack_eigenvectors", False, [["Eigen"]], [self]) + + +register("HMath.Matrix.LAPACK.Eigen", Eigen) + + +class GeneralizedEigen(LinearValue): + """Original HMath.Matrix.LAPACK.GeneralizedEigen immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.GeneralizedEigen" + + def __init__(self, eigen_alpha, eigen_beta, generalized_eigenvectors): + self._initialize( + "hmath_linear_lapack_new_generalized_eigen", + False, + [ + ["list", ["Complex", ["Double"]]], + ["list", ["Double"]], + ["Matrix", ["Complex", ["Double"]]], + ], + [eigen_alpha, eigen_beta, generalized_eigenvectors], + ) + + @property + def eigen_alpha(self): + return _invoke( + "hmath_linear_lapack_eigen_alpha", False, [["GeneralizedEigen"]], [self] + ) + + @property + def eigen_beta(self): + return _invoke( + "hmath_linear_lapack_eigen_beta", False, [["GeneralizedEigen"]], [self] + ) + + @property + def generalized_eigenvectors(self): + return _invoke( + "hmath_linear_lapack_generalized_eigenvectors", + False, + [["GeneralizedEigen"]], + [self], + ) + + +register("HMath.Matrix.LAPACK.GeneralizedEigen", GeneralizedEigen) + + +class Schur(LinearValue): + """Original HMath.Matrix.LAPACK.Schur immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.Schur" + + def __init__(self, schur_q, schur_t, schur_eigenvalues): + self._initialize( + "hmath_linear_lapack_new_schur", + False, + [ + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["list", ["Complex", ["Double"]]], + ], + [schur_q, schur_t, schur_eigenvalues], + ) + + @property + def schur_q(self): + return _invoke("hmath_linear_lapack_schur_q", False, [["Schur"]], [self]) + + @property + def schur_t(self): + return _invoke("hmath_linear_lapack_schur_t", False, [["Schur"]], [self]) + + @property + def schur_eigenvalues(self): + return _invoke( + "hmath_linear_lapack_schur_eigenvalues", False, [["Schur"]], [self] + ) + + +register("HMath.Matrix.LAPACK.Schur", Schur) + + +class QZ(LinearValue): + """Original HMath.Matrix.LAPACK.QZ immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.QZ" + + def __init__(self, qz_q, qz_z, qz_s, qz_t, qz_alpha, qz_beta): + self._initialize( + "hmath_linear_lapack_new_qz", + False, + [ + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["Matrix", ["Double"]], + ["list", ["Complex", ["Double"]]], + ["list", ["Double"]], + ], + [qz_q, qz_z, qz_s, qz_t, qz_alpha, qz_beta], + ) + + @property + def qz_q(self): + return _invoke("hmath_linear_lapack_qz_q", False, [["QZ"]], [self]) + + @property + def qz_z(self): + return _invoke("hmath_linear_lapack_qz_z", False, [["QZ"]], [self]) + + @property + def qz_s(self): + return _invoke("hmath_linear_lapack_qz_s", False, [["QZ"]], [self]) + + @property + def qz_t(self): + return _invoke("hmath_linear_lapack_qz_t", False, [["QZ"]], [self]) + + @property + def qz_alpha(self): + return _invoke("hmath_linear_lapack_qz_alpha", False, [["QZ"]], [self]) + + @property + def qz_beta(self): + return _invoke("hmath_linear_lapack_qz_beta", False, [["QZ"]], [self]) + + +register("HMath.Matrix.LAPACK.QZ", QZ) + + +class Hessenberg(LinearValue): + """Original HMath.Matrix.LAPACK.Hessenberg immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.Hessenberg" + + def __init__(self, hessenberg_q, hessenberg_h): + self._initialize( + "hmath_linear_lapack_new_hessenberg", + False, + [["Matrix", ["Double"]], ["Matrix", ["Double"]]], + [hessenberg_q, hessenberg_h], + ) + + @property + def hessenberg_q(self): + return _invoke( + "hmath_linear_lapack_hessenberg_q", False, [["Hessenberg"]], [self] + ) + + @property + def hessenberg_h(self): + return _invoke( + "hmath_linear_lapack_hessenberg_h", False, [["Hessenberg"]], [self] + ) + + +register("HMath.Matrix.LAPACK.Hessenberg", Hessenberg) + + +class Balance(LinearValue): + """Original HMath.Matrix.LAPACK.Balance immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.Balance" + + def __init__(self, balanced_matrix, balance_scales): + self._initialize( + "hmath_linear_lapack_new_balance", + False, + [["Matrix", ["Double"]], ["list", ["Double"]]], + [balanced_matrix, balance_scales], + ) + + @property + def balanced_matrix(self): + return _invoke( + "hmath_linear_lapack_balanced_matrix", False, [["Balance"]], [self] + ) + + @property + def balance_scales(self): + return _invoke( + "hmath_linear_lapack_balance_scales", False, [["Balance"]], [self] + ) + + +register("HMath.Matrix.LAPACK.Balance", Balance) + + +class ComplexSVD(LinearValue): + """Original HMath.Matrix.LAPACK.ComplexSVD immutable owner.""" + + _source_type = "HMath.Matrix.LAPACK.ComplexSVD" + + def __init__(self, complex_u, complex_singular_values, complex_vt): + self._initialize( + "hmath_linear_lapack_new_complex_svd", + False, + [ + ["Matrix", ["Complex", ["Double"]]], + ["list", ["Double"]], + ["Matrix", ["Complex", ["Double"]]], + ], + [complex_u, complex_singular_values, complex_vt], + ) + + @property + def complex_u(self): + return _invoke("hmath_linear_lapack_complex_u", False, [["ComplexSVD"]], [self]) + + @property + def complex_singular_values(self): + return _invoke( + "hmath_linear_lapack_complex_singular_values", + False, + [["ComplexSVD"]], + [self], + ) + + @property + def complex_vt(self): + return _invoke( + "hmath_linear_lapack_complex_vt", False, [["ComplexSVD"]], [self] + ) + + +register("HMath.Matrix.LAPACK.ComplexSVD", ComplexSVD) + + +def svd(matrix1): + "Compute thin real SVD A=U*diag(s)*VT via LAPACK, with descending nonnegative singular values and k=min(m,n). Return m-by-k U and k-by-n VT. Invalid input, unavailable backend, allocation bounds or LAPACK failure returns Left MathError. Call original HMath.Matrix.LAPACK.svd :: Matrix Double -> Either MathError SVD" + return _invoke( + "hmath_linear_lapack_svd", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def full_svd(matrix1): + "Full square U and V^T, including null-space completion. Call original HMath.Matrix.LAPACK.fullSVD :: Matrix Double -> Either MathError SVD" + return _invoke( + "hmath_linear_lapack_full_svd", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def truncated_svd(index1, matrix2): + "Given retained rank k then real matrix, compute thin SVD and retain its first k components. Reject k outside the available rank dimensions; decomposition failures propagate. Call original HMath.Matrix.LAPACK.truncatedSVD :: Int -> Matrix Double -> Either MathError SVD" + return _invoke( + "hmath_linear_lapack_truncated_svd", + False, + [["Int"], ["Matrix", ["Double"]]], + [index1, matrix2], + ) + + +def randomized_svd(index1, index2, index3, integer4, matrix5): + "Randomized range finder with an explicit seed, oversampling, and power iterations, followed by a small deterministic SVD. The Gaussian test matrix uses Box-Muller on a local LCG, so results are reproducible, not cryptographic. Call original HMath.Matrix.LAPACK.randomizedSVD :: Int -> Int -> Int -> Integer -> Matrix Double -> Either MathError SVD" + return _invoke( + "hmath_linear_lapack_randomized_svd", + False, + [["Int"], ["Int"], ["Int"], ["Integer"], ["Matrix", ["Double"]]], + [index1, index2, index3, integer4, matrix5], + ) + + +def eigen(matrix1): + "Compute complex eigenvalues and right eigenvectors of a finite real square matrix via LAPACK. Complex-conjugate pairs are decoded into complex columns. Invalid shape/backend/numeric failures return Left MathError. Call original HMath.Matrix.LAPACK.eigen :: Matrix Double -> Either MathError Eigen" + return _invoke( + "hmath_linear_lapack_eigen", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def symmetric_eigen(matrix1): + "Real symmetric eigensolver with orthonormal columns, sorted ascending. Call original HMath.Matrix.LAPACK.symmetricEigen :: Matrix Double -> Either MathError Eigen" + return _invoke( + "hmath_linear_lapack_symmetric_eigen", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def generalized_eigen(matrix1, matrix2): + "Given equally sized square matrices A,B, compute generalized alpha/beta eigenvalue representation and right eigenvectors. Retain alpha/beta to represent infinite eigenvalues safely; invalid input or LAPACK failure propagates. Call original HMath.Matrix.LAPACK.generalizedEigen :: Matrix Double -> Matrix Double -> Either MathError GeneralizedEigen" + return _invoke( + "hmath_linear_lapack_generalized_eigen", + False, + [["Matrix", ["Double"]], ["Matrix", ["Double"]]], + [matrix1, matrix2], + ) + + +def schur(matrix1): + "Compute real Schur form A=Q*T*transpose(Q), returning orthogonal Q, quasi-upper-triangular T and complex eigenvalues. Require finite square input and available LAPACK; failures return Left MathError. Call original HMath.Matrix.LAPACK.schur :: Matrix Double -> Either MathError Schur" + return _invoke( + "hmath_linear_lapack_schur", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def qz(matrix1, matrix2): + "Compute generalized real Schur factors for a finite square matrix pair A,B, retaining Q,Z,S,T and alpha/beta eigenvalues. Shape/backend/LAPACK errors return Left MathError. Call original HMath.Matrix.LAPACK.qz :: Matrix Double -> Matrix Double -> Either MathError QZ" + return _invoke( + "hmath_linear_lapack_qz", + False, + [["Matrix", ["Double"]], ["Matrix", ["Double"]]], + [matrix1, matrix2], + ) + + +def hessenberg(matrix1): + "Reduce finite real square A to upper Hessenberg H with orthogonal Q, satisfying A=Q*H*transpose(Q). Invalid shape or backend/decomposition failures propagate. Call original HMath.Matrix.LAPACK.hessenberg :: Matrix Double -> Either MathError Hessenberg" + return _invoke( + "hmath_linear_lapack_hessenberg", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def balance(matrix1): + "Balance a real square matrix by diagonal scaling, returning the balanced matrix and scales needed to interpret its basis. Invalid finite-input/shape checks or LAPACK failures return Left MathError. Call original HMath.Matrix.LAPACK.balance :: Matrix Double -> Either MathError Balance" + return _invoke( + "hmath_linear_lapack_balance", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def complex_svd(matrix1): + "Compute thin complex SVD with conjugate-transposed right factor VT and real nonnegative singular values. Require finite complex entries and available LAPACK. Invalid storage sizes/backend/decomposition fails. Call original HMath.Matrix.LAPACK.complexSVD :: Matrix (Complex Double) -> Either MathError ComplexSVD" + return _invoke( + "hmath_linear_lapack_complex_svd", + False, + [["Matrix", ["Complex", ["Double"]]]], + [matrix1], + ) + + +def complex_eigen(matrix1): + "Compute complex eigenvalues and right eigenvectors of a finite complex square matrix via LAPACK. Invalid shape, backend availability, bounds or decomposition errors return Left MathError. Call original HMath.Matrix.LAPACK.complexEigen :: Matrix (Complex Double) -> Either MathError Eigen" + return _invoke( + "hmath_linear_lapack_complex_eigen", + False, + [["Matrix", ["Complex", ["Double"]]]], + [matrix1], + ) + + +def svd_u(svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.svdU :: SVD -> field" + return _invoke("hmath_linear_lapack_svd_u", False, [["SVD"]], [svd1]) + + +def singular_values(svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.singularValues :: SVD -> field" + return _invoke("hmath_linear_lapack_singular_values", False, [["SVD"]], [svd1]) + + +def svd_vt(svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.svdVT :: SVD -> field" + return _invoke("hmath_linear_lapack_svd_vt", False, [["SVD"]], [svd1]) + + +def eigenvalues(eigen1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.eigenvalues :: Eigen -> field" + return _invoke("hmath_linear_lapack_eigenvalues", False, [["Eigen"]], [eigen1]) + + +def eigenvectors(eigen1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.eigenvectors :: Eigen -> field" + return _invoke("hmath_linear_lapack_eigenvectors", False, [["Eigen"]], [eigen1]) + + +def eigen_alpha(generalized_eigen1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.eigenAlpha :: GeneralizedEigen -> field" + return _invoke( + "hmath_linear_lapack_eigen_alpha", + False, + [["GeneralizedEigen"]], + [generalized_eigen1], + ) + + +def eigen_beta(generalized_eigen1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.eigenBeta :: GeneralizedEigen -> field" + return _invoke( + "hmath_linear_lapack_eigen_beta", + False, + [["GeneralizedEigen"]], + [generalized_eigen1], + ) + + +def generalized_eigenvectors(generalized_eigen1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.generalizedEigenvectors :: GeneralizedEigen -> field" + return _invoke( + "hmath_linear_lapack_generalized_eigenvectors", + False, + [["GeneralizedEigen"]], + [generalized_eigen1], + ) + + +def schur_q(schur1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.schurQ :: Schur -> field" + return _invoke("hmath_linear_lapack_schur_q", False, [["Schur"]], [schur1]) + + +def schur_t(schur1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.schurT :: Schur -> field" + return _invoke("hmath_linear_lapack_schur_t", False, [["Schur"]], [schur1]) + + +def schur_eigenvalues(schur1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.schurEigenvalues :: Schur -> field" + return _invoke( + "hmath_linear_lapack_schur_eigenvalues", False, [["Schur"]], [schur1] + ) + + +def qz_q(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzQ :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_q", False, [["QZ"]], [qz1]) + + +def qz_z(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzZ :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_z", False, [["QZ"]], [qz1]) + + +def qz_s(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzS :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_s", False, [["QZ"]], [qz1]) + + +def qz_t(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzT :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_t", False, [["QZ"]], [qz1]) + + +def qz_alpha(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzAlpha :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_alpha", False, [["QZ"]], [qz1]) + + +def qz_beta(qz1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.qzBeta :: QZ -> field" + return _invoke("hmath_linear_lapack_qz_beta", False, [["QZ"]], [qz1]) + + +def hessenberg_q(hessenberg1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.hessenbergQ :: Hessenberg -> field" + return _invoke( + "hmath_linear_lapack_hessenberg_q", False, [["Hessenberg"]], [hessenberg1] + ) + + +def hessenberg_h(hessenberg1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.hessenbergH :: Hessenberg -> field" + return _invoke( + "hmath_linear_lapack_hessenberg_h", False, [["Hessenberg"]], [hessenberg1] + ) + + +def balanced_matrix(balance1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.balancedMatrix :: Balance -> field" + return _invoke( + "hmath_linear_lapack_balanced_matrix", False, [["Balance"]], [balance1] + ) + + +def balance_scales(balance1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.balanceScales :: Balance -> field" + return _invoke( + "hmath_linear_lapack_balance_scales", False, [["Balance"]], [balance1] + ) + + +def complex_u(complex_svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.complexU :: ComplexSVD -> field" + return _invoke( + "hmath_linear_lapack_complex_u", False, [["ComplexSVD"]], [complex_svd1] + ) + + +def complex_singular_values(complex_svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.complexSingularValues :: ComplexSVD -> field" + return _invoke( + "hmath_linear_lapack_complex_singular_values", + False, + [["ComplexSVD"]], + [complex_svd1], + ) + + +def complex_vt(complex_svd1): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Matrix.LAPACK.complexVT :: ComplexSVD -> field" + return _invoke( + "hmath_linear_lapack_complex_vt", False, [["ComplexSVD"]], [complex_svd1] + ) + + +__all__ = [ + "QZ", + "SVD", + "Balance", + "ComplexSVD", + "Eigen", + "GeneralizedEigen", + "Hessenberg", + "Schur", + "balance", + "balance_scales", + "balanced_matrix", + "complex_eigen", + "complex_singular_values", + "complex_svd", + "complex_u", + "complex_vt", + "eigen", + "eigen_alpha", + "eigen_beta", + "eigenvalues", + "eigenvectors", + "full_svd", + "generalized_eigen", + "generalized_eigenvectors", + "hessenberg", + "hessenberg_h", + "hessenberg_q", + "qz", + "qz_alpha", + "qz_beta", + "qz_q", + "qz_s", + "qz_t", + "qz_z", + "randomized_svd", + "schur", + "schur_eigenvalues", + "schur_q", + "schur_t", + "singular_values", + "svd", + "svd_u", + "svd_vt", + "symmetric_eigen", + "truncated_svd", +] diff --git a/bindings/python/_hmath_native/linear.py b/bindings/python/_hmath_native/linear.py new file mode 100644 index 0000000..5e00b06 --- /dev/null +++ b/bindings/python/_hmath_native/linear.py @@ -0,0 +1,204 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call +from ._numeric_objects import _call_value, _uses_value + + +def dot(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.dot; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_dot', ['fs', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['fs', 'fs'], 'f', 'float32', '_f32'), + 'float64': (['fs', 'fs'], 'f', 'float64', '_f64'), + 'rational': (['qs', 'qs'], 'q', None, '_rational'), + 'integer': (['zs', 'zs'], 'z', None, '_integer'), + 'int8': (['int8s', 'int8s'], 'int8', None, '_i8'), + 'int16': (['int16s', 'int16s'], 'int16', None, '_i16'), + 'int32': (['int32s', 'int32s'], 'int32', None, '_i32'), + 'int64': (['int64s', 'int64s'], 'int64', None, '_i64'), + 'uint8': (['uint8s', 'uint8s'], 'uint8', None, '_u8'), + 'uint16': (['uint16s', 'uint16s'], 'uint16', None, '_u16'), + 'uint32': (['uint32s', 'uint32s'], 'uint32', None, '_u32'), + 'uint64': (['uint64s', 'uint64s'], 'uint64', None, '_u64'), + 'intp': (['intps', 'intps'], 'intp', None, '_int'), + 'uintp': (['uintps', 'uintps'], 'uintp', None, '_word'), + 'complex64': (['cs', 'cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs', 'cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_dot', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) + + +def dot_checked(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.dotChecked; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_dot_checked', ['fs', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['fs', 'fs'], 'f', 'float32', '_f32'), + 'float64': (['fs', 'fs'], 'f', 'float64', '_f64'), + 'rational': (['qs', 'qs'], 'q', None, '_rational'), + 'integer': (['zs', 'zs'], 'z', None, '_integer'), + 'int8': (['int8s', 'int8s'], 'int8', None, '_i8'), + 'int16': (['int16s', 'int16s'], 'int16', None, '_i16'), + 'int32': (['int32s', 'int32s'], 'int32', None, '_i32'), + 'int64': (['int64s', 'int64s'], 'int64', None, '_i64'), + 'uint8': (['uint8s', 'uint8s'], 'uint8', None, '_u8'), + 'uint16': (['uint16s', 'uint16s'], 'uint16', None, '_u16'), + 'uint32': (['uint32s', 'uint32s'], 'uint32', None, '_u32'), + 'uint64': (['uint64s', 'uint64s'], 'uint64', None, '_u64'), + 'intp': (['intps', 'intps'], 'intp', None, '_int'), + 'uintp': (['uintps', 'uintps'], 'uintp', None, '_word'), + 'complex64': (['cs', 'cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs', 'cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_dot_checked', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) + + +def magnitude(argument1, *, dtype='float64'): + """Call HMath.Linear.magnitude; preserve its argument order, result and errors.""" + if _uses_value([argument1], dtype, ordered=False): + return _call_value('hmath_linear_magnitude', ['fs'], [argument1], dtype) + variants = { + 'float32': (['fs'], 'f', 'float32', '_f32'), + 'float64': (['fs'], 'f', 'float64', '_f64'), + 'complex64': (['cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_magnitude', kinds, result, [argument1], precision, 0, symbol_suffix=suffix) + + +def normalize(argument1, *, dtype='float64'): + """Call HMath.Linear.normalize; preserve its argument order, result and errors.""" + if _uses_value([argument1], dtype, ordered=False): + return _call_value('hmath_linear_normalize', ['fs'], [argument1], dtype) + variants = { + 'float32': (['fs'], 'fd', 'float32', '_f32'), + 'float64': (['fs'], 'fd', 'float64', '_f64'), + 'complex64': (['cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_normalize', kinds, result, [argument1], precision, 0, symbol_suffix=suffix) + + +def add(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.add; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_add', ['fs', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['fs', 'fs'], 'fd', 'float32', '_f32'), + 'float64': (['fs', 'fs'], 'fd', 'float64', '_f64'), + 'rational': (['qs', 'qs'], 'qd', None, '_rational'), + 'integer': (['zs', 'zs'], 'zd', None, '_integer'), + 'int8': (['int8s', 'int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s', 'int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s', 'int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s', 'int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s', 'uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s', 'uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s', 'uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s', 'uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps', 'intps'], 'intpd', None, '_int'), + 'uintp': (['uintps', 'uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs', 'cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs', 'cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_add', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) + + +def add_checked(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.addChecked; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_add_checked', ['fs', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['fs', 'fs'], 'fd', 'float32', '_f32'), + 'float64': (['fs', 'fs'], 'fd', 'float64', '_f64'), + 'rational': (['qs', 'qs'], 'qd', None, '_rational'), + 'integer': (['zs', 'zs'], 'zd', None, '_integer'), + 'int8': (['int8s', 'int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s', 'int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s', 'int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s', 'int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s', 'uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s', 'uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s', 'uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s', 'uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps', 'intps'], 'intpd', None, '_int'), + 'uintp': (['uintps', 'uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs', 'cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs', 'cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_add_checked', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) + + +def subtract_checked(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.subtractChecked; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_subtract_checked', ['fs', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['fs', 'fs'], 'fd', 'float32', '_f32'), + 'float64': (['fs', 'fs'], 'fd', 'float64', '_f64'), + 'rational': (['qs', 'qs'], 'qd', None, '_rational'), + 'integer': (['zs', 'zs'], 'zd', None, '_integer'), + 'int8': (['int8s', 'int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s', 'int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s', 'int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s', 'int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s', 'uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s', 'uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s', 'uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s', 'uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps', 'intps'], 'intpd', None, '_int'), + 'uintp': (['uintps', 'uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs', 'cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs', 'cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_subtract_checked', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) + + +def scale(argument1, argument2, *, dtype='float64'): + """Call HMath.Linear.scale; preserve its argument order, result and errors.""" + if _uses_value([argument1, argument2], dtype, ordered=False): + return _call_value('hmath_linear_scale', ['f', 'fs'], [argument1, argument2], dtype) + variants = { + 'float32': (['f', 'fs'], 'fd', 'float32', '_f32'), + 'float64': (['f', 'fs'], 'fd', 'float64', '_f64'), + 'rational': (['q', 'qs'], 'qd', None, '_rational'), + 'integer': (['z', 'zs'], 'zd', None, '_integer'), + 'int8': (['int8', 'int8s'], 'int8d', None, '_i8'), + 'int16': (['int16', 'int16s'], 'int16d', None, '_i16'), + 'int32': (['int32', 'int32s'], 'int32d', None, '_i32'), + 'int64': (['int64', 'int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8', 'uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16', 'uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32', 'uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64', 'uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intp', 'intps'], 'intpd', None, '_int'), + 'uintp': (['uintp', 'uintps'], 'uintpd', None, '_word'), + 'complex64': (['c', 'cs'], 'cd', 'float32', '_c64'), + 'complex128': (['c', 'cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_linear_scale', kinds, result, [argument1, argument2], precision, 0, symbol_suffix=suffix) diff --git a/bindings/python/_hmath_native/machinelearning.py b/bindings/python/_hmath_native/machinelearning.py new file mode 100644 index 0000000..7a70bf4 --- /dev/null +++ b/bindings/python/_hmath_native/machinelearning.py @@ -0,0 +1,1296 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_machinelearning_bindings.py; do not edit. +"""Original immutable estimators, preprocessing, labels and fit diagnostics.""" +from ._numerical_base import _invoke +from ._value import Value, register + +Dataset = list + + +class ClusterModel(Value): + """Actual immutable HMath.MachineLearning.Clustering.ClusterModel owner.""" + + +register(310, ClusterModel) + + +class GaussianMixture(Value): + """Actual immutable HMath.MachineLearning.Clustering.GaussianMixture owner.""" + + +register(311, GaussianMixture) + + +class Linkage(Value): + """Actual immutable HMath.MachineLearning.Clustering.Linkage owner.""" + + +register(312, Linkage) + + +class Merge(Value): + """Actual immutable HMath.MachineLearning.Clustering.Merge owner.""" + + +register(313, Merge) + + +class CCA(Value): + """Actual immutable HMath.MachineLearning.Decomposition.CCA owner.""" + + +register(314, CCA) + + +class FactorAnalysis(Value): + """Actual immutable HMath.MachineLearning.Decomposition.FactorAnalysis owner.""" + + +register(315, FactorAnalysis) + + +class ICA(Value): + """Actual immutable HMath.MachineLearning.Decomposition.ICA owner.""" + + +register(316, ICA) + + +class IncrementalPCA(Value): + """Actual immutable HMath.MachineLearning.Decomposition.IncrementalPCA owner.""" + + +register(317, IncrementalPCA) + + +class KernelPCA(Value): + """Actual immutable HMath.MachineLearning.Decomposition.KernelPCA owner.""" + + +register(318, KernelPCA) + + +class PCA(Value): + """Actual immutable HMath.MachineLearning.Decomposition.PCA owner.""" + + +register(319, PCA) + + +class PLS(Value): + """Actual immutable HMath.MachineLearning.Decomposition.PLS owner.""" + + +register(320, PLS) + + +class Fit(Value): + """Actual immutable HMath.MachineLearning.Internal.Fit owner.""" + + +register(321, Fit) + + +class MLConfig(Value): + """Actual immutable HMath.MachineLearning.Internal.MLConfig owner.""" + + +register(322, MLConfig) + + +class IndexKind(Value): + """Actual immutable HMath.MachineLearning.Neighbors.IndexKind owner.""" + + +register(323, IndexKind) + + +class IsolationForest(Value): + """Actual immutable HMath.MachineLearning.Neighbors.IsolationForest owner.""" + + +register(324, IsolationForest) + + +class LSH(Value): + """Actual immutable HMath.MachineLearning.Neighbors.LSH owner.""" + + +register(325, LSH) + + +class NeighborResult(Value): + """Actual immutable HMath.MachineLearning.Neighbors.NeighborResult owner.""" + + +register(326, NeighborResult) + + +class OneClassSVM(Value): + """Actual immutable HMath.MachineLearning.Neighbors.OneClassSVM owner.""" + + +register(327, OneClassSVM) + + +class SpatialIndex(Value): + """Actual immutable HMath.MachineLearning.Neighbors.SpatialIndex owner.""" + + +register(328, SpatialIndex) + + +class Encoder(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Encoder owner.""" + + +register(329, Encoder) + + +class Fold(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Fold owner.""" + + +register(330, Fold) + + +class Imputation(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Imputation owner.""" + + +register(331, Imputation) + + +class Imputer(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Imputer owner.""" + + +register(332, Imputer) + + +class PowerTransform(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.PowerTransform owner.""" + + +register(333, PowerTransform) + + +class QuantileTransformer(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.QuantileTransformer owner.""" + + +register(334, QuantileTransformer) + + +class Scaler(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Scaler owner.""" + + +register(335, Scaler) + + +class Scaling(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.Scaling owner.""" + + +register(336, Scaling) + + +class UnknownCategory(Value): + """Actual immutable HMath.MachineLearning.Preprocessing.UnknownCategory owner.""" + + +register(337, UnknownCategory) + + +class BayesFamily(Value): + """Actual immutable HMath.MachineLearning.Regression.BayesFamily owner.""" + + +register(338, BayesFamily) + + +class BayesianLinear(Value): + """Actual immutable HMath.MachineLearning.Regression.BayesianLinear owner.""" + + +register(339, BayesianLinear) + + +class Discriminant(Value): + """Actual immutable HMath.MachineLearning.Regression.Discriminant owner.""" + + +register(340, Discriminant) + + +class GLM(Value): + """Actual immutable HMath.MachineLearning.Regression.GLM owner.""" + + +register(341, GLM) + + +class GLMFamily(Value): + """Actual immutable HMath.MachineLearning.Regression.GLMFamily owner.""" + + +register(342, GLMFamily) + + +class GPClassifier(Value): + """Actual immutable HMath.MachineLearning.Regression.GPClassifier owner.""" + + +register(343, GPClassifier) + + +class GaussianProcess(Value): + """Actual immutable HMath.MachineLearning.Regression.GaussianProcess owner.""" + + +register(344, GaussianProcess) + + +class Kernel(Value): + """Actual immutable HMath.MachineLearning.Regression.Kernel owner.""" + + +register(345, Kernel) + + +class LinearModel(Value): + """Actual immutable HMath.MachineLearning.Regression.LinearModel owner.""" + + +register(346, LinearModel) + + +class MultinomialModel(Value): + """Actual immutable HMath.MachineLearning.Regression.MultinomialModel owner.""" + + +register(347, MultinomialModel) + + +class NaiveBayes(Value): + """Actual immutable HMath.MachineLearning.Regression.NaiveBayes owner.""" + + +register(348, NaiveBayes) + + +class Penalty(Value): + """Actual immutable HMath.MachineLearning.Regression.Penalty owner.""" + + +register(349, Penalty) + + +class RecursiveLS(Value): + """Actual immutable HMath.MachineLearning.Regression.RecursiveLS owner.""" + + +register(350, RecursiveLS) + + +class SVM(Value): + """Actual immutable HMath.MachineLearning.Regression.SVM owner.""" + + +register(351, SVM) + + +def describe(value): + """Inspect original native state without evaluating text as mathematics.""" + return _invoke("hmath_ml_describe", [["Value"]], [value]) + + +def parts(value): + """Inspect original native state without evaluating text as mathematics.""" + return _invoke("hmath_ml_parts", [["Value"]], [value]) + + +def average(): + """HMath.MachineLearning.Clustering.Average :: Linkage.""" + return _invoke('hmath_ml_average', [], []) + + +def complete(): + """HMath.MachineLearning.Clustering.Complete :: Linkage.""" + return _invoke('hmath_ml_complete', [], []) + + +def merge(count, count2, number, count3): + """HMath.MachineLearning.Clustering.Merge :: Int -> Int -> Double -> Int -> Merge.""" + return _invoke('hmath_ml_merge', [['Int'], ['Int'], ['Double'], ['Int']], [count, count2, number, count3]) + + +def single(): + """HMath.MachineLearning.Clustering.Single :: Linkage.""" + return _invoke('hmath_ml_single', [], []) + + +def ward(): + """HMath.MachineLearning.Clustering.Ward :: Linkage.""" + return _invoke('hmath_ml_ward', [], []) + + +def affinity_propagation(ml_config, number, number2, dataset): + """HMath.MachineLearning.Clustering.affinityPropagation :: MLConfig -> Double -> Double -> Dataset -> Either MathError (Fit [Int]).""" + return _invoke('hmath_ml_affinity_propagation', [['MLConfig'], ['Double'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, number, number2, dataset]) + + +def cluster_centers(cluster_model): + """HMath.MachineLearning.Clustering.clusterCenters :: ClusterModel -> Dataset.""" + return _invoke('hmath_ml_cluster_centers', [['ClusterModel']], [cluster_model]) + + +def cut_hierarchy(count, count2, values): + """HMath.MachineLearning.Clustering.cutHierarchy :: Int -> Int -> [Merge] -> Either MathError [Int].""" + return _invoke('hmath_ml_cut_hierarchy', [['Int'], ['Int'], ['list', ['Merge']]], [count, count2, values]) + + +def dbscan(number, count, dataset): + """HMath.MachineLearning.Clustering.dbscan :: Double -> Int -> Dataset -> Either MathError [Int].""" + return _invoke('hmath_ml_dbscan', [['Double'], ['Int'], ['list', ['list', ['Double']]]], [number, count, dataset]) + + +def extract_optics(number, values): + """HMath.MachineLearning.Clustering.extractOPTICS :: Double -> [(Int, Maybe Double, Maybe Double)] -> Either MathError [Int].""" + return _invoke('hmath_ml_extract_optics', [['Double'], ['list', ['tuple', ['Int'], ['maybe', ['Double']], ['maybe', ['Double']]]]], [number, values]) + + +def fit_gaussian_mixture(ml_config, count, number, dataset): + """HMath.MachineLearning.Clustering.fitGaussianMixture :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit GaussianMixture).""" + return _invoke('hmath_ml_fit_gaussian_mixture', [['MLConfig'], ['Int'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, count, number, dataset]) + + +def hierarchical(linkage, dataset): + """HMath.MachineLearning.Clustering.hierarchical :: Linkage -> Dataset -> Either MathError [Merge].""" + return _invoke('hmath_ml_hierarchical', [['Linkage'], ['list', ['list', ['Double']]]], [linkage, dataset]) + + +def k_means(ml_config, count, dataset): + """HMath.MachineLearning.Clustering.kMeans :: MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel).""" + return _invoke('hmath_ml_k_means', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, dataset]) + + +def k_means_plus_plus(ml_config, count, dataset): + """HMath.MachineLearning.Clustering.kMeansPlusPlus :: MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel).""" + return _invoke('hmath_ml_k_means_plus_plus', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, dataset]) + + +def k_medoids(ml_config, count, dataset): + """HMath.MachineLearning.Clustering.kMedoids :: MLConfig -> Int -> Dataset -> Either MathError (Fit [Int]).""" + return _invoke('hmath_ml_k_medoids', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, dataset]) + + +def left_cluster(merge): + """HMath.MachineLearning.Clustering.leftCluster :: Merge -> Int.""" + return _invoke('hmath_ml_left_cluster', [['Merge']], [merge]) + + +def mean_shift(ml_config, number, dataset): + """HMath.MachineLearning.Clustering.meanShift :: MLConfig -> Double -> Dataset -> Either MathError (Fit ClusterModel).""" + return _invoke('hmath_ml_mean_shift', [['MLConfig'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, number, dataset]) + + +def merge_distance(merge): + """HMath.MachineLearning.Clustering.mergeDistance :: Merge -> Double.""" + return _invoke('hmath_ml_merge_distance', [['Merge']], [merge]) + + +def merged_size(merge): + """HMath.MachineLearning.Clustering.mergedSize :: Merge -> Int.""" + return _invoke('hmath_ml_merged_size', [['Merge']], [merge]) + + +def mini_batch_k_means(ml_config, count, count2, dataset): + """HMath.MachineLearning.Clustering.miniBatchKMeans :: MLConfig -> Int -> Int -> Dataset -> Either MathError (Fit ClusterModel).""" + return _invoke('hmath_ml_mini_batch_k_means', [['MLConfig'], ['Int'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, count2, dataset]) + + +def mixture_covariances(gaussian_mixture): + """HMath.MachineLearning.Clustering.mixtureCovariances :: GaussianMixture -> [Dataset].""" + return _invoke('hmath_ml_mixture_covariances', [['GaussianMixture']], [gaussian_mixture]) + + +def mixture_means(gaussian_mixture): + """HMath.MachineLearning.Clustering.mixtureMeans :: GaussianMixture -> Dataset.""" + return _invoke('hmath_ml_mixture_means', [['GaussianMixture']], [gaussian_mixture]) + + +def mixture_responsibilities(gaussian_mixture, dataset): + """HMath.MachineLearning.Clustering.mixtureResponsibilities :: GaussianMixture -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_mixture_responsibilities', [['GaussianMixture'], ['list', ['list', ['Double']]]], [gaussian_mixture, dataset]) + + +def mixture_weights(gaussian_mixture): + """HMath.MachineLearning.Clustering.mixtureWeights :: GaussianMixture -> [Double].""" + return _invoke('hmath_ml_mixture_weights', [['GaussianMixture']], [gaussian_mixture]) + + +def optics(number, count, dataset): + """HMath.MachineLearning.Clustering.optics :: Double -> Int -> Dataset -> Either MathError [(Int, Maybe Double, Maybe Double)].""" + return _invoke('hmath_ml_optics', [['Double'], ['Int'], ['list', ['list', ['Double']]]], [number, count, dataset]) + + +def predict_clusters(cluster_model, dataset): + """HMath.MachineLearning.Clustering.predictClusters :: ClusterModel -> Dataset -> Either MathError [Int].""" + return _invoke('hmath_ml_predict_clusters', [['ClusterModel'], ['list', ['list', ['Double']]]], [cluster_model, dataset]) + + +def right_cluster(merge): + """HMath.MachineLearning.Clustering.rightCluster :: Merge -> Int.""" + return _invoke('hmath_ml_right_cluster', [['Merge']], [merge]) + + +def spectral_clustering(ml_config, count, number, dataset): + """HMath.MachineLearning.Clustering.spectralClustering :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit [Int]).""" + return _invoke('hmath_ml_spectral_clustering', [['MLConfig'], ['Int'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, count, number, dataset]) + + +def canonical_correlations(cca): + """HMath.MachineLearning.Decomposition.canonicalCorrelations :: CCA -> [Double].""" + return _invoke('hmath_ml_canonical_correlations', [['CCA']], [cca]) + + +def classical_mds(count, dataset): + """HMath.MachineLearning.Decomposition.classicalMDS :: Int -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_classical_mds', [['Int'], ['list', ['list', ['Double']]]], [count, dataset]) + + +def factor_loadings(factor_analysis): + """HMath.MachineLearning.Decomposition.factorLoadings :: FactorAnalysis -> Dataset.""" + return _invoke('hmath_ml_factor_loadings', [['FactorAnalysis']], [factor_analysis]) + + +def factor_noise(factor_analysis): + """HMath.MachineLearning.Decomposition.factorNoise :: FactorAnalysis -> [Double].""" + return _invoke('hmath_ml_factor_noise', [['FactorAnalysis']], [factor_analysis]) + + +def finish_pca(count, incremental_pca): + """HMath.MachineLearning.Decomposition.finishPCA :: Int -> IncrementalPCA -> Either MathError PCA.""" + return _invoke('hmath_ml_finish_pca', [['Int'], ['IncrementalPCA']], [count, incremental_pca]) + + +def fit_cca(count, number, dataset, dataset2): + """HMath.MachineLearning.Decomposition.fitCCA :: Int -> Double -> Dataset -> Dataset -> Either MathError CCA.""" + return _invoke('hmath_ml_fit_cca', [['Int'], ['Double'], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]]], [count, number, dataset, dataset2]) + + +def fit_factor_analysis(ml_config, count, number, dataset): + """HMath.MachineLearning.Decomposition.fitFactorAnalysis :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit FactorAnalysis).""" + return _invoke('hmath_ml_fit_factor_analysis', [['MLConfig'], ['Int'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, count, number, dataset]) + + +def fit_ica(ml_config, count, dataset): + """HMath.MachineLearning.Decomposition.fitICA :: MLConfig -> Int -> Dataset -> Either MathError (Fit ICA).""" + return _invoke('hmath_ml_fit_ica', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, dataset]) + + +def fit_kernel_pca(count, kernel, dataset): + """HMath.MachineLearning.Decomposition.fitKernelPCA :: Int -> Kernel -> Dataset -> Either MathError KernelPCA.""" + return _invoke('hmath_ml_fit_kernel_pca', [['Int'], ['Kernel'], ['list', ['list', ['Double']]]], [count, kernel, dataset]) + + +def fit_pca(count, dataset): + """HMath.MachineLearning.Decomposition.fitPCA :: Int -> Dataset -> Either MathError PCA.""" + return _invoke('hmath_ml_fit_pca', [['Int'], ['list', ['list', ['Double']]]], [count, dataset]) + + +def fit_pls(ml_config, count, dataset, dataset2): + """HMath.MachineLearning.Decomposition.fitPLS :: MLConfig -> Int -> Dataset -> Dataset -> Either MathError (Fit PLS).""" + return _invoke('hmath_ml_fit_pls', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]]], [ml_config, count, dataset, dataset2]) + + +def incremental_pca(count): + """HMath.MachineLearning.Decomposition.incrementalPCA :: Int -> Either MathError IncrementalPCA.""" + return _invoke('hmath_ml_incremental_pca', [['Int']], [count]) + + +def inverse_pca(pca, dataset): + """HMath.MachineLearning.Decomposition.inversePCA :: PCA -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_inverse_pca', [['PCA'], ['list', ['list', ['Double']]]], [pca, dataset]) + + +def isomap(count, count2, dataset): + """HMath.MachineLearning.Decomposition.isomap :: Int -> Int -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_isomap', [['Int'], ['Int'], ['list', ['list', ['Double']]]], [count, count2, dataset]) + + +def merge_pca(incremental_pca, incremental_pca2): + """HMath.MachineLearning.Decomposition.mergePCA :: IncrementalPCA -> IncrementalPCA -> Either MathError IncrementalPCA.""" + return _invoke('hmath_ml_merge_pca', [['IncrementalPCA'], ['IncrementalPCA']], [incremental_pca, incremental_pca2]) + + +def pca_components(pca): + """HMath.MachineLearning.Decomposition.pcaComponents :: PCA -> Dataset.""" + return _invoke('hmath_ml_pca_components', [['PCA']], [pca]) + + +def pca_mean(pca): + """HMath.MachineLearning.Decomposition.pcaMean :: PCA -> [Double].""" + return _invoke('hmath_ml_pca_mean', [['PCA']], [pca]) + + +def pca_variances(pca): + """HMath.MachineLearning.Decomposition.pcaVariances :: PCA -> [Double].""" + return _invoke('hmath_ml_pca_variances', [['PCA']], [pca]) + + +def predict_pls(pls, dataset): + """HMath.MachineLearning.Decomposition.predictPLS :: PLS -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_predict_pls', [['PLS'], ['list', ['list', ['Double']]]], [pls, dataset]) + + +def random_projection(ml_config, count, dataset): + """HMath.MachineLearning.Decomposition.randomProjection :: MLConfig -> Int -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_random_projection', [['MLConfig'], ['Int'], ['list', ['list', ['Double']]]], [ml_config, count, dataset]) + + +def transform_cca(cca, dataset, dataset2): + """HMath.MachineLearning.Decomposition.transformCCA :: CCA -> Dataset -> Dataset -> Either MathError (Dataset, Dataset).""" + return _invoke('hmath_ml_transform_cca', [['CCA'], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]]], [cca, dataset, dataset2]) + + +def transform_ica(ica, dataset): + """HMath.MachineLearning.Decomposition.transformICA :: ICA -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_transform_ica', [['ICA'], ['list', ['list', ['Double']]]], [ica, dataset]) + + +def transform_kernel_pca(kernel_pca, dataset): + """HMath.MachineLearning.Decomposition.transformKernelPCA :: KernelPCA -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_transform_kernel_pca', [['KernelPCA'], ['list', ['list', ['Double']]]], [kernel_pca, dataset]) + + +def transform_pca(pca, dataset): + """HMath.MachineLearning.Decomposition.transformPCA :: PCA -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_transform_pca', [['PCA'], ['list', ['list', ['Double']]]], [pca, dataset]) + + +def truncated_svd(count, dataset): + """HMath.MachineLearning.Decomposition.truncatedSVD :: Int -> Dataset -> Either MathError (Dataset, [Double], Dataset).""" + return _invoke('hmath_ml_truncated_svd', [['Int'], ['list', ['list', ['Double']]]], [count, dataset]) + + +def tsne(ml_config, count, number, dataset): + """HMath.MachineLearning.Decomposition.tsne :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit Dataset).""" + return _invoke('hmath_ml_tsne', [['MLConfig'], ['Int'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, count, number, dataset]) + + +def umap(ml_config, count, count2, number, number2, dataset): + """HMath.MachineLearning.Decomposition.umap :: MLConfig -> Int -> Int -> Double -> Double -> Dataset -> Either MathError (Fit Dataset).""" + return _invoke('hmath_ml_umap', [['MLConfig'], ['Int'], ['Int'], ['Double'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, count, count2, number, number2, dataset]) + + +def update_pca(incremental_pca, dataset): + """HMath.MachineLearning.Decomposition.updatePCA :: IncrementalPCA -> Dataset -> Either MathError IncrementalPCA.""" + return _invoke('hmath_ml_update_pca', [['IncrementalPCA'], ['list', ['list', ['Double']]]], [incremental_pca, dataset]) + + +def fit(value, count, number, flag): + """HMath.MachineLearning.Internal.Fit :: a -> Int -> Double -> Bool -> Fit a.""" + return _invoke('hmath_ml_fit', [['Value'], ['Int'], ['Double'], ['Bool']], [value, count, number, flag]) + + +def ml_config(count, number, number2, seed): + """HMath.MachineLearning.Internal.MLConfig :: Int -> Double -> Double -> Word64 -> MLConfig.""" + return _invoke('hmath_ml_ml_config', [['Int'], ['Double'], ['Double'], ['Word64']], [count, number, number2, seed]) + + +def default_ml_config(): + """HMath.MachineLearning.Internal.defaultMLConfig :: MLConfig.""" + return _invoke('hmath_ml_default_ml_config', [], []) + + +def fit_converged(fit): + """HMath.MachineLearning.Internal.fitConverged :: Fit a -> Bool.""" + return _invoke('hmath_ml_fit_converged', [['Fit']], [fit]) + + +def fit_iterations(fit): + """HMath.MachineLearning.Internal.fitIterations :: Fit a -> Int.""" + return _invoke('hmath_ml_fit_iterations', [['Fit']], [fit]) + + +def fit_residual(fit): + """HMath.MachineLearning.Internal.fitResidual :: Fit a -> Double.""" + return _invoke('hmath_ml_fit_residual', [['Fit']], [fit]) + + +def fitted(fit): + """HMath.MachineLearning.Internal.fitted :: Fit a -> a.""" + return _invoke('hmath_ml_fitted', [['Fit']], [fit]) + + +def ml_iterations(ml_config): + """HMath.MachineLearning.Internal.mlIterations :: MLConfig -> Int.""" + return _invoke('hmath_ml_ml_iterations', [['MLConfig']], [ml_config]) + + +def ml_rate(ml_config): + """HMath.MachineLearning.Internal.mlRate :: MLConfig -> Double.""" + return _invoke('hmath_ml_ml_rate', [['MLConfig']], [ml_config]) + + +def ml_seed(ml_config): + """HMath.MachineLearning.Internal.mlSeed :: MLConfig -> Word64.""" + return _invoke('hmath_ml_ml_seed', [['MLConfig']], [ml_config]) + + +def ml_tolerance(ml_config): + """HMath.MachineLearning.Internal.mlTolerance :: MLConfig -> Double.""" + return _invoke('hmath_ml_ml_tolerance', [['MLConfig']], [ml_config]) + + +def ball_tree(): + """HMath.MachineLearning.Neighbors.BallTree :: IndexKind.""" + return _invoke('hmath_ml_ball_tree', [], []) + + +def kd_tree(): + """HMath.MachineLearning.Neighbors.KDTree :: IndexKind.""" + return _invoke('hmath_ml_kd_tree', [], []) + + +def neighbor_result(values, count, flag): + """HMath.MachineLearning.Neighbors.NeighborResult :: [(Int, Double)] -> Int -> Bool -> NeighborResult.""" + return _invoke('hmath_ml_neighbor_result', [['list', ['tuple', ['Int'], ['Double']]], ['Int'], ['Bool']], [values, count, flag]) + + +def build_index(index_kind, count, dataset): + """HMath.MachineLearning.Neighbors.buildIndex :: IndexKind -> Int -> Dataset -> Either MathError SpatialIndex.""" + return _invoke('hmath_ml_build_index', [['IndexKind'], ['Int'], ['list', ['list', ['Double']]]], [index_kind, count, dataset]) + + +def build_lsh(seed, count, count2, number, dataset): + """HMath.MachineLearning.Neighbors.buildLSH :: Word64 -> Int -> Int -> Double -> Dataset -> Either MathError LSH.""" + return _invoke('hmath_ml_build_lsh', [['Word64'], ['Int'], ['Int'], ['Double'], ['list', ['list', ['Double']]]], [seed, count, count2, number, dataset]) + + +def decision_one_class_svm(one_class_svm, dataset): + """HMath.MachineLearning.Neighbors.decisionOneClassSVM :: OneClassSVM -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_decision_one_class_svm', [['OneClassSVM'], ['list', ['list', ['Double']]]], [one_class_svm, dataset]) + + +def exhaustive(neighbor_result): + """HMath.MachineLearning.Neighbors.exhaustive :: NeighborResult -> Bool.""" + return _invoke('hmath_ml_exhaustive', [['NeighborResult']], [neighbor_result]) + + +def fit_isolation_forest(seed, count, count2, dataset): + """HMath.MachineLearning.Neighbors.fitIsolationForest :: Word64 -> Int -> Int -> Dataset -> Either MathError IsolationForest.""" + return _invoke('hmath_ml_fit_isolation_forest', [['Word64'], ['Int'], ['Int'], ['list', ['list', ['Double']]]], [seed, count, count2, dataset]) + + +def fit_one_class_svm(ml_config, kernel, number, dataset): + """HMath.MachineLearning.Neighbors.fitOneClassSVM :: MLConfig -> Kernel -> Double -> Dataset -> Either MathError (Fit OneClassSVM).""" + return _invoke('hmath_ml_fit_one_class_svm', [['MLConfig'], ['Kernel'], ['Double'], ['list', ['list', ['Double']]]], [ml_config, kernel, number, dataset]) + + +def knn_classify(count, spatial_index, values, dataset): + """HMath.MachineLearning.Neighbors.knnClassify :: Int -> SpatialIndex -> [Int] -> Dataset -> Either MathError [Int].""" + return _invoke('hmath_ml_knn_classify', [['Int'], ['SpatialIndex'], ['list', ['Int']], ['list', ['list', ['Double']]]], [count, spatial_index, values, dataset]) + + +def knn_regress(count, spatial_index, values, dataset): + """HMath.MachineLearning.Neighbors.knnRegress :: Int -> SpatialIndex -> [Double] -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_knn_regress', [['Int'], ['SpatialIndex'], ['list', ['Double']], ['list', ['list', ['Double']]]], [count, spatial_index, values, dataset]) + + +def local_outlier_factor(count, dataset): + """HMath.MachineLearning.Neighbors.localOutlierFactor :: Int -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_local_outlier_factor', [['Int'], ['list', ['list', ['Double']]]], [count, dataset]) + + +def nearest_neighbors(count, count2, spatial_index, values): + """HMath.MachineLearning.Neighbors.nearestNeighbors :: Int -> Int -> SpatialIndex -> [Double] -> Either MathError NeighborResult.""" + return _invoke('hmath_ml_nearest_neighbors', [['Int'], ['Int'], ['SpatialIndex'], ['list', ['Double']]], [count, count2, spatial_index, values]) + + +def neighbors(neighbor_result): + """HMath.MachineLearning.Neighbors.neighbors :: NeighborResult -> [(Int, Double)].""" + return _invoke('hmath_ml_neighbors', [['NeighborResult']], [neighbor_result]) + + +def query_lsh(count, lsh, values): + """HMath.MachineLearning.Neighbors.queryLSH :: Int -> LSH -> [Double] -> Either MathError [(Int, Double)].""" + return _invoke('hmath_ml_query_lsh', [['Int'], ['LSH'], ['list', ['Double']]], [count, lsh, values]) + + +def score_isolation_forest(isolation_forest, dataset): + """HMath.MachineLearning.Neighbors.scoreIsolationForest :: IsolationForest -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_score_isolation_forest', [['IsolationForest'], ['list', ['list', ['Double']]]], [isolation_forest, dataset]) + + +def visited_leaves(neighbor_result): + """HMath.MachineLearning.Neighbors.visitedLeaves :: NeighborResult -> Int.""" + return _invoke('hmath_ml_visited_leaves', [['NeighborResult']], [neighbor_result]) + + +def box_cox(number): + """HMath.MachineLearning.Preprocessing.BoxCox :: Double -> PowerTransform.""" + return _invoke('hmath_ml_box_cox', [['Double']], [number]) + + +def constant_impute(number): + """HMath.MachineLearning.Preprocessing.ConstantImpute :: Double -> Imputation.""" + return _invoke('hmath_ml_constant_impute', [['Double']], [number]) + + +def fold(values, values2): + """HMath.MachineLearning.Preprocessing.Fold :: [Int] -> [Int] -> Fold.""" + return _invoke('hmath_ml_fold', [['list', ['Int']], ['list', ['Int']]], [values, values2]) + + +def mean_impute(): + """HMath.MachineLearning.Preprocessing.MeanImpute :: Imputation.""" + return _invoke('hmath_ml_mean_impute', [], []) + + +def median_impute(): + """HMath.MachineLearning.Preprocessing.MedianImpute :: Imputation.""" + return _invoke('hmath_ml_median_impute', [], []) + + +def min_max(): + """HMath.MachineLearning.Preprocessing.MinMax :: Scaling.""" + return _invoke('hmath_ml_min_max', [], []) + + +def reject_unknown(): + """HMath.MachineLearning.Preprocessing.RejectUnknown :: UnknownCategory.""" + return _invoke('hmath_ml_reject_unknown', [], []) + + +def robust_scale(): + """HMath.MachineLearning.Preprocessing.RobustScale :: Scaling.""" + return _invoke('hmath_ml_robust_scale', [], []) + + +def standardize(): + """HMath.MachineLearning.Preprocessing.Standardize :: Scaling.""" + return _invoke('hmath_ml_standardize', [], []) + + +def yeo_johnson(number): + """HMath.MachineLearning.Preprocessing.YeoJohnson :: Double -> PowerTransform.""" + return _invoke('hmath_ml_yeo_johnson', [['Double']], [number]) + + +def zero_unknown(): + """HMath.MachineLearning.Preprocessing.ZeroUnknown :: UnknownCategory.""" + return _invoke('hmath_ml_zero_unknown', [], []) + + +def fit_encoder(values, *, prototype=None): + """HMath.MachineLearning.Preprocessing.fitEncoder :: Ord a => [a] -> Either MathError (Encoder a).""" + return _invoke('hmath_ml_fit_encoder', [['list', ['Value']], ['Value']], [values, prototype]) + + +def fit_imputer(imputation, dataset): + """HMath.MachineLearning.Preprocessing.fitImputer :: Imputation -> Dataset -> Either MathError Imputer.""" + return _invoke('hmath_ml_fit_imputer', [['Imputation'], ['list', ['list', ['Double']]]], [imputation, dataset]) + + +def fit_quantile_transformer(dataset): + """HMath.MachineLearning.Preprocessing.fitQuantileTransformer :: Dataset -> Either MathError QuantileTransformer.""" + return _invoke('hmath_ml_fit_quantile_transformer', [['list', ['list', ['Double']]]], [dataset]) + + +def fit_scaler(scaling, dataset): + """HMath.MachineLearning.Preprocessing.fitScaler :: Scaling -> Dataset -> Either MathError Scaler.""" + return _invoke('hmath_ml_fit_scaler', [['Scaling'], ['list', ['list', ['Double']]]], [scaling, dataset]) + + +def grid_search(values, values2, function): + """HMath.MachineLearning.Preprocessing.gridSearch :: [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double).""" + return _invoke('hmath_ml_grid_search', [['list', ['Value']], ['list', ['Fold']], ['function', ['Value'], ['Fold'], ['either', ['Double']]]], [values, values2, function]) + + +def impute(imputer, dataset): + """HMath.MachineLearning.Preprocessing.impute :: Imputer -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_impute', [['Imputer'], ['list', ['list', ['Double']]]], [imputer, dataset]) + + +def inverse_power_transform(power_transform, dataset): + """HMath.MachineLearning.Preprocessing.inversePowerTransform :: PowerTransform -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_inverse_power_transform', [['PowerTransform'], ['list', ['list', ['Double']]]], [power_transform, dataset]) + + +def inverse_quantile_transform(quantile_transformer, dataset): + """HMath.MachineLearning.Preprocessing.inverseQuantileTransform :: QuantileTransformer -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_inverse_quantile_transform', [['QuantileTransformer'], ['list', ['list', ['Double']]]], [quantile_transformer, dataset]) + + +def inverse_transform(scaler, dataset): + """HMath.MachineLearning.Preprocessing.inverseTransform :: Scaler -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_inverse_transform', [['Scaler'], ['list', ['list', ['Double']]]], [scaler, dataset]) + + +def k_fold(seed, count, count2): + """HMath.MachineLearning.Preprocessing.kFold :: Word64 -> Int -> Int -> Either MathError [Fold].""" + return _invoke('hmath_ml_k_fold', [['Word64'], ['Int'], ['Int']], [seed, count, count2]) + + +def label_decode(encoder, values): + """HMath.MachineLearning.Preprocessing.labelDecode :: Encoder a -> [Int] -> Either MathError [a].""" + return _invoke('hmath_ml_label_decode', [['Encoder'], ['list', ['Int']]], [encoder, values]) + + +def label_encode(encoder, values): + """HMath.MachineLearning.Preprocessing.labelEncode :: Eq a => Encoder a -> [a] -> Either MathError [Int].""" + return _invoke('hmath_ml_label_encode', [['Encoder'], ['list', ['Value']]], [encoder, values]) + + +def one_hot_encode(unknown_category, encoder, values): + """HMath.MachineLearning.Preprocessing.oneHotEncode :: Eq a => UnknownCategory -> Encoder a -> [a] -> Either MathError Dataset.""" + return _invoke('hmath_ml_one_hot_encode', [['UnknownCategory'], ['Encoder'], ['list', ['Value']]], [unknown_category, encoder, values]) + + +def power_transform(power_transform, dataset): + """HMath.MachineLearning.Preprocessing.powerTransform :: PowerTransform -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_power_transform', [['PowerTransform'], ['list', ['list', ['Double']]]], [power_transform, dataset]) + + +def quantile_transform(quantile_transformer, dataset): + """HMath.MachineLearning.Preprocessing.quantileTransform :: QuantileTransformer -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_quantile_transform', [['QuantileTransformer'], ['list', ['list', ['Double']]]], [quantile_transformer, dataset]) + + +def random_search(seed, count, values, values2, function): + """HMath.MachineLearning.Preprocessing.randomSearch :: Word64 -> Int -> [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double).""" + return _invoke('hmath_ml_random_search', [['Word64'], ['Int'], ['list', ['Value']], ['list', ['Fold']], ['function', ['Value'], ['Fold'], ['either', ['Double']]]], [seed, count, values, values2, function]) + + +def stratified_k_fold(seed, count, values, *, prototype=None): + """HMath.MachineLearning.Preprocessing.stratifiedKFold :: Ord a => Word64 -> Int -> [a] -> Either MathError [Fold].""" + return _invoke('hmath_ml_stratified_k_fold', [['Word64'], ['Int'], ['list', ['Value']], ['Value']], [seed, count, values, prototype]) + + +def train_test_split(seed, number, count): + """HMath.MachineLearning.Preprocessing.trainTestSplit :: Word64 -> Double -> Int -> Either MathError Fold.""" + return _invoke('hmath_ml_train_test_split', [['Word64'], ['Double'], ['Int']], [seed, number, count]) + + +def training_indices(fold): + """HMath.MachineLearning.Preprocessing.trainingIndices :: Fold -> [Int].""" + return _invoke('hmath_ml_training_indices', [['Fold']], [fold]) + + +def transform(scaler, dataset): + """HMath.MachineLearning.Preprocessing.transform :: Scaler -> Dataset -> Either MathError Dataset.""" + return _invoke('hmath_ml_transform', [['Scaler'], ['list', ['list', ['Double']]]], [scaler, dataset]) + + +def validation_indices(fold): + """HMath.MachineLearning.Preprocessing.validationIndices :: Fold -> [Int].""" + return _invoke('hmath_ml_validation_indices', [['Fold']], [fold]) + + +def bernoulli_bayes(): + """HMath.MachineLearning.Regression.BernoulliBayes :: BayesFamily.""" + return _invoke('hmath_ml_bernoulli_bayes', [], []) + + +def binomial_logit(): + """HMath.MachineLearning.Regression.BinomialLogit :: GLMFamily.""" + return _invoke('hmath_ml_binomial_logit', [], []) + + +def elastic_net(number, number2): + """HMath.MachineLearning.Regression.ElasticNet :: Double -> Double -> Penalty.""" + return _invoke('hmath_ml_elastic_net', [['Double'], ['Double']], [number, number2]) + + +def gaussian_bayes(): + """HMath.MachineLearning.Regression.GaussianBayes :: BayesFamily.""" + return _invoke('hmath_ml_gaussian_bayes', [], []) + + +def lasso(number): + """HMath.MachineLearning.Regression.Lasso :: Double -> Penalty.""" + return _invoke('hmath_ml_lasso', [['Double']], [number]) + + +def linear_kernel(): + """HMath.MachineLearning.Regression.LinearKernel :: Kernel.""" + return _invoke('hmath_ml_linear_kernel', [], []) + + +def multinomial_bayes(): + """HMath.MachineLearning.Regression.MultinomialBayes :: BayesFamily.""" + return _invoke('hmath_ml_multinomial_bayes', [], []) + + +def ordinary(): + """HMath.MachineLearning.Regression.Ordinary :: Penalty.""" + return _invoke('hmath_ml_ordinary', [], []) + + +def poisson_log(): + """HMath.MachineLearning.Regression.PoissonLog :: GLMFamily.""" + return _invoke('hmath_ml_poisson_log', [], []) + + +def polynomial_kernel(count, number, number2): + """HMath.MachineLearning.Regression.PolynomialKernel :: Int -> Double -> Double -> Kernel.""" + return _invoke('hmath_ml_polynomial_kernel', [['Int'], ['Double'], ['Double']], [count, number, number2]) + + +def rbf_kernel(number): + """HMath.MachineLearning.Regression.RBFKernel :: Double -> Kernel.""" + return _invoke('hmath_ml_rbf_kernel', [['Double']], [number]) + + +def ridge(number): + """HMath.MachineLearning.Regression.Ridge :: Double -> Penalty.""" + return _invoke('hmath_ml_ridge', [['Double']], [number]) + + +def bayesian_covariance(bayesian_linear): + """HMath.MachineLearning.Regression.bayesianCovariance :: BayesianLinear -> Dataset.""" + return _invoke('hmath_ml_bayesian_covariance', [['BayesianLinear']], [bayesian_linear]) + + +def bayesian_mean(bayesian_linear): + """HMath.MachineLearning.Regression.bayesianMean :: BayesianLinear -> LinearModel.""" + return _invoke('hmath_ml_bayesian_mean', [['BayesianLinear']], [bayesian_linear]) + + +def coefficients(linear_model): + """HMath.MachineLearning.Regression.coefficients :: LinearModel -> [Double].""" + return _invoke('hmath_ml_coefficients', [['LinearModel']], [linear_model]) + + +def decision_svm(svm, dataset): + """HMath.MachineLearning.Regression.decisionSVM :: SVM -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_decision_svm', [['SVM'], ['list', ['list', ['Double']]]], [svm, dataset]) + + +def fit_bayesian(number, number2, dataset, values): + """HMath.MachineLearning.Regression.fitBayesian :: Double -> Double -> Dataset -> [Double] -> Either MathError BayesianLinear.""" + return _invoke('hmath_ml_fit_bayesian', [['Double'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [number, number2, dataset, values]) + + +def fit_discriminant(flag, number, dataset, values): + """HMath.MachineLearning.Regression.fitDiscriminant :: Bool -> Double -> Dataset -> [Int] -> Either MathError Discriminant.""" + return _invoke('hmath_ml_fit_discriminant', [['Bool'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Int']]], [flag, number, dataset, values]) + + +def fit_glm(ml_config, glm_family, number, dataset, values): + """HMath.MachineLearning.Regression.fitGLM :: MLConfig -> GLMFamily -> Double -> Dataset -> [Double] -> Either MathError (Fit GLM).""" + return _invoke('hmath_ml_fit_glm', [['MLConfig'], ['GLMFamily'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [ml_config, glm_family, number, dataset, values]) + + +def fit_gp_classifier(ml_config, kernel, dataset, values): + """HMath.MachineLearning.Regression.fitGPClassifier :: MLConfig -> Kernel -> Dataset -> [Double] -> Either MathError (Fit GPClassifier).""" + return _invoke('hmath_ml_fit_gp_classifier', [['MLConfig'], ['Kernel'], ['list', ['list', ['Double']]], ['list', ['Double']]], [ml_config, kernel, dataset, values]) + + +def fit_gaussian_process(kernel, number, dataset, values): + """HMath.MachineLearning.Regression.fitGaussianProcess :: Kernel -> Double -> Dataset -> [Double] -> Either MathError GaussianProcess.""" + return _invoke('hmath_ml_fit_gaussian_process', [['Kernel'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [kernel, number, dataset, values]) + + +def fit_linear(ml_config, penalty, dataset, values): + """HMath.MachineLearning.Regression.fitLinear :: MLConfig -> Penalty -> Dataset -> [Double] -> Either MathError (Fit LinearModel).""" + return _invoke('hmath_ml_fit_linear', [['MLConfig'], ['Penalty'], ['list', ['list', ['Double']]], ['list', ['Double']]], [ml_config, penalty, dataset, values]) + + +def fit_multinomial(ml_config, number, dataset, values): + """HMath.MachineLearning.Regression.fitMultinomial :: MLConfig -> Double -> Dataset -> [Int] -> Either MathError (Fit MultinomialModel).""" + return _invoke('hmath_ml_fit_multinomial', [['MLConfig'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Int']]], [ml_config, number, dataset, values]) + + +def fit_naive_bayes(bayes_family, number, dataset, values): + """HMath.MachineLearning.Regression.fitNaiveBayes :: BayesFamily -> Double -> Dataset -> [Int] -> Either MathError NaiveBayes.""" + return _invoke('hmath_ml_fit_naive_bayes', [['BayesFamily'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Int']]], [bayes_family, number, dataset, values]) + + +def fit_robust(ml_config, number, dataset, values): + """HMath.MachineLearning.Regression.fitRobust :: MLConfig -> Double -> Dataset -> [Double] -> Either MathError (Fit LinearModel).""" + return _invoke('hmath_ml_fit_robust', [['MLConfig'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [ml_config, number, dataset, values]) + + +def fit_svm(ml_config, kernel, number, dataset, values): + """HMath.MachineLearning.Regression.fitSVM :: MLConfig -> Kernel -> Double -> Dataset -> [Double] -> Either MathError (Fit SVM).""" + return _invoke('hmath_ml_fit_svm', [['MLConfig'], ['Kernel'], ['Double'], ['list', ['list', ['Double']]], ['list', ['Double']]], [ml_config, kernel, number, dataset, values]) + + +def fit_weighted(dataset, values, values2): + """HMath.MachineLearning.Regression.fitWeighted :: Dataset -> [Double] -> [Double] -> Either MathError LinearModel.""" + return _invoke('hmath_ml_fit_weighted', [['list', ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [dataset, values, values2]) + + +def kernel(kernel, values, values2): + """HMath.MachineLearning.Regression.kernel :: Kernel -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_ml_kernel', [['Kernel'], ['list', ['Double']], ['list', ['Double']]], [kernel, values, values2]) + + +def polynomial_features(count, values): + """HMath.MachineLearning.Regression.polynomialFeatures :: Int -> [Double] -> Either MathError Dataset.""" + return _invoke('hmath_ml_polynomial_features', [['Int'], ['list', ['Double']]], [count, values]) + + +def predict_discriminant(discriminant, dataset): + """HMath.MachineLearning.Regression.predictDiscriminant :: Discriminant -> Dataset -> Either MathError [Int].""" + return _invoke('hmath_ml_predict_discriminant', [['Discriminant'], ['list', ['list', ['Double']]]], [discriminant, dataset]) + + +def predict_glm(glm, dataset): + """HMath.MachineLearning.Regression.predictGLM :: GLM -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_predict_glm', [['GLM'], ['list', ['list', ['Double']]]], [glm, dataset]) + + +def predict_gp_classifier(gp_classifier, dataset): + """HMath.MachineLearning.Regression.predictGPClassifier :: GPClassifier -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_predict_gp_classifier', [['GPClassifier'], ['list', ['list', ['Double']]]], [gp_classifier, dataset]) + + +def predict_gaussian_process(gaussian_process, dataset): + """HMath.MachineLearning.Regression.predictGaussianProcess :: GaussianProcess -> Dataset -> Either MathError [(Double, Double)].""" + return _invoke('hmath_ml_predict_gaussian_process', [['GaussianProcess'], ['list', ['list', ['Double']]]], [gaussian_process, dataset]) + + +def predict_linear(linear_model, dataset): + """HMath.MachineLearning.Regression.predictLinear :: LinearModel -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_predict_linear', [['LinearModel'], ['list', ['list', ['Double']]]], [linear_model, dataset]) + + +def predict_multinomial(multinomial_model, dataset): + """HMath.MachineLearning.Regression.predictMultinomial :: MultinomialModel -> Dataset -> Either MathError [[(Int, Double)]].""" + return _invoke('hmath_ml_predict_multinomial', [['MultinomialModel'], ['list', ['list', ['Double']]]], [multinomial_model, dataset]) + + +def predict_naive_bayes(naive_bayes, dataset): + """HMath.MachineLearning.Regression.predictNaiveBayes :: NaiveBayes -> Dataset -> Either MathError [Int].""" + return _invoke('hmath_ml_predict_naive_bayes', [['NaiveBayes'], ['list', ['list', ['Double']]]], [naive_bayes, dataset]) + + +def predict_svm(svm, dataset): + """HMath.MachineLearning.Regression.predictSVM :: SVM -> Dataset -> Either MathError [Double].""" + return _invoke('hmath_ml_predict_svm', [['SVM'], ['list', ['list', ['Double']]]], [svm, dataset]) + + +def recursive_coefficients(recursive_ls): + """HMath.MachineLearning.Regression.recursiveCoefficients :: RecursiveLS -> [Double].""" + return _invoke('hmath_ml_recursive_coefficients', [['RecursiveLS']], [recursive_ls]) + + +def recursive_ls(count, number, number2): + """HMath.MachineLearning.Regression.recursiveLS :: Int -> Double -> Double -> Either MathError RecursiveLS.""" + return _invoke('hmath_ml_recursive_ls', [['Int'], ['Double'], ['Double']], [count, number, number2]) + + +def update_recursive_ls(recursive_ls, values, number): + """HMath.MachineLearning.Regression.updateRecursiveLS :: RecursiveLS -> [Double] -> Double -> Either MathError RecursiveLS.""" + return _invoke('hmath_ml_update_recursive_ls', [['RecursiveLS'], ['list', ['Double']], ['Double']], [recursive_ls, values, number]) + + +__all__ = [ + "CCA", + "GLM", + "ICA", + "LSH", + "PCA", + "PLS", + "SVM", + "BayesFamily", + "BayesianLinear", + "ClusterModel", + "Dataset", + "Discriminant", + "Encoder", + "FactorAnalysis", + "Fit", + "Fold", + "GLMFamily", + "GPClassifier", + "GaussianMixture", + "GaussianProcess", + "Imputation", + "Imputer", + "IncrementalPCA", + "IndexKind", + "IsolationForest", + "Kernel", + "KernelPCA", + "LinearModel", + "Linkage", + "MLConfig", + "Merge", + "MultinomialModel", + "NaiveBayes", + "NeighborResult", + "OneClassSVM", + "Penalty", + "PowerTransform", + "QuantileTransformer", + "RecursiveLS", + "Scaler", + "Scaling", + "SpatialIndex", + "UnknownCategory", + "affinity_propagation", + "average", + "ball_tree", + "bayesian_covariance", + "bayesian_mean", + "bernoulli_bayes", + "binomial_logit", + "box_cox", + "build_index", + "build_lsh", + "canonical_correlations", + "classical_mds", + "cluster_centers", + "coefficients", + "complete", + "constant_impute", + "cut_hierarchy", + "dbscan", + "decision_one_class_svm", + "decision_svm", + "default_ml_config", + "describe", + "elastic_net", + "exhaustive", + "extract_optics", + "factor_loadings", + "factor_noise", + "finish_pca", + "fit", + "fit_bayesian", + "fit_cca", + "fit_converged", + "fit_discriminant", + "fit_encoder", + "fit_factor_analysis", + "fit_gaussian_mixture", + "fit_gaussian_process", + "fit_glm", + "fit_gp_classifier", + "fit_ica", + "fit_imputer", + "fit_isolation_forest", + "fit_iterations", + "fit_kernel_pca", + "fit_linear", + "fit_multinomial", + "fit_naive_bayes", + "fit_one_class_svm", + "fit_pca", + "fit_pls", + "fit_quantile_transformer", + "fit_residual", + "fit_robust", + "fit_scaler", + "fit_svm", + "fit_weighted", + "fitted", + "fold", + "gaussian_bayes", + "grid_search", + "hierarchical", + "impute", + "incremental_pca", + "inverse_pca", + "inverse_power_transform", + "inverse_quantile_transform", + "inverse_transform", + "isomap", + "k_fold", + "k_means", + "k_means_plus_plus", + "k_medoids", + "kd_tree", + "kernel", + "knn_classify", + "knn_regress", + "label_decode", + "label_encode", + "lasso", + "left_cluster", + "linear_kernel", + "local_outlier_factor", + "mean_impute", + "mean_shift", + "median_impute", + "merge", + "merge_distance", + "merge_pca", + "merged_size", + "min_max", + "mini_batch_k_means", + "mixture_covariances", + "mixture_means", + "mixture_responsibilities", + "mixture_weights", + "ml_config", + "ml_iterations", + "ml_rate", + "ml_seed", + "ml_tolerance", + "multinomial_bayes", + "nearest_neighbors", + "neighbor_result", + "neighbors", + "one_hot_encode", + "optics", + "ordinary", + "parts", + "pca_components", + "pca_mean", + "pca_variances", + "poisson_log", + "polynomial_features", + "polynomial_kernel", + "power_transform", + "predict_clusters", + "predict_discriminant", + "predict_gaussian_process", + "predict_glm", + "predict_gp_classifier", + "predict_linear", + "predict_multinomial", + "predict_naive_bayes", + "predict_pls", + "predict_svm", + "quantile_transform", + "query_lsh", + "random_projection", + "random_search", + "rbf_kernel", + "recursive_coefficients", + "recursive_ls", + "reject_unknown", + "ridge", + "right_cluster", + "robust_scale", + "score_isolation_forest", + "single", + "spectral_clustering", + "standardize", + "stratified_k_fold", + "train_test_split", + "training_indices", + "transform", + "transform_cca", + "transform_ica", + "transform_kernel_pca", + "transform_pca", + "truncated_svd", + "tsne", + "umap", + "update_pca", + "update_recursive_ls", + "validation_indices", + "visited_leaves", + "ward", + "yeo_johnson", + "zero_unknown" +] diff --git a/bindings/python/_hmath_native/matrix.py b/bindings/python/_hmath_native/matrix.py new file mode 100644 index 0000000..929d4bd --- /dev/null +++ b/bindings/python/_hmath_native/matrix.py @@ -0,0 +1,461 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_matrix_bindings.py. +from ._matrix_base import LU, QR, Matrix, _invoke, shape, to_list + +__all__ = [ + "LU", + "QR", + "Matrix", + "add_matrix", + "add_matrix_checked", + "apply_q", + "apply_qt", + "at", + "at_checked", + "determinant", + "determinant_lu", + "diagonal", + "diagonal_checked", + "from_list", + "from_list_checked", + "hadamard", + "hadamard_checked", + "identity", + "identity_checked", + "inverse", + "least_squares", + "least_squares_matrix", + "lu_decompose", + "lu_decompose_with_tolerance", + "lu_lower", + "lu_permutation", + "lu_upper", + "multiply", + "multiply_checked", + "qr_decompose", + "qr_decompose_with_tolerance", + "qr_permutation", + "qr_q", + "qr_r", + "qr_rank", + "reshape", + "reshape_checked", + "ridge_solve", + "ridge_solve_matrix", + "scale_matrix", + "shape", + "slice_matrix", + "slice_matrix_checked", + "solve", + "solve_lu", + "solve_matrix", + "solve_matrix_lu", + "solve_matrix_qr", + "solve_qr", + "subtract_matrix", + "subtract_matrix_checked", + "to_list", + "transpose_matrix", + "zero_matrix", + "zero_matrix_checked" +] + + +def from_list(rows, columns, values, *, dtype="float64"): + """Call HMath.Matrix.fromList with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_from_list', 'iiv', 'm', 'maybe', + [rows, columns, values], dtype, + ) + + +def zero_matrix(rows, columns, *, dtype="float64"): + """Call HMath.Matrix.zeroMatrix with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_zero_matrix', 'ii', 'm', 'maybe', + [rows, columns], dtype, + ) + + +def diagonal(values, *, dtype="float64"): + """Call HMath.Matrix.diagonal with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_diagonal', 'v', 'm', 'maybe', + [values], dtype, + ) + + +def at(matrix, row, column): + """Call HMath.Matrix.at with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_at', 'mii', 'f', 'maybe', + [matrix, row, column], None, + ) + + +def slice_matrix(start_row, start_column, rows, columns, matrix): + """Call HMath.Matrix.sliceMatrix with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_slice_matrix', 'iiiim', 'm', 'maybe', + [start_row, start_column, rows, columns, matrix], None, + ) + + +def reshape(rows, columns, matrix): + """Call HMath.Matrix.reshape with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_reshape', 'iim', 'm', 'maybe', + [rows, columns, matrix], None, + ) + + +def add_matrix(matrix, right): + """Call HMath.Matrix.addMatrix with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_add_matrix', 'mm', 'm', 'maybe', + [matrix, right], None, + ) + + +def subtract_matrix(matrix, right): + """Call HMath.Matrix.subtractMatrix with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_subtract_matrix', 'mm', 'm', 'maybe', + [matrix, right], None, + ) + + +def hadamard(matrix, right): + """Call HMath.Matrix.hadamard with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_hadamard', 'mm', 'm', 'maybe', + [matrix, right], None, + ) + + +def multiply(matrix, right): + """Call HMath.Matrix.multiply with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_multiply', 'mm', 'm', 'maybe', + [matrix, right], None, + ) + + +def identity(order, *, dtype="float64"): + """Call HMath.Matrix.identity with its original argument order and maybe convention.""" + return _invoke( + 'hmath_dense_identity', 'i', 'm', 'maybe', + [order], dtype, + ) + + +def from_list_checked(rows, columns, values, *, dtype="float64"): + """Call HMath.Matrix.fromListChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_from_list_checked', 'iiv', 'm', 'either', + [rows, columns, values], dtype, + ) + + +def zero_matrix_checked(rows, columns, *, dtype="float64"): + """Call HMath.Matrix.zeroMatrixChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_zero_matrix_checked', 'ii', 'm', 'either', + [rows, columns], dtype, + ) + + +def diagonal_checked(values, *, dtype="float64"): + """Call HMath.Matrix.diagonalChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_diagonal_checked', 'v', 'm', 'either', + [values], dtype, + ) + + +def at_checked(matrix, row, column): + """Call HMath.Matrix.atChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_at_checked', 'mii', 'f', 'either', + [matrix, row, column], None, + ) + + +def slice_matrix_checked(start_row, start_column, rows, columns, matrix): + """Call HMath.Matrix.sliceMatrixChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_slice_matrix_checked', 'iiiim', 'm', 'either', + [start_row, start_column, rows, columns, matrix], None, + ) + + +def reshape_checked(rows, columns, matrix): + """Call HMath.Matrix.reshapeChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_reshape_checked', 'iim', 'm', 'either', + [rows, columns, matrix], None, + ) + + +def add_matrix_checked(matrix, right): + """Call HMath.Matrix.addMatrixChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_add_matrix_checked', 'mm', 'm', 'either', + [matrix, right], None, + ) + + +def subtract_matrix_checked(matrix, right): + """Call HMath.Matrix.subtractMatrixChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_subtract_matrix_checked', 'mm', 'm', 'either', + [matrix, right], None, + ) + + +def hadamard_checked(matrix, right): + """Call HMath.Matrix.hadamardChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_hadamard_checked', 'mm', 'm', 'either', + [matrix, right], None, + ) + + +def multiply_checked(matrix, right): + """Call HMath.Matrix.multiplyChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_multiply_checked', 'mm', 'm', 'either', + [matrix, right], None, + ) + + +def identity_checked(order, *, dtype="float64"): + """Call HMath.Matrix.identityChecked with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_identity_checked', 'i', 'm', 'either', + [order], dtype, + ) + + +def scale_matrix(scalar, matrix): + """Call HMath.Matrix.scaleMatrix with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_scale_matrix', 'fm', 'm', 'pure', + [scalar, matrix], None, + ) + + +def transpose_matrix(matrix): + """Call HMath.Matrix.transposeMatrix with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_transpose_matrix', 'm', 'm', 'pure', + [matrix], None, + ) + + +def lu_decompose(matrix): + """Call HMath.Matrix.LU.luDecompose with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_lu_decompose', 'm', 'l', 'either', + [matrix], None, + ) + + +def lu_decompose_with_tolerance(tolerance, matrix): + """Call HMath.Matrix.LU.luDecomposeWithTolerance with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_lu_decompose_with_tolerance', 'fm', 'l', 'either', + [tolerance, matrix], None, + ) + + +def lu_lower(factors): + """Call HMath.Matrix.LU.luLower with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_lu_lu_lower', 'l', 'm', 'pure', + [factors], None, + ) + + +def lu_upper(factors): + """Call HMath.Matrix.LU.luUpper with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_lu_lu_upper', 'l', 'm', 'pure', + [factors], None, + ) + + +def lu_permutation(factors): + """Call HMath.Matrix.LU.luPermutation with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_lu_lu_permutation', 'l', 'p', 'pure', + [factors], None, + ) + + +def solve_lu(factors, rhs): + """Call HMath.Matrix.LU.solveLU with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_solve_lu', 'lv', 'v', 'either', + [factors, rhs], None, + ) + + +def solve_matrix_lu(factors, rhs): + """Call HMath.Matrix.LU.solveMatrixLU with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_solve_matrix_lu', 'lm', 'm', 'either', + [factors, rhs], None, + ) + + +def solve(matrix, rhs): + """Call HMath.Matrix.LU.solve with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_solve', 'mv', 'v', 'either', + [matrix, rhs], None, + ) + + +def solve_matrix(matrix, rhs): + """Call HMath.Matrix.LU.solveMatrix with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_solve_matrix', 'mm', 'm', 'either', + [matrix, rhs], None, + ) + + +def determinant_lu(factors): + """Call HMath.Matrix.LU.determinantLU with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_determinant_lu', 'l', 'f', 'either', + [factors], None, + ) + + +def determinant(matrix): + """Call HMath.Matrix.LU.determinant with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_determinant', 'm', 'f', 'either', + [matrix], None, + ) + + +def inverse(matrix): + """Call HMath.Matrix.LU.inverse with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_lu_inverse', 'm', 'm', 'either', + [matrix], None, + ) + + +def qr_decompose(matrix): + """Call HMath.Matrix.QR.qrDecompose with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_qr_decompose', 'm', 'q', 'either', + [matrix], None, + ) + + +def qr_decompose_with_tolerance(tolerance, matrix): + """Call HMath.Matrix.QR.qrDecomposeWithTolerance with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_qr_decompose_with_tolerance', 'fm', 'q', 'either', + [tolerance, matrix], None, + ) + + +def qr_q(factors): + """Call HMath.Matrix.QR.qrQ with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_qr_qr_q', 'q', 'm', 'pure', + [factors], None, + ) + + +def qr_r(factors): + """Call HMath.Matrix.QR.qrR with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_qr_qr_r', 'q', 'm', 'pure', + [factors], None, + ) + + +def qr_permutation(factors): + """Call HMath.Matrix.QR.qrPermutation with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_qr_qr_permutation', 'q', 'p', 'pure', + [factors], None, + ) + + +def qr_rank(factors): + """Call HMath.Matrix.QR.qrRank with its original argument order and pure convention.""" + return _invoke( + 'hmath_dense_qr_qr_rank', 'q', 'i', 'pure', + [factors], None, + ) + + +def apply_q(factors, rhs): + """Call HMath.Matrix.QR.applyQ with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_apply_q', 'qm', 'm', 'either', + [factors, rhs], None, + ) + + +def apply_qt(factors, rhs): + """Call HMath.Matrix.QR.applyQT with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_apply_qt', 'qm', 'm', 'either', + [factors, rhs], None, + ) + + +def solve_matrix_qr(factors, rhs): + """Call HMath.Matrix.QR.solveMatrixQR with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_solve_matrix_qr', 'qm', 'm', 'either', + [factors, rhs], None, + ) + + +def solve_qr(factors, rhs): + """Call HMath.Matrix.QR.solveQR with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_solve_qr', 'qv', 'v', 'either', + [factors, rhs], None, + ) + + +def least_squares(matrix, rhs): + """Call HMath.Matrix.QR.leastSquares with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_least_squares', 'mv', 'v', 'either', + [matrix, rhs], None, + ) + + +def least_squares_matrix(matrix, rhs): + """Call HMath.Matrix.QR.leastSquaresMatrix with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_least_squares_matrix', 'mm', 'm', 'either', + [matrix, rhs], None, + ) + + +def ridge_solve(lambda_, matrix, rhs): + """Call HMath.Matrix.QR.ridgeSolve with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_ridge_solve', 'fmv', 'v', 'either', + [lambda_, matrix, rhs], None, + ) + + +def ridge_solve_matrix(lambda_, matrix, rhs): + """Call HMath.Matrix.QR.ridgeSolveMatrix with its original argument order and either convention.""" + return _invoke( + 'hmath_dense_qr_ridge_solve_matrix', 'fmm', 'm', 'either', + [lambda_, matrix, rhs], None, + ) diff --git a/bindings/python/_hmath_native/matrix_advanced.py b/bindings/python/_hmath_native/matrix_advanced.py new file mode 100644 index 0000000..e502cd2 --- /dev/null +++ b/bindings/python/_hmath_native/matrix_advanced.py @@ -0,0 +1,377 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Matrix.Advanced public operations and owned records.""" + +from ._linear_base import _invoke + + +def generate_matrix(index1, index2, function3, *, dtype=None): + "Given row count, column count, then zero-based (row,column) generator, construct a row-major matrix. Negative dimensions or Int-size element product overflow return Left MathError. Call original HMath.Matrix.Advanced.generateMatrix :: Int -> Int -> (Int -> Int -> a) -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_generate_matrix", + True, + [["Int"], ["Int"], ["function", ["Int"], ["Int"], ["a"]]], + [index1, index2, function3], + dtype=dtype, + ) + + +def triangular_matrix(flag1, matrix2, *, dtype=None): + "Given lower flag then matrix, preserve entries on/below the diagonal if True, on/above if False, and zero the rest. Rectangular matrices are allowed; return checked construction result. Call original HMath.Matrix.Advanced.triangularMatrix :: Bool -> Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_triangular_matrix", + True, + [["Bool"], ["Matrix", ["a"]]], + [flag1, matrix2], + dtype=dtype, + ) + + +def symmetric_matrix(matrix1, *, dtype=None): + "Return (A+transpose(A))/2 for a square matrix. Non-square input returns NonSquareMatrix; arithmetic follows Fractional. Call original HMath.Matrix.Advanced.symmetricMatrix :: Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_symmetric_matrix", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def hermitian_matrix(matrix1, *, dtype=None): + "Return (A+conjugateTranspose(A))/2 for a square complex matrix. Non-square input fails; this symmetrizes rather than merely asserting the original is Hermitian. Call original HMath.Matrix.Advanced.hermitianMatrix :: Matrix (Complex a) -> Either MathError (Matrix (Complex a))" + return _invoke( + "hmath_linear_matrix_advanced_hermitian_matrix", + True, + [["Matrix", ["Complex", ["a"]]]], + [matrix1], + dtype=dtype, + ) + + +def permutation_matrix(values1, *, dtype=None): + "Given a permutation p of [0..n-1], construct n-by-n P with P[i,p[i]]=1. Duplicate, missing, or out-of-range indices return Left InvalidArgument. Call original HMath.Matrix.Advanced.permutationMatrix :: [Int] -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_permutation_matrix", + True, + [["list", ["Int"]]], + [values1], + dtype=dtype, + ) + + +def block_matrix(values1, *, dtype=None): + "Assemble a rectangular grid of matrix blocks. Require equal heights within each block row and equal widths within each block column. Ragged grids or total-size overflow fail; empty grids yield a 0-by-0 matrix. Call original HMath.Matrix.Advanced.blockMatrix :: [[Matrix a]] -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_block_matrix", + True, + [["list", ["list", ["Matrix", ["a"]]]]], + [values1], + dtype=dtype, + ) + + +def banded_matrix(index1, index2, values3, *, dtype=None): + "Given rows, columns, then (diagonal offset,values) pairs, construct a matrix with zeros elsewhere. Offset k means column-row=k. Each list must match that diagonal's length; duplicates add. Invalid dimensions/counts fail. Call original HMath.Matrix.Advanced.bandedMatrix :: Int -> Int -> [(Int, [a])] -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_banded_matrix", + True, + [["Int"], ["Int"], ["list", ["tuple", ["Int"], ["list", ["a"]]]]], + [index1, index2, values3], + dtype=dtype, + ) + + +def conjugate_transpose(matrix1, *, dtype=None): + "Transpose a complex matrix and conjugate every entry, exchanging its row/column dimensions. Call original HMath.Matrix.Advanced.conjugateTranspose :: Matrix (Complex a) -> Matrix (Complex a)" + return _invoke( + "hmath_linear_matrix_advanced_conjugate_transpose", + True, + [["Matrix", ["Complex", ["a"]]]], + [matrix1], + dtype=dtype, + ) + + +def zip_matrix_with(function1, matrix2, matrix3, *, dtype=None): + "Given elementwise function and two identically shaped matrices, apply it to corresponding entries and return a new matrix. Mismatched shapes return ShapeMismatch. Call original HMath.Matrix.Advanced.zipMatrixWith :: (a -> b -> c) -> Matrix a -> Matrix b -> Either MathError (Matrix c)" + return _invoke( + "hmath_linear_matrix_advanced_zip_matrix_with", + True, + [["function", ["a"], ["b"], ["c"]], ["Matrix", ["a"]], ["Matrix", ["b"]]], + [function1, matrix2, matrix3], + dtype=dtype, + ) + + +def batched_multiply(values1, values2, *, dtype=None): + "Multiply pairs of matrices from equally long lists, preserving batch order. Different batch lengths or any checked multiplication failure return Left MathError. Call original HMath.Matrix.Advanced.batchedMultiply :: [Matrix a] -> [Matrix a] -> Either MathError [Matrix a]" + return _invoke( + "hmath_linear_matrix_advanced_batched_multiply", + True, + [["list", ["Matrix", ["a"]]], ["list", ["Matrix", ["a"]]]], + [values1, values2], + dtype=dtype, + ) + + +def kronecker(matrix1, matrix2, *, dtype=None): + "Return the block Kronecker product of matrices A and B, of shape (Arows*Brows,Acols*Bcols). Reject dimension/element-count overflow. Call original HMath.Matrix.Advanced.kronecker :: Matrix a -> Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_kronecker", + True, + [["Matrix", ["a"]], ["Matrix", ["a"]]], + [matrix1, matrix2], + dtype=dtype, + ) + + +def khatri_rao(matrix1, matrix2, *, dtype=None): + "Return columnwise Kronecker product, requiring equal column counts. Shape is (Arows*Brows,columns); mismatched columns or dimension overflow fail. Call original HMath.Matrix.Advanced.khatriRao :: Matrix a -> Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_khatri_rao", + True, + [["Matrix", ["a"]], ["Matrix", ["a"]]], + [matrix1, matrix2], + dtype=dtype, + ) + + +def matrix_power(integer1, matrix2, *, dtype=None): + "Given Integer exponent then square real matrix, compute power by squaring. Zero yields identity; negative exponent inverts first. Non-square/singular input or multiplication errors propagate. Call original HMath.Matrix.Advanced.matrixPower :: Integer -> Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_power", + True, + [["Integer"], ["Matrix", ["a"]]], + [integer1, matrix2], + dtype=dtype, + ) + + +def trace(matrix1, *, dtype=None): + "Return sum of main diagonal of a square matrix; non-square input returns NonSquareMatrix. A 0-by-0 matrix has trace zero. Call original HMath.Matrix.Advanced.trace :: Matrix a -> Either MathError a" + return _invoke( + "hmath_linear_matrix_advanced_trace", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def matrix_norm1(matrix1, *, dtype=None): + "Return maximum absolute column sum (induced one norm). Empty dimensions give zero; no finiteness check is added. Call original HMath.Matrix.Advanced.matrixNorm1 :: Matrix a -> a" + return _invoke( + "hmath_linear_matrix_advanced_matrix_norm1", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def matrix_norm_infinity(matrix1, *, dtype=None): + "Return maximum absolute row sum (induced infinity norm). A matrix with no elements gives zero. Call original HMath.Matrix.Advanced.matrixNormInfinity :: Matrix a -> a" + return _invoke( + "hmath_linear_matrix_advanced_matrix_norm_infinity", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def frobenius_norm(matrix1, *, dtype=None): + "Return scaled Euclidean norm of all entries, reducing intermediate overflow; empty matrix norm is zero. No Either result is added. Call original HMath.Matrix.Advanced.frobeniusNorm :: Matrix a -> a" + return _invoke( + "hmath_linear_matrix_advanced_frobenius_norm", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def spectral_norm(matrix1): + "Return largest singular value via SVD, or zero for an empty singular spectrum. Invalid input/backend decomposition failures return Left MathError. Call original HMath.Matrix.Advanced.spectralNorm :: Matrix Double -> Either MathError Double" + return _invoke( + "hmath_linear_matrix_advanced_spectral_norm", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def matrix_rank(double1, matrix2): + "Given finite nonnegative relative tolerance then matrix, count positive singular values whose ratio to the largest exceeds tolerance. Zero tolerance counts all positive singular values. Invalid tolerance or SVD failure propagates. Call original HMath.Matrix.Advanced.matrixRank :: Double -> Matrix Double -> Either MathError Int" + return _invoke( + "hmath_linear_matrix_advanced_matrix_rank", + False, + [["Double"], ["Matrix", ["Double"]]], + [double1, matrix2], + ) + + +def pseudoinverse(double1, matrix2): + "Given relative singular-value tolerance then m-by-n matrix, return n-by-m Moore-Penrose pseudoinverse via thresholded SVD. Rectangular/rank-deficient inputs are supported; invalid tolerance or numeric/decomposition failures propagate. Call original HMath.Matrix.Advanced.pseudoinverse :: Double -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_pseudoinverse", + False, + [["Double"], ["Matrix", ["Double"]]], + [double1, matrix2], + ) + + +def condition_number(matrix1): + "Return largest/smallest singular-value ratio; singular matrices yield positive infinity, empty spectrum yields 1. Input/SVD failures return Left MathError. Call original HMath.Matrix.Advanced.conditionNumber :: Matrix Double -> Either MathError Double" + return _invoke( + "hmath_linear_matrix_advanced_condition_number", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def column_space(double1, matrix2): + "Given relative SVD rank tolerance then matrix, return columns of left singular vectors spanning its numerical column space. Invalid tolerance/decomposition errors propagate. Call original HMath.Matrix.Advanced.columnSpace :: Double -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_column_space", + False, + [["Double"], ["Matrix", ["Double"]]], + [double1, matrix2], + ) + + +def row_space(double1, matrix2): + "Given relative rank tolerance then matrix, return a column basis for its row space by applying columnSpace to its transpose. Call original HMath.Matrix.Advanced.rowSpace :: Double -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_row_space", + False, + [["Double"], ["Matrix", ["Double"]]], + [double1, matrix2], + ) + + +def null_space(double1, matrix2): + "Given relative singular-value tolerance then m-by-n matrix, return an n-by-(n-rank) basis for its numerical right null space using full SVD. Invalid tolerance/decomposition failures propagate. Call original HMath.Matrix.Advanced.nullSpace :: Double -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_null_space", + False, + [["Double"], ["Matrix", ["Double"]]], + [double1, matrix2], + ) + + +def change_coordinates(matrix1, matrix2, values3, *, dtype=None): + "Given source basis matrix, target square basis matrix, then source coordinate list, map to physical coordinates and solve in target basis. Shape mismatch, singular target, and checked solve errors propagate. Call original HMath.Matrix.Advanced.changeCoordinates :: Matrix a -> Matrix a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_matrix_advanced_change_coordinates", + True, + [["Matrix", ["a"]], ["Matrix", ["a"]], ["list", ["a"]]], + [matrix1, matrix2, values3], + dtype=dtype, + ) + + +def matrix_exp(scalar1, index2, matrix3, *, dtype=None): + "Given positive finite tolerance, positive iteration budget, then square finite matrix, approximate exp(A) by scaling, Taylor series and squaring. Return NonConvergence on exhausted series budget; input/shape/numerical failures propagate. Call original HMath.Matrix.Advanced.matrixExp :: a -> Int -> Matrix a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_exp", + True, + [["a"], ["Int"], ["Matrix", ["a"]]], + [scalar1, index2, matrix3], + dtype=dtype, + ) + + +def matrix_log(matrix1): + "Compute principal real matrix logarithm of a symmetric positive-definite Double matrix using symmetric eigendecomposition. Reject non-square/asymmetric matrices, nonpositive spectrum, non-real decomposition, or numeric failure. Call original HMath.Matrix.Advanced.matrixLog :: Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_log", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def matrix_sqrt(matrix1): + "Compute symmetric positive-semidefinite matrix square root by spectral decomposition; tolerate eigenvalues down to -1e-12 and clamp them to zero. Invalid shape/symmetry/spectrum or decomposition failure returns Left MathError. Call original HMath.Matrix.Advanced.matrixSqrt :: Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_sqrt", + False, + [["Matrix", ["Double"]]], + [matrix1], + ) + + +def polar(matrix1): + "Return (U,P) from SVD so A=U*P, with P positive semidefinite; rectangular input uses the thin polar factors. Validation/decomposition/multiplication errors propagate. Call original HMath.Matrix.Advanced.polar :: Matrix Double -> Either MathError (Matrix Double, Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_polar", False, [["Matrix", ["Double"]]], [matrix1] + ) + + +def complex_pseudoinverse(double1, matrix2): + "Complex128 Moore-Penrose pseudoinverse, thresholded relative to the largest singular value. Both rectangular and rank-deficient inputs are supported. Call original HMath.Matrix.Advanced.complexPseudoinverse :: Double -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double))" + return _invoke( + "hmath_linear_matrix_advanced_complex_pseudoinverse", + False, + [["Double"], ["Matrix", ["Complex", ["Double"]]]], + [double1, matrix2], + ) + + +def matrix_sqrt_general(double1, index2, matrix3): + "Principal square root for invertible real matrices whose spectra avoid the nonpositive real axis. This nonsymmetric reference method uses scaled Denman-Beavers iteration with private inverse solves. The budget bounds the number of coupled iterations; failure to meet the reconstruction tolerance returns NonConvergence. Ill-conditioned inverse steps may report a LU error. The existing matrixSqrt additionally handles symmetric singular PSD inputs. Call original HMath.Matrix.Advanced.matrixSqrtGeneral :: Double -> Int -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_sqrt_general", + False, + [["Double"], ["Int"], ["Matrix", ["Double"]]], + [double1, index2, matrix3], + ) + + +def matrix_log_general(double1, index2, matrix3): + "Real principal matrix logarithm on the same spectral domain as matrixSqrtGeneral. Inverse scaling by successive principal square roots makes the Mercator series converge in matrix 1-norm. The budget bounds each phase: root reductions, each inner Denman-Beavers solve, series terms, and the final exponential reconstruction check. There is no unbounded convergence loop. Call original HMath.Matrix.Advanced.matrixLogGeneral :: Double -> Int -> Matrix Double -> Either MathError (Matrix Double)" + return _invoke( + "hmath_linear_matrix_advanced_matrix_log_general", + False, + [["Double"], ["Int"], ["Matrix", ["Double"]]], + [double1, index2, matrix3], + ) + + +__all__ = [ + "banded_matrix", + "batched_multiply", + "block_matrix", + "change_coordinates", + "column_space", + "complex_pseudoinverse", + "condition_number", + "conjugate_transpose", + "frobenius_norm", + "generate_matrix", + "hermitian_matrix", + "khatri_rao", + "kronecker", + "matrix_exp", + "matrix_log", + "matrix_log_general", + "matrix_norm1", + "matrix_norm_infinity", + "matrix_power", + "matrix_rank", + "matrix_sqrt", + "matrix_sqrt_general", + "null_space", + "permutation_matrix", + "polar", + "pseudoinverse", + "row_space", + "spectral_norm", + "symmetric_matrix", + "trace", + "triangular_matrix", + "zip_matrix_with", +] diff --git a/bindings/python/_hmath_native/numbertheory.py b/bindings/python/_hmath_native/numbertheory.py new file mode 100644 index 0000000..a9bc86f --- /dev/null +++ b/bindings/python/_hmath_native/numbertheory.py @@ -0,0 +1,486 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def gcd_integer(argument1, argument2): + """Call HMath.NumberTheory.gcdInteger; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_gcd_integer', + ['z', 'z'], + 'z', + [argument1, argument2], + None, + 0, + ) + + +def lcm_integer(argument1, argument2): + """Call HMath.NumberTheory.lcmInteger; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_lcm_integer', + ['z', 'z'], + 'z', + [argument1, argument2], + None, + 0, + ) + + +def extended_g_c_d(a, b): + """Call HMath.NumberTheory.extendedGCD; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_extended_g_c_d', + ['z', 'z'], + 'zzz', + [a, b], + None, + 0, + ) + + +def bezout(a, b): + """Call HMath.NumberTheory.bezout; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_bezout', + ['z', 'z'], + 'zz', + [a, b], + None, + 0, + ) + + +def mod_pow(a, e, m): + """Call HMath.NumberTheory.modPow; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_mod_pow', + ['z', 'z', 'z'], + 'z', + [a, e, m], + None, + 0, + ) + + +def mod_inverse(a, m): + """Call HMath.NumberTheory.modInverse; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_mod_inverse', + ['z', 'z'], + 'z', + [a, m], + None, + 0, + ) + + +def integer_square_root(n): + """Call HMath.NumberTheory.integerSquareRoot; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_integer_square_root', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def is_prime_exact(budget, n): + """Call HMath.NumberTheory.isPrimeExact; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_is_prime_exact', + ['i', 'z'], + 'b', + [budget, n], + None, + 0, + ) + + +def next_prime(budget, n): + """Call HMath.NumberTheory.nextPrime; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_next_prime', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def miller_rabin(bases, n): + """Call HMath.NumberTheory.millerRabin; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_miller_rabin', + ['zs', 'z'], + 'b', + [bases, n], + None, + 0, + ) + + +def baillie_p_s_w(n): + """Call HMath.NumberTheory.bailliePSW; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_baillie_p_s_w', + ['z'], + 'b', + [n], + None, + 0, + ) + + +def sieve_eratosthenes(bound): + """Call HMath.NumberTheory.sieveEratosthenes; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_sieve_eratosthenes', + ['i'], + 'zd', + [bound], + None, + 0, + ) + + +def sieve_atkin(bound): + """Call HMath.NumberTheory.sieveAtkin; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_sieve_atkin', + ['i'], + 'zd', + [bound], + None, + 0, + ) + + +def segmented_sieve(lo, hi): + """Call HMath.NumberTheory.segmentedSieve; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_segmented_sieve', + ['z', 'z'], + 'zd', + [lo, hi], + None, + 0, + ) + + +def pollard_rho(budget, seed, n): + """Call HMath.NumberTheory.pollardRho; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_pollard_rho', + ['i', 'z', 'z'], + 'z', + [budget, seed, n], + None, + 0, + ) + + +def pollard_p_minus_one(bound, base, n): + """Call HMath.NumberTheory.pollardPMinusOne; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_pollard_p_minus_one', + ['i', 'z', 'z'], + 'z', + [bound, base, n], + None, + 0, + ) + + +def fermat_factor(budget, n): + """Call HMath.NumberTheory.fermatFactor; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_fermat_factor', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def divisors(budget, n): + """Call HMath.NumberTheory.divisors; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_divisors', + ['i', 'z'], + 'zd', + [budget, n], + None, + 0, + ) + + +def divisor_sum(budget, n): + """Call HMath.NumberTheory.divisorSum; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_divisor_sum', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def divisor_count(budget, n): + """Call HMath.NumberTheory.divisorCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_divisor_count', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def euler_totient(budget, n): + """Call HMath.NumberTheory.eulerTotient; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_euler_totient', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def carmichael(budget, n): + """Call HMath.NumberTheory.carmichael; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_carmichael', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def mobius(budget, n): + """Call HMath.NumberTheory.mobius; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_mobius', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def liouville(budget, n): + """Call HMath.NumberTheory.liouville; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_liouville', + ['i', 'z'], + 'z', + [budget, n], + None, + 0, + ) + + +def multiplicative_order(budget, a, m): + """Call HMath.NumberTheory.multiplicativeOrder; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_multiplicative_order', + ['i', 'z', 'z'], + 'z', + [budget, a, m], + None, + 0, + ) + + +def primitive_root(budget, m): + """Call HMath.NumberTheory.primitiveRoot; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_primitive_root', + ['i', 'z'], + 'z', + [budget, m], + None, + 0, + ) + + +def discrete_log(budget, a, b, m): + """Call HMath.NumberTheory.discreteLog; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_discrete_log', + ['i', 'z', 'z', 'z'], + 'z', + [budget, a, b, m], + None, + 0, + ) + + +def legendre_symbol(budget, a, p): + """Call HMath.NumberTheory.legendreSymbol; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_legendre_symbol', + ['i', 'z', 'z'], + 'z', + [budget, a, p], + None, + 0, + ) + + +def jacobi_symbol(a, n): + """Call HMath.NumberTheory.jacobiSymbol; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_jacobi_symbol', + ['z', 'z'], + 'z', + [a, n], + None, + 0, + ) + + +def kronecker_symbol(a, n): + """Call HMath.NumberTheory.kroneckerSymbol; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_kronecker_symbol', + ['z', 'z'], + 'z', + [a, n], + None, + 0, + ) + + +def tonelli_shanks(budget, a, p): + """Call HMath.NumberTheory.tonelliShanks; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_tonelli_shanks', + ['i', 'z', 'z'], + 'z', + [budget, a, p], + None, + 0, + ) + + +def continued_fraction(r): + """Call HMath.NumberTheory.continuedFraction; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_continued_fraction', + ['q'], + 'zd', + [r], + None, + 0, + ) + + +def from_continued_fraction(argument1): + """Call HMath.NumberTheory.fromContinuedFraction; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_from_continued_fraction', + ['zs'], + 'q', + [argument1], + None, + 0, + ) + + +def convergents(xs): + """Call HMath.NumberTheory.convergents; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_convergents', + ['zs'], + 'qd', + [xs], + None, + 0, + ) + + +def farey(n): + """Call HMath.NumberTheory.farey; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_farey', + ['z'], + 'qd', + [n], + None, + 0, + ) + + +def pell_fundamental(budget, d): + """Call HMath.NumberTheory.pellFundamental; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_pell_fundamental', + ['i', 'z'], + 'zz', + [budget, d], + None, + 0, + ) + + +def is_perfect_number(budget, n): + """Call HMath.NumberTheory.isPerfectNumber; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_is_perfect_number', + ['i', 'z'], + 'b', + [budget, n], + None, + 0, + ) + + +def are_amicable(budget, a, b): + """Call HMath.NumberTheory.areAmicable; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_are_amicable', + ['i', 'z', 'z'], + 'b', + [budget, a, b], + None, + 0, + ) + + +def partition_count(n): + """Call HMath.NumberTheory.partitionCount; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_partition_count', + ['i'], + 'z', + [n], + None, + 0, + ) + + +def fibonacci_fast(n): + """Call HMath.NumberTheory.fibonacciFast; preserve its argument order, result and errors.""" + return _call( + 'hmath_numbertheory_fibonacci_fast', + ['z'], + 'z', + [n], + None, + 0, + ) + + +from .numbertheory_extras import * diff --git a/bindings/python/_hmath_native/numbertheory_extras.py b/bindings/python/_hmath_native/numbertheory_extras.py new file mode 100644 index 0000000..0a1b4c8 --- /dev/null +++ b/bindings/python/_hmath_native/numbertheory_extras.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_scalar_extras.py; do not edit. +from ._scalar_extras_base import _invoke + + +def chinese_remainder(congruences): + """HMath.NumberTheory.chineseRemainder :: [(Integer,Integer)] -> Either MathError (Integer,Integer).""" + return _invoke('hmath_numbertheory_chinese_remainder', ['[(Integer,Integer)]'], [congruences], '(Integer,Integer)') + + +def linear_diophantine(a, b, c): + """HMath.NumberTheory.linearDiophantine :: Integer -> Integer -> Integer -> Either MathError (Integer,Integer,Integer,Integer).""" + return _invoke('hmath_numbertheory_linear_diophantine', ['Integer', 'Integer', 'Integer'], [a, b, c], '(Integer,Integer,Integer,Integer)') + + +def perfect_power(value): + """HMath.NumberTheory.perfectPower :: Integer -> Maybe (Integer,Int).""" + return _invoke('hmath_numbertheory_perfect_power', ['Integer'], [value], 'Maybe (Integer,Int)') + + +def prime_factorization(budget, value): + """HMath.NumberTheory.primeFactorization :: Int -> Integer -> Either MathError [(Integer,Int)].""" + return _invoke('hmath_numbertheory_prime_factorization', ['Int', 'Integer'], [budget, value], '[(Integer,Int)]') + + +def partitions(value): + """HMath.NumberTheory.partitions :: Int -> Either MathError [[Int]].""" + return _invoke('hmath_numbertheory_partitions', ['Int'], [value], '[[Int]]') + + +__all__ = [ + "chinese_remainder", + "linear_diophantine", + "partitions", + "perfect_power", + "prime_factorization" +] diff --git a/bindings/python/_hmath_native/numeric.py b/bindings/python/_hmath_native/numeric.py new file mode 100644 index 0000000..e5f2215 --- /dev/null +++ b/bindings/python/_hmath_native/numeric.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def next_after(argument1, argument2, *, dtype='float64'): + """Call HMath.Numeric.nextAfter; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_next_after', + ['f', 'f'], + 'f', + [argument1, argument2], + dtype, + 0, + ) + + +def ldexp(argument1, argument2, *, dtype='float64'): + """Call HMath.Numeric.ldexp; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_ldexp', + ['f', 'i'], + 'f', + [argument1, argument2], + dtype, + 0, + ) + + +def ulp_distance(a, b, *, dtype='float64'): + """Call HMath.Numeric.ulpDistance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_numeric_ulp_distance', + ['f', 'f'], + 'z', + [a, b], + dtype, + 0, + ) + + +def within_u_l_ps(n, a, b, *, dtype='float64'): + """Call HMath.Numeric.withinULPs; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_numeric_within_u_l_ps', + ['z', 'f', 'f'], + 'b', + [n, a, b], + dtype, + 0, + ) + + +def kahan_sum(argument1, *, dtype='float64'): + """Call HMath.Numeric.kahanSum; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_kahan_sum', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def neumaier_sum(argument1, *, dtype='float64'): + """Call HMath.Numeric.neumaierSum; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_neumaier_sum', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def pairwise_sum(argument1, *, dtype='float64'): + """Call HMath.Numeric.pairwiseSum; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_pairwise_sum', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def logsumexp(argument1, *, dtype='float64'): + """Call HMath.Numeric.logsumexp; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_logsumexp', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def sum_error_bound(argument1, *, dtype='float64'): + """Call HMath.Numeric.sumErrorBound; preserve its argument order, result and errors.""" + return _call( + 'hmath_numeric_sum_error_bound', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/numeric_types.py b/bindings/python/_hmath_native/numeric_types.py new file mode 100644 index 0000000..6222096 --- /dev/null +++ b/bindings/python/_hmath_native/numeric_types.py @@ -0,0 +1,927 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_types.py; do not edit. +"""Original HMath.Numeric types and Constants records. + +Factories return immutable owned NumericValue objects for structured types. +Standard scalar results decode to Python numbers; use boxed properties +on NumericValue when preserving a scalar dtype through callbacks. +""" +from ._numeric_types_runtime import ( + IEEEClass, + NumericException, + NumericValue, + RoundingMode, + _call_named, + number, +) + +_SIGNATURES = { + "type_name": [ + "o" + ], + "binary": [ + "i32", + "o", + "o" + ], + "unary": [ + "i32", + "o" + ], + "literal_integer": [ + "o", + "z" + ], + "literal_rational": [ + "o", + "q" + ], + "integer_power": [ + "o", + "z" + ], + "equal": [ + "o", + "o" + ], + "sequence_get": [ + "o", + "i" + ], + "round_rational": [ + "mode", + "q" + ], + "classify": [ + "o" + ], + "frexp": [ + "o" + ], + "numeric_limits": [ + "o" + ], + "integer_limits": [ + "o" + ], + "float16_limits": [], + "bfloat16_limits": [], + "numeric_limits_record": [ + "o", + "o", + "o", + "o", + "i", + "i", + "i" + ], + "minimum_normal": [ + "o" + ], + "minimum_subnormal": [ + "o" + ], + "maximum_finite": [ + "o" + ], + "machine_epsilon": [ + "o" + ], + "significand_digits": [ + "o" + ], + "minimum_exponent": [ + "o" + ], + "maximum_exponent": [ + "o" + ], + "safe_integral_cast": [ + "o", + "i32" + ], + "saturating_cast": [ + "o", + "i32" + ], + "real_to_integral": [ + "mode", + "o", + "i32" + ], + "narrow_float": [ + "o", + "i32" + ], + "float16": [ + "mode", + "f64" + ], + "bfloat16": [ + "mode", + "f64" + ], + "float16_from_bits": [ + "u16" + ], + "bfloat16_from_bits": [ + "u16" + ], + "float16_bits": [ + "half" + ], + "bfloat16_bits": [ + "bhalf" + ], + "from_float16": [ + "half" + ], + "from_bfloat16": [ + "bhalf" + ], + "rounded": [ + "o", + "flags" + ], + "rounded_value": [ + "o" + ], + "numerical_exceptions": [ + "o" + ], + "big_float": [ + "i", + "mode", + "q" + ], + "extended": [ + "q" + ], + "big_precision": [ + "big" + ], + "big_rational": [ + "big" + ], + "big_to_double": [ + "big" + ], + "big_add": [ + "big", + "big" + ], + "big_subtract": [ + "big", + "big" + ], + "big_multiply": [ + "big", + "big" + ], + "big_divide": [ + "big", + "big" + ], + "big_sqrt": [ + "big" + ], + "big_exp": [ + "big" + ], + "big_log": [ + "big" + ], + "mixed_add": [ + "big", + "f64" + ], + "mixed_multiply": [ + "big", + "f64" + ], + "fixed": [ + "i", + "mode", + "q" + ], + "fixed_rational": [ + "fixed" + ], + "fixed_add": [ + "fixed", + "fixed" + ], + "fixed_multiply": [ + "mode", + "fixed", + "fixed" + ], + "fixed_divide": [ + "mode", + "fixed", + "fixed" + ], + "decimal": [ + "i", + "mode", + "q" + ], + "decimal_rational": [ + "decimal" + ], + "decimal_add": [ + "decimal", + "decimal" + ], + "decimal_multiply": [ + "mode", + "decimal", + "decimal" + ], + "decimal_divide": [ + "mode", + "decimal", + "decimal" + ], + "fixed_scale": [ + "fixed" + ], + "fixed_coefficient": [ + "fixed" + ], + "interval": [ + "f64", + "f64" + ], + "interval_bounds": [ + "interval" + ], + "interval_contains": [ + "interval", + "f64" + ], + "interval_add": [ + "interval", + "interval" + ], + "interval_subtract": [ + "interval", + "interval" + ], + "interval_multiply": [ + "interval", + "interval" + ], + "interval_divide": [ + "interval", + "interval" + ], + "dual": [ + "o", + "o" + ], + "primal": [ + "o" + ], + "tangent": [ + "o" + ], + "derivative": [ + "callback", + "o" + ], + "quaternion": [ + "o", + "o", + "o", + "o" + ], + "quaternion_conjugate": [ + "o" + ], + "quaternion_norm": [ + "o" + ], + "quaternion_inverse": [ + "o" + ], + "quaternion_component": [ + "o", + "i" + ], + "dual_quaternion": [ + "o", + "o" + ], + "dual_quaternion_component": [ + "o", + "i" + ], + "dual_quaternion_multiply": [ + "o", + "o" + ], + "dual_quaternion_inverse": [ + "o" + ], + "rotate_vector": [ + "o", + "o", + "o", + "o" + ], + "rigid_transform": [ + "o", + "o", + "o", + "o" + ], + "transform_point": [ + "o", + "o", + "o", + "o" + ], + "constant": [ + "text", + "q", + "q", + "q", + "text", + "text" + ], + "constant_name": [ + "o" + ], + "constant_value": [ + "o" + ], + "standard_uncertainty": [ + "o" + ], + "approximation_bound": [ + "o" + ], + "constant_unit": [ + "o" + ], + "constant_source": [ + "o" + ], + "constant_as": [ + "o", + "i32" + ], + "constant_as_like": [ + "o", + "o" + ], + "mathematical_constants": [], + "physical_constants": [], + "speed_of_light": [], + "planck_constant": [], + "elementary_charge": [], + "boltzmann_constant": [], + "avogadro_constant": [], + "gravitational_constant": [], + "electron_mass": [], + "astronomical_unit": [] +} + +def type_name(value, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('type_name', [value], raw=boxed) + +def binary(operation, a, b, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('binary', [operation, a, b], raw=boxed) + +def unary(operation, value, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('unary', [operation, value], raw=boxed) + +def literal_integer(like, value, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('literal_integer', [like, value], raw=boxed) + +def literal_rational(like, value, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('literal_rational', [like, value], raw=boxed) + +def integer_power(value, power, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('integer_power', [value, power], raw=boxed) + +def equal(a, b, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('equal', [a, b], raw=boxed) + +def sequence_get(value, index, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('sequence_get', [value, index], raw=boxed) + +def round_rational(mode, value, *, boxed=False): + """HMath.Numeric.roundRational; retains the original type/rounding/error contract.""" + return _call_named('round_rational', [mode, value], raw=boxed) + +def classify(value, *, boxed=False): + """HMath.Numeric.classify; retains the original type/rounding/error contract.""" + return _call_named('classify', [value], raw=boxed) + +def frexp(value, *, boxed=False): + """HMath.Numeric.frexp; retains the original type/rounding/error contract.""" + return _call_named('frexp', [value], raw=boxed) + +def numeric_limits(value, *, boxed=False): + """HMath.Numeric.numericLimits; retains the original type/rounding/error contract.""" + return _call_named('numeric_limits', [value], raw=boxed) + +def integer_limits(value, *, boxed=False): + """HMath.Numeric.integerLimits; retains the original type/rounding/error contract.""" + return _call_named('integer_limits', [value], raw=boxed) + +def float16_limits(*, boxed=False): + """HMath.Numeric.float16Limits; retains the original type/rounding/error contract.""" + return _call_named('float16_limits', [], raw=boxed) + +def bfloat16_limits(*, boxed=False): + """HMath.Numeric.bfloat16Limits; retains the original type/rounding/error contract.""" + return _call_named('bfloat16_limits', [], raw=boxed) + +def numeric_limits_record(normal, subnormal, maximum_value, epsilon, digits, low, high, *, boxed=False): + """HMath.Numeric.NumericLimits; retains the original type/rounding/error contract.""" + return _call_named('numeric_limits_record', [normal, subnormal, maximum_value, epsilon, digits, low, high], raw=boxed) + +def minimum_normal(value, *, boxed=False): + """HMath.Numeric.minimumNormal; retains the original type/rounding/error contract.""" + return _call_named('minimum_normal', [value], raw=boxed) + +def minimum_subnormal(value, *, boxed=False): + """HMath.Numeric.minimumSubnormal; retains the original type/rounding/error contract.""" + return _call_named('minimum_subnormal', [value], raw=boxed) + +def maximum_finite(value, *, boxed=False): + """HMath.Numeric.maximumFinite; retains the original type/rounding/error contract.""" + return _call_named('maximum_finite', [value], raw=boxed) + +def machine_epsilon(value, *, boxed=False): + """HMath.Numeric.machineEpsilon; retains the original type/rounding/error contract.""" + return _call_named('machine_epsilon', [value], raw=boxed) + +def significand_digits(value, *, boxed=False): + """HMath.Numeric.significandDigits; retains the original type/rounding/error contract.""" + return _call_named('significand_digits', [value], raw=boxed) + +def minimum_exponent(value, *, boxed=False): + """HMath.Numeric.minimumExponent; retains the original type/rounding/error contract.""" + return _call_named('minimum_exponent', [value], raw=boxed) + +def maximum_exponent(value, *, boxed=False): + """HMath.Numeric.maximumExponent; retains the original type/rounding/error contract.""" + return _call_named('maximum_exponent', [value], raw=boxed) + +def safe_integral_cast(value, dtype, *, boxed=False): + """HMath.Numeric.safeIntegralCast; retains the original type/rounding/error contract.""" + return _call_named('safe_integral_cast', [value, dtype], raw=boxed) + +def saturating_cast(value, dtype, *, boxed=False): + """HMath.Numeric.saturatingCast; retains the original type/rounding/error contract.""" + return _call_named('saturating_cast', [value, dtype], raw=boxed) + +def real_to_integral(mode, value, dtype, *, boxed=False): + """HMath.Numeric.realToIntegral; retains the original type/rounding/error contract.""" + return _call_named('real_to_integral', [mode, value, dtype], raw=boxed) + +def narrow_float(value, dtype, *, boxed=False): + """HMath.Numeric.narrowFloat; retains the original type/rounding/error contract.""" + return _call_named('narrow_float', [value, dtype], raw=boxed) + +def float16(mode, value, *, boxed=False): + """HMath.Numeric.float16; retains the original type/rounding/error contract.""" + return _call_named('float16', [mode, value], raw=boxed) + +def bfloat16(mode, value, *, boxed=False): + """HMath.Numeric.bfloat16; retains the original type/rounding/error contract.""" + return _call_named('bfloat16', [mode, value], raw=boxed) + +def float16_from_bits(bits, *, boxed=False): + """HMath.Numeric.float16FromBits; retains the original type/rounding/error contract.""" + return _call_named('float16_from_bits', [bits], raw=boxed) + +def bfloat16_from_bits(bits, *, boxed=False): + """HMath.Numeric.bfloat16FromBits; retains the original type/rounding/error contract.""" + return _call_named('bfloat16_from_bits', [bits], raw=boxed) + +def float16_bits(value, *, boxed=False): + """HMath.Numeric.float16Bits; retains the original type/rounding/error contract.""" + return _call_named('float16_bits', [value], raw=boxed) + +def bfloat16_bits(value, *, boxed=False): + """HMath.Numeric.bfloat16Bits; retains the original type/rounding/error contract.""" + return _call_named('bfloat16_bits', [value], raw=boxed) + +def from_float16(value, *, boxed=False): + """HMath.Numeric.fromFloat16; retains the original type/rounding/error contract.""" + return _call_named('from_float16', [value], raw=boxed) + +def from_bfloat16(value, *, boxed=False): + """HMath.Numeric.fromBFloat16; retains the original type/rounding/error contract.""" + return _call_named('from_bfloat16', [value], raw=boxed) + +def rounded(value, flags, *, boxed=False): + """HMath.Numeric.Rounded; retains the original type/rounding/error contract.""" + return _call_named('rounded', [value, flags], raw=boxed) + +def rounded_value(value, *, boxed=False): + """HMath.Numeric.roundedValue; retains the original type/rounding/error contract.""" + return _call_named('rounded_value', [value], raw=boxed) + +def numerical_exceptions(value, *, boxed=False): + """HMath.Numeric.numericalExceptions; retains the original type/rounding/error contract.""" + return _call_named('numerical_exceptions', [value], raw=boxed) + +def big_float(precision, mode, value, *, boxed=False): + """HMath.Numeric.bigFloat; retains the original type/rounding/error contract.""" + return _call_named('big_float', [precision, mode, value], raw=boxed) + +def extended(value, *, boxed=False): + """HMath.Numeric.extended; retains the original type/rounding/error contract.""" + return _call_named('extended', [value], raw=boxed) + +def big_precision(value, *, boxed=False): + """HMath.Numeric.bigPrecision; retains the original type/rounding/error contract.""" + return _call_named('big_precision', [value], raw=boxed) + +def big_rational(value, *, boxed=False): + """HMath.Numeric.bigRational; retains the original type/rounding/error contract.""" + return _call_named('big_rational', [value], raw=boxed) + +def big_to_double(value, *, boxed=False): + """HMath.Numeric.bigToDouble; retains the original type/rounding/error contract.""" + return _call_named('big_to_double', [value], raw=boxed) + +def big_add(a, b, *, boxed=False): + """HMath.Numeric.bigAdd; retains the original type/rounding/error contract.""" + return _call_named('big_add', [a, b], raw=boxed) + +def big_subtract(a, b, *, boxed=False): + """HMath.Numeric.bigSubtract; retains the original type/rounding/error contract.""" + return _call_named('big_subtract', [a, b], raw=boxed) + +def big_multiply(a, b, *, boxed=False): + """HMath.Numeric.bigMultiply; retains the original type/rounding/error contract.""" + return _call_named('big_multiply', [a, b], raw=boxed) + +def big_divide(a, b, *, boxed=False): + """HMath.Numeric.bigDivide; retains the original type/rounding/error contract.""" + return _call_named('big_divide', [a, b], raw=boxed) + +def big_sqrt(value, *, boxed=False): + """HMath.Numeric.bigSqrt; retains the original type/rounding/error contract.""" + return _call_named('big_sqrt', [value], raw=boxed) + +def big_exp(value, *, boxed=False): + """HMath.Numeric.bigExp; retains the original type/rounding/error contract.""" + return _call_named('big_exp', [value], raw=boxed) + +def big_log(value, *, boxed=False): + """HMath.Numeric.bigLog; retains the original type/rounding/error contract.""" + return _call_named('big_log', [value], raw=boxed) + +def mixed_add(a, b, *, boxed=False): + """HMath.Numeric.mixedAdd; retains the original type/rounding/error contract.""" + return _call_named('mixed_add', [a, b], raw=boxed) + +def mixed_multiply(a, b, *, boxed=False): + """HMath.Numeric.mixedMultiply; retains the original type/rounding/error contract.""" + return _call_named('mixed_multiply', [a, b], raw=boxed) + +def fixed(scale, mode, value, *, boxed=False): + """HMath.Numeric.fixed; retains the original type/rounding/error contract.""" + return _call_named('fixed', [scale, mode, value], raw=boxed) + +def fixed_rational(value, *, boxed=False): + """HMath.Numeric.fixedRational; retains the original type/rounding/error contract.""" + return _call_named('fixed_rational', [value], raw=boxed) + +def fixed_add(a, b, *, boxed=False): + """HMath.Numeric.fixedAdd; retains the original type/rounding/error contract.""" + return _call_named('fixed_add', [a, b], raw=boxed) + +def fixed_multiply(mode, a, b, *, boxed=False): + """HMath.Numeric.fixedMultiply; retains the original type/rounding/error contract.""" + return _call_named('fixed_multiply', [mode, a, b], raw=boxed) + +def fixed_divide(mode, a, b, *, boxed=False): + """HMath.Numeric.fixedDivide; retains the original type/rounding/error contract.""" + return _call_named('fixed_divide', [mode, a, b], raw=boxed) + +def decimal(scale, mode, value, *, boxed=False): + """HMath.Numeric.decimal; retains the original type/rounding/error contract.""" + return _call_named('decimal', [scale, mode, value], raw=boxed) + +def decimal_rational(value, *, boxed=False): + """HMath.Numeric.decimalRational; retains the original type/rounding/error contract.""" + return _call_named('decimal_rational', [value], raw=boxed) + +def decimal_add(a, b, *, boxed=False): + """HMath.Numeric.decimalAdd; retains the original type/rounding/error contract.""" + return _call_named('decimal_add', [a, b], raw=boxed) + +def decimal_multiply(mode, a, b, *, boxed=False): + """HMath.Numeric.decimalMultiply; retains the original type/rounding/error contract.""" + return _call_named('decimal_multiply', [mode, a, b], raw=boxed) + +def decimal_divide(mode, a, b, *, boxed=False): + """HMath.Numeric.decimalDivide; retains the original type/rounding/error contract.""" + return _call_named('decimal_divide', [mode, a, b], raw=boxed) + +def fixed_scale(value, *, boxed=False): + """HMath.Numeric.fixedScale; retains the original type/rounding/error contract.""" + return _call_named('fixed_scale', [value], raw=boxed) + +def fixed_coefficient(value, *, boxed=False): + """HMath.Numeric.fixedCoefficient; retains the original type/rounding/error contract.""" + return _call_named('fixed_coefficient', [value], raw=boxed) + +def interval(low, high, *, boxed=False): + """HMath.Numeric.interval; retains the original type/rounding/error contract.""" + return _call_named('interval', [low, high], raw=boxed) + +def interval_bounds(value, *, boxed=False): + """HMath.Numeric.intervalBounds; retains the original type/rounding/error contract.""" + return _call_named('interval_bounds', [value], raw=boxed) + +def interval_contains(value, point, *, boxed=False): + """HMath.Numeric.intervalContains; retains the original type/rounding/error contract.""" + return _call_named('interval_contains', [value, point], raw=boxed) + +def interval_add(a, b, *, boxed=False): + """HMath.Numeric.intervalAdd; retains the original type/rounding/error contract.""" + return _call_named('interval_add', [a, b], raw=boxed) + +def interval_subtract(a, b, *, boxed=False): + """HMath.Numeric.intervalSubtract; retains the original type/rounding/error contract.""" + return _call_named('interval_subtract', [a, b], raw=boxed) + +def interval_multiply(a, b, *, boxed=False): + """HMath.Numeric.intervalMultiply; retains the original type/rounding/error contract.""" + return _call_named('interval_multiply', [a, b], raw=boxed) + +def interval_divide(a, b, *, boxed=False): + """HMath.Numeric.intervalDivide; retains the original type/rounding/error contract.""" + return _call_named('interval_divide', [a, b], raw=boxed) + +def dual(primal_value, tangent_value, *, boxed=False): + """HMath.Numeric.Dual; retains the original type/rounding/error contract.""" + return _call_named('dual', [primal_value, tangent_value], raw=boxed) + +def primal(value, *, boxed=False): + """HMath.Numeric.primal; retains the original type/rounding/error contract.""" + return _call_named('primal', [value], raw=boxed) + +def tangent(value, *, boxed=False): + """HMath.Numeric.tangent; retains the original type/rounding/error contract.""" + return _call_named('tangent', [value], raw=boxed) + +def derivative(function, value, *, boxed=False): + """HMath.Numeric.derivative; retains the original type/rounding/error contract.""" + return _call_named('derivative', [function, value], raw=boxed) + +def quaternion(real, i, j, k, *, boxed=False): + """HMath.Numeric.Quaternion; retains the original type/rounding/error contract.""" + return _call_named('quaternion', [real, i, j, k], raw=boxed) + +def quaternion_conjugate(value, *, boxed=False): + """HMath.Numeric.quaternionConjugate; retains the original type/rounding/error contract.""" + return _call_named('quaternion_conjugate', [value], raw=boxed) + +def quaternion_norm(value, *, boxed=False): + """HMath.Numeric.quaternionNorm; retains the original type/rounding/error contract.""" + return _call_named('quaternion_norm', [value], raw=boxed) + +def quaternion_inverse(value, *, boxed=False): + """HMath.Numeric.quaternionInverse; retains the original type/rounding/error contract.""" + return _call_named('quaternion_inverse', [value], raw=boxed) + +def quaternion_component(value, index, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('quaternion_component', [value, index], raw=boxed) + +def dual_quaternion(real, dual, *, boxed=False): + """HMath.Numeric.DualQuaternion; retains the original type/rounding/error contract.""" + return _call_named('dual_quaternion', [real, dual], raw=boxed) + +def dual_quaternion_component(value, index, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('dual_quaternion_component', [value, index], raw=boxed) + +def dual_quaternion_multiply(a, b, *, boxed=False): + """HMath.Numeric.dualQuaternionMultiply; retains the original type/rounding/error contract.""" + return _call_named('dual_quaternion_multiply', [a, b], raw=boxed) + +def dual_quaternion_inverse(value, *, boxed=False): + """HMath.Numeric.dualQuaternionInverse; retains the original type/rounding/error contract.""" + return _call_named('dual_quaternion_inverse', [value], raw=boxed) + +def rotate_vector(value, x, y, z, *, boxed=False): + """HMath.Numeric.rotateVector; retains the original type/rounding/error contract.""" + return _call_named('rotate_vector', [value, x, y, z], raw=boxed) + +def rigid_transform(value, x, y, z, *, boxed=False): + """HMath.Numeric.rigidTransform; retains the original type/rounding/error contract.""" + return _call_named('rigid_transform', [value, x, y, z], raw=boxed) + +def transform_point(value, x, y, z, *, boxed=False): + """HMath.Numeric.transformPoint; retains the original type/rounding/error contract.""" + return _call_named('transform_point', [value, x, y, z], raw=boxed) + +def constant(name, value, uncertainty, approximation, unit, source, *, boxed=False): + """HMath.Constants.Constant; retains the original type/rounding/error contract.""" + return _call_named('constant', [name, value, uncertainty, approximation, unit, source], raw=boxed) + +def constant_name(value, *, boxed=False): + """HMath.Constants.constantName; retains the original type/rounding/error contract.""" + return _call_named('constant_name', [value], raw=boxed) + +def constant_value(value, *, boxed=False): + """HMath.Constants.constantValue; retains the original type/rounding/error contract.""" + return _call_named('constant_value', [value], raw=boxed) + +def standard_uncertainty(value, *, boxed=False): + """HMath.Constants.standardUncertainty; retains the original type/rounding/error contract.""" + return _call_named('standard_uncertainty', [value], raw=boxed) + +def approximation_bound(value, *, boxed=False): + """HMath.Constants.approximationBound; retains the original type/rounding/error contract.""" + return _call_named('approximation_bound', [value], raw=boxed) + +def constant_unit(value, *, boxed=False): + """HMath.Constants.constantUnit; retains the original type/rounding/error contract.""" + return _call_named('constant_unit', [value], raw=boxed) + +def constant_source(value, *, boxed=False): + """HMath.Constants.constantSource; retains the original type/rounding/error contract.""" + return _call_named('constant_source', [value], raw=boxed) + +def constant_as(value, dtype, *, boxed=False): + """HMath.Constants.constantAs; retains the original type/rounding/error contract.""" + return _call_named('constant_as', [value, dtype], raw=boxed) + +def constant_as_like(value, prototype, *, boxed=False): + """Typed representation helper; no alternate numerical algorithm.""" + return _call_named('constant_as_like', [value, prototype], raw=boxed) + +def mathematical_constants(*, boxed=False): + """HMath.Constants.mathematicalConstants; retains the original type/rounding/error contract.""" + return _call_named('mathematical_constants', [], raw=boxed) + +def physical_constants(*, boxed=False): + """HMath.Constants.physicalConstants; retains the original type/rounding/error contract.""" + return _call_named('physical_constants', [], raw=boxed) + +def speed_of_light(*, boxed=False): + """HMath.Constants.speedOfLight; retains the original type/rounding/error contract.""" + return _call_named('speed_of_light', [], raw=boxed) + +def planck_constant(*, boxed=False): + """HMath.Constants.planckConstant; retains the original type/rounding/error contract.""" + return _call_named('planck_constant', [], raw=boxed) + +def elementary_charge(*, boxed=False): + """HMath.Constants.elementaryCharge; retains the original type/rounding/error contract.""" + return _call_named('elementary_charge', [], raw=boxed) + +def boltzmann_constant(*, boxed=False): + """HMath.Constants.boltzmannConstant; retains the original type/rounding/error contract.""" + return _call_named('boltzmann_constant', [], raw=boxed) + +def avogadro_constant(*, boxed=False): + """HMath.Constants.avogadroConstant; retains the original type/rounding/error contract.""" + return _call_named('avogadro_constant', [], raw=boxed) + +def gravitational_constant(*, boxed=False): + """HMath.Constants.gravitationalConstant; retains the original type/rounding/error contract.""" + return _call_named('gravitational_constant', [], raw=boxed) + +def electron_mass(*, boxed=False): + """HMath.Constants.electronMass; retains the original type/rounding/error contract.""" + return _call_named('electron_mass', [], raw=boxed) + +def astronomical_unit(*, boxed=False): + """HMath.Constants.astronomicalUnit; retains the original type/rounding/error contract.""" + return _call_named('astronomical_unit', [], raw=boxed) + +__all__ = [ + "IEEEClass", + "NumericException", + "NumericValue", + "RoundingMode", + "approximation_bound", + "astronomical_unit", + "avogadro_constant", + "bfloat16", + "bfloat16_bits", + "bfloat16_from_bits", + "bfloat16_limits", + "big_add", + "big_divide", + "big_exp", + "big_float", + "big_log", + "big_multiply", + "big_precision", + "big_rational", + "big_sqrt", + "big_subtract", + "big_to_double", + "binary", + "boltzmann_constant", + "classify", + "constant", + "constant_as", + "constant_as_like", + "constant_name", + "constant_source", + "constant_unit", + "constant_value", + "decimal", + "decimal_add", + "decimal_divide", + "decimal_multiply", + "decimal_rational", + "derivative", + "dual", + "dual_quaternion", + "dual_quaternion_component", + "dual_quaternion_inverse", + "dual_quaternion_multiply", + "electron_mass", + "elementary_charge", + "equal", + "extended", + "fixed", + "fixed_add", + "fixed_coefficient", + "fixed_divide", + "fixed_multiply", + "fixed_rational", + "fixed_scale", + "float16", + "float16_bits", + "float16_from_bits", + "float16_limits", + "frexp", + "from_bfloat16", + "from_float16", + "gravitational_constant", + "integer_limits", + "integer_power", + "interval", + "interval_add", + "interval_bounds", + "interval_contains", + "interval_divide", + "interval_multiply", + "interval_subtract", + "literal_integer", + "literal_rational", + "machine_epsilon", + "mathematical_constants", + "maximum_exponent", + "maximum_finite", + "minimum_exponent", + "minimum_normal", + "minimum_subnormal", + "mixed_add", + "mixed_multiply", + "narrow_float", + "number", + "numeric_limits", + "numeric_limits_record", + "numerical_exceptions", + "physical_constants", + "planck_constant", + "primal", + "quaternion", + "quaternion_component", + "quaternion_conjugate", + "quaternion_inverse", + "quaternion_norm", + "real_to_integral", + "rigid_transform", + "rotate_vector", + "round_rational", + "rounded", + "rounded_value", + "safe_integral_cast", + "saturating_cast", + "sequence_get", + "significand_digits", + "speed_of_light", + "standard_uncertainty", + "tangent", + "transform_point", + "type_name", + "unary" +] diff --git a/bindings/python/_hmath_native/ode.py b/bindings/python/_hmath_native/ode.py new file mode 100644 index 0000000..fca3790 --- /dev/null +++ b/bindings/python/_hmath_native/ode.py @@ -0,0 +1,300 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numerical_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Method(Value): + """Owned immutable original HMath.ODE.Method.""" + + +register(212, Method) + + +class ODEOptions(Value): + """Owned immutable original HMath.ODE.ODEOptions.""" + + +register(213, ODEOptions) + + +class Trajectory(Value): + """Owned immutable original HMath.ODE.Trajectory.""" + + +register(214, Trajectory) + + +class EventDirection(Value): + """Owned immutable original HMath.ODE.EventDirection.""" + + +register(215, EventDirection) + + +class Event(Value): + """Owned immutable original HMath.ODE.Event.""" + + +register(216, Event) + + +class HamiltonianMethod(Value): + """Owned immutable original HMath.ODE.HamiltonianMethod.""" + + +register(217, HamiltonianMethod) + + +from typing import Callable as _Callable +ODE = _Callable[[float, list[float]], list[float]] + + +def euler(): + """HMath.ODE.Euler :: Method.""" + return _invoke('hmath_ode_euler', [], []) + + +def heun(): + """HMath.ODE.Heun :: Method.""" + return _invoke('hmath_ode_heun', [], []) + + +def midpoint(): + """HMath.ODE.Midpoint :: Method.""" + return _invoke('hmath_ode_midpoint', [], []) + + +def rk2(): + """HMath.ODE.RK2 :: Method.""" + return _invoke('hmath_ode_rk2', [], []) + + +def rk4(): + """HMath.ODE.RK4 :: Method.""" + return _invoke('hmath_ode_rk4', [], []) + + +def rk23(): + """HMath.ODE.RK23 :: Method.""" + return _invoke('hmath_ode_rk23', [], []) + + +def rk45(): + """HMath.ODE.RK45 :: Method.""" + return _invoke('hmath_ode_rk45', [], []) + + +def dormand_prince(): + """HMath.ODE.DormandPrince :: Method.""" + return _invoke('hmath_ode_dormand_prince', [], []) + + +def dop853(): + """HMath.ODE.DOP853 :: Method.""" + return _invoke('hmath_ode_dop853', [], []) + + +def adams_bashforth(): + """HMath.ODE.AdamsBashforth :: Method.""" + return _invoke('hmath_ode_adams_bashforth', [], []) + + +def adams_moulton(): + """HMath.ODE.AdamsMoulton :: Method.""" + return _invoke('hmath_ode_adams_moulton', [], []) + + +def predictor_corrector(): + """HMath.ODE.PredictorCorrector :: Method.""" + return _invoke('hmath_ode_predictor_corrector', [], []) + + +def backward_euler(): + """HMath.ODE.BackwardEuler :: Method.""" + return _invoke('hmath_ode_backward_euler', [], []) + + +def bdf(): + """HMath.ODE.BDF :: Method.""" + return _invoke('hmath_ode_bdf', [], []) + + +def radau(): + """HMath.ODE.Radau :: Method.""" + return _invoke('hmath_ode_radau', [], []) + + +def rosenbrock(): + """HMath.ODE.Rosenbrock :: Method.""" + return _invoke('hmath_ode_rosenbrock', [], []) + + +def ode_options(ode_absolute_tolerance, ode_relative_tolerance, initial_step, minimum_step, maximum_step, maximum_steps, newton_iterations): + """HMath.ODE.ODEOptions :: Double -> Double -> Double -> Double -> Double -> Int -> Int -> ODEOptions.""" + return _invoke('hmath_ode_ode_options', [['Double'], ['Double'], ['Double'], ['Double'], ['Double'], ['Int'], ['Int']], [ode_absolute_tolerance, ode_relative_tolerance, initial_step, minimum_step, maximum_step, maximum_steps, newton_iterations]) + + +def ode_absolute_tolerance(value): + """HMath.ODE.odeAbsoluteTolerance :: ODEOptions -> Double.""" + return _invoke('hmath_ode_ode_absolute_tolerance', [['ODEOptions']], [value]) + + +def ode_relative_tolerance(value): + """HMath.ODE.odeRelativeTolerance :: ODEOptions -> Double.""" + return _invoke('hmath_ode_ode_relative_tolerance', [['ODEOptions']], [value]) + + +def initial_step(value): + """HMath.ODE.initialStep :: ODEOptions -> Double.""" + return _invoke('hmath_ode_initial_step', [['ODEOptions']], [value]) + + +def minimum_step(value): + """HMath.ODE.minimumStep :: ODEOptions -> Double.""" + return _invoke('hmath_ode_minimum_step', [['ODEOptions']], [value]) + + +def maximum_step(value): + """HMath.ODE.maximumStep :: ODEOptions -> Double.""" + return _invoke('hmath_ode_maximum_step', [['ODEOptions']], [value]) + + +def maximum_steps(value): + """HMath.ODE.maximumSteps :: ODEOptions -> Int.""" + return _invoke('hmath_ode_maximum_steps', [['ODEOptions']], [value]) + + +def newton_iterations(value): + """HMath.ODE.newtonIterations :: ODEOptions -> Int.""" + return _invoke('hmath_ode_newton_iterations', [['ODEOptions']], [value]) + + +def default_ode_options(): + """HMath.ODE.defaultODEOptions :: ODEOptions.""" + return _invoke('hmath_ode_default_ode_options', [], []) + + +def trajectory(trajectory_times, trajectory_states, trajectory_derivatives): + """HMath.ODE.Trajectory :: [Double] -> [[Double]] -> [[Double]] -> Trajectory.""" + return _invoke('hmath_ode_trajectory', [['list', ['Double']], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]]], [trajectory_times, trajectory_states, trajectory_derivatives]) + + +def trajectory_times(value): + """HMath.ODE.trajectoryTimes :: Trajectory -> [Double].""" + return _invoke('hmath_ode_trajectory_times', [['Trajectory']], [value]) + + +def trajectory_states(value): + """HMath.ODE.trajectoryStates :: Trajectory -> [[Double]].""" + return _invoke('hmath_ode_trajectory_states', [['Trajectory']], [value]) + + +def trajectory_derivatives(value): + """HMath.ODE.trajectoryDerivatives :: Trajectory -> [[Double]].""" + return _invoke('hmath_ode_trajectory_derivatives', [['Trajectory']], [value]) + + +def solve_ivp(method, options, panels, f, start, end, initial): + """HMath.ODE.solveIVP :: Method -> ODEOptions -> Int -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_ivp', [['ODEMethod'], ['ODEOptions'], ['Int'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']]], [method, options, panels, f, start, end, initial]) + + +def solve_adaptive(method, options, f, start, end, initial): + """HMath.ODE.solveAdaptive :: Method -> ODEOptions -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_adaptive', [['ODEMethod'], ['ODEOptions'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']]], [method, options, f, start, end, initial]) + + +def interpolate_trajectory(trajectory, t): + """HMath.ODE.interpolateTrajectory :: Trajectory -> Double -> Either MathError [Double].""" + return _invoke('hmath_ode_interpolate_trajectory', [['Trajectory'], ['Double']], [trajectory, t]) + + +def any_direction(): + """HMath.ODE.AnyDirection :: EventDirection.""" + return _invoke('hmath_ode_any_direction', [], []) + + +def rising(): + """HMath.ODE.Rising :: EventDirection.""" + return _invoke('hmath_ode_rising', [], []) + + +def falling(): + """HMath.ODE.Falling :: EventDirection.""" + return _invoke('hmath_ode_falling', [], []) + + +def event(event_time, event_state): + """HMath.ODE.Event :: Double -> [Double] -> Event.""" + return _invoke('hmath_ode_event', [['Double'], ['list', ['Double']]], [event_time, event_state]) + + +def event_time(value): + """HMath.ODE.eventTime :: Event -> Double.""" + return _invoke('hmath_ode_event_time', [['Event']], [value]) + + +def event_state(value): + """HMath.ODE.eventState :: Event -> [Double].""" + return _invoke('hmath_ode_event_state', [['Event']], [value]) + + +def locate_events(direction, tolerance, function, trajectory): + """HMath.ODE.locateEvents :: EventDirection -> Double -> (Double -> [Double] -> Double) -> Trajectory -> Either MathError [Event].""" + return _invoke('hmath_ode_locate_events', [['EventDirection'], ['Double'], ['function', ['Double'], ['list', ['Double']], ['Double']], ['Trajectory']], [direction, tolerance, function, trajectory]) + + +def solve_boundary(method, options, panels, f, boundary, start, end, guess): + """HMath.ODE.solveBoundary :: Method -> ODEOptions -> Int -> ODE -> ([Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_boundary', [['ODEMethod'], ['ODEOptions'], ['Int'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']]], [method, options, panels, f, boundary, start, end, guess]) + + +def solve_dae(options, panels, residual, start, end, initial, initial_derivative): + """HMath.ODE.solveDAE :: ODEOptions -> Int -> (Double -> [Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_dae', [['ODEOptions'], ['Int'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']], ['list', ['Double']]], [options, panels, residual, start, end, initial, initial_derivative]) + + +def symplectic_euler(): + """HMath.ODE.SymplecticEuler :: HamiltonianMethod.""" + return _invoke('hmath_ode_symplectic_euler', [], []) + + +def verlet(): + """HMath.ODE.Verlet :: HamiltonianMethod.""" + return _invoke('hmath_ode_verlet', [], []) + + +def leapfrog(): + """HMath.ODE.Leapfrog :: HamiltonianMethod.""" + return _invoke('hmath_ode_leapfrog', [], []) + + +def solve_hamiltonian(method, panels, velocity, force, start, end, q0, p0): + """HMath.ODE.solveHamiltonian :: HamiltonianMethod -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_hamiltonian', [['HamiltonianMethod'], ['Int'], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']], ['list', ['Double']]], [method, panels, velocity, force, start, end, q0, p0]) + + +def solve_nystrom(panels, acceleration, start, end, q0, v0): + """HMath.ODE.solveNystrom :: Int -> (Double -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory.""" + return _invoke('hmath_ode_solve_nystrom', [['Int'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']], ['list', ['Double']]], [panels, acceleration, start, end, q0, v0]) + + +def sensitivities(method, options, panels, h, family, parameters, start, end, initial): + """HMath.ODE.sensitivities :: Method -> ODEOptions -> Int -> Double -> ([Double] -> ODE) -> [Double] -> Double -> Double -> [Double] -> Either MathError (Matrix Double).""" + return _invoke('hmath_ode_sensitivities', [['ODEMethod'], ['ODEOptions'], ['Int'], ['Double'], ['function', ['list', ['Double']], ['Double'], ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']], ['Double'], ['Double'], ['list', ['Double']]], [method, options, panels, h, family, parameters, start, end, initial]) + + +def equilibrium(options, field, guess): + """HMath.ODE.equilibrium :: ODEOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_ode_equilibrium', [['ODEOptions'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']]], [options, field, guess]) + + +def phase_trajectories(value, value2, value3, value4, value5, value6, value7): + """HMath.ODE.phaseTrajectories :: Method -> ODEOptions -> Int -> ([Double] -> [Double]) -> Double -> Double -> [[Double]] -> Either MathError [Trajectory].""" + return _invoke('hmath_ode_phase_trajectories', [['ODEMethod'], ['ODEOptions'], ['Int'], ['function', ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['list', ['Double']]]], [value, value2, value3, value4, value5, value6, value7]) + + +def lyapunov_exponents(options, panels, difference_step, f, start, end, initial): + """HMath.ODE.lyapunovExponents :: ODEOptions -> Int -> Double -> ODE -> Double -> Double -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_ode_lyapunov_exponents', [['ODEOptions'], ['Int'], ['Double'], ['function', ['Double'], ['list', ['Double']], ['list', ['Double']]], ['Double'], ['Double'], ['list', ['Double']]], [options, panels, difference_step, f, start, end, initial]) diff --git a/bindings/python/_hmath_native/optimization.py b/bindings/python/_hmath_native/optimization.py new file mode 100644 index 0000000..fd5b91c --- /dev/null +++ b/bindings/python/_hmath_native/optimization.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Haskell first-order optimizer state and updates, in binary64.""" + +import ctypes as C +import threading +from enum import IntEnum + +from ._numeric import _int + + +class GradientMethod(IntEnum): + GRADIENT_DESCENT = 0 + MOMENTUM = 1 + NESTEROV = 2 + ADAGRAD = 3 + RMSPROP = 4 + ADADELTA = 5 + ADAM = 6 + ADAMW = 7 + AMSGRAD = 8 + ADAMAX = 9 + NADAM = 10 + RADAM = 11 + + +def _api(name, *types): + import hmath + + return C.CFUNCTYPE(C.c_int, *types)((name, hmath._lib)) + + +class OptimizerState: + """Immutable native state; close it explicitly or use a with statement. + + A live state prevents final runtime shutdown. Independent optimizer steps + may share a state. A returned state does not modify or depend on its parent. + """ + + def __init__(self, dimension): + import hmath + + self._lock, self._ptr = threading.RLock(), C.c_void_p() + hmath.initialize() + call = _api( + "hmath_initialize_optimizer", C.c_void_p, C.c_ssize_t, C.POINTER(C.c_void_p) + ) + hmath._check(call(None, _int(dimension), C.byref(self._ptr))) + + @classmethod + def _adopt(cls, pointer): + instance = object.__new__(cls) + instance._lock, instance._ptr = threading.RLock(), pointer + return instance + + def close(self): + import hmath + + with self._lock: + if self._ptr: + C.CFUNCTYPE(None, C.c_void_p)( + ("hmath_optimizer_state_release", hmath._lib) + )(self._ptr) + self._ptr = C.c_void_p() + + def __enter__(self): + with self._lock: + if not self._ptr: + raise ValueError("optimizer state is closed") + return self + + def __exit__(self, *_): + self.close() + + def __del__(self): + if getattr(self, "_ptr", None): + self.close() + + +def initialize_optimizer(dimension): + """HMath.Optimization.FirstOrder.initializeOptimizer, with unchanged errors.""" + return OptimizerState(dimension) + + +def optimizer_step(method, rate, state, parameters, gradient): + """Return (new_parameters, new_state) without modifying the original state. + + Calls Haskell optimizerStep directly. Its fixed beta1=.9, beta2=.999, + epsilon=1e-8 and AdamW weight decay=.01 are preserved. This function does + not evaluate a loss function or change the supplied gradient. + """ + import hmath + + method = GradientMethod(method) + if not isinstance(state, OptimizerState): + raise TypeError("state must be an OptimizerState") + parameters, gradient = tuple(parameters), tuple(gradient) + xs = (C.c_double * len(parameters))(*parameters) + gs = (C.c_double * len(gradient))(*gradient) + result = (C.c_double * len(parameters))() + # Allocate the Python owner before creating a native state so Python-side + # allocation failures cannot leak a runtime reservation. + next_state = OptimizerState._adopt(C.c_void_p()) + call = _api( + "hmath_optimizer_step", + C.c_void_p, + C.c_int, + C.c_double, + C.c_void_p, + C.POINTER(C.c_double), + C.c_size_t, + C.POINTER(C.c_double), + C.c_size_t, + C.POINTER(C.c_double), + C.c_size_t, + C.POINTER(C.c_void_p), + ) + with state._lock: + if not state._ptr: + raise ValueError("optimizer state is closed") + hmath._check( + call( + None, + method, + rate, + state._ptr, + xs, + len(xs), + gs, + len(gs), + result, + len(result), + C.byref(next_state._ptr), + ) + ) + return list(result), next_state + + +# Extended original optimization API (records, methods, constraints, solvers and callbacks). +from ._optimization_all import * diff --git a/bindings/python/_hmath_native/optimization_common.py b/bindings/python/_hmath_native/optimization_common.py new file mode 100644 index 0000000..45359ab --- /dev/null +++ b/bindings/python/_hmath_native/optimization_common.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def dot(a, b, *, dtype='float64'): + """Call HMath.Optimization.Common.dot; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_optimization_common_dot', + ['fs', 'fs'], + 'f', + [a, b], + dtype, + 0, + ) + + +def norm(xs, *, dtype='float64'): + """Call HMath.Optimization.Common.norm; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_optimization_common_norm', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def add(argument1, argument2, *, dtype='float64'): + """Call HMath.Optimization.Common.add; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_optimization_common_add', + ['fs', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def sub(argument1, argument2, *, dtype='float64'): + """Call HMath.Optimization.Common.sub; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_optimization_common_sub', + ['fs', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def scale(argument1, argument2, *, dtype='float64'): + """Call HMath.Optimization.Common.scale; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_optimization_common_scale', + ['f', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/pde.py b/bindings/python/_hmath_native/pde.py new file mode 100644 index 0000000..1239b73 --- /dev/null +++ b/bindings/python/_hmath_native/pde.py @@ -0,0 +1,239 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numerical_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Grid(Value): + """Owned immutable original HMath.PDE.Grid.""" + + +register(218, Grid) + + +class Boundary(Value): + """Owned immutable original HMath.PDE.Boundary.""" + + +register(219, Boundary) + + +class Discretization(Value): + """Owned immutable original HMath.PDE.Discretization.""" + + +register(220, Discretization) + + +class PDEOperator(Value): + """Owned immutable original HMath.PDE.PDEOperator.""" + + +register(221, PDEOperator) + + +class PDEResult(Value): + """Owned immutable original HMath.PDE.PDEResult.""" + + +register(222, PDEResult) + + +def dirichlet(value): + """HMath.PDE.Dirichlet :: Double -> Boundary.""" + return _invoke('hmath_pde_dirichlet', [['Double']], [value]) + + +def neumann(value): + """HMath.PDE.Neumann :: Double -> Boundary.""" + return _invoke('hmath_pde_neumann', [['Double']], [value]) + + +def robin(value, value2, value3): + """HMath.PDE.Robin :: Double -> Double -> Double -> Boundary.""" + return _invoke('hmath_pde_robin', [['Double'], ['Double'], ['Double']], [value, value2, value3]) + + +def periodic(): + """HMath.PDE.Periodic :: Boundary.""" + return _invoke('hmath_pde_periodic', [], []) + + +def finite_difference(): + """HMath.PDE.FiniteDifference :: Discretization.""" + return _invoke('hmath_pde_finite_difference', [], []) + + +def finite_volume(): + """HMath.PDE.FiniteVolume :: Discretization.""" + return _invoke('hmath_pde_finite_volume', [], []) + + +def finite_element(): + """HMath.PDE.FiniteElement :: Discretization.""" + return _invoke('hmath_pde_finite_element', [], []) + + +def pde_result(pde_values, pde_residual, pde_error_estimate): + """HMath.PDE.PDEResult :: [Double] -> Double -> Double -> PDEResult.""" + return _invoke('hmath_pde_pde_result', [['list', ['Double']], ['Double'], ['Double']], [pde_values, pde_residual, pde_error_estimate]) + + +def pde_values(value): + """HMath.PDE.pdeValues :: PDEResult -> [Double].""" + return _invoke('hmath_pde_pde_values', [['PDEResult']], [value]) + + +def pde_residual(value): + """HMath.PDE.pdeResidual :: PDEResult -> Double.""" + return _invoke('hmath_pde_pde_residual', [['PDEResult']], [value]) + + +def pde_error_estimate(value): + """HMath.PDE.pdeErrorEstimate :: PDEResult -> Double.""" + return _invoke('hmath_pde_pde_error_estimate', [['PDEResult']], [value]) + + +def grid(dims, bounds, periodic): + """HMath.PDE.grid :: [Int] -> [(Double, Double)] -> [Bool] -> Either MathError Grid.""" + return _invoke('hmath_pde_grid', [['list', ['Int']], ['list', ['tuple', ['Double'], ['Double']]], ['list', ['Bool']]], [dims, bounds, periodic]) + + +def grid_shape(value): + """HMath.PDE.gridShape :: Grid -> [Int].""" + return _invoke('hmath_pde_grid_shape', [['Grid']], [value]) + + +def grid_spacing(value): + """HMath.PDE.gridSpacing :: Grid -> [Double].""" + return _invoke('hmath_pde_grid_spacing', [['Grid']], [value]) + + +def flatten_index(value, value2): + """HMath.PDE.flattenIndex :: Grid -> [Int] -> Either MathError Int.""" + return _invoke('hmath_pde_flatten_index', [['Grid'], ['list', ['Int']]], [value, value2]) + + +def unflatten_index(value, value2): + """HMath.PDE.unflattenIndex :: Grid -> Int -> Either MathError [Int].""" + return _invoke('hmath_pde_unflatten_index', [['Grid'], ['Int']], [value, value2]) + + +def grid_coordinates(value): + """HMath.PDE.gridCoordinates :: Grid -> [[Double]].""" + return _invoke('hmath_pde_grid_coordinates', [['Grid']], [value]) + + +def assemble_pde(value, value2, value3, value4, value5): + """HMath.PDE.assemblePDE :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Double -> Either MathError PDEOperator.""" + return _invoke('hmath_pde_assemble_pde', [['Discretization'], ['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['list', ['Double']], ['Double']], [value, value2, value3, value4, value5]) + + +def pde_stiffness(value): + """HMath.PDE.pdeStiffness :: PDEOperator -> S.Sparse Double.""" + return _invoke('hmath_pde_pde_stiffness', [['PDEOperator']], [value]) + + +def pde_mass(value): + """HMath.PDE.pdeMass :: PDEOperator -> S.Sparse Double.""" + return _invoke('hmath_pde_pde_mass', [['PDEOperator']], [value]) + + +def pde_boundary_load(value): + """HMath.PDE.pdeBoundaryLoad :: PDEOperator -> [Double].""" + return _invoke('hmath_pde_pde_boundary_load', [['PDEOperator']], [value]) + + +def solve_elliptic(value, value2): + """HMath.PDE.solveElliptic :: PDEOperator -> [Double] -> Either MathError PDEResult.""" + return _invoke('hmath_pde_solve_elliptic', [['PDEOperator'], ['list', ['Double']]], [value, value2]) + + +def poisson(method, g, bc, forcing): + """HMath.PDE.poisson :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError PDEResult.""" + return _invoke('hmath_pde_poisson', [['Discretization'], ['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['list', ['Double']]], [method, g, bc, forcing]) + + +def laplace(method, g, bc): + """HMath.PDE.laplace :: Discretization -> Grid -> [(Boundary, Boundary)] -> Either MathError PDEResult.""" + return _invoke('hmath_pde_laplace', [['Discretization'], ['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]]], [method, g, bc]) + + +def helmholtz(method, g, bc, k, forcing): + """HMath.PDE.helmholtz :: Discretization -> Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> Either MathError PDEResult.""" + return _invoke('hmath_pde_helmholtz', [['Discretization'], ['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['Double'], ['list', ['Double']]], [method, g, bc, k, forcing]) + + +def spatial_gradient(value, value2): + """HMath.PDE.spatialGradient :: Grid -> [Double] -> Either MathError [[Double]].""" + return _invoke('hmath_pde_spatial_gradient', [['Grid'], ['list', ['Double']]], [value, value2]) + + +def laplacian_stencil(g, bc, values): + """HMath.PDE.laplacianStencil :: Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_pde_laplacian_stencil', [['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['list', ['Double']]], [g, bc, values]) + + +def spectral_derivative(value, value2, value3, value4): + """HMath.PDE.spectralDerivative :: Grid -> Int -> Int -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_pde_spectral_derivative', [['Grid'], ['Int'], ['Int'], ['list', ['Double']]], [value, value2, value3, value4]) + + +def spectral_laplacian(g, values): + """HMath.PDE.spectralLaplacian :: Grid -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_pde_spectral_laplacian', [['Grid'], ['list', ['Double']]], [g, values]) + + +def spectral_poisson(value, value2, value3): + """HMath.PDE.spectralPoisson :: Grid -> Double -> [Double] -> Either MathError PDEResult.""" + return _invoke('hmath_pde_spectral_poisson', [['Grid'], ['Double'], ['list', ['Double']]], [value, value2, value3]) + + +def pseudo_spectral_diffusion(g, kappas, values): + """HMath.PDE.pseudoSpectralDiffusion :: Grid -> [Double] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_pde_pseudo_spectral_diffusion', [['Grid'], ['list', ['Double']], ['list', ['Double']]], [g, kappas, values]) + + +def method_of_lines(value, value2, value3, value4, value5): + """HMath.PDE.methodOfLines :: O.Method -> PDEOperator -> (Double -> [Double]) -> [Double] -> [Double] -> Either MathError O.Trajectory.""" + return _invoke('hmath_pde_method_of_lines', [['ODEMethod'], ['PDEOperator'], ['function', ['Double'], ['list', ['Double']]], ['list', ['Double']], ['list', ['Double']]], [value, value2, value3, value4, value5]) + + +def heat(value, value2, value3, value4, value5): + """HMath.PDE.heat :: Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> [Double] -> Either MathError O.Trajectory.""" + return _invoke('hmath_pde_heat', [['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['Double'], ['list', ['Double']], ['list', ['Double']]], [value, value2, value3, value4, value5]) + + +def diffusion(method, g, bc, kappas, times, initial): + """HMath.PDE.diffusion :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> [Double] -> [Double] -> Either MathError O.Trajectory.""" + return _invoke('hmath_pde_diffusion', [['Discretization'], ['Grid'], ['list', ['tuple', ['Boundary'], ['Boundary']]], ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], [method, g, bc, kappas, times, initial]) + + +def wave(g, speed, times, initial, velocity): + """HMath.PDE.wave :: Grid -> Double -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]].""" + return _invoke('hmath_pde_wave', [['Grid'], ['Double'], ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], [g, speed, times, initial, velocity]) + + +def advection(value, value2, value3, value4): + """HMath.PDE.advection :: Grid -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]].""" + return _invoke('hmath_pde_advection', [['Grid'], ['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], [value, value2, value3, value4]) + + +def advection_diffusion(value, value2, value3, value4, value5): + """HMath.PDE.advectionDiffusion :: Grid -> [Double] -> Double -> [Double] -> [Double] -> Either MathError [[Double]].""" + return _invoke('hmath_pde_advection_diffusion', [['Grid'], ['list', ['Double']], ['Double'], ['list', ['Double']], ['list', ['Double']]], [value, value2, value3, value4, value5]) + + +def stability_limit(g, diffusivity, velocity): + """HMath.PDE.stabilityLimit :: Grid -> Double -> [Double] -> Either MathError Double.""" + return _invoke('hmath_pde_stability_limit', [['Grid'], ['Double'], ['list', ['Double']]], [g, diffusivity, velocity]) + + +def cfl_number(g, diffusivity, velocity, dt): + """HMath.PDE.cflNumber :: Grid -> Double -> [Double] -> Double -> Either MathError Double.""" + return _invoke('hmath_pde_cfl_number', [['Grid'], ['Double'], ['list', ['Double']], ['Double']], [g, diffusivity, velocity, dt]) + + +def manufactured_error(g, exact, values): + """HMath.PDE.manufacturedError :: Grid -> ([Double] -> Double) -> [Double] -> Either MathError Double.""" + return _invoke('hmath_pde_manufactured_error', [['Grid'], ['function', ['list', ['Double']], ['Double']], ['list', ['Double']]], [g, exact, values]) diff --git a/bindings/python/_hmath_native/polynomial.py b/bindings/python/_hmath_native/polynomial.py new file mode 100644 index 0000000..6ce597d --- /dev/null +++ b/bindings/python/_hmath_native/polynomial.py @@ -0,0 +1,349 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_polynomial_bindings.py. +"""Direct typed bindings to every public HMath.Polynomial operation.""" + +from ._polynomial_base import ( + Polynomial, + PowerSeries, + RationalFunction, + _call, + _construct, + _prototype_call, + _typed_call, + chebyshev_approximation, +) + +__all__ = [ + "Polynomial", + "PowerSeries", + "RationalFunction", + "aberth_ehrlich", + "add_polynomial", + "add_rational_function", + "add_series", + "bernstein_polynomial", + "chebyshev_approximation", + "chebyshev_polynomial", + "coefficients", + "companion_matrix", + "compose_polynomial", + "compose_series", + "count_real_roots", + "differentiate_polynomial", + "differentiate_series", + "divide_polynomial", + "divide_series", + "durand_kerner", + "evaluate_polynomial", + "evaluate_rational_function", + "exp_series", + "factor_rational_polynomial", + "gcd_polynomial", + "hermite_polynomial", + "integrate_polynomial", + "integrate_series", + "isolate_real_roots", + "lagrange_interpolation", + "laguerre_polynomial", + "legendre_polynomial", + "log_series", + "monic_polynomial", + "multiply_polynomial", + "multiply_rational_function", + "multiply_series", + "newton_interpolation", + "partial_fractions", + "polynomial", + "polynomial_degree", + "polynomial_equal", + "polynomial_regression", + "power_series", + "rational_denominator", + "rational_function", + "rational_function_equal", + "rational_numerator", + "rational_roots", + "reciprocal_series", + "scale_polynomial", + "series_coefficients", + "series_equal", + "square_free_factors", + "sturm_sequence", + "subtract_polynomial", +] + + +def polynomial(coefficients, *, dtype="float64"): + "HMath.Polynomial.polynomial: Construct a polynomial, deleting trailing exact zeros (no floating tolerance). Returns Polynomial." + return _construct("hmath_polynomial_polynomial", coefficients, dtype) + + +def coefficients(polynomial): + "HMath.Polynomial.coefficients: Ascending coefficients, with no trailing zero; zero gives an empty list. Returns ascending coefficient list." + return _call("hmath_polynomial_coefficients", polynomial) + + +def polynomial_degree(polynomial): + "HMath.Polynomial.polynomialDegree: Degree of a nonzero polynomial; zero has no degree. Returns integer degree, or None for the zero polynomial." + return _call("hmath_polynomial_polynomial_degree", polynomial) + + +def evaluate_polynomial(polynomial, x): + "HMath.Polynomial.evaluatePolynomial: Horner evaluation, with the constant coefficient first in storage. Returns coefficient scalar." + return _typed_call("hmath_polynomial_evaluate_polynomial", 0, [1], polynomial, x) + + +def add_polynomial(left, right): + "HMath.Polynomial.addPolynomial: Coefficientwise addition with canonical exact-zero normalization. Returns Polynomial." + return _call("hmath_polynomial_add_polynomial", left, right) + + +def subtract_polynomial(left, right): + "HMath.Polynomial.subtractPolynomial: Coefficientwise subtraction. Returns Polynomial." + return _call("hmath_polynomial_subtract_polynomial", left, right) + + +def scale_polynomial(scalar, polynomial): + "HMath.Polynomial.scalePolynomial: Multiply every coefficient by a scalar. Returns Polynomial." + return _typed_call("hmath_polynomial_scale_polynomial", 1, [0], scalar, polynomial) + + +def multiply_polynomial(left, right): + "HMath.Polynomial.multiplyPolynomial: Exact schoolbook convolution, including zero polynomials. Returns Polynomial." + return _call("hmath_polynomial_multiply_polynomial", left, right) + + +def compose_polynomial(outer, inner): + "HMath.Polynomial.composePolynomial: Composition `p(q(x))` by polynomial Horner evaluation. Returns Polynomial." + return _call("hmath_polynomial_compose_polynomial", outer, inner) + + +def divide_polynomial(numerator, denominator): + "HMath.Polynomial.dividePolynomial: Long division over a field. Exact coefficient equality controls termination; numerical cancellation is truncated at the eliminated leading coefficient. Zero denominator is rejected. Returns (quotient, remainder)." + return _call("hmath_polynomial_divide_polynomial", numerator, denominator) + + +def monic_polynomial(polynomial): + "HMath.Polynomial.monicPolynomial: Normalize a nonzero polynomial to leading coefficient one; zero remains zero. Returns Polynomial." + return _call("hmath_polynomial_monic_polynomial", polynomial) + + +def gcd_polynomial(left, right): + "HMath.Polynomial.gcdPolynomial: Monic Euclidean GCD over an exact field; `gcd(0,0)=0`. Returns Polynomial." + return _call("hmath_polynomial_gcd_polynomial", left, right) + + +def differentiate_polynomial(polynomial): + "HMath.Polynomial.differentiatePolynomial: Formal derivative. Returns Polynomial." + return _call("hmath_polynomial_differentiate_polynomial", polynomial) + + +def integrate_polynomial(constant, polynomial): + "HMath.Polynomial.integratePolynomial: Formal integral with the supplied integration constant. Returns Polynomial." + return _typed_call( + "hmath_polynomial_integrate_polynomial", 1, [0], constant, polynomial + ) + + +def square_free_factors(polynomial): + "HMath.Polynomial.squareFreeFactors: Monic square-free factors with positive multiplicities over Rational. The leading coefficient is omitted; constant polynomials have no factors. Returns list of (monic factor, multiplicity)." + return _call("hmath_polynomial_square_free_factors", polynomial) + + +def rational_roots(budget, polynomial): + "HMath.Polynomial.rationalRoots: Rational roots with exact multiplicities using the rational-root theorem. Budget applies to integer factorization of numerator and leading coefficient. Returns list of (exact Rational root, multiplicity)." + return _call("hmath_polynomial_rational_roots", budget, polynomial) + + +def factor_rational_polynomial(budget, polynomial): + "HMath.Polynomial.factorRationalPolynomial: Complete rational factorization by bounded Kronecker interpolation. Returns the original leading scalar and monic irreducible factors with multiplicity. Every candidate is divided exactly. Exhausting the candidate budget reports failure, never an unsupported claim of irreducibility. Intended for small exact polynomials; coefficient divisor enumeration also uses this budget. Returns (leading scalar, [(monic factor, multiplicity)])." + return _call("hmath_polynomial_factor_rational_polynomial", budget, polynomial) + + +def sturm_sequence(polynomial): + "HMath.Polynomial.sturmSequence: Sturm chain over exact rationals, after removing the derivative GCD. Zero polynomial is invalid. Square-free normalization ensures a repeated root cannot make every chain member vanish and destroy one-sided variation counts. Returns list of exact Rational polynomials." + return _call("hmath_polynomial_sturm_sequence", polynomial) + + +def count_real_roots(polynomial, left, right): + "HMath.Polynomial.countRealRoots: Number of distinct real roots in `(a,b]`. Endpoints that are roots of the polynomial are rejected to make the interval convention unambiguous. Returns integer number of roots." + return _typed_call( + "hmath_polynomial_count_real_roots", 0, [1, 2], polynomial, left, right + ) + + +def isolate_real_roots(depth, width, polynomial): + "HMath.Polynomial.isolateRealRoots: Isolate every distinct real root in rational intervals with disjoint interiors and width at most tolerance. Intervals have the root-count convention (a,b]; shared endpoints belong to the interval on their left. Bisection budget bounds visited intervals; all arithmetic is exact. Returns list of exact Rational endpoint pairs." + return _typed_call( + "hmath_polynomial_isolate_real_roots", 2, [1], depth, width, polynomial + ) + + +def durand_kerner(iterations, tolerance, polynomial): + "HMath.Polynomial.durandKerner: DurandKerner simultaneous complex root iteration. Distinct initial roots are placed on a Cauchy-bound circle; repeated roots may converge slowly. Returns list of Complex Double roots." + return _call( + "hmath_polynomial_durand_kerner", iterations, float(tolerance), polynomial + ) + + +def aberth_ehrlich(iterations, tolerance, polynomial): + "HMath.Polynomial.aberthEhrlich: AberthEhrlich simultaneous iteration, combining Newton corrections with mutual-root repulsion. All roots are verified against a scaled residual. Returns list of Complex Double roots." + return _call( + "hmath_polynomial_aberth_ehrlich", iterations, float(tolerance), polynomial + ) + + +def companion_matrix(polynomial): + "HMath.Polynomial.companionMatrix: Frobenius companion matrix of a nonconstant polynomial, with ones on the subdiagonal and negated monic coefficients in the last column. Returns interoperable Matrix with the same coefficient type." + return _call("hmath_polynomial_companion_matrix", polynomial) + + +def lagrange_interpolation(points, *, dtype="float64"): + "HMath.Polynomial.lagrangeInterpolation: Exact Lagrange interpolating polynomial. Duplicate nodes are rejected. Returns Polynomial." + return _prototype_call("hmath_polynomial_lagrange_interpolation", dtype, points) + + +def newton_interpolation(points, *, dtype="float64"): + "HMath.Polynomial.newtonInterpolation: Newton divided differences, returned in the standard power basis. Returns Polynomial." + return _prototype_call("hmath_polynomial_newton_interpolation", dtype, points) + + +def chebyshev_polynomial(degree, *, dtype="float64"): + "HMath.Polynomial.chebyshevPolynomial: Chebyshev T_n, normalized by T_0=1, T_1=x. Returns Polynomial." + return _prototype_call("hmath_polynomial_chebyshev_polynomial", dtype, degree) + + +def legendre_polynomial(degree, *, dtype="float64"): + "HMath.Polynomial.legendrePolynomial: Legendre P_n, normalized by P_n(1)=1. Returns Polynomial." + return _prototype_call("hmath_polynomial_legendre_polynomial", dtype, degree) + + +def hermite_polynomial(degree, *, dtype="float64"): + "HMath.Polynomial.hermitePolynomial: Physicists' Hermite H_n: H_0=1, H_1=2x. Returns Polynomial." + return _prototype_call("hmath_polynomial_hermite_polynomial", dtype, degree) + + +def laguerre_polynomial(degree, *, dtype="float64"): + "HMath.Polynomial.laguerrePolynomial: Ordinary Laguerre L_n with alpha=0 and L_n(0)=1. Returns Polynomial." + return _prototype_call("hmath_polynomial_laguerre_polynomial", dtype, degree) + + +def bernstein_polynomial(degree, index, *, dtype="float64"): + "HMath.Polynomial.bernsteinPolynomial: Bernstein basis `binomial(n,k)*x^k*(1-x)^(n-k)` for 0<=k<=n. Returns Polynomial." + return _prototype_call( + "hmath_polynomial_bernstein_polynomial", dtype, degree, index + ) + + +def polynomial_regression(degree, points, *, dtype="float64"): + "HMath.Polynomial.polynomialRegression: Least-squares power-basis regression using column-pivoted Householder QR. Degree must be nonnegative; undersampling, nonfinite data and rank deficiency are reported by the checked design-matrix solver. Returns Polynomial." + return _prototype_call( + "hmath_polynomial_polynomial_regression", dtype, degree, points + ) + + +def power_series(coefficients, *, dtype="float64"): + "HMath.Polynomial.powerSeries: Construct a jet with explicit coefficients, including trailing zeros. Returns PowerSeries." + return _construct("hmath_polynomial_power_series", coefficients, dtype) + + +def series_coefficients(series): + "HMath.Polynomial.seriesCoefficients: Stored Taylor coefficients; coefficient n multiplies x^n, not x^n/n!. Returns coefficient list, including trailing zeros." + return _call("hmath_polynomial_series_coefficients", series) + + +def add_series(left, right): + "HMath.Polynomial.addSeries: Add jets to their common truncation order. Returns PowerSeries." + return _call("hmath_polynomial_add_series", left, right) + + +def multiply_series(left, right): + "HMath.Polynomial.multiplySeries: Multiply jets by truncated convolution. Returns PowerSeries." + return _call("hmath_polynomial_multiply_series", left, right) + + +def reciprocal_series(series): + "HMath.Polynomial.reciprocalSeries: Reciprocal jet from coefficient recurrence; constant term must be nonzero. Returns PowerSeries." + return _call("hmath_polynomial_reciprocal_series", series) + + +def divide_series(numerator, denominator): + "HMath.Polynomial.divideSeries: Divide jets to their common order; denominator constant must be nonzero. Returns PowerSeries." + return _call("hmath_polynomial_divide_series", numerator, denominator) + + +def compose_series(outer, inner): + "HMath.Polynomial.composeSeries: Formal composition to the inner jet's order. Inner constant must be zero, so unknown higher outer coefficients cannot affect the returned jet. Returns PowerSeries." + return _call("hmath_polynomial_compose_series", outer, inner) + + +def differentiate_series(series): + "HMath.Polynomial.differentiateSeries: Derivative jet has one fewer coefficient. Returns PowerSeries." + return _call("hmath_polynomial_differentiate_series", series) + + +def integrate_series(constant, series): + "HMath.Polynomial.integrateSeries: Integral jet with supplied constant, one coefficient longer. Returns PowerSeries." + return _typed_call("hmath_polynomial_integrate_series", 1, [0], constant, series) + + +def exp_series(series): + "HMath.Polynomial.expSeries: Exponential of a finite jet from b'=a'b; constant uses the coefficient type's exp. The output has the same truncation order. Returns PowerSeries." + return _call("hmath_polynomial_exp_series", series) + + +def log_series(series): + "HMath.Polynomial.logSeries: Formal log through derivative/division/integration. Requires positive real constant term, with exact truncation matching the input jet. Returns PowerSeries." + return _call("hmath_polynomial_log_series", series) + + +def rational_function(numerator, denominator): + "HMath.Polynomial.rationalFunction: Normalize by polynomial GCD and reject a zero denominator. Returns RationalFunction." + return _call("hmath_polynomial_rational_function", numerator, denominator) + + +def rational_numerator(function): + "HMath.Polynomial.rationalNumerator: Reduced numerator. Returns Polynomial." + return _call("hmath_polynomial_rational_numerator", function) + + +def rational_denominator(function): + "HMath.Polynomial.rationalDenominator: Monic reduced denominator. Returns Polynomial." + return _call("hmath_polynomial_rational_denominator", function) + + +def evaluate_rational_function(function, x): + "HMath.Polynomial.evaluateRationalFunction: Exact evaluation, rejecting poles. Returns exact Rational scalar." + return _typed_call( + "hmath_polynomial_evaluate_rational_function", 0, [1], function, x + ) + + +def add_rational_function(left, right): + "HMath.Polynomial.addRationalFunction: Exact rational-function addition with cancellation. Returns RationalFunction." + return _call("hmath_polynomial_add_rational_function", left, right) + + +def multiply_rational_function(left, right): + "HMath.Polynomial.multiplyRationalFunction: Exact rational-function multiplication with cancellation. Returns RationalFunction." + return _call("hmath_polynomial_multiply_rational_function", left, right) + + +def partial_fractions(budget, function): + "HMath.Polynomial.partialFractions: Exact partial fractions over Q. Each term is `(numerator,monic irreducible denominator,power)` and numerator degree is smaller than denominator degree. Supports repeated and nonlinear factors. Kronecker factorization and linear elimination are bounded by the supplied candidate budget. Returns (polynomial part, [(numerator, denominator, power)])." + return _call("hmath_polynomial_partial_fractions", budget, function) + + +def polynomial_equal(left, right): + "HMath.Polynomial.polynomialEqual: Original derived Eq comparison; coefficient types must match. Returns Boolean." + return _call("hmath_polynomial_polynomial_equal", left, right) + + +def series_equal(left, right): + "HMath.Polynomial.seriesEqual: Original derived Eq comparison; coefficient types must match. Returns Boolean." + return _call("hmath_polynomial_series_equal", left, right) + + +def rational_function_equal(left, right): + "HMath.Polynomial.rationalFunctionEqual: Original derived Eq comparison; coefficient types must match. Returns Boolean." + return _call("hmath_polynomial_rational_function_equal", left, right) diff --git a/bindings/python/_hmath_native/probability.py b/bindings/python/_hmath_native/probability.py new file mode 100644 index 0000000..ba0fd07 --- /dev/null +++ b/bindings/python/_hmath_native/probability.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def gamma_poisson_update(shapePrior, ratePrior, xs, *, dtype='float64'): + """Call HMath.Probability.gammaPoissonUpdate; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_gamma_poisson_update', + ['f', 'f', 'is'], + 'ff', + [shapePrior, ratePrior, xs], + dtype, + 0, + ) + + +def normal_normal_update(mu, priorVariance, observationVariance, xs, *, dtype='float64'): + """Call HMath.Probability.normalNormalUpdate; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_normal_normal_update', + ['f', 'f', 'f', 'fs'], + 'ff', + [mu, priorVariance, observationVariance, xs], + dtype, + 0, + ) + + +def conditional_probability(joint, given, *, dtype='float64'): + """Call HMath.Probability.conditionalProbability; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_conditional_probability', + ['f', 'f'], + 'f', + [joint, given], + dtype, + 0, + ) + + +def bayes(priors, likelihoods, *, dtype='float64'): + """Call HMath.Probability.bayes; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_bayes', + ['fs', 'fs'], + 'fd', + [priors, likelihoods], + dtype, + 0, + ) + + +def multinomial_p_m_f(ps, counts, *, dtype='float64'): + """Call HMath.Probability.multinomialPMF; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_multinomial_p_m_f', + ['fs', 'is'], + 'f', + [ps, counts], + dtype, + 0, + ) + + +def dirichlet_density(as_, xs, *, dtype='float64'): + """Call HMath.Probability.dirichletDensity; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_probability_dirichlet_density', + ['fs', 'fs'], + 'f', + [as_, xs], + dtype, + 0, + ) + + +from .probability_values import * diff --git a/bindings/python/_hmath_native/probability_values.py b/bindings/python/_hmath_native/probability_values.py new file mode 100644 index 0000000..0982aa5 --- /dev/null +++ b/bindings/python/_hmath_native/probability_values.py @@ -0,0 +1,690 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_stochastic_bindings.py. +"""Original HMath.Probability remaining public functions and owned immutable records.""" + +from ._stochastic_base import StochasticValue, _invoke +from ._value import register + + +class Distribution(StochasticValue): + """Original HMath.Probability.Distribution immutable owner.""" + + +register(243, Distribution) + + +class Markov(StochasticValue): + """Original HMath.Probability.Markov immutable owner.""" + + +register(244, Markov) + + +class HMM(StochasticValue): + """Original HMath.Probability.HMM immutable owner.""" + + +register(245, HMM) + + +def validate_distribution(argument1): + "Check finite parameters, support ordering, probability normalization, and declared per-family reference budgets." + return _invoke( + "hmath_stochastic_probability_validate_distribution", + [["Distribution"]], + [argument1], + ) + + +def log_density(argument1, argument2): + "Log density or mass; zero probability is negative infinity, while an integrable endpoint singularity is positive infinity. Observations must be finite." + return _invoke( + "hmath_stochastic_probability_log_density", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def density(argument1, argument2): + "Probability mass for discrete families or density for continuous families. At integrable density singularities the result can be positive infinity; outside support it is zero." + return _invoke( + "hmath_stochastic_probability_density", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def cdf(argument1, argument2): + "P(X\\<=x). Gamma/beta and classical transformed families use analytic special-function identities. Remaining finite-support continuous cases use 2048-panel Simpson integration; Skellam drops a tail beyond 14 standard deviations plus 20 counts." + return _invoke( + "hmath_stochastic_probability_cdf", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def survival(argument1, argument2): + "P(X>x), using direct upper tails for normal, gamma, beta, t, F, binomial and Poisson to avoid cancellation. Other families use the CDF complement." + return _invoke( + "hmath_stochastic_probability_survival", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def quantile(argument1, argument2): + "Generalized inverse CDF, p in [0,1]; endpoints return mathematical support bounds, including infinities. Interior values use analytic transforms or bounded bracketing/bisection." + return _invoke( + "hmath_stochastic_probability_quantile", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def hazard(argument1, argument2): + "Density divided by survival. For zero survival returns positive infinity by convention." + return _invoke( + "hmath_stochastic_probability_hazard", + [["Distribution"], ["Double"]], + [argument1, argument2], + ) + + +def log_likelihood(argument1, argument2): + "Sum of independent observation log probabilities. Impossible data produce negative infinity." + return _invoke( + "hmath_stochastic_probability_log_likelihood", + [["Distribution"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def moments(argument1): + "Mean and population variance. Infinite/nonexistent moments return a domain error rather than a numeric value that could be mistaken for a finite moment." + return _invoke( + "hmath_stochastic_probability_moments", [["Distribution"]], [argument1] + ) + + +def entropy(argument1): + "Shannon or differential entropy in nats. Closed forms are used when available; other families use the documented expectation quadrature." + return _invoke( + "hmath_stochastic_probability_entropy", [["Distribution"]], [argument1] + ) + + +def expectation(argument1, argument2): + "Reference expectation under a distribution. Empirical/mixture cases are exact weighted sums; count families truncate at 1e-10 tail quantiles, continuous families use 4096 midpoint probability-space nodes. No certified quadrature error is claimed." + return _invoke( + "hmath_stochastic_probability_expectation", + [["Distribution"], ["function", ["Double"], ["Double"]]], + [argument1, argument2], + ) + + +def sample(argument1, argument2): + "Draw a model sample and updated immutable RNG; specialized gamma/normal/count samplers are reused, with inverse-CDF sampling for remaining families." + return _invoke( + "hmath_stochastic_probability_sample", + [["Distribution"], ["RNG"]], + [argument1, argument2], + ) + + +def fit_normal(argument1): + "Normal maximum-likelihood fit; variance divides by n. Constant data are rejected because this continuous family requires positive standard deviation." + return _invoke( + "hmath_stochastic_probability_fit_normal", [["list", ["Double"]]], [argument1] + ) + + +def fit_exponential(argument1): + "Maximum-likelihood rate for nonnegative observations with strictly positive total." + return _invoke( + "hmath_stochastic_probability_fit_exponential", + [["list", ["Double"]]], + [argument1], + ) + + +def fit_bernoulli(argument1): + "Maximum-likelihood probability for nonempty binary observations." + return _invoke( + "hmath_stochastic_probability_fit_bernoulli", + [["list", ["Double"]]], + [argument1], + ) + + +def fit_mle_grid(argument1, argument2): + "Select the maximum-likelihood model from an explicit finite candidate grid; this is grid search, not continuous parameter optimization." + return _invoke( + "hmath_stochastic_probability_fit_mle_grid", + [["list", ["Distribution"]], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def fit_map_grid(argument1, argument2, argument3): + "Select the maximum log-likelihood plus caller-supplied log prior over a finite model grid. Log priors must be finite." + return _invoke( + "hmath_stochastic_probability_fit_map_grid", + [ + ["list", ["Distribution"]], + ["list", ["Double"]], + ["function", ["Distribution"], ["Double"]], + ], + [argument1, argument2, argument3], + ) + + +def beta_bernoulli_update(argument1, argument2, argument3): + "Conjugate Beta prior update from success/failure observations, returning posterior concentrations (alpha,beta)." + return _invoke( + "hmath_stochastic_probability_beta_bernoulli_update", + [["Double"], ["Double"], ["list", ["Bool"]]], + [argument1, argument2, argument3], + ) + + +def goodness_of_fit(argument1, argument2): + "Two-sided one-sample Kolmogorov distance against a specified CDF. Returns the distance only; no discrete-null p-value is implied." + return _invoke( + "hmath_stochastic_probability_goodness_of_fit", + [["Distribution"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def gaussian_kde(argument1, argument2): + "Construct an equal-weight Gaussian kernel density with strictly positive bandwidth and finite nonempty observations." + return _invoke( + "hmath_stochastic_probability_gaussian_kde", + [["Double"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def multivariate_normal_log_density(argument1, argument2, argument3): + "Log density for a finite mean/point and symmetric positive-definite covariance, validated by Cholesky." + return _invoke( + "hmath_stochastic_probability_multivariate_normal_log_density", + [["list", ["Double"]], ["Matrix", ["Double"]], ["list", ["Double"]]], + [argument1, argument2, argument3], + ) + + +def sample_multivariate_normal(argument1, argument2, argument3): + "Cholesky-transform independent standard normals; returns a vector and updated state." + return _invoke( + "hmath_stochastic_probability_sample_multivariate_normal", + [["list", ["Double"]], ["Matrix", ["Double"]], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def wishart_log_density(argument1, argument2, argument3): + "Wishart log density for real degrees of freedom nu>p-1 and positive-definite p-by-p scale and observation matrices." + return _invoke( + "hmath_stochastic_probability_wishart_log_density", + [["Double"], ["Matrix", ["Double"]], ["Matrix", ["Double"]]], + [argument1, argument2, argument3], + ) + + +def sample_wishart(argument1, argument2, argument3): + "Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu\\<=100000." + return _invoke( + "hmath_stochastic_probability_sample_wishart", + [["Int"], ["Matrix", ["Double"]], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def markov(argument1): + "Validate and construct a row-stochastic matrix with 1..1024 states; row sums tolerate absolute error 1e-12." + return _invoke( + "hmath_stochastic_probability_markov", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def transition(argument1, argument2): + "Advance a normalized state-probability row vector by one Markov step." + return _invoke( + "hmath_stochastic_probability_transition", + [["Markov"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def stationary(argument1, argument2, argument3): + "Stationary probabilities by damped power iteration, with caller iteration budget and positive residual tolerance. Reducible chains can have multiple stationary laws." + return _invoke( + "hmath_stochastic_probability_stationary", + [["Int"], ["Double"], ["Markov"]], + [argument1, argument2, argument3], + ) + + +def hmm(argument1, argument2, argument3): + "Validate initial probabilities, square transition matrix and equally sized categorical-emission rows." + return _invoke( + "hmath_stochastic_probability_hmm", + [ + ["list", ["Double"]], + ["list", ["list", ["Double"]]], + ["list", ["list", ["Double"]]], + ], + [argument1, argument2, argument3], + ) + + +def forward(argument1, argument2): + "Scaled forward returns log likelihood, normalized alpha rows and per-time scaling constants. This avoids the product underflow of raw probability DP." + return _invoke( + "hmath_stochastic_probability_forward", + [["HMM"], ["list", ["Int"]]], + [argument1, argument2], + ) + + +def backward(argument1, argument2): + "Scaled backward messages using the same per-time normalizers as forward; terminal message is the all-ones vector." + return _invoke( + "hmath_stochastic_probability_backward", + [["HMM"], ["list", ["Int"]]], + [argument1, argument2], + ) + + +def posterior_states(argument1, argument2): + "Posterior state probabilities at each observation time from normalized alpha-beta products." + return _invoke( + "hmath_stochastic_probability_posterior_states", + [["HMM"], ["list", ["Int"]]], + [argument1, argument2], + ) + + +def viterbi(argument1, argument2): + "Most likely state path and its joint log probability, via max-product dynamic programming in log space." + return _invoke( + "hmath_stochastic_probability_viterbi", + [["HMM"], ["list", ["Int"]]], + [argument1, argument2], + ) + + +def baum_welch(argument1, argument2, argument3, argument4): + "Baum--Welch EM for one observation sequence, pseudocount>=0. Transition rows with zero expected occupancy retain their old row. Fixed iteration budget." + return _invoke( + "hmath_stochastic_probability_baum_welch", + [["Int"], ["Double"], ["HMM"], ["list", ["Int"]]], + [argument1, argument2, argument3, argument4], + ) + + +def bernoulli(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_bernoulli", [["Double"]], [argument1] + ) + + +def binomial(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_binomial", + [["Int"], ["Double"]], + [argument1, argument2], + ) + + +def negative_binomial(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_negative_binomial", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def geometric(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_geometric", [["Double"]], [argument1] + ) + + +def hypergeometric(argument1, argument2, argument3): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_hypergeometric", + [["Int"], ["Int"], ["Int"]], + [argument1, argument2, argument3], + ) + + +def poisson(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_poisson", [["Double"]], [argument1] + ) + + +def categorical(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_categorical", + [["list", ["Double"]]], + [argument1], + ) + + +def discrete_uniform(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_discrete_uniform", + [["Int"], ["Int"]], + [argument1, argument2], + ) + + +def uniform(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_uniform", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def normal(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_normal", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def log_normal(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_log_normal", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def exponential(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_exponential", [["Double"]], [argument1] + ) + + +def gamma(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_gamma", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def beta(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_beta", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def chi_square(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_chi_square", [["Double"]], [argument1] + ) + + +def student_t(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_student_t", [["Double"]], [argument1] + ) + + +def fisher_f(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_fisher_f", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def cauchy(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_cauchy", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def laplace(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_laplace", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def logistic(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_logistic", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def weibull(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_weibull", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def pareto(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_pareto", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def rayleigh(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_rayleigh", [["Double"]], [argument1] + ) + + +def maxwell(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_maxwell", [["Double"]], [argument1] + ) + + +def gumbel(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_gumbel", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def generalized_extreme_value(argument1, argument2, argument3): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_generalized_extreme_value", + [["Double"], ["Double"], ["Double"]], + [argument1, argument2, argument3], + ) + + +def beta_binomial(argument1, argument2, argument3): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_beta_binomial", + [["Int"], ["Double"], ["Double"]], + [argument1, argument2, argument3], + ) + + +def skellam(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_skellam", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def von_mises(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_von_mises", + [["Double"], ["Double"]], + [argument1, argument2], + ) + + +def triangular(argument1, argument2, argument3): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_triangular", + [["Double"], ["Double"], ["Double"]], + [argument1, argument2, argument3], + ) + + +def truncated_normal(argument1, argument2, argument3, argument4): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_truncated_normal", + [["Double"], ["Double"], ["Double"], ["Double"]], + [argument1, argument2, argument3, argument4], + ) + + +def mixture(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_mixture", + [["list", ["tuple", ["Double"], ["Distribution"]]]], + [argument1], + ) + + +def empirical(argument1): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_empirical", + [["list", ["Double"]]], + [argument1], + ) + + +def new_gaussian_kde(argument1, argument2): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke( + "hmath_stochastic_probability_new_gaussian_kde", + [["Double"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +__all__ = [ + "HMM", + "Distribution", + "Markov", + "backward", + "baum_welch", + "bernoulli", + "beta", + "beta_bernoulli_update", + "beta_binomial", + "binomial", + "categorical", + "cauchy", + "cdf", + "chi_square", + "density", + "discrete_uniform", + "empirical", + "entropy", + "expectation", + "exponential", + "fisher_f", + "fit_bernoulli", + "fit_exponential", + "fit_map_grid", + "fit_mle_grid", + "fit_normal", + "forward", + "gamma", + "gaussian_kde", + "generalized_extreme_value", + "geometric", + "goodness_of_fit", + "gumbel", + "hazard", + "hmm", + "hypergeometric", + "laplace", + "log_density", + "log_likelihood", + "log_normal", + "logistic", + "markov", + "maxwell", + "mixture", + "moments", + "multivariate_normal_log_density", + "negative_binomial", + "new_gaussian_kde", + "normal", + "pareto", + "poisson", + "posterior_states", + "quantile", + "rayleigh", + "sample", + "sample_multivariate_normal", + "sample_wishart", + "skellam", + "stationary", + "student_t", + "survival", + "transition", + "triangular", + "truncated_normal", + "uniform", + "validate_distribution", + "viterbi", + "von_mises", + "weibull", + "wishart_log_density", +] diff --git a/bindings/python/_hmath_native/quaternion.py b/bindings/python/_hmath_native/quaternion.py new file mode 100644 index 0000000..3580b56 --- /dev/null +++ b/bindings/python/_hmath_native/quaternion.py @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_rotation_bindings.py; do not edit. +"""Original HMath.Quaternion finite Double operations.""" +from ._rotations_base import Quaternion, _call + +__all__ = [ + "Quaternion", + "add", + "axis_angle", + "components", + "conjugate", + "exponential", + "from_euler", + "from_matrix", + "inverse", + "logarithm", + "multiply", + "nlerp", + "norm", + "normalize", + "quaternion", + "rotate_vector", + "scale", + "slerp", + "squad", + "swing_twist", + "to_axis_angle", + "to_euler", + "to_matrix" +] + + +def quaternion(w, x, y, z): + """Call HMath.Quaternion.quaternion with its original validation and result structure.""" + return _call('hmath_quaternion_quaternion', ['d', 'd', 'd', 'd'], w, x, y, z) + +def components(value): + """Call HMath.Quaternion.components with its original validation and result structure.""" + return _call('hmath_quaternion_components', ['q'], value) + +def norm(value): + """Call HMath.Quaternion.norm with its original validation and result structure.""" + return _call('hmath_quaternion_norm', ['q'], value) + +def normalize(value): + """Call HMath.Quaternion.normalize with its original validation and result structure.""" + return _call('hmath_quaternion_normalize', ['q'], value) + +def inverse(value): + """Call HMath.Quaternion.inverse with its original validation and result structure.""" + return _call('hmath_quaternion_inverse', ['q'], value) + +def conjugate(value): + """Call HMath.Quaternion.conjugate with its original validation and result structure.""" + return _call('hmath_quaternion_conjugate', ['q'], value) + +def multiply(a, b): + """Call HMath.Quaternion.multiply with its original validation and result structure.""" + return _call('hmath_quaternion_multiply', ['q', 'q'], a, b) + +def add(a, b): + """Call HMath.Quaternion.add with its original validation and result structure.""" + return _call('hmath_quaternion_add', ['q', 'q'], a, b) + +def scale(factor, value): + """Call HMath.Quaternion.scale with its original validation and result structure.""" + return _call('hmath_quaternion_scale', ['d', 'q'], factor, value) + +def rotate_vector(value, vector): + """Call HMath.Quaternion.rotateVector with its original validation and result structure.""" + return _call('hmath_quaternion_rotate_vector', ['q', 'v'], value, vector) + +def axis_angle(axis, angle): + """Call HMath.Quaternion.axisAngle with its original validation and result structure.""" + return _call('hmath_quaternion_axis_angle', ['v', 'd'], axis, angle) + +def to_axis_angle(value): + """Call HMath.Quaternion.toAxisAngle with its original validation and result structure.""" + return _call('hmath_quaternion_to_axis_angle', ['q'], value) + +def from_euler(roll, pitch, yaw): + """Call HMath.Quaternion.fromEuler with its original validation and result structure.""" + return _call('hmath_quaternion_from_euler', ['d', 'd', 'd'], roll, pitch, yaw) + +def to_euler(value): + """Call HMath.Quaternion.toEuler with its original validation and result structure.""" + return _call('hmath_quaternion_to_euler', ['q'], value) + +def to_matrix(value): + """Call HMath.Quaternion.toMatrix with its original validation and result structure.""" + return _call('hmath_quaternion_to_matrix', ['q'], value) + +def from_matrix(matrix): + """Call HMath.Quaternion.fromMatrix with its original validation and result structure.""" + return _call('hmath_quaternion_from_matrix', ['m'], matrix) + +def nlerp(fraction, a, b): + """Call HMath.Quaternion.nlerp with its original validation and result structure.""" + return _call('hmath_quaternion_nlerp', ['d', 'q', 'q'], fraction, a, b) + +def slerp(fraction, a, b): + """Call HMath.Quaternion.slerp with its original validation and result structure.""" + return _call('hmath_quaternion_slerp', ['d', 'q', 'q'], fraction, a, b) + +def squad(fraction, q0, q1, q2, q3): + """Call HMath.Quaternion.squad with its original validation and result structure.""" + return _call('hmath_quaternion_squad', ['d', 'q', 'q', 'q', 'q'], fraction, q0, q1, q2, q3) + +def exponential(value): + """Call HMath.Quaternion.exponential with its original validation and result structure.""" + return _call('hmath_quaternion_exponential', ['q'], value) + +def logarithm(value): + """Call HMath.Quaternion.logarithm with its original validation and result structure.""" + return _call('hmath_quaternion_logarithm', ['q'], value) + +def swing_twist(axis, value): + """Call HMath.Quaternion.swingTwist with its original validation and result structure.""" + return _call('hmath_quaternion_swing_twist', ['v', 'q'], axis, value) diff --git a/bindings/python/_hmath_native/random.py b/bindings/python/_hmath_native/random.py new file mode 100644 index 0000000..ddb3564 --- /dev/null +++ b/bindings/python/_hmath_native/random.py @@ -0,0 +1,62 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def importance(values, weights, *, dtype='float64'): + """Call HMath.Random.importance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_random_importance', + ['fs', 'fs'], + 'f', + [values, weights], + dtype, + 0, + ) + + +def halton(dimension, index, *, dtype='float64'): + """Call HMath.Random.halton; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_random_halton', + ['i', 'i'], + 'fd', + [dimension, index], + dtype, + 0, + ) + + +def sobol(dimension, index, *, dtype='float64'): + """Call HMath.Random.sobol; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_random_sobol', + ['i', 'i'], + 'fd', + [dimension, index], + dtype, + 0, + ) + + +def faure(d, ix, *, dtype='float64'): + """Call HMath.Random.faure; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_random_faure', + ['i', 'i'], + 'fd', + [d, ix], + dtype, + 0, + ) + + +from .random_values import * diff --git a/bindings/python/_hmath_native/random_values.py b/bindings/python/_hmath_native/random_values.py new file mode 100644 index 0000000..4747d83 --- /dev/null +++ b/bindings/python/_hmath_native/random_values.py @@ -0,0 +1,438 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_stochastic_bindings.py. +"""Original HMath.Random remaining public functions and owned immutable records.""" + +from ._stochastic_base import StochasticValue, _invoke +from ._value import register + + +class Generator(StochasticValue): + """Original HMath.Random.Generator immutable owner.""" + + +register(241, Generator) + + +class RNG(StochasticValue): + """Original HMath.Random.RNG immutable owner.""" + + def __init__(self, generator, seed): + self._initialize( + "hmath_stochastic_random_seed_rng", + [["Generator"], ["Word64"]], + [generator, seed], + ) + + def serialize(self): + return _invoke("hmath_stochastic_random_serialize_rng", [["RNG"]], [self]) + + +register(240, RNG) + + +class AliasTable(StochasticValue): + """Original HMath.Random.AliasTable immutable owner.""" + + +register(242, AliasTable) + + +def clone_rng(argument1): + "Copy an immutable state; the copy produces exactly the same future outputs." + return _invoke("hmath_stochastic_random_clone_rng", [["RNG"]], [argument1]) + + +def seed_rng(argument1, argument2): + "Deterministically encode a 64-bit seed. Shift engines use SplitMix64 expansion; MT uses the low 32 bits and its standard initialization recurrence. PCG uses a fixed odd stream increment and an offset initial state. Counter engines use the seed as key; ChaCha expands it into a 256-bit simulation key." + return _invoke( + "hmath_stochastic_random_seed_rng", + [["Generator"], ["Word64"]], + [argument1, argument2], + ) + + +def next_word64(argument1): + "Produce one word and its successor state. Fixed-width arithmetic wraps modulo 2^32 or 2^64 as required by the algorithm." + return _invoke("hmath_stochastic_random_next_word64", [["RNG"]], [argument1]) + + +def split_rng(argument1): + "Create two deterministic child streams by hashing two successive parent words. The original immutable parent is unchanged; see the module-level non-overlap caveat." + return _invoke("hmath_stochastic_random_split_rng", [["RNG"]], [argument1]) + + +def serialize_rng(argument1): + "Serialize full state, including pending block output, with the versioned hmath-rng-1 prefix." + return _invoke("hmath_stochastic_random_serialize_rng", [["RNG"]], [argument1]) + + +def restore_rng(argument1): + "Parse a versioned full state and validate generator lengths, forbidden zero states, and MT word/index ranges." + return _invoke("hmath_stochastic_random_restore_rng", [["String"]], [argument1]) + + +def uniform(argument1): + "Uniform 53-bit real on [0,1), using the most significant random bits." + return _invoke("hmath_stochastic_random_uniform", [["RNG"]], [argument1]) + + +def uniform_open(argument1): + "Uniform 52-bit midpoint real on (0,1), safe as input to logarithms." + return _invoke("hmath_stochastic_random_uniform_open", [["RNG"]], [argument1]) + + +def uniform_int(argument1, argument2, argument3): + "Unbiased inclusive integer range using 64-bit rejection. Supports the complete machine Int range; rejects reversed bounds." + return _invoke( + "hmath_stochastic_random_uniform_int", + [["Int"], ["Int"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def sample_n(argument1, argument2, argument3): + "Run a checked sampler sequentially, returning values and final state. Count must lie in [0,10000000]." + return _invoke( + "hmath_stochastic_random_sample_n", + [ + ["Int"], + ["function", ["RNG"], ["Either", ["MathError"], ["tuple", ["a"], ["RNG"]]]], + ["RNG"], + ], + [argument1, argument2, argument3], + ) + + +def box_muller(argument1): + "Standard normal through the polar-coordinate Box--Muller transform, consuming two uniforms." + return _invoke("hmath_stochastic_random_box_muller", [["RNG"]], [argument1]) + + +def marsaglia_normal(argument1): + "Standard normal through Marsaglia polar disk rejection, with 10000-proposal budget." + return _invoke("hmath_stochastic_random_marsaglia_normal", [["RNG"]], [argument1]) + + +def ziggurat_normal(argument1): + "Marsaglia--Tsang 128-layer Ziggurat normal generator. Horizontal rectangles have equal area; the base includes an exponentially proposed tail. Published normal cutoff/area constants: https://doi.org/10.18637/jss.v005.i08 Tables are generated by the area recurrence, not embedded implementation data." + return _invoke("hmath_stochastic_random_ziggurat_normal", [["RNG"]], [argument1]) + + +def normal(argument1, argument2, argument3): + "Normal sample with finite mean and strictly positive standard deviation. Arithmetic overflow returns NonFiniteResult." + return _invoke( + "hmath_stochastic_random_normal", + [["Double"], ["Double"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def exponential(argument1, argument2): + "Exponential sample parameterized by strictly positive rate, via an open-uniform logarithm." + return _invoke( + "hmath_stochastic_random_exponential", + [["Double"], ["RNG"]], + [argument1, argument2], + ) + + +def gamma(argument1, argument2, argument3): + "Gamma shape/scale sample using Marsaglia--Tsang rejection and the shape-augmentation identity below shape one; 10000-proposal budget." + return _invoke( + "hmath_stochastic_random_gamma", + [["Double"], ["Double"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def beta(argument1, argument2, argument3): + "Beta(a,b) as the ratio of independent gamma variates. Positive parameters required; unresolved underflow returns an error." + return _invoke( + "hmath_stochastic_random_beta", + [["Double"], ["Double"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def poisson(argument1, argument2): + "Poisson count by exponential-arrival inversion. Rate is in [0,100000], work is capped at one million arrivals." + return _invoke( + "hmath_stochastic_random_poisson", [["Double"], ["RNG"]], [argument1, argument2] + ) + + +def binomial(argument1, argument2, argument3): + "Binomial count from n independent Bernoulli trials. n<=10000000 and p in [0,1]." + return _invoke( + "hmath_stochastic_random_binomial", + [["Int"], ["Double"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def weighted(argument1, argument2): + "Draw an index in proportion to finite nonnegative weights; max scaling handles subnormal or overflowing totals and zero weights are never selected." + return _invoke( + "hmath_stochastic_random_weighted", + [["list", ["Double"]], ["RNG"]], + [argument1, argument2], + ) + + +def alias_table(argument1): + "Build a Walker alias table from finite nonnegative weights with positive maximum; max scaling avoids overflow." + return _invoke( + "hmath_stochastic_random_alias_table", [["list", ["Double"]]], [argument1] + ) + + +def alias_sample(argument1, argument2): + "Draw an index from an already validated alias table, using one uniform integer and one uniform real." + return _invoke( + "hmath_stochastic_random_alias_sample", + [["AliasTable"], ["RNG"]], + [argument1, argument2], + ) + + +def shuffle(argument1, argument2): + "Fisher--Yates permutation of list positions. This immutable list reference implementation costs quadratic time." + return _invoke( + "hmath_stochastic_random_shuffle", + [["list", ["a"]], ["RNG"]], + [argument1, argument2], + ) + + +def with_replacement(argument1, argument2, argument3): + "Draw count values independently from a nonempty finite population, preserving duplicates." + return _invoke( + "hmath_stochastic_random_with_replacement", + [["Int"], ["list", ["a"]], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def without_replacement(argument1, argument2, argument3): + "Uniform subset in shuffled order. Count cannot exceed population length; uniqueness is by position." + return _invoke( + "hmath_stochastic_random_without_replacement", + [["Int"], ["list", ["a"]], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def reservoir(argument1, argument2, argument3): + "Algorithm R reservoir over a finite stream, retaining k positions uniformly without replacement." + return _invoke( + "hmath_stochastic_random_reservoir", + [["Int"], ["list", ["a"]], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def stratified(argument1, argument2): + "One uniform point per equal-width interval of [0,1), in increasing stratum order." + return _invoke( + "hmath_stochastic_random_stratified", [["Int"], ["RNG"]], [argument1, argument2] + ) + + +def rejection(argument1, argument2, argument3, argument4): + "Accept proposals with the supplied target/envelope probability in [0,1]; the first argument is a hard proposal budget." + return _invoke( + "hmath_stochastic_random_rejection", + [ + ["Int"], + ["function", ["Double"], ["Double"]], + [ + "function", + ["RNG"], + ["Either", ["MathError"], ["tuple", ["Double"], ["RNG"]]], + ], + ["RNG"], + ], + [argument1, argument2, argument3, argument4], + ) + + +def inverse_transform(argument1, argument2): + "Apply a checked inverse CDF to an open uniform; propagates inverse-domain or nonconvergence errors." + return _invoke( + "hmath_stochastic_random_inverse_transform", + [["function", ["Double"], ["Either", ["MathError"], ["Double"]]], ["RNG"]], + [argument1, argument2], + ) + + +def metropolis_hastings(argument1, argument2, argument3, argument4, argument5): + "Symmetric random-walk Metropolis in log density. Returned chain includes each post-proposal state. Non-finite log densities are rejected." + return _invoke( + "hmath_stochastic_random_metropolis_hastings", + [ + ["Int"], + ["Double"], + ["function", ["Double"], ["Double"]], + ["Double"], + ["RNG"], + ], + [argument1, argument2, argument3, argument4, argument5], + ) + + +def gibbs(argument1, argument2, argument3, argument4): + "A full Gibbs sweep uses caller-supplied exact conditional samplers in coordinate order. Shape is checked after each conditional." + return _invoke( + "hmath_stochastic_random_gibbs", + [ + ["Int"], + [ + "list", + [ + "function", + ["list", ["Double"]], + ["RNG"], + ["Either", ["MathError"], ["tuple", ["Double"], ["RNG"]]], + ], + ], + ["list", ["Double"]], + ["RNG"], + ], + [argument1, argument2, argument3, argument4], + ) + + +def hamiltonian_monte_carlo( + argument1, argument2, argument3, argument4, argument5, argument6, argument7 +): + "Identity-mass HMC with Gaussian momentum, leapfrog count and positive step size, log density and its gradient. Returns post-Metropolis states; finite-gradient shapes are checked." + return _invoke( + "hmath_stochastic_random_hamiltonian_monte_carlo", + [ + ["Int"], + ["Int"], + ["Double"], + ["function", ["list", ["Double"]], ["Double"]], + ["function", ["list", ["Double"]], ["list", ["Double"]]], + ["list", ["Double"]], + ["RNG"], + ], + [argument1, argument2, argument3, argument4, argument5, argument6, argument7], + ) + + +def monte_carlo(argument1, argument2, argument3): + "Uniform-[0,1] Monte Carlo integral and estimated standard error from at least two draws. This is a stochastic estimate, not a certified bound." + return _invoke( + "hmath_stochastic_random_monte_carlo", + [["function", ["Double"], ["Double"]], ["Int"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def latin_hypercube(argument1, argument2, argument3): + "Random n-by-d Latin hypercube in [0,1), with a separate Fisher--Yates stratum permutation per axis; n>0 and 1<=d<=1024." + return _invoke( + "hmath_stochastic_random_latin_hypercube", + [["Int"], ["Int"], ["RNG"]], + [argument1, argument2, argument3], + ) + + +def random_quality(argument1, argument2): + "Mean, population variance, and lag-one correlation; descriptive quality diagnostics, not a cryptographic certification or a replacement for TestU01." + return _invoke( + "hmath_stochastic_random_random_quality", + [["Int"], ["RNG"]], + [argument1, argument2], + ) + + +def entropy_seed(): + "Read eight bytes from the operating system entropy device, little endian. IO exceptions are propagated; this deliberately has no time-based fallback." + return _invoke("hmath_stochastic_random_entropy_seed", [], []) + + +def pcg32(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_pcg32", [], []) + + +def xoshiro256_star_star(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_xoshiro256_star_star", [], []) + + +def xoroshiro128_plus(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_xoroshiro128_plus", [], []) + + +def mt19937(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_mt19937", [], []) + + +def philox4x32(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_philox4x32", [], []) + + +def threefry2x64(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_threefry2x64", [], []) + + +def cha_cha20(): + "Construct the original public variant; positional fields retain their exact source types and order." + return _invoke("hmath_stochastic_random_new_cha_cha20", [], []) + + +__all__ = [ + "RNG", + "AliasTable", + "Generator", + "alias_sample", + "alias_table", + "beta", + "binomial", + "box_muller", + "cha_cha20", + "clone_rng", + "entropy_seed", + "exponential", + "gamma", + "gibbs", + "hamiltonian_monte_carlo", + "inverse_transform", + "latin_hypercube", + "marsaglia_normal", + "metropolis_hastings", + "monte_carlo", + "mt19937", + "next_word64", + "normal", + "pcg32", + "philox4x32", + "poisson", + "random_quality", + "rejection", + "reservoir", + "restore_rng", + "sample_n", + "seed_rng", + "serialize_rng", + "shuffle", + "split_rng", + "stratified", + "threefry2x64", + "uniform", + "uniform_int", + "uniform_open", + "weighted", + "with_replacement", + "without_replacement", + "xoroshiro128_plus", + "xoshiro256_star_star", + "ziggurat_normal", +] diff --git a/bindings/python/_hmath_native/root.py b/bindings/python/_hmath_native/root.py new file mode 100644 index 0000000..80bd7fd --- /dev/null +++ b/bindings/python/_hmath_native/root.py @@ -0,0 +1,275 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numerical_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class RootOptions(Value): + """Owned immutable original HMath.Root.RootOptions.""" + + +register(204, RootOptions) + + +class RootResult(Value): + """Owned immutable original HMath.Root.RootResult.""" + + +register(205, RootResult) + + +class Bracket(Value): + """Owned immutable original HMath.Root.Bracket.""" + + +register(206, Bracket) + + +class BracketMethod(Value): + """Owned immutable original HMath.Root.BracketMethod.""" + + +register(207, BracketMethod) + + +class DerivativeMethod(Value): + """Owned immutable original HMath.Root.DerivativeMethod.""" + + +register(208, DerivativeMethod) + + +class FixedPointMethod(Value): + """Owned immutable original HMath.Root.FixedPointMethod.""" + + +register(209, FixedPointMethod) + + +class SystemMethod(Value): + """Owned immutable original HMath.Root.SystemMethod.""" + + +register(210, SystemMethod) + + +class SystemRootResult(Value): + """Owned immutable original HMath.Root.SystemRootResult.""" + + +register(211, SystemRootResult) + + +def root_options(root_max_iterations, root_max_evaluations, root_tolerance, root_step_tolerance): + """HMath.Root.RootOptions :: Int -> Int -> Double -> Double -> RootOptions.""" + return _invoke('hmath_root_root_options', [['Int'], ['Int'], ['Double'], ['Double']], [root_max_iterations, root_max_evaluations, root_tolerance, root_step_tolerance]) + + +def root_max_iterations(value): + """HMath.Root.rootMaxIterations :: RootOptions -> Int.""" + return _invoke('hmath_root_root_max_iterations', [['RootOptions']], [value]) + + +def root_max_evaluations(value): + """HMath.Root.rootMaxEvaluations :: RootOptions -> Int.""" + return _invoke('hmath_root_root_max_evaluations', [['RootOptions']], [value]) + + +def root_tolerance(value): + """HMath.Root.rootTolerance :: RootOptions -> Double.""" + return _invoke('hmath_root_root_tolerance', [['RootOptions']], [value]) + + +def root_step_tolerance(value): + """HMath.Root.rootStepTolerance :: RootOptions -> Double.""" + return _invoke('hmath_root_root_step_tolerance', [['RootOptions']], [value]) + + +def default_root_options(): + """HMath.Root.defaultRootOptions :: RootOptions.""" + return _invoke('hmath_root_default_root_options', [], []) + + +def root_result(root_value, root_residual, root_error_bound, root_iterations, root_evaluations): + """HMath.Root.RootResult :: Double -> Double -> Maybe Double -> Int -> Int -> RootResult.""" + return _invoke('hmath_root_root_result', [['Double'], ['Double'], ['maybe', ['Double']], ['Int'], ['Int']], [root_value, root_residual, root_error_bound, root_iterations, root_evaluations]) + + +def root_value(value): + """HMath.Root.rootValue :: RootResult -> Double.""" + return _invoke('hmath_root_root_value', [['RootResult']], [value]) + + +def root_residual(value): + """HMath.Root.rootResidual :: RootResult -> Double.""" + return _invoke('hmath_root_root_residual', [['RootResult']], [value]) + + +def root_error_bound(value): + """HMath.Root.rootErrorBound :: RootResult -> Maybe Double.""" + return _invoke('hmath_root_root_error_bound', [['RootResult']], [value]) + + +def root_iterations(value): + """HMath.Root.rootIterations :: RootResult -> Int.""" + return _invoke('hmath_root_root_iterations', [['RootResult']], [value]) + + +def root_evaluations(value): + """HMath.Root.rootEvaluations :: RootResult -> Int.""" + return _invoke('hmath_root_root_evaluations', [['RootResult']], [value]) + + +def bisection(): + """HMath.Root.Bisection :: BracketMethod.""" + return _invoke('hmath_root_bisection', [], []) + + +def regula_falsi(): + """HMath.Root.RegulaFalsi :: BracketMethod.""" + return _invoke('hmath_root_regula_falsi', [], []) + + +def illinois(): + """HMath.Root.Illinois :: BracketMethod.""" + return _invoke('hmath_root_illinois', [], []) + + +def brent(): + """HMath.Root.Brent :: BracketMethod.""" + return _invoke('hmath_root_brent', [], []) + + +def ridder(): + """HMath.Root.Ridder :: BracketMethod.""" + return _invoke('hmath_root_ridder', [], []) + + +def newton(): + """HMath.Root.Newton :: DerivativeMethod.""" + return _invoke('hmath_root_newton', [], []) + + +def halley(): + """HMath.Root.Halley :: DerivativeMethod.""" + return _invoke('hmath_root_halley', [], []) + + +def householder3(): + """HMath.Root.Householder3 :: DerivativeMethod.""" + return _invoke('hmath_root_householder3', [], []) + + +def picard(): + """HMath.Root.Picard :: FixedPointMethod.""" + return _invoke('hmath_root_picard', [], []) + + +def aitken(): + """HMath.Root.Aitken :: FixedPointMethod.""" + return _invoke('hmath_root_aitken', [], []) + + +def steffensen_fixed(): + """HMath.Root.SteffensenFixed :: FixedPointMethod.""" + return _invoke('hmath_root_steffensen_fixed', [], []) + + +def multivariate_newton(): + """HMath.Root.MultivariateNewton :: SystemMethod.""" + return _invoke('hmath_root_multivariate_newton', [], []) + + +def newton_trust_region(value): + """HMath.Root.NewtonTrustRegion :: Double -> SystemMethod.""" + return _invoke('hmath_root_newton_trust_region', [['Double']], [value]) + + +def broyden(): + """HMath.Root.Broyden :: SystemMethod.""" + return _invoke('hmath_root_broyden', [], []) + + +def system_root_result(system_root, system_residual, system_iterations, system_evaluations): + """HMath.Root.SystemRootResult :: [Double] -> Double -> Int -> Int -> SystemRootResult.""" + return _invoke('hmath_root_system_root_result', [['list', ['Double']], ['Double'], ['Int'], ['Int']], [system_root, system_residual, system_iterations, system_evaluations]) + + +def system_root(value): + """HMath.Root.systemRoot :: SystemRootResult -> [Double].""" + return _invoke('hmath_root_system_root', [['SystemRootResult']], [value]) + + +def system_residual(value): + """HMath.Root.systemResidual :: SystemRootResult -> Double.""" + return _invoke('hmath_root_system_residual', [['SystemRootResult']], [value]) + + +def system_iterations(value): + """HMath.Root.systemIterations :: SystemRootResult -> Int.""" + return _invoke('hmath_root_system_iterations', [['SystemRootResult']], [value]) + + +def system_evaluations(value): + """HMath.Root.systemEvaluations :: SystemRootResult -> Int.""" + return _invoke('hmath_root_system_evaluations', [['SystemRootResult']], [value]) + + +def bracket(f, a, b): + """HMath.Root.bracket :: (Double -> Double) -> Double -> Double -> Either MathError Bracket.""" + return _invoke('hmath_root_bracket', [['function', ['Double'], ['Double']], ['Double'], ['Double']], [f, a, b]) + + +def solve_bracket(value, value2, value3, value4): + """HMath.Root.solveBracket :: BracketMethod -> RootOptions -> (Double -> Double) -> Bracket -> Either MathError RootResult.""" + return _invoke('hmath_root_solve_bracket', [['BracketMethod'], ['RootOptions'], ['function', ['Double'], ['Double']], ['Bracket']], [value, value2, value3, value4]) + + +def bracket_scan(o, f, a, b, cells): + """HMath.Root.bracketScan :: RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [Bracket].""" + return _invoke('hmath_root_bracket_scan', [['RootOptions'], ['function', ['Double'], ['Double']], ['Double'], ['Double'], ['Int']], [o, f, a, b, cells]) + + +def isolate_intervals(o, f, a, b, cells): + """HMath.Root.isolateIntervals :: RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [RootResult].""" + return _invoke('hmath_root_isolate_intervals', [['RootOptions'], ['function', ['Double'], ['Double']], ['Double'], ['Double'], ['Int']], [o, f, a, b, cells]) + + +def solve_derivative(method, o, f, derivatives, x0): + """HMath.Root.solveDerivative :: DerivativeMethod -> RootOptions -> (Double -> Double) -> [Double -> Double] -> Double -> Either MathError RootResult.""" + return _invoke('hmath_root_solve_derivative', [['DerivativeMethod'], ['RootOptions'], ['function', ['Double'], ['Double']], ['list', ['function', ['Double'], ['Double']]], ['Double']], [method, o, f, derivatives, x0]) + + +def secant(o, f, a, b): + """HMath.Root.secant :: RootOptions -> (Double -> Double) -> Double -> Double -> Either MathError RootResult.""" + return _invoke('hmath_root_secant', [['RootOptions'], ['function', ['Double'], ['Double']], ['Double'], ['Double']], [o, f, a, b]) + + +def steffensen(o, f, x0): + """HMath.Root.steffensen :: RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult.""" + return _invoke('hmath_root_steffensen', [['RootOptions'], ['function', ['Double'], ['Double']], ['Double']], [o, f, x0]) + + +def fixed_point(method, o, g, x0): + """HMath.Root.fixedPoint :: FixedPointMethod -> RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult.""" + return _invoke('hmath_root_fixed_point', [['FixedPointMethod'], ['RootOptions'], ['function', ['Double'], ['Double']], ['Double']], [method, o, g, x0]) + + +def anderson(depth, regularization, o, g, x0): + """HMath.Root.anderson :: Int -> Double -> RootOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError SystemRootResult.""" + return _invoke('hmath_root_anderson', [['Int'], ['Double'], ['RootOptions'], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['Double']]], [depth, regularization, o, g, x0]) + + +def solve_system(method, o, f, jac, x0): + """HMath.Root.solveSystem :: SystemMethod -> RootOptions -> ([Double] -> [Double]) -> ([Double] -> [[Double]]) -> [Double] -> Either MathError SystemRootResult.""" + return _invoke('hmath_root_solve_system', [['SystemMethod'], ['RootOptions'], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['list', ['Double']]]], ['list', ['Double']]], [method, o, f, jac, x0]) + + +def polynomial_roots(o, p): + """HMath.Root.polynomialRoots :: RootOptions -> P.Polynomial (Complex Double) -> Either MathError [Complex Double].""" + return _invoke('hmath_root_polynomial_roots', [['RootOptions'], ['ComplexPolynomial']], [o, p]) + + +def real_polynomial_roots(budget, tolerance, p): + """HMath.Root.realPolynomialRoots :: Int -> Rational -> P.Polynomial Rational -> Either MathError [(Rational, Rational, Int)].""" + return _invoke('hmath_root_real_polynomial_roots', [['Int'], ['Rational'], ['RationalPolynomial']], [budget, tolerance, p]) diff --git a/bindings/python/_hmath_native/rotation.py b/bindings/python/_hmath_native/rotation.py new file mode 100644 index 0000000..3e6bbdb --- /dev/null +++ b/bindings/python/_hmath_native/rotation.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_rotation_bindings.py; do not edit. +"""Original HMath.Rotation finite Double operations.""" +from ._rotations_base import SE3, SO3, DualQuaternion, _call + +__all__ = [ + "SE3", + "SO3", + "DualQuaternion", + "compose", + "compose_rotation", + "dual_parts", + "dual_quaternion", + "exp_se3", + "exp_so3", + "from_dual_quaternion", + "from_homogeneous", + "identity_rotation", + "identity_transform", + "interpolate_dual", + "inverse", + "inverse_dual", + "inverse_rotation", + "log_se3", + "log_so3", + "multiply_dual", + "rotate", + "rotation_part", + "rotation_quaternion", + "se3", + "so3", + "to_dual_quaternion", + "to_homogeneous", + "transform_point", + "translation_part" +] + + +def so3(value): + """Call HMath.Rotation.so3 with its original validation and result structure.""" + return _call('hmath_rotation_so3', ['q'], value) + +def rotation_quaternion(value): + """Call HMath.Rotation.rotationQuaternion with its original validation and result structure.""" + return _call('hmath_rotation_rotation_quaternion', ['r'], value) + +def identity_rotation(): + """Call HMath.Rotation.identityRotation with its original validation and result structure.""" + return _call('hmath_rotation_identity_rotation', []) + +def compose_rotation(a, b): + """Call HMath.Rotation.composeRotation with its original validation and result structure.""" + return _call('hmath_rotation_compose_rotation', ['r', 'r'], a, b) + +def inverse_rotation(value): + """Call HMath.Rotation.inverseRotation with its original validation and result structure.""" + return _call('hmath_rotation_inverse_rotation', ['r'], value) + +def rotate(value, vector): + """Call HMath.Rotation.rotate with its original validation and result structure.""" + return _call('hmath_rotation_rotate', ['r', 'v'], value, vector) + +def exp_so3(omega): + """Call HMath.Rotation.expSO3 with its original validation and result structure.""" + return _call('hmath_rotation_exp_so3', ['v'], omega) + +def log_so3(value): + """Call HMath.Rotation.logSO3 with its original validation and result structure.""" + return _call('hmath_rotation_log_so3', ['r'], value) + +def se3(rotation, translation): + """Call HMath.Rotation.se3 with its original validation and result structure.""" + return _call('hmath_rotation_se3', ['r', 'v'], rotation, translation) + +def rotation_part(value): + """Call HMath.Rotation.rotationPart with its original validation and result structure.""" + return _call('hmath_rotation_rotation_part', ['t'], value) + +def translation_part(value): + """Call HMath.Rotation.translationPart with its original validation and result structure.""" + return _call('hmath_rotation_translation_part', ['t'], value) + +def identity_transform(): + """Call HMath.Rotation.identityTransform with its original validation and result structure.""" + return _call('hmath_rotation_identity_transform', []) + +def compose(a, b): + """Call HMath.Rotation.compose with its original validation and result structure.""" + return _call('hmath_rotation_compose', ['t', 't'], a, b) + +def inverse(value): + """Call HMath.Rotation.inverse with its original validation and result structure.""" + return _call('hmath_rotation_inverse', ['t'], value) + +def transform_point(value, point): + """Call HMath.Rotation.transformPoint with its original validation and result structure.""" + return _call('hmath_rotation_transform_point', ['t', 'v'], value, point) + +def exp_se3(twist): + """Call HMath.Rotation.expSE3 with its original validation and result structure.""" + return _call('hmath_rotation_exp_se3', ['twist'], twist) + +def log_se3(value): + """Call HMath.Rotation.logSE3 with its original validation and result structure.""" + return _call('hmath_rotation_log_se3', ['t'], value) + +def to_homogeneous(value): + """Call HMath.Rotation.toHomogeneous with its original validation and result structure.""" + return _call('hmath_rotation_to_homogeneous', ['t'], value) + +def from_homogeneous(matrix): + """Call HMath.Rotation.fromHomogeneous with its original validation and result structure.""" + return _call('hmath_rotation_from_homogeneous', ['m'], matrix) + +def dual_quaternion(real, dual): + """Call HMath.Rotation.dualQuaternion with its original validation and result structure.""" + return _call('hmath_rotation_dual_quaternion', ['q', 'q'], real, dual) + +def dual_parts(value): + """Call HMath.Rotation.dualParts with its original validation and result structure.""" + return _call('hmath_rotation_dual_parts', ['dq'], value) + +def to_dual_quaternion(value): + """Call HMath.Rotation.toDualQuaternion with its original validation and result structure.""" + return _call('hmath_rotation_to_dual_quaternion', ['t'], value) + +def from_dual_quaternion(value): + """Call HMath.Rotation.fromDualQuaternion with its original validation and result structure.""" + return _call('hmath_rotation_from_dual_quaternion', ['dq'], value) + +def multiply_dual(a, b): + """Call HMath.Rotation.multiplyDual with its original validation and result structure.""" + return _call('hmath_rotation_multiply_dual', ['dq', 'dq'], a, b) + +def inverse_dual(value): + """Call HMath.Rotation.inverseDual with its original validation and result structure.""" + return _call('hmath_rotation_inverse_dual', ['dq'], value) + +def interpolate_dual(fraction, a, b): + """Call HMath.Rotation.interpolateDual with its original validation and result structure.""" + return _call('hmath_rotation_interpolate_dual', ['d', 'dq', 'dq'], fraction, a, b) diff --git a/bindings/python/_hmath_native/scalar.py b/bindings/python/_hmath_native/scalar.py new file mode 100644 index 0000000..901c809 --- /dev/null +++ b/bindings/python/_hmath_native/scalar.py @@ -0,0 +1,975 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call +from ._numeric_objects import _call_value, _uses_value + + +def add(a, b, *, dtype='float64'): + """Call HMath.Scalar.add; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_add', ['f', 'f'], [a, b], dtype) + variants = { + 'float32': (['f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + 'complex64': (['c', 'c'], 'c', 'float32', '_c64'), + 'complex128': (['c', 'c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_add', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def subtract_scalar(a, b, *, dtype='float64'): + """Call HMath.Scalar.subtractScalar; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_subtract_scalar', ['f', 'f'], [a, b], dtype) + variants = { + 'float32': (['f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + 'complex64': (['c', 'c'], 'c', 'float32', '_c64'), + 'complex128': (['c', 'c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_subtract_scalar', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def multiply(a, b, *, dtype='float64'): + """Call HMath.Scalar.multiply; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_multiply', ['f', 'f'], [a, b], dtype) + variants = { + 'float32': (['f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + 'complex64': (['c', 'c'], 'c', 'float32', '_c64'), + 'complex128': (['c', 'c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_multiply', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def minimum_scalar(a, b, *, dtype='float64'): + """Call HMath.Scalar.minimumScalar; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=True): + return _call_value('hmath_scalar_minimum_scalar', ['f', 'f'], [a, b], dtype) + variants = { + 'float32': (['f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_minimum_scalar', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def maximum_scalar(a, b, *, dtype='float64'): + """Call HMath.Scalar.maximumScalar; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=True): + return _call_value('hmath_scalar_maximum_scalar', ['f', 'f'], [a, b], dtype) + variants = { + 'float32': (['f', 'f'], 'f', 'float32', '_f32'), + 'float64': (['f', 'f'], 'f', 'float64', '_f64'), + 'rational': (['q', 'q'], 'q', None, '_rational'), + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_maximum_scalar', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def absolute(x, *, dtype='float64'): + """Call HMath.Scalar.absolute; preserve its argument order, result and errors.""" + if _uses_value([x], dtype, ordered=False): + return _call_value('hmath_scalar_absolute', ['f'], [x], dtype) + variants = { + 'float32': (['f'], 'f', 'float32', '_f32'), + 'float64': (['f'], 'f', 'float64', '_f64'), + 'rational': (['q'], 'q', None, '_rational'), + 'integer': (['z'], 'z', None, '_integer'), + 'int8': (['int8'], 'int8', None, '_i8'), + 'int16': (['int16'], 'int16', None, '_i16'), + 'int32': (['int32'], 'int32', None, '_i32'), + 'int64': (['int64'], 'int64', None, '_i64'), + 'uint8': (['uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64'], 'uint64', None, '_u64'), + 'intp': (['intp'], 'intp', None, '_int'), + 'uintp': (['uintp'], 'uintp', None, '_word'), + 'complex64': (['c'], 'c', 'float32', '_c64'), + 'complex128': (['c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_absolute', kinds, result, [x], precision, 0, symbol_suffix=suffix) + + +def sign(x, *, dtype='float64'): + """Call HMath.Scalar.sign; preserve its argument order, result and errors.""" + if _uses_value([x], dtype, ordered=False): + return _call_value('hmath_scalar_sign', ['f'], [x], dtype) + variants = { + 'float32': (['f'], 'f', 'float32', '_f32'), + 'float64': (['f'], 'f', 'float64', '_f64'), + 'rational': (['q'], 'q', None, '_rational'), + 'integer': (['z'], 'z', None, '_integer'), + 'int8': (['int8'], 'int8', None, '_i8'), + 'int16': (['int16'], 'int16', None, '_i16'), + 'int32': (['int32'], 'int32', None, '_i32'), + 'int64': (['int64'], 'int64', None, '_i64'), + 'uint8': (['uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64'], 'uint64', None, '_u64'), + 'intp': (['intp'], 'intp', None, '_int'), + 'uintp': (['uintp'], 'uintp', None, '_word'), + 'complex64': (['c'], 'c', 'float32', '_c64'), + 'complex128': (['c'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_sign', kinds, result, [x], precision, 0, symbol_suffix=suffix) + + +def divide(a, b, *, dtype='float64'): + """Call HMath.Scalar.divide; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_divide', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def power(a, b, *, dtype='float64'): + """Call HMath.Scalar.power; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_power', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def hypot(a, b, *, dtype='float64'): + """Call HMath.Scalar.hypot; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_hypot', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def clamp_checked(low, high, value, *, dtype='float64'): + """Call HMath.Scalar.clampChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_clamp_checked', + ['f', 'f', 'f'], + 'f', + [low, high, value], + dtype, + 0, + ) + + +def lerp_checked(a, b, t, *, dtype='float64'): + """Call HMath.Scalar.lerpChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_lerp_checked', + ['f', 'f', 'f'], + 'f', + [a, b, t], + dtype, + 0, + ) + + +def inverse_lerp(a, b, x, *, dtype='float64'): + """Call HMath.Scalar.inverseLerp; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_inverse_lerp', + ['f', 'f', 'f'], + 'f', + [a, b, x], + dtype, + 0, + ) + + +def smoothstep(a, b, x, *, dtype='float64'): + """Call HMath.Scalar.smoothstep; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_smoothstep', + ['f', 'f', 'f'], + 'f', + [a, b, x], + dtype, + 0, + ) + + +def smootherstep(a, b, x, *, dtype='float64'): + """Call HMath.Scalar.smootherstep; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_smootherstep', + ['f', 'f', 'f'], + 'f', + [a, b, x], + dtype, + 0, + ) + + +def remap(a, b, c, d, x, *, dtype='float64'): + """Call HMath.Scalar.remap; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_remap', + ['f', 'f', 'f', 'f', 'f'], + 'f', + [a, b, c, d, x], + dtype, + 0, + ) + + +def step(edge, x, *, dtype='float64'): + """Call HMath.Scalar.step; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_step', + ['f', 'f'], + 'f', + [edge, x], + dtype, + 0, + ) + + +def sqrt_checked(x, *, dtype='float64'): + """Call HMath.Scalar.sqrtChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_sqrt_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def cube_root(x, *, dtype='float64'): + """Call HMath.Scalar.cubeRoot; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_cube_root', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def reciprocal_sqrt(x, *, dtype='float64'): + """Call HMath.Scalar.reciprocalSqrt; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_reciprocal_sqrt', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def exp_checked(x, *, dtype='float64'): + """Call HMath.Scalar.expChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_exp_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def log_checked(x, *, dtype='float64'): + """Call HMath.Scalar.logChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_log_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def expm1(x, *, dtype='float64'): + """Call HMath.Scalar.expm1; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_expm1', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def log1p(x, *, dtype='float64'): + """Call HMath.Scalar.log1p; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_log1p', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def integer_power(a, n, *, dtype='float64'): + """Call HMath.Scalar.integerPower; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_integer_power', + ['f', 'z'], + 'f', + [a, n], + dtype, + 0, + ) + + +def nth_root(n, x, *, dtype='float64'): + """Call HMath.Scalar.nthRoot; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_nth_root', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def round_digits(n, x, *, dtype='float64'): + """Call HMath.Scalar.roundDigits; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_round_digits', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def absolute_error(actual, expected, *, dtype='float64'): + """Call HMath.Scalar.absoluteError; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_absolute_error', + ['f', 'f'], + 'f', + [actual, expected], + dtype, + 0, + ) + + +def relative_error(actual, expected, *, dtype='float64'): + """Call HMath.Scalar.relativeError; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_relative_error', + ['f', 'f'], + 'f', + [actual, expected], + dtype, + 0, + ) + + +def fused_multiply_add(a, b, c, *, dtype='float64'): + """Call HMath.Scalar.fusedMultiplyAdd; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_fused_multiply_add', + ['f', 'f', 'f'], + 'f', + [a, b, c], + dtype, + 0, + ) + + +def checked_float_multiply(a, b, *, dtype='float64'): + """Call HMath.Scalar.checkedFloatMultiply; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_checked_float_multiply', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def floor_checked(x, *, dtype='float64'): + """Call HMath.Scalar.floorChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_floor_checked', + ['f'], + 'z', + [x], + dtype, + 0, + ) + + +def ceil_checked(x, *, dtype='float64'): + """Call HMath.Scalar.ceilChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_ceil_checked', + ['f'], + 'z', + [x], + dtype, + 0, + ) + + +def round_checked(x, *, dtype='float64'): + """Call HMath.Scalar.roundChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_round_checked', + ['f'], + 'z', + [x], + dtype, + 0, + ) + + +def truncate_checked(x, *, dtype='float64'): + """Call HMath.Scalar.truncateChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_truncate_checked', + ['f'], + 'z', + [x], + dtype, + 0, + ) + + +def bankers_round(x, *, dtype='float64'): + """Call HMath.Scalar.bankersRound; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_bankers_round', + ['f'], + 'z', + [x], + dtype, + 0, + ) + + +def integer_fraction(x, *, dtype='float64'): + """Call HMath.Scalar.integerFraction; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_integer_fraction', + ['f'], + 'zf', + [x], + dtype, + 0, + ) + + +def quotient_remainder(a, b): + """Call HMath.Scalar.quotientRemainder; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_quotient_remainder', + ['z', 'z'], + 'zz', + [a, b], + None, + 0, + ) + + +def euclidean_division(a, b): + """Call HMath.Scalar.euclideanDivision; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_euclidean_division', + ['z', 'z'], + 'zz', + [a, b], + None, + 0, + ) + + +def positive_modulo(a, modulus, *, dtype='integer'): + """Call HMath.Scalar.positiveModulo; preserve its argument order, result and errors.""" + if _uses_value([a, modulus], dtype, ordered=False): + return _call_value('hmath_scalar_positive_modulo', ['z', 'z'], [a, modulus], dtype) + variants = { + 'integer': (['z', 'z'], 'z', None, '_integer'), + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_positive_modulo', kinds, result, [a, modulus], precision, 0, symbol_suffix=suffix) + + +def modular_power(a, n, modulus): + """Call HMath.Scalar.modularPower; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_modular_power', + ['z', 'z', 'z'], + 'z', + [a, n, modulus], + None, + 0, + ) + + +def factorial_checked(n): + """Call HMath.Scalar.factorialChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_factorial_checked', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def double_factorial(n): + """Call HMath.Scalar.doubleFactorial; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_double_factorial', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def fibonacci_checked(n): + """Call HMath.Scalar.fibonacciChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_fibonacci_checked', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def lucas(n): + """Call HMath.Scalar.lucas; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_lucas', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def catalan(n): + """Call HMath.Scalar.catalan; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_catalan', + ['z'], + 'z', + [n], + None, + 0, + ) + + +def rising_factorial(x, n): + """Call HMath.Scalar.risingFactorial; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_rising_factorial', + ['z', 'z'], + 'z', + [x, n], + None, + 0, + ) + + +def falling_factorial(x, n): + """Call HMath.Scalar.fallingFactorial; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_falling_factorial', + ['z', 'z'], + 'z', + [x, n], + None, + 0, + ) + + +def permutations(n, k): + """Call HMath.Scalar.permutations; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_permutations', + ['z', 'z'], + 'z', + [n, k], + None, + 0, + ) + + +def combinations(n, k): + """Call HMath.Scalar.combinations; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_combinations', + ['z', 'z'], + 'z', + [n, k], + None, + 0, + ) + + +def bernoulli(n): + """Call HMath.Scalar.bernoulli; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_bernoulli', + ['i'], + 'q', + [n], + None, + 0, + ) + + +def harmonic(n): + """Call HMath.Scalar.harmonic; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_harmonic', + ['z'], + 'q', + [n], + None, + 0, + ) + + +def cumulative_sum(values, *, dtype='float64'): + """Call HMath.Scalar.cumulativeSum; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_scalar_cumulative_sum', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'fs', 'float32', '_f32'), + 'float64': (['fs'], 'fs', 'float64', '_f64'), + 'rational': (['qs'], 'qd', None, '_rational'), + 'integer': (['zs'], 'zd', None, '_integer'), + 'int8': (['int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps'], 'intpd', None, '_int'), + 'uintp': (['uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_cumulative_sum', kinds, result, [values], precision, 0, symbol_suffix=suffix) + + +def cumulative_product(values, *, dtype='float64'): + """Call HMath.Scalar.cumulativeProduct; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_scalar_cumulative_product', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'fs', 'float32', '_f32'), + 'float64': (['fs'], 'fs', 'float64', '_f64'), + 'rational': (['qs'], 'qd', None, '_rational'), + 'integer': (['zs'], 'zd', None, '_integer'), + 'int8': (['int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps'], 'intpd', None, '_int'), + 'uintp': (['uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_cumulative_product', kinds, result, [values], precision, 0, symbol_suffix=suffix) + + +def prefix_sum(values, *, dtype='float64'): + """Call HMath.Scalar.prefixSum; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_scalar_prefix_sum', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'fs', 'float32', '_f32'), + 'float64': (['fs'], 'fs', 'float64', '_f64'), + 'rational': (['qs'], 'qd', None, '_rational'), + 'integer': (['zs'], 'zd', None, '_integer'), + 'int8': (['int8s'], 'int8d', None, '_i8'), + 'int16': (['int16s'], 'int16d', None, '_i16'), + 'int32': (['int32s'], 'int32d', None, '_i32'), + 'int64': (['int64s'], 'int64d', None, '_i64'), + 'uint8': (['uint8s'], 'uint8d', None, '_u8'), + 'uint16': (['uint16s'], 'uint16d', None, '_u16'), + 'uint32': (['uint32s'], 'uint32d', None, '_u32'), + 'uint64': (['uint64s'], 'uint64d', None, '_u64'), + 'intp': (['intps'], 'intpd', None, '_int'), + 'uintp': (['uintps'], 'uintpd', None, '_word'), + 'complex64': (['cs'], 'cd', 'float32', '_c64'), + 'complex128': (['cs'], 'cd', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_prefix_sum', kinds, result, [values], precision, 1, symbol_suffix=suffix) + + +def multinomial(ks): + """Call HMath.Scalar.multinomial; preserve its argument order, result and errors.""" + return _call( + 'hmath_scalar_multinomial', + ['zs'], + 'z', + [ks], + None, + 0, + ) + + +def saturating_add(a, b, *, dtype='intp'): + """Call HMath.Scalar.saturatingAdd; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_saturating_add', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_saturating_add', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def saturating_subtract(a, b, *, dtype='intp'): + """Call HMath.Scalar.saturatingSubtract; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_saturating_subtract', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_saturating_subtract', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def saturating_multiply(a, b, *, dtype='intp'): + """Call HMath.Scalar.saturatingMultiply; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_saturating_multiply', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_saturating_multiply', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def checked_add(a, b, *, dtype='intp'): + """Call HMath.Scalar.checkedAdd; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_checked_add', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_checked_add', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def checked_subtract(a, b, *, dtype='intp'): + """Call HMath.Scalar.checkedSubtract; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_checked_subtract', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_checked_subtract', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) + + +def checked_multiply(a, b, *, dtype='intp'): + """Call HMath.Scalar.checkedMultiply; preserve its argument order, result and errors.""" + if _uses_value([a, b], dtype, ordered=False): + return _call_value('hmath_scalar_checked_multiply', ['f', 'f'], [a, b], dtype) + variants = { + 'int8': (['int8', 'int8'], 'int8', None, '_i8'), + 'int16': (['int16', 'int16'], 'int16', None, '_i16'), + 'int32': (['int32', 'int32'], 'int32', None, '_i32'), + 'int64': (['int64', 'int64'], 'int64', None, '_i64'), + 'uint8': (['uint8', 'uint8'], 'uint8', None, '_u8'), + 'uint16': (['uint16', 'uint16'], 'uint16', None, '_u16'), + 'uint32': (['uint32', 'uint32'], 'uint32', None, '_u32'), + 'uint64': (['uint64', 'uint64'], 'uint64', None, '_u64'), + 'intp': (['intp', 'intp'], 'intp', None, '_int'), + 'uintp': (['uintp', 'uintp'], 'uintp', None, '_word'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_scalar_checked_multiply', kinds, result, [a, b], precision, 0, symbol_suffix=suffix) diff --git a/bindings/python/_hmath_native/shape_values.py b/bindings/python/_hmath_native/shape_values.py new file mode 100644 index 0000000..0bbbdc6 --- /dev/null +++ b/bindings/python/_hmath_native/shape_values.py @@ -0,0 +1,180 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original checked shapes and genuine nominal KnownNat/KnownShape witnesses.""" + +from ._algebra_base import invoke +from ._foundation_base import FoundationValue, _invoke, register + + +class Shape(FoundationValue): + """Original HMath.API.Shape.Shape owner.""" + + _source_type = "HMath.API.Shape.Shape" + + @property + def dimensions(self): + return shape_dimensions(self) + + @property + def elements(self): + return shape_elements(self) + + +register("HMath.API.Shape.Shape", Shape) + + +class StaticMatrix(FoundationValue): + """Original HMath.API.Shape.StaticMatrix owner.""" + + _source_type = "HMath.API.Shape.StaticMatrix" + + +register("HMath.API.Shape.StaticMatrix", StaticMatrix) + + +class KnownShape: + """Original recursive type-level natural-list witness interface.""" + + @staticmethod + def reflected_shape(dimensions): + return reflected_shape(dimensions) + + +class StaticTensor(FoundationValue): + """Original HMath.API.Shape.StaticTensor owner.""" + + _source_type = "HMath.API.Shape.StaticTensor" + + +register("HMath.API.Shape.StaticTensor", StaticTensor) + + +class Coordinates(FoundationValue): + """Original HMath.API.Shape.Coordinates owner.""" + + _source_type = "HMath.API.Shape.Coordinates" + + @property + def values(self): + return coordinate_values(self) + + +register("HMath.API.Shape.Coordinates", Coordinates) + + +def shape_dimensions(shape): + """Original HMath.API.Shape.shapeDimensions; borrowed inputs, owned result.""" + return _invoke("hmath_shape_shape_dimensions", [["Value"]], [shape]) + + +def shape_elements(shape): + """Original HMath.API.Shape.shapeElements; borrowed inputs, owned result.""" + return _invoke("hmath_shape_shape_elements", [["Value"]], [shape]) + + +def make_shape(dimensions): + """Original HMath.API.Shape.makeShape; borrowed inputs, owned result.""" + return _invoke("hmath_shape_make_shape", [["list", ["Int"]]], [dimensions]) + + +def scalar_shape(shape): + """Original HMath.API.Shape.ScalarShape; borrowed inputs, owned result.""" + return _invoke("hmath_shape_scalar_shape", [["Value"]], [shape]) + + +def vector_shape(shape): + """Original HMath.API.Shape.VectorShape; borrowed inputs, owned result.""" + return _invoke("hmath_shape_vector_shape", [["Value"]], [shape]) + + +def matrix_shape(shape): + """Original HMath.API.Shape.MatrixShape; borrowed inputs, owned result.""" + return _invoke("hmath_shape_matrix_shape", [["Value"]], [shape]) + + +def static_matrix(rows, columns, matrix): + """Original HMath.API.Shape.staticMatrix; borrowed inputs, owned result.""" + return _invoke( + "hmath_shape_static_matrix", + [["Integer"], ["Integer"], ["Value"]], + [rows, columns, matrix], + ) + + +def dynamic_matrix(matrix): + """Original HMath.API.Shape.dynamicMatrix; borrowed inputs, owned result.""" + return _invoke("hmath_shape_dynamic_matrix", [["Value"]], [matrix]) + + +def static_multiply(left, right): + """Original HMath.API.Shape.staticMultiply; borrowed inputs, owned result.""" + return _invoke("hmath_shape_static_multiply", [["Value"], ["Value"]], [left, right]) + + +def static_transpose(matrix): + """Original HMath.API.Shape.staticTranspose; borrowed inputs, owned result.""" + return _invoke("hmath_shape_static_transpose", [["Value"]], [matrix]) + + +def reflected_shape(dimensions): + """Original HMath.API.Shape.reflectedShape; borrowed inputs, owned result.""" + return _invoke("hmath_shape_reflected_shape", [["list", ["Integer"]]], [dimensions]) + + +def static_tensor(dimensions, tensor): + """Original HMath.API.Shape.staticTensor; borrowed inputs, owned result.""" + return _invoke( + "hmath_shape_static_tensor", + [["list", ["Integer"]], ["Value"]], + [dimensions, tensor], + ) + + +def dynamic_tensor(tensor): + """Original HMath.API.Shape.dynamicTensor; borrowed inputs, owned result.""" + return _invoke("hmath_shape_dynamic_tensor", [["Value"]], [tensor]) + + +def coordinates(length, values, *, dtype=None): + """Construct an original Coordinates n a with explicit nominal length.""" + return invoke( + "hmath_shape_coordinates", + [["Integer"], ["list", ["a"]]], + [length, values], + "typed", + dtype, + ) + + +def coordinate_values(coordinates): + """Original HMath.API.Shape.coordinateValues; borrowed inputs, owned result.""" + return _invoke("hmath_shape_coordinate_values", [["Value"]], [coordinates]) + + +def coordinates_to_vector(coordinates): + """Original HMath.API.Shape.coordinatesToVector; borrowed inputs, owned result.""" + return _invoke("hmath_shape_coordinates_to_vector", [["Value"]], [coordinates]) + + +__all__ = [ + "Coordinates", + "KnownShape", + "Shape", + "StaticMatrix", + "StaticTensor", + "coordinate_values", + "coordinates", + "coordinates_to_vector", + "dynamic_matrix", + "dynamic_tensor", + "make_shape", + "matrix_shape", + "reflected_shape", + "scalar_shape", + "shape_dimensions", + "shape_elements", + "static_matrix", + "static_multiply", + "static_tensor", + "static_transpose", + "vector_shape", +] diff --git a/bindings/python/_hmath_native/signal.py b/bindings/python/_hmath_native/signal.py new file mode 100644 index 0000000..b396ce9 --- /dev/null +++ b/bindings/python/_hmath_native/signal.py @@ -0,0 +1,342 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def convolution(xs, ys, *, dtype='float64'): + """Call HMath.Signal.convolution; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_convolution', + ['fs', 'fs'], + 'fd', + [xs, ys], + dtype, + 0, + ) + + +def circular_convolution(x, y, *, dtype='float64'): + """Call HMath.Signal.circularConvolution; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_circular_convolution', + ['fs', 'fs'], + 'fd', + [x, y], + dtype, + 0, + ) + + +def correlation(x, y, *, dtype='float64'): + """Call HMath.Signal.correlation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_correlation', + ['fs', 'fs'], + 'fd', + [x, y], + dtype, + 0, + ) + + +def autocorrelation(x, *, dtype='float64'): + """Call HMath.Signal.autocorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_autocorrelation', + ['fs'], + 'fd', + [x], + dtype, + 0, + ) + + +def overlap_add(block, kernel, xs, *, dtype='float64'): + """Call HMath.Signal.overlapAdd; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_overlap_add', + ['i', 'fs', 'fs'], + 'fd', + [block, kernel, xs], + dtype, + 0, + ) + + +def overlap_save(fftLength, kernel, xs, *, dtype='float64'): + """Call HMath.Signal.overlapSave; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_overlap_save', + ['i', 'fs', 'fs'], + 'fd', + [fftLength, kernel, xs], + dtype, + 0, + ) + + +def moving_average(count, xs, *, dtype='float64'): + """Call HMath.Signal.movingAverage; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_moving_average', + ['i', 'fs'], + 'fd', + [count, xs], + dtype, + 0, + ) + + +def median_filter(argument1, argument2, *, dtype='float64'): + """Call HMath.Signal.medianFilter; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_median_filter', + ['i', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def gaussian_filter(width, sigma, xs, *, dtype='float64'): + """Call HMath.Signal.gaussianFilter; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_gaussian_filter', + ['i', 'f', 'fs'], + 'fd', + [width, sigma, xs], + dtype, + 0, + ) + + +def savitzky_golay(width, degree, derivative, spacing, xs, *, dtype='float64'): + """Call HMath.Signal.savitzkyGolay; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_savitzky_golay', + ['i', 'i', 'i', 'f', 'fs'], + 'fd', + [width, degree, derivative, spacing, xs], + dtype, + 0, + ) + + +def downsample(factor, offset, xs, *, dtype='float64'): + """Call HMath.Signal.downsample; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_downsample', + ['i', 'i', 'fs'], + 'fd', + [factor, offset, xs], + dtype, + 0, + ) + + +def upsample(factor, xs, *, dtype='float64'): + """Call HMath.Signal.upsample; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_upsample', + ['i', 'fs'], + 'fd', + [factor, xs], + dtype, + 0, + ) + + +def resample_polyphase(up, down, kernel, xs, *, dtype='float64'): + """Call HMath.Signal.resamplePolyphase; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_resample_polyphase', + ['i', 'i', 'fs', 'fs'], + 'fd', + [up, down, kernel, xs], + dtype, + 0, + ) + + +def resample(up, down, taps, xs, *, dtype='float64'): + """Call HMath.Signal.resample; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_resample', + ['i', 'i', 'i', 'fs'], + 'fd', + [up, down, taps, xs], + dtype, + 0, + ) + + +def anti_alias(factor, taps, xs, *, dtype='float64'): + """Call HMath.Signal.antiAlias; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_anti_alias', + ['i', 'i', 'fs'], + 'fd', + [factor, taps, xs], + dtype, + 0, + ) + + +def zero_crossings(xs, *, dtype='float64'): + """Call HMath.Signal.zeroCrossings; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_zero_crossings', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def envelope(xs, *, dtype='float64'): + """Call HMath.Signal.envelope; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_envelope', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def unwrap_phase(xs, *, dtype='float64'): + """Call HMath.Signal.unwrapPhase; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_unwrap_phase', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def detrend(linear, xs, *, dtype='float64'): + """Call HMath.Signal.detrend; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_detrend', + ['b', 'fs'], + 'fd', + [linear, xs], + dtype, + 0, + ) + + +def normalize(xs, *, dtype='float64'): + """Call HMath.Signal.normalize; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_normalize', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def smooth(argument1, argument2, *, dtype='float64'): + """Call HMath.Signal.smooth; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_smooth', + ['i', 'fs'], + 'fd', + [argument1, argument2], + dtype, + 0, + ) + + +def noise_estimate(xs, *, dtype='float64'): + """Call HMath.Signal.noiseEstimate; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_noise_estimate', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def signal_to_noise(signal, noise, *, dtype='float64'): + """Call HMath.Signal.signalToNoise; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_signal_to_noise', + ['fs', 'fs'], + 'f', + [signal, noise], + dtype, + 0, + ) + + +def rms(xs, *, dtype='float64'): + """Call HMath.Signal.rms; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_signal_rms', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +from .signal_values import * diff --git a/bindings/python/_hmath_native/signal_values.py b/bindings/python/_hmath_native/signal_values.py new file mode 100644 index 0000000..4799722 --- /dev/null +++ b/bindings/python/_hmath_native/signal_values.py @@ -0,0 +1,355 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_spectral_bindings.py. +from ._numerical_base import _invoke +from ._value import Value, register + + +class Filter(Value): + """Owned immutable original HMath.Signal.Filter.""" + + +register(360, Filter) + + +class FilterFamily(Value): + """Owned immutable original HMath.Signal.FilterFamily.""" + + +register(361, FilterFamily) + + +class FilterBand(Value): + """Owned immutable original HMath.Signal.FilterBand.""" + + +register(362, FilterBand) + + +class Window(Value): + """Owned immutable original HMath.Signal.Window.""" + + +register(363, Window) + + +class Peak(Value): + """Owned immutable original HMath.Signal.Peak.""" + + +register(364, Peak) + + +class Wavelet(Value): + """Owned immutable original HMath.Signal.Wavelet.""" + + +register(365, Wavelet) + + +class WaveletTree(Value): + """Owned immutable original HMath.Signal.WaveletTree.""" + + +register(366, WaveletTree) + + +class MotherWavelet(Value): + """Owned immutable original HMath.Signal.MotherWavelet.""" + + +register(367, MotherWavelet) + + +class WaveletPacket(Value): + """Owned immutable original HMath.Signal.WaveletPacket.""" + + +register(368, WaveletPacket) + + +def iir(numerator, denominator): + """HMath.Signal.iir :: [Double] -> [Double] -> Either MathError Filter.""" + return _invoke('hmath_signal_value_iir', [['list', ['Double']], ['list', ['Double']]], [numerator, denominator]) + + +def fir(b): + """HMath.Signal.fir :: [Double] -> Either MathError Filter.""" + return _invoke('hmath_signal_value_fir', [['list', ['Double']]], [b]) + + +def filter_coefficients(value): + """HMath.Signal.filterCoefficients :: Filter -> ([Double], [Double]).""" + return _invoke('hmath_signal_value_filter_coefficients', [['Filter']], [value]) + + +def filter_state(value): + """HMath.Signal.filterState :: Filter -> [Double].""" + return _invoke('hmath_signal_value_filter_state', [['Filter']], [value]) + + +def reset_filter(value): + """HMath.Signal.resetFilter :: Filter -> Filter.""" + return _invoke('hmath_signal_value_reset_filter', [['Filter']], [value]) + + +def filter_signal(value, value2): + """HMath.Signal.filterSignal :: Filter -> [Double] -> Either MathError ([Double], Filter).""" + return _invoke('hmath_signal_value_filter_signal', [['Filter'], ['list', ['Double']]], [value, value2]) + + +def frequency_response(value, value2): + """HMath.Signal.frequencyResponse :: Filter -> Double -> Either MathError (Complex Double).""" + return _invoke('hmath_signal_value_frequency_response', [['Filter'], ['Double']], [value, value2]) + + +def butterworth(): + """HMath.Signal.Butterworth :: FilterFamily.""" + return _invoke('hmath_signal_value_butterworth', [], []) + + +def chebyshev_i(value): + """HMath.Signal.ChebyshevI :: Double -> FilterFamily.""" + return _invoke('hmath_signal_value_chebyshev_i', [['Double']], [value]) + + +def chebyshev_ii(value): + """HMath.Signal.ChebyshevII :: Double -> FilterFamily.""" + return _invoke('hmath_signal_value_chebyshev_ii', [['Double']], [value]) + + +def elliptic(value, value2): + """HMath.Signal.Elliptic :: Double -> Double -> FilterFamily.""" + return _invoke('hmath_signal_value_elliptic', [['Double'], ['Double']], [value, value2]) + + +def bessel(): + """HMath.Signal.Bessel :: FilterFamily.""" + return _invoke('hmath_signal_value_bessel', [], []) + + +def lowpass(value): + """HMath.Signal.Lowpass :: Double -> FilterBand.""" + return _invoke('hmath_signal_value_lowpass', [['Double']], [value]) + + +def highpass(value): + """HMath.Signal.Highpass :: Double -> FilterBand.""" + return _invoke('hmath_signal_value_highpass', [['Double']], [value]) + + +def bandpass(value, value2): + """HMath.Signal.Bandpass :: Double -> Double -> FilterBand.""" + return _invoke('hmath_signal_value_bandpass', [['Double'], ['Double']], [value, value2]) + + +def bandstop(value, value2): + """HMath.Signal.Bandstop :: Double -> Double -> FilterBand.""" + return _invoke('hmath_signal_value_bandstop', [['Double'], ['Double']], [value, value2]) + + +def design_iir(family, band, order, rate): + """HMath.Signal.designIIR :: FilterFamily -> FilterBand -> Int -> Double -> Either MathError Filter.""" + return _invoke('hmath_signal_value_design_iir', [['FilterFamily'], ['FilterBand'], ['Int'], ['Double']], [family, band, order, rate]) + + +def notch(omega, quality): + """HMath.Signal.notch :: Double -> Double -> Either MathError Filter.""" + return _invoke('hmath_signal_value_notch', [['Double'], ['Double']], [omega, quality]) + + +def all_pass(omega, quality): + """HMath.Signal.allPass :: Double -> Double -> Either MathError Filter.""" + return _invoke('hmath_signal_value_all_pass', [['Double'], ['Double']], [omega, quality]) + + +def wiener(width, noise, xs): + """HMath.Signal.wiener :: Int -> Maybe Double -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_signal_value_wiener', [['Int'], ['maybe', ['Double']], ['list', ['Double']]], [width, noise, xs]) + + +def hann(): + """HMath.Signal.Hann :: Window.""" + return _invoke('hmath_signal_value_hann', [], []) + + +def hamming(): + """HMath.Signal.Hamming :: Window.""" + return _invoke('hmath_signal_value_hamming', [], []) + + +def blackman(): + """HMath.Signal.Blackman :: Window.""" + return _invoke('hmath_signal_value_blackman', [], []) + + +def bartlett(): + """HMath.Signal.Bartlett :: Window.""" + return _invoke('hmath_signal_value_bartlett', [], []) + + +def kaiser(value): + """HMath.Signal.Kaiser :: Double -> Window.""" + return _invoke('hmath_signal_value_kaiser', [['Double']], [value]) + + +def gaussian(value): + """HMath.Signal.Gaussian :: Double -> Window.""" + return _invoke('hmath_signal_value_gaussian', [['Double']], [value]) + + +def tukey(value): + """HMath.Signal.Tukey :: Double -> Window.""" + return _invoke('hmath_signal_value_tukey', [['Double']], [value]) + + +def flat_top(): + """HMath.Signal.FlatTop :: Window.""" + return _invoke('hmath_signal_value_flat_top', [], []) + + +def dolph_chebyshev(value): + """HMath.Signal.DolphChebyshev :: Double -> Window.""" + return _invoke('hmath_signal_value_dolph_chebyshev', [['Double']], [value]) + + +def window(kind, n): + """HMath.Signal.window :: Window -> Int -> Either MathError [Double].""" + return _invoke('hmath_signal_value_window', [['Window'], ['Int']], [kind, n]) + + +def windowed_sinc(kind, taps, cutoff, rate): + """HMath.Signal.windowedSinc :: Window -> Int -> Double -> Double -> Either MathError [Double].""" + return _invoke('hmath_signal_value_windowed_sinc', [['Window'], ['Int'], ['Double'], ['Double']], [kind, taps, cutoff, rate]) + + +def peak(peak_index, peak_height, peak_prominence, peak_width): + """HMath.Signal.Peak :: Int -> Double -> Double -> Double -> Peak.""" + return _invoke('hmath_signal_value_peak', [['Int'], ['Double'], ['Double'], ['Double']], [peak_index, peak_height, peak_prominence, peak_width]) + + +def peak_index(value): + """HMath.Signal.peakIndex :: Peak -> Int.""" + return _invoke('hmath_signal_value_peak_index', [['Peak']], [value]) + + +def peak_height(value): + """HMath.Signal.peakHeight :: Peak -> Double.""" + return _invoke('hmath_signal_value_peak_height', [['Peak']], [value]) + + +def peak_prominence(value): + """HMath.Signal.peakProminence :: Peak -> Double.""" + return _invoke('hmath_signal_value_peak_prominence', [['Peak']], [value]) + + +def peak_width(value): + """HMath.Signal.peakWidth :: Peak -> Double.""" + return _invoke('hmath_signal_value_peak_width', [['Peak']], [value]) + + +def peaks(minimum_prominence, minimum_distance, xs): + """HMath.Signal.peaks :: Double -> Int -> [Double] -> Either MathError [Peak].""" + return _invoke('hmath_signal_value_peaks', [['Double'], ['Int'], ['list', ['Double']]], [minimum_prominence, minimum_distance, xs]) + + +def kalman(value, value2, value3, value4, value5, value6): + """HMath.Signal.kalman :: [[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState.""" + return _invoke('hmath_signal_value_kalman', [['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['Double']], ['GaussianState']], [value, value2, value3, value4, value5, value6]) + + +def extended_kalman(value, value2, value3, value4, value5, value6): + """HMath.Signal.extendedKalman :: ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState.""" + return _invoke('hmath_signal_value_extended_kalman', [['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['Double']], ['GaussianState']], [value, value2, value3, value4, value5, value6]) + + +def unscented_kalman(alpha, beta, kappa, transition, measurement, q, r, measured, state): + """HMath.Signal.unscentedKalman :: Double -> Double -> Double -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState.""" + return _invoke('hmath_signal_value_unscented_kalman', [['Double'], ['Double'], ['Double'], ['function', ['list', ['Double']], ['list', ['Double']]], ['function', ['list', ['Double']], ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['Double']], ['GaussianState']], [alpha, beta, kappa, transition, measurement, q, r, measured, state]) + + +def haar(): + """HMath.Signal.Haar :: Wavelet.""" + return _invoke('hmath_signal_value_haar', [], []) + + +def daubechies2(): + """HMath.Signal.Daubechies2 :: Wavelet.""" + return _invoke('hmath_signal_value_daubechies2', [], []) + + +def daubechies4(): + """HMath.Signal.Daubechies4 :: Wavelet.""" + return _invoke('hmath_signal_value_daubechies4', [], []) + + +def biorthogonal53(): + """HMath.Signal.Biorthogonal53 :: Wavelet.""" + return _invoke('hmath_signal_value_biorthogonal53', [], []) + + +def wavelet_approximation(value): + """HMath.Signal.waveletApproximation :: WaveletTree -> [Double].""" + return _invoke('hmath_signal_value_wavelet_approximation', [['WaveletTree']], [value]) + + +def wavelet_details(value): + """HMath.Signal.waveletDetails :: WaveletTree -> [[Double]].""" + return _invoke('hmath_signal_value_wavelet_details', [['WaveletTree']], [value]) + + +def dwt(family, levels, xs): + """HMath.Signal.dwt :: Wavelet -> Int -> [Double] -> Either MathError WaveletTree.""" + return _invoke('hmath_signal_value_dwt', [['Wavelet'], ['Int'], ['list', ['Double']]], [family, levels, xs]) + + +def idwt(value): + """HMath.Signal.idwt :: WaveletTree -> Either MathError [Double].""" + return _invoke('hmath_signal_value_idwt', [['WaveletTree']], [value]) + + +def morlet(value): + """HMath.Signal.Morlet :: Double -> MotherWavelet.""" + return _invoke('hmath_signal_value_morlet', [['Double']], [value]) + + +def mexican_hat(): + """HMath.Signal.MexicanHat :: MotherWavelet.""" + return _invoke('hmath_signal_value_mexican_hat', [], []) + + +def gaussian_derivative(): + """HMath.Signal.GaussianDerivative :: MotherWavelet.""" + return _invoke('hmath_signal_value_gaussian_derivative', [], []) + + +def cwt(mother, spacing, scales, xs): + """HMath.Signal.cwt :: MotherWavelet -> Double -> [Double] -> [Double] -> Either MathError [[Complex Double]].""" + return _invoke('hmath_signal_value_cwt', [['MotherWavelet'], ['Double'], ['list', ['Double']], ['list', ['Double']]], [mother, spacing, scales, xs]) + + +def wavelet_packets(family, levels, xs): + """HMath.Signal.waveletPackets :: Wavelet -> Int -> [Double] -> Either MathError WaveletPacket.""" + return _invoke('hmath_signal_value_wavelet_packets', [['Wavelet'], ['Int'], ['list', ['Double']]], [family, levels, xs]) + + +def inverse_wavelet_packets(value): + """HMath.Signal.inverseWaveletPackets :: WaveletPacket -> Either MathError [Double].""" + return _invoke('hmath_signal_value_inverse_wavelet_packets', [['WaveletPacket']], [value]) + + +def packet_bands(value): + """HMath.Signal.packetBands :: WaveletPacket -> [[Double]].""" + return _invoke('hmath_signal_value_packet_bands', [['WaveletPacket']], [value]) + + +def wavelet_denoise(family, levels, threshold, xs): + """HMath.Signal.waveletDenoise :: Wavelet -> Int -> Maybe Double -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_signal_value_wavelet_denoise', [['Wavelet'], ['Int'], ['maybe', ['Double']], ['list', ['Double']]], [family, levels, threshold, xs]) + + +from .timeseries import GaussianState as GaussianState, gaussian_state as gaussian_state, state_mean as state_mean, state_covariance as state_covariance + + +def describe(value): + """Return the original Haskell Show representation of a spectral object.""" + return _invoke("hmath_spectral_describe", [["Value"]], [value]) diff --git a/bindings/python/_hmath_native/sparse.py b/bindings/python/_hmath_native/sparse.py new file mode 100644 index 0000000..cc3759a --- /dev/null +++ b/bindings/python/_hmath_native/sparse.py @@ -0,0 +1,595 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Sparse public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class Sparse(LinearValue): + """Original HMath.Sparse.Sparse immutable owner.""" + + _source_type = "HMath.Sparse.Sparse" + + def __init__(self, rows, columns, entries, *, dtype=None): + self._initialize( + "hmath_linear_sparse_sparse", + True, + [["Int"], ["Int"], ["list", ["tuple", ["Int"], ["Int"], ["a"]]]], + [rows, columns, entries], + dtype, + ) + + +register("HMath.Sparse.Sparse", Sparse) + + +class SparseFormat(LinearValue): + """Original HMath.Sparse.SparseFormat immutable owner.""" + + _source_type = "HMath.Sparse.SparseFormat" + + +register("HMath.Sparse.SparseFormat", SparseFormat) + + +class SparseLU(LinearValue): + """Original HMath.Sparse.SparseLU immutable owner.""" + + _source_type = "HMath.Sparse.SparseLU" + + +register("HMath.Sparse.SparseLU", SparseLU) + + +class SparseQR(LinearValue): + """Original HMath.Sparse.SparseQR immutable owner.""" + + _source_type = "HMath.Sparse.SparseQR" + + +register("HMath.Sparse.SparseQR", SparseQR) + + +class SparseTensor(LinearValue): + """Original HMath.Sparse.SparseTensor immutable owner.""" + + _source_type = "HMath.Sparse.SparseTensor" + + def __init__(self, shape, entries, *, dtype=None): + self._initialize( + "hmath_linear_sparse_sparse_tensor", + True, + [["list", ["Int"]], ["list", ["tuple", ["list", ["Int"]], ["a"]]]], + [shape, entries], + dtype, + ) + + +register("HMath.Sparse.SparseTensor", SparseTensor) + + +def sparse(index1, index2, values3, *, dtype=None): + "Given rows,columns,then (row,column,value) entries, validate coordinates, sum duplicates and remove explicit zeros. Return canonical ordered sparse storage; invalid shape/indices or size overflow fail. Call original HMath.Sparse.sparse :: Int -> Int -> [(Int, Int, a)] -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_sparse", + True, + [["Int"], ["Int"], ["list", ["tuple", ["Int"], ["Int"], ["a"]]]], + [index1, index2, values3], + dtype=dtype, + ) + + +def sparse_shape(sparse1, *, dtype=None): + "Return declared (row count,column count), including empty dimensions. Call original HMath.Sparse.sparseShape :: Sparse a -> (Int, Int)" + return _invoke( + "hmath_linear_sparse_sparse_shape", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_entries(sparse1, *, dtype=None): + "Return canonical nonzero (row,column,value) triples in ascending coordinate order. Call original HMath.Sparse.sparseEntries :: Sparse a -> [(Int, Int, a)]" + return _invoke( + "hmath_linear_sparse_sparse_entries", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def nonzeros(sparse1, *, dtype=None): + "Return stored nonzero count after duplicate coalescing and zero removal. Call original HMath.Sparse.nonzeros :: Sparse a -> Int" + return _invoke( + "hmath_linear_sparse_nonzeros", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def from_format(sparse_format1, *, dtype=None): + "Validate COO/CSR/CSC/DIA/BSR/ELLPACK dimensions, pointers/indices and values, then construct canonical sparse storage. Invalid layout or coordinates return Left MathError. Call original HMath.Sparse.fromFormat :: SparseFormat a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_from_format", + True, + [["SparseFormat", ["a"]]], + [sparse_format1], + dtype=dtype, + ) + + +def to_coo(sparse1, *, dtype=None): + "Return coordinate-list SparseFormat with explicit row/column/value arrays, preserving canonical nonzeros. Call original HMath.Sparse.toCOO :: Sparse a -> SparseFormat a" + return _invoke( + "hmath_linear_sparse_to_coo", True, [["Sparse", ["a"]]], [sparse1], dtype=dtype + ) + + +def to_csr(sparse1, *, dtype=None): + "Return compressed sparse row format with row offsets, column indices and nonzero values. Call original HMath.Sparse.toCSR :: Sparse a -> SparseFormat a" + return _invoke( + "hmath_linear_sparse_to_csr", True, [["Sparse", ["a"]]], [sparse1], dtype=dtype + ) + + +def to_csc(sparse1, *, dtype=None): + "Return compressed sparse column format with column offsets, row indices and values. Call original HMath.Sparse.toCSC :: Sparse a -> SparseFormat a" + return _invoke( + "hmath_linear_sparse_to_csc", True, [["Sparse", ["a"]]], [sparse1], dtype=dtype + ) + + +def to_dia(sparse1, *, dtype=None): + "Return diagonal sparse format; absent positions in represented diagonals are padded with zero. Call original HMath.Sparse.toDIA :: Sparse a -> SparseFormat a" + return _invoke( + "hmath_linear_sparse_to_dia", True, [["Sparse", ["a"]]], [sparse1], dtype=dtype + ) + + +def to_bsr(index1, index2, sparse3, *, dtype=None): + "Given positive block rows,block columns,then sparse matrix, build block-sparse-row format with zero padding within edge blocks. Invalid block dimensions or size overflow fails. Call original HMath.Sparse.toBSR :: Int -> Int -> Sparse a -> Either MathError (SparseFormat a)" + return _invoke( + "hmath_linear_sparse_to_bsr", + True, + [["Int"], ["Int"], ["Sparse", ["a"]]], + [index1, index2, sparse3], + dtype=dtype, + ) + + +def to_ellpack(sparse1, *, dtype=None): + "Return ELLPACK padded row storage, using row width equal to maximum nonzeros per row. Invalid/overflowing storage dimensions fail. Call original HMath.Sparse.toELLPACK :: Sparse a -> Either MathError (SparseFormat a)" + return _invoke( + "hmath_linear_sparse_to_ellpack", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_to_dense(sparse1, *, dtype=None): + "Return a dense Matrix with the same dimensions and zeros for missing entries. Checked dense element-count overflow can fail. Call original HMath.Sparse.sparseToDense :: Sparse a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_sparse_sparse_to_dense", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def dense_to_sparse(matrix1, *, dtype=None): + "Convert a dense matrix to canonical sparse storage, discarding exact zeros and preserving dimensions. Call original HMath.Sparse.denseToSparse :: Matrix a -> Sparse a" + return _invoke( + "hmath_linear_sparse_dense_to_sparse", + True, + [["Matrix", ["a"]]], + [matrix1], + dtype=dtype, + ) + + +def sparse_transpose(sparse1, *, dtype=None): + "Exchange row/column coordinates and dimensions without changing values, returning canonical sparse order. Call original HMath.Sparse.sparseTranspose :: Sparse a -> Sparse a" + return _invoke( + "hmath_linear_sparse_sparse_transpose", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_add(sparse1, sparse2, *, dtype=None): + "Add equal-shaped sparse matrices, coalescing entries and dropping resulting zeros. Shape mismatch or checked construction errors fail. Call original HMath.Sparse.sparseAdd :: Sparse a -> Sparse a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_sparse_add", + True, + [["Sparse", ["a"]], ["Sparse", ["a"]]], + [sparse1, sparse2], + dtype=dtype, + ) + + +def sparse_subtract(sparse1, sparse2, *, dtype=None): + "Subtract right sparse values from left for equal shapes; coalesce and remove zeros. Shape mismatch fails. Call original HMath.Sparse.sparseSubtract :: Sparse a -> Sparse a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_sparse_subtract", + True, + [["Sparse", ["a"]], ["Sparse", ["a"]]], + [sparse1, sparse2], + dtype=dtype, + ) + + +def spmv(sparse1, values2, *, dtype=None): + "Given sparse matrix then dense vector, return matrix-vector product. Vector length must equal column count; mismatch returns Left MathError. Call original HMath.Sparse.spmv :: Sparse a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_sparse_spmv", + True, + [["Sparse", ["a"]], ["list", ["a"]]], + [sparse1, values2], + dtype=dtype, + ) + + +def spmm(sparse1, sparse2, *, dtype=None): + "Multiply compatible sparse matrices using sparse row contributions. Inner-dimension mismatch or output construction errors return Left MathError. Call original HMath.Sparse.spmm :: Sparse a -> Sparse a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_spmm", + True, + [["Sparse", ["a"]], ["Sparse", ["a"]]], + [sparse1, sparse2], + dtype=dtype, + ) + + +def sparse_kronecker(sparse1, sparse2, *, dtype=None): + "Return sparse Kronecker product, multiplying row/column dimensions and nonzero pairs. Dimension/product overflow fails. Call original HMath.Sparse.sparseKronecker :: Sparse a -> Sparse a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_sparse_kronecker", + True, + [["Sparse", ["a"]], ["Sparse", ["a"]]], + [sparse1, sparse2], + dtype=dtype, + ) + + +def sparse_triangular_solve(flag1, sparse2, values3, *, dtype=None): + "Given lower Bool,square finite sparse matrix,then RHS list, solve by forward/back substitution. Require correct triangular structure and matching RHS length; zero diagonal pivots or non-finite arithmetic fail. Call original HMath.Sparse.sparseTriangularSolve :: Bool -> Sparse a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_sparse_sparse_triangular_solve", + True, + [["Bool"], ["Sparse", ["a"]], ["list", ["a"]]], + [flag1, sparse2, values3], + dtype=dtype, + ) + + +def sparse_diagonal_solve(sparse1, values2, *, dtype=None): + "Given diagonal square sparse matrix then RHS, divide by each diagonal pivot. Off-diagonal entries, shape mismatch, zero pivots or non-finite data fail. Call original HMath.Sparse.sparseDiagonalSolve :: Sparse a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_sparse_sparse_diagonal_solve", + True, + [["Sparse", ["a"]], ["list", ["a"]]], + [sparse1, values2], + dtype=dtype, + ) + + +def sparse_lu_lower(sparse_lu1, *, dtype=None): + "Extract unit lower-triangular sparse factor from a SparseLU result. Call original HMath.Sparse.sparseLULower :: SparseLU a -> Sparse a" + return _invoke( + "hmath_linear_sparse_sparse_lu_lower", + True, + [["SparseLU", ["a"]]], + [sparse_lu1], + dtype=dtype, + ) + + +def sparse_lu_upper(sparse_lu1, *, dtype=None): + "Extract upper-triangular sparse factor from a SparseLU result. Call original HMath.Sparse.sparseLUUpper :: SparseLU a -> Sparse a" + return _invoke( + "hmath_linear_sparse_sparse_lu_upper", + True, + [["SparseLU", ["a"]]], + [sparse_lu1], + dtype=dtype, + ) + + +def sparse_lu_permutation(sparse_lu1, *, dtype=None): + "Return LU row permutation in pivoted order, for reconstructing P*A=L*U. Call original HMath.Sparse.sparseLUPermutation :: SparseLU a -> [Int]" + return _invoke( + "hmath_linear_sparse_sparse_lu_permutation", + True, + [["SparseLU", ["a"]]], + [sparse_lu1], + dtype=dtype, + ) + + +def sparse_lu(scalar1, sparse2, *, dtype=None): + "Given finite nonnegative relative pivot tolerance then square finite sparse matrix, compute sparse LU with row pivoting. Invalid tolerance/input, zero/near-singular pivots or numerical failure returns Left MathError. Call original HMath.Sparse.sparseLU :: a -> Sparse a -> Either MathError (SparseLU a)" + return _invoke( + "hmath_linear_sparse_sparse_lu", + True, + [["a"], ["Sparse", ["a"]]], + [scalar1, sparse2], + dtype=dtype, + ) + + +def sparse_solve_lu(sparse_lu1, values2, *, dtype=None): + "Given sparse LU factors then RHS list, apply row permutation and triangular solves. Dimension mismatch, singularity or non-finite input/result fails. Call original HMath.Sparse.sparseSolveLU :: SparseLU a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_sparse_sparse_solve_lu", + True, + [["SparseLU", ["a"]], ["list", ["a"]]], + [sparse_lu1, values2], + dtype=dtype, + ) + + +def sparse_cholesky(sparse1, *, dtype=None): + "Factor a symmetric positive-definite finite sparse matrix into a lower sparse factor. Invalid shape/symmetry, nonpositive pivots or numerical failure returns Left MathError. Call original HMath.Sparse.sparseCholesky :: Sparse a -> Either MathError (Sparse a)" + return _invoke( + "hmath_linear_sparse_sparse_cholesky", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_qr_upper(sparse_qr1, *, dtype=None): + "Extract upper-triangular/trapezoidal sparse R from a sparse QR factorization. Call original HMath.Sparse.sparseQRUpper :: SparseQR a -> Sparse a" + return _invoke( + "hmath_linear_sparse_sparse_qr_upper", + True, + [["SparseQR", ["a"]]], + [sparse_qr1], + dtype=dtype, + ) + + +def sparse_qr(sparse1, *, dtype=None): + "Given finite nonnegative tolerance then sparse matrix, compute its checked sparse QR factors. Invalid tolerance, input or numerical failure returns Left MathError. Call original HMath.Sparse.sparseQR :: Sparse a -> Either MathError (SparseQR a)" + return _invoke( + "hmath_linear_sparse_sparse_qr", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_qr_apply_qt(sparse_qr1, values2, *, dtype=None): + "Given sparse QR factors then compatible RHS list, apply transpose(Q) without constructing dense Q. Invalid length or non-finite arithmetic fails. Call original HMath.Sparse.sparseQRApplyQT :: SparseQR a -> [a] -> Either MathError [a]" + return _invoke( + "hmath_linear_sparse_sparse_qr_apply_qt", + True, + [["SparseQR", ["a"]], ["list", ["a"]]], + [sparse_qr1, values2], + dtype=dtype, + ) + + +def sparse_graph(sparse1, *, dtype=None): + "For a square sparse matrix, return one adjacency row per vertex with stored (column,value) neighbors. Non-square matrix returns Left MathError. Call original HMath.Sparse.sparseGraph :: Sparse a -> Either MathError [(Int, [(Int, a)])]" + return _invoke( + "hmath_linear_sparse_sparse_graph", + True, + [["Sparse", ["a"]]], + [sparse1], + dtype=dtype, + ) + + +def sparse_storage_bytes(index1, sparse2, *, dtype=None): + "Logical payload bytes: two machine-width indices and caller-provided scalar width per nonzero. Runtime Map node overhead is implementation dependent. Call original HMath.Sparse.sparseStorageBytes :: Int -> Sparse a -> Either MathError Integer" + return _invoke( + "hmath_linear_sparse_sparse_storage_bytes", + True, + [["Int"], ["Sparse", ["a"]]], + [index1, sparse2], + dtype=dtype, + ) + + +def sparse_tensor(values1, values2, *, dtype=None): + "Given dimensions then (coordinate-list,value) entries, validate rank/bounds, sum duplicate coordinates and remove zeros. Invalid shape/indices return Left MathError. Call original HMath.Sparse.sparseTensor :: [Int] -> [([Int], a)] -> Either MathError (SparseTensor a)" + return _invoke( + "hmath_linear_sparse_sparse_tensor", + True, + [["list", ["Int"]], ["list", ["tuple", ["list", ["Int"]], ["a"]]]], + [values1, values2], + dtype=dtype, + ) + + +def sparse_tensor_shape(sparse_tensor1, *, dtype=None): + "Return axis dimensions of a sparse tensor; [] denotes a scalar. Call original HMath.Sparse.sparseTensorShape :: SparseTensor a -> [Int]" + return _invoke( + "hmath_linear_sparse_sparse_tensor_shape", + True, + [["SparseTensor", ["a"]]], + [sparse_tensor1], + dtype=dtype, + ) + + +def sparse_tensor_entries(sparse_tensor1, *, dtype=None): + "Return canonical nonzero (coordinate list,value) pairs in lexicographic coordinate order. Call original HMath.Sparse.sparseTensorEntries :: SparseTensor a -> [([Int], a)]" + return _invoke( + "hmath_linear_sparse_sparse_tensor_entries", + True, + [["SparseTensor", ["a"]]], + [sparse_tensor1], + dtype=dtype, + ) + + +def sparse_tensor_lookup(sparse_tensor1, values2, *, dtype=None): + "Given sparse tensor then full zero-based coordinates, return stored value or zero. Wrong rank or out-of-range indices fail. Call original HMath.Sparse.sparseTensorLookup :: SparseTensor a -> [Int] -> Either MathError a" + return _invoke( + "hmath_linear_sparse_sparse_tensor_lookup", + True, + [["SparseTensor", ["a"]], ["list", ["Int"]]], + [sparse_tensor1, values2], + dtype=dtype, + ) + + +def sparse_eigen_reference(integer1, sparse2): + "Small-problem spectral reference backend. The caller explicitly authorizes a dense element budget; oversized matrices fail before generating zeros. This is not a scalable sparse eigensolver/SVD and never silently densifies. Call original HMath.Sparse.sparseEigenReference :: Integer -> Sparse Double -> Either MathError Eigen" + return _invoke( + "hmath_linear_sparse_sparse_eigen_reference", + False, + [["Integer"], ["Sparse", ["Double"]]], + [integer1, sparse2], + ) + + +def sparse_svd_reference(integer1, sparse2): + "Given explicit dense-byte budget then sparse Double matrix, densify only if within budget and run checked dense SVD. This is a reference fallback, not a sparse iterative SVD; budget/backend/numeric errors fail. Call original HMath.Sparse.sparseSVDReference :: Integer -> Sparse Double -> Either MathError SVD" + return _invoke( + "hmath_linear_sparse_sparse_svd_reference", + False, + [["Integer"], ["Sparse", ["Double"]]], + [integer1, sparse2], + ) + + +def coo(index1, index2, values3, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.COO :: constructor" + return _invoke( + "hmath_linear_sparse_new_coo", + True, + [["Int"], ["Int"], ["list", ["tuple", ["Int"], ["Int"], ["a"]]]], + [index1, index2, values3], + dtype=dtype, + ) + + +def csr(index1, index2, values3, values4, values5, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.CSR :: constructor" + return _invoke( + "hmath_linear_sparse_new_csr", + True, + [["Int"], ["Int"], ["list", ["Int"]], ["list", ["Int"]], ["list", ["a"]]], + [index1, index2, values3, values4, values5], + dtype=dtype, + ) + + +def csc(index1, index2, values3, values4, values5, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.CSC :: constructor" + return _invoke( + "hmath_linear_sparse_new_csc", + True, + [["Int"], ["Int"], ["list", ["Int"]], ["list", ["Int"]], ["list", ["a"]]], + [index1, index2, values3, values4, values5], + dtype=dtype, + ) + + +def dia(index1, index2, values3, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.DIA :: constructor" + return _invoke( + "hmath_linear_sparse_new_dia", + True, + [["Int"], ["Int"], ["list", ["tuple", ["Int"], ["list", ["a"]]]]], + [index1, index2, values3], + dtype=dtype, + ) + + +def bsr(index1, index2, index3, index4, values5, values6, values7, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.BSR :: constructor" + return _invoke( + "hmath_linear_sparse_new_bsr", + True, + [ + ["Int"], + ["Int"], + ["Int"], + ["Int"], + ["list", ["Int"]], + ["list", ["Int"]], + ["list", ["list", ["a"]]], + ], + [index1, index2, index3, index4, values5, values6, values7], + dtype=dtype, + ) + + +def ellpack(index1, index2, index3, values4, values5, *, dtype=None): + "Construct the original public variant; positional fields retain their exact source types and order. Call original HMath.Sparse.ELLPACK :: constructor" + return _invoke( + "hmath_linear_sparse_new_ellpack", + True, + [["Int"], ["Int"], ["Int"], ["list", ["Int"]], ["list", ["a"]]], + [index1, index2, index3, values4, values5], + dtype=dtype, + ) + + +__all__ = [ + "Sparse", + "SparseFormat", + "SparseLU", + "SparseQR", + "SparseTensor", + "bsr", + "coo", + "csc", + "csr", + "dense_to_sparse", + "dia", + "ellpack", + "from_format", + "nonzeros", + "sparse", + "sparse_add", + "sparse_cholesky", + "sparse_diagonal_solve", + "sparse_eigen_reference", + "sparse_entries", + "sparse_graph", + "sparse_kronecker", + "sparse_lu", + "sparse_lu_lower", + "sparse_lu_permutation", + "sparse_lu_upper", + "sparse_qr", + "sparse_qr_apply_qt", + "sparse_qr_upper", + "sparse_shape", + "sparse_solve_lu", + "sparse_storage_bytes", + "sparse_subtract", + "sparse_svd_reference", + "sparse_tensor", + "sparse_tensor_entries", + "sparse_tensor_lookup", + "sparse_tensor_shape", + "sparse_to_dense", + "sparse_transpose", + "sparse_triangular_solve", + "spmm", + "spmv", + "to_bsr", + "to_coo", + "to_csc", + "to_csr", + "to_dia", + "to_ellpack", +] diff --git a/bindings/python/_hmath_native/sparse_spectral.py b/bindings/python/_hmath_native/sparse_spectral.py new file mode 100644 index 0000000..22811da --- /dev/null +++ b/bindings/python/_hmath_native/sparse_spectral.py @@ -0,0 +1,424 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Sparse.Spectral public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class SparseSpectralOptions(LinearValue): + """Original HMath.Sparse.Spectral.SparseSpectralOptions immutable owner.""" + + _source_type = "HMath.Sparse.Spectral.SparseSpectralOptions" + + def __init__( + self, + sparse_absolute_tolerance, + sparse_relative_tolerance, + sparse_iteration_limit, + sparse_workspace_limit, + *, + dtype=None, + ): + self._initialize( + "hmath_linear_sparse_spectral_new_sparse_spectral_options", + True, + [["a"], ["a"], ["Int"], ["Integer"]], + [ + sparse_absolute_tolerance, + sparse_relative_tolerance, + sparse_iteration_limit, + sparse_workspace_limit, + ], + dtype, + ) + + @property + def sparse_absolute_tolerance(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_absolute_tolerance", + True, + [["SparseSpectralOptions", ["a"]]], + [self], + ) + + @property + def sparse_relative_tolerance(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_relative_tolerance", + True, + [["SparseSpectralOptions", ["a"]]], + [self], + ) + + @property + def sparse_iteration_limit(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_iteration_limit", + True, + [["SparseSpectralOptions", ["a"]]], + [self], + ) + + @property + def sparse_workspace_limit(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_workspace_limit", + True, + [["SparseSpectralOptions", ["a"]]], + [self], + ) + + +register("HMath.Sparse.Spectral.SparseSpectralOptions", SparseSpectralOptions) + + +class SparseEigenResult(LinearValue): + """Original HMath.Sparse.Spectral.SparseEigenResult immutable owner.""" + + _source_type = "HMath.Sparse.Spectral.SparseEigenResult" + + def __init__( + self, + sparse_eigenvalue, + sparse_eigenvector, + sparse_eigen_residual, + sparse_eigen_iterations, + *, + dtype=None, + ): + self._initialize( + "hmath_linear_sparse_spectral_new_sparse_eigen_result", + True, + [["a"], ["list", ["a"]], ["a"], ["Int"]], + [ + sparse_eigenvalue, + sparse_eigenvector, + sparse_eigen_residual, + sparse_eigen_iterations, + ], + dtype, + ) + + @property + def sparse_eigenvalue(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigenvalue", + True, + [["SparseEigenResult", ["a"]]], + [self], + ) + + @property + def sparse_eigenvector(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigenvector", + True, + [["SparseEigenResult", ["a"]]], + [self], + ) + + @property + def sparse_eigen_residual(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigen_residual", + True, + [["SparseEigenResult", ["a"]]], + [self], + ) + + @property + def sparse_eigen_iterations(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigen_iterations", + True, + [["SparseEigenResult", ["a"]]], + [self], + ) + + +register("HMath.Sparse.Spectral.SparseEigenResult", SparseEigenResult) + + +class SparseSVD(LinearValue): + """Original HMath.Sparse.Spectral.SparseSVD immutable owner.""" + + _source_type = "HMath.Sparse.Spectral.SparseSVD" + + def __init__( + self, + sparse_singular_values, + sparse_left_vectors, + sparse_right_vectors, + sparse_singular_residuals, + sparse_singular_iterations, + *, + dtype=None, + ): + self._initialize( + "hmath_linear_sparse_spectral_new_sparse_svd", + True, + [ + ["list", ["a"]], + ["list", ["list", ["a"]]], + ["list", ["list", ["a"]]], + ["list", ["tuple", ["a"], ["a"]]], + ["list", ["Int"]], + ], + [ + sparse_singular_values, + sparse_left_vectors, + sparse_right_vectors, + sparse_singular_residuals, + sparse_singular_iterations, + ], + dtype, + ) + + @property + def sparse_singular_values(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_values", + True, + [["SparseSVD", ["a"]]], + [self], + ) + + @property + def sparse_left_vectors(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_left_vectors", + True, + [["SparseSVD", ["a"]]], + [self], + ) + + @property + def sparse_right_vectors(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_right_vectors", + True, + [["SparseSVD", ["a"]]], + [self], + ) + + @property + def sparse_singular_residuals(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_residuals", + True, + [["SparseSVD", ["a"]]], + [self], + ) + + @property + def sparse_singular_iterations(self): + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_iterations", + True, + [["SparseSVD", ["a"]]], + [self], + ) + + +register("HMath.Sparse.Spectral.SparseSVD", SparseSVD) + + +def default_sparse_spectral_options(*, dtype=None): + "Absolute tolerance 1e-12, relative tolerance 1e-10, 1000 iterations per pair and a workspace limit of ten million scalar elements. Call original HMath.Sparse.Spectral.defaultSparseSpectralOptions :: SparseSpectralOptions a" + return _invoke( + "hmath_linear_sparse_spectral_default_sparse_spectral_options", + True, + [], + [], + dtype=dtype, + ) + + +def sparse_dominant_eigen(sparse_spectral_options1, sparse2, values3, *, dtype=None): + "Symmetric power iteration targeting the eigenvalue of largest magnitude. Exact symmetry and finite input are required. The caller supplies a nonzero finite initial vector; its projection onto the desired eigenspace must be nonzero. An initial eigenvector can converge with a zero budget. Equal opposite dominant eigenvalues may cause non-convergence. Returned residuals do not prove that the converged eigenvalue is the largest when the initial projection is zero. Call original HMath.Sparse.Spectral.sparseDominantEigen :: SparseSpectralOptions a -> Sparse a -> [a] -> Either MathError (SparseEigenResult a)" + return _invoke( + "hmath_linear_sparse_spectral_sparse_dominant_eigen", + True, + [["SparseSpectralOptions", ["a"]], ["Sparse", ["a"]], ["list", ["a"]]], + [sparse_spectral_options1, sparse2, values3], + dtype=dtype, + ) + + +def sparse_truncated_svd( + sparse_spectral_options1, index2, integer3, sparse4, *, dtype=None +): + "Truncated SVD by two-sided power iteration and two-pass orthogonal deflation. The seed initializes a local deterministic stream, with no global RNG state. Both original singular residuals must meet the configured tolerance. The algorithm targets descending singular values if starting vectors have nonzero projection and the successive singular values are separated; it does not claim a certified rank or ordering when these power-method assumptions fail. Exact null images report RankDeficient, rather than inventing zero singular vectors. Small positive singular values may be returned within tolerance; requesting more vectors than the numerical rank can also exhaust the budget. k=0 returns empty factors, including for empty/zero inputs. Call original HMath.Sparse.Spectral.sparseTruncatedSVD :: SparseSpectralOptions a -> Int -> Integer -> Sparse a -> Either MathError (SparseSVD a)" + return _invoke( + "hmath_linear_sparse_spectral_sparse_truncated_svd", + True, + [["SparseSpectralOptions", ["a"]], ["Int"], ["Integer"], ["Sparse", ["a"]]], + [sparse_spectral_options1, index2, integer3, sparse4], + dtype=dtype, + ) + + +def sparse_absolute_tolerance(sparse_spectral_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseAbsoluteTolerance :: SparseSpectralOptions -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_absolute_tolerance", + True, + [["SparseSpectralOptions", ["a"]]], + [sparse_spectral_options1], + dtype=dtype, + ) + + +def sparse_relative_tolerance(sparse_spectral_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseRelativeTolerance :: SparseSpectralOptions -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_relative_tolerance", + True, + [["SparseSpectralOptions", ["a"]]], + [sparse_spectral_options1], + dtype=dtype, + ) + + +def sparse_iteration_limit(sparse_spectral_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseIterationLimit :: SparseSpectralOptions -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_iteration_limit", + True, + [["SparseSpectralOptions", ["a"]]], + [sparse_spectral_options1], + dtype=dtype, + ) + + +def sparse_workspace_limit(sparse_spectral_options1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseWorkspaceLimit :: SparseSpectralOptions -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_workspace_limit", + True, + [["SparseSpectralOptions", ["a"]]], + [sparse_spectral_options1], + dtype=dtype, + ) + + +def sparse_eigenvalue(sparse_eigen_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseEigenvalue :: SparseEigenResult -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigenvalue", + True, + [["SparseEigenResult", ["a"]]], + [sparse_eigen_result1], + dtype=dtype, + ) + + +def sparse_eigenvector(sparse_eigen_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseEigenvector :: SparseEigenResult -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigenvector", + True, + [["SparseEigenResult", ["a"]]], + [sparse_eigen_result1], + dtype=dtype, + ) + + +def sparse_eigen_residual(sparse_eigen_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseEigenResidual :: SparseEigenResult -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigen_residual", + True, + [["SparseEigenResult", ["a"]]], + [sparse_eigen_result1], + dtype=dtype, + ) + + +def sparse_eigen_iterations(sparse_eigen_result1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseEigenIterations :: SparseEigenResult -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_eigen_iterations", + True, + [["SparseEigenResult", ["a"]]], + [sparse_eigen_result1], + dtype=dtype, + ) + + +def sparse_singular_values(sparse_svd1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseSingularValues :: SparseSVD -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_values", + True, + [["SparseSVD", ["a"]]], + [sparse_svd1], + dtype=dtype, + ) + + +def sparse_left_vectors(sparse_svd1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseLeftVectors :: SparseSVD -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_left_vectors", + True, + [["SparseSVD", ["a"]]], + [sparse_svd1], + dtype=dtype, + ) + + +def sparse_right_vectors(sparse_svd1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseRightVectors :: SparseSVD -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_right_vectors", + True, + [["SparseSVD", ["a"]]], + [sparse_svd1], + dtype=dtype, + ) + + +def sparse_singular_residuals(sparse_svd1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseSingularResiduals :: SparseSVD -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_residuals", + True, + [["SparseSVD", ["a"]]], + [sparse_svd1], + dtype=dtype, + ) + + +def sparse_singular_iterations(sparse_svd1, *, dtype=None): + "Read the original immutable public field; no numerical conversion is performed. Call original HMath.Sparse.Spectral.sparseSingularIterations :: SparseSVD -> field" + return _invoke( + "hmath_linear_sparse_spectral_sparse_singular_iterations", + True, + [["SparseSVD", ["a"]]], + [sparse_svd1], + dtype=dtype, + ) + + +__all__ = [ + "SparseEigenResult", + "SparseSVD", + "SparseSpectralOptions", + "default_sparse_spectral_options", + "sparse_absolute_tolerance", + "sparse_dominant_eigen", + "sparse_eigen_iterations", + "sparse_eigen_residual", + "sparse_eigenvalue", + "sparse_eigenvector", + "sparse_iteration_limit", + "sparse_left_vectors", + "sparse_relative_tolerance", + "sparse_right_vectors", + "sparse_singular_iterations", + "sparse_singular_residuals", + "sparse_singular_values", + "sparse_truncated_svd", + "sparse_workspace_limit", +] diff --git a/bindings/python/_hmath_native/special.py b/bindings/python/_hmath_native/special.py new file mode 100644 index 0000000..1493277 --- /dev/null +++ b/bindings/python/_hmath_native/special.py @@ -0,0 +1,921 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import SFResult, _call + + +def gamma(x, *, dtype='float64'): + """Call HMath.Special.gamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_gamma', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def log_gamma(x, *, dtype='float64'): + """Call HMath.Special.logGamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_log_gamma', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def log_beta(a, b, *, dtype='float64'): + """Call HMath.Special.logBeta; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_log_beta', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def beta(a, b, *, dtype='float64'): + """Call HMath.Special.beta; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_beta', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def gamma_p(a, x, *, dtype='float64'): + """Call HMath.Special.gammaP; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_gamma_p', + ['f', 'f'], + 'f', + [a, x], + dtype, + 0, + ) + + +def gamma_q(a, x, *, dtype='float64'): + """Call HMath.Special.gammaQ; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_gamma_q', + ['f', 'f'], + 'f', + [a, x], + dtype, + 0, + ) + + +def incomplete_gamma(a, x, *, dtype='float64'): + """Call HMath.Special.incompleteGamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_incomplete_gamma', + ['f', 'f'], + 'f', + [a, x], + dtype, + 0, + ) + + +def beta_i(a, b, x, *, dtype='float64'): + """Call HMath.Special.betaI; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_beta_i', + ['f', 'f', 'f'], + 'f', + [a, b, x], + dtype, + 0, + ) + + +def incomplete_beta(a, b, x, *, dtype='float64'): + """Call HMath.Special.incompleteBeta; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_incomplete_beta', + ['f', 'f', 'f'], + 'f', + [a, b, x], + dtype, + 0, + ) + + +def digamma(x, *, dtype='float64'): + """Call HMath.Special.digamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_digamma', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def trigamma(argument1, *, dtype='float64'): + """Call HMath.Special.trigamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_trigamma', + ['f'], + 'f', + [argument1], + dtype, + 0, + ) + + +def polygamma(n, x, *, dtype='float64'): + """Call HMath.Special.polygamma; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_polygamma', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def erf(x, *, dtype='float64'): + """Call HMath.Special.erf; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_erf', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def erfc(x, *, dtype='float64'): + """Call HMath.Special.erfc; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_erfc', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def erfcx(x, *, dtype='float64'): + """Call HMath.Special.erfcx; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_erfcx', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def normal_c_d_f(x, *, dtype='float64'): + """Call HMath.Special.normalCDF; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_normal_c_d_f', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def normal_quantile(p, *, dtype='float64'): + """Call HMath.Special.normalQuantile; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_normal_quantile', + ['f'], + 'f', + [p], + dtype, + 0, + ) + + +def inverse_erf(x, *, dtype='float64'): + """Call HMath.Special.inverseErf; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_inverse_erf', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def dawson(x, *, dtype='float64'): + """Call HMath.Special.dawson; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_dawson', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def exponential_integral(n, x, *, dtype='float64'): + """Call HMath.Special.exponentialIntegral; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_exponential_integral', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def logarithmic_integral(x, *, dtype='float64'): + """Call HMath.Special.logarithmicIntegral; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_logarithmic_integral', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def sine_integral(x, *, dtype='float64'): + """Call HMath.Special.sineIntegral; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_sine_integral', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def cosine_integral(x, *, dtype='float64'): + """Call HMath.Special.cosineIntegral; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_cosine_integral', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def fresnel(x, *, dtype='float64'): + """Call HMath.Special.fresnel; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_fresnel', + ['f'], + 'sf2', + [x], + dtype, + 0, + ) + + +def elliptic_f(phi, m, *, dtype='float64'): + """Call HMath.Special.ellipticF; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_elliptic_f', + ['f', 'f'], + 'sf', + [phi, m], + dtype, + 0, + ) + + +def elliptic_e(phi, m, *, dtype='float64'): + """Call HMath.Special.ellipticE; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_elliptic_e', + ['f', 'f'], + 'sf', + [phi, m], + dtype, + 0, + ) + + +def elliptic_pi(n, phi, m, *, dtype='float64'): + """Call HMath.Special.ellipticPi; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_elliptic_pi', + ['f', 'f', 'f'], + 'sf', + [n, phi, m], + dtype, + 0, + ) + + +def jacobi_elliptic(u, m, *, dtype='float64'): + """Call HMath.Special.jacobiElliptic; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_jacobi_elliptic', + ['f', 'f'], + 'fff', + [u, m], + dtype, + 0, + ) + + +def bessel_j(n, x, *, dtype='float64'): + """Call HMath.Special.besselJ; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bessel_j', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def bessel_y(n, x, *, dtype='float64'): + """Call HMath.Special.besselY; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bessel_y', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def bessel_i(n, x, *, dtype='float64'): + """Call HMath.Special.besselI; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bessel_i', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def scaled_bessel_i(n, x, *, dtype='float64'): + """Call HMath.Special.scaledBesselI; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_scaled_bessel_i', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def bessel_k(n, x, *, dtype='float64'): + """Call HMath.Special.besselK; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bessel_k', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def scaled_bessel_k(n, x, *, dtype='float64'): + """Call HMath.Special.scaledBesselK; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_scaled_bessel_k', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def spherical_bessel_j(n, x, *, dtype='float64'): + """Call HMath.Special.sphericalBesselJ; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_spherical_bessel_j', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def spherical_bessel_y(n, x, *, dtype='float64'): + """Call HMath.Special.sphericalBesselY; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_spherical_bessel_y', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def airy(x, *, dtype='float64'): + """Call HMath.Special.airy; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_airy', + ['f'], + 'sf4', + [x], + dtype, + 0, + ) + + +def struve(nu, x, *, dtype='float64'): + """Call HMath.Special.struve; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_struve', + ['f', 'f'], + 'sf', + [nu, x], + dtype, + 0, + ) + + +def hypergeometric(as_, bs, z, *, dtype='float64'): + """Call HMath.Special.hypergeometric; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_hypergeometric', + ['fs', 'fs', 'f'], + 'sf', + [as_, bs, z], + dtype, + 0, + ) + + +def hypergeometric1_f1(a, b, z, *, dtype='float64'): + """Call HMath.Special.hypergeometric1F1; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_hypergeometric1_f1', + ['f', 'f', 'f'], + 'sf', + [a, b, z], + dtype, + 0, + ) + + +def hypergeometric2_f1(a, b, c, z, *, dtype='float64'): + """Call HMath.Special.hypergeometric2F1; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_hypergeometric2_f1', + ['f', 'f', 'f', 'f'], + 'sf', + [a, b, c, z], + dtype, + 0, + ) + + +def legendre(n, x, *, dtype='float64'): + """Call HMath.Special.legendre; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_legendre', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def associated_legendre(l, m, x, *, dtype='float64'): + """Call HMath.Special.associatedLegendre; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_associated_legendre', + ['i', 'i', 'f'], + 'f', + [l, m, x], + dtype, + 0, + ) + + +def hurwitz_zeta(s, q, *, dtype='float64'): + """Call HMath.Special.hurwitzZeta; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_hurwitz_zeta', + ['f', 'f'], + 'sf', + [s, q], + dtype, + 0, + ) + + +def riemann_zeta(s, *, dtype='float64'): + """Call HMath.Special.riemannZeta; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_riemann_zeta', + ['f'], + 'sf', + [s], + dtype, + 0, + ) + + +def polylogarithm(s, z, *, dtype='float64'): + """Call HMath.Special.polylogarithm; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_polylogarithm', + ['f', 'f'], + 'sf', + [s, z], + dtype, + 0, + ) + + +def dilogarithm(x, *, dtype='float64'): + """Call HMath.Special.dilogarithm; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_dilogarithm', + ['f'], + 'sf', + [x], + dtype, + 0, + ) + + +def lambert_w(branch, x, *, dtype='float64'): + """Call HMath.Special.lambertW; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_lambert_w', + ['i', 'f'], + 'sf', + [branch, x], + dtype, + 0, + ) + + +def debye(n, x, *, dtype='float64'): + """Call HMath.Special.debye; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_debye', + ['i', 'f'], + 'sf', + [n, x], + dtype, + 0, + ) + + +def clausen(theta, *, dtype='float64'): + """Call HMath.Special.clausen; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_clausen', + ['f'], + 'sf', + [theta], + dtype, + 0, + ) + + +def fermi_dirac(order, eta, *, dtype='float64'): + """Call HMath.Special.fermiDirac; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_fermi_dirac', + ['f', 'f'], + 'sf', + [order, eta], + dtype, + 0, + ) + + +def bose_einstein(order, eta, *, dtype='float64'): + """Call HMath.Special.boseEinstein; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bose_einstein', + ['f', 'f'], + 'sf', + [order, eta], + dtype, + 0, + ) + + +def coulomb_wave(l, eta, rho, *, dtype='float64'): + """Call HMath.Special.coulombWave; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_coulomb_wave', + ['i', 'f', 'f'], + 'sf2', + [l, eta, rho], + dtype, + 0, + ) + + +def gegenbauer(n, a, x, *, dtype='float64'): + """Call HMath.Special.gegenbauer; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_gegenbauer', + ['i', 'f', 'f'], + 'f', + [n, a, x], + dtype, + 0, + ) + + +def parabolic_cylinder(nu, x, *, dtype='float64'): + """Call HMath.Special.parabolicCylinder; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_parabolic_cylinder', + ['f', 'f'], + 'sf', + [nu, x], + dtype, + 0, + ) + + +def mathieu(evenMode, n, q, x, *, dtype='float64'): + """Call HMath.Special.mathieu; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_mathieu', + ['b', 'i', 'f', 'f'], + 'fsf', + [evenMode, n, q, x], + dtype, + 0, + ) + + +def bernoulli_polynomial(n, x, *, dtype='float64'): + """Call HMath.Special.bernoulliPolynomial; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_bernoulli_polynomial', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def euler_polynomial(n, x, *, dtype='float64'): + """Call HMath.Special.eulerPolynomial; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_euler_polynomial', + ['i', 'f'], + 'f', + [n, x], + dtype, + 0, + ) + + +def wigner3j(j1, j2, j3, m1, m2, m3, *, dtype='float64'): + """Call HMath.Special.wigner3j; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_wigner3j', + ['i', 'i', 'i', 'i', 'i', 'i'], + 'f', + [j1, j2, j3, m1, m2, m3], + dtype, + 0, + ) + + +def wigner6j(a, b, c, d, e, f, *, dtype='float64'): + """Call HMath.Special.wigner6j; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_wigner6j', + ['i', 'i', 'i', 'i', 'i', 'i'], + 'f', + [a, b, c, d, e, f], + dtype, + 0, + ) + + +def wigner9j(js, *, dtype='float64'): + """Call HMath.Special.wigner9j; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_wigner9j', + ['is'], + 'f', + [js], + dtype, + 0, + ) + + +def clebsch_gordan(j1, m1, j2, m2, j, m, *, dtype='float64'): + """Call HMath.Special.clebschGordan; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_clebsch_gordan', + ['i', 'i', 'i', 'i', 'i', 'i'], + 'f', + [j1, m1, j2, m2, j, m], + dtype, + 0, + ) + + +def hankel(kind, order, x, *, dtype='float64'): + """Call HMath.Special.hankel; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_hankel', + ['i', 'i', 'f'], + 'c', + [kind, order, x], + dtype, + 0, + ) + + +def spherical_harmonic(degree, order, theta, phi, *, dtype='float64'): + """Call HMath.Special.sphericalHarmonic; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_spherical_harmonic', + ['i', 'i', 'f', 'f'], + 'c', + [degree, order, theta, phi], + dtype, + 0, + ) + + +def complex1_f1(a, b, z, *, dtype='float64'): + """Call HMath.Special.complex1F1; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_special_complex1_f1', + ['c', 'c', 'c'], + 'c', + [a, b, z], + dtype, + 0, + ) + + +__all__ = ['SFResult', 'airy', 'associated_legendre', 'bernoulli_polynomial', 'bessel_i', 'bessel_j', 'bessel_k', 'bessel_y', 'beta', 'beta_i', 'bose_einstein', 'clausen', 'clebsch_gordan', 'complex1_f1', 'cosine_integral', 'coulomb_wave', 'dawson', 'debye', 'digamma', 'dilogarithm', 'elliptic_e', 'elliptic_f', 'elliptic_pi', 'erf', 'erfc', 'erfcx', 'euler_polynomial', 'exponential_integral', 'fermi_dirac', 'fresnel', 'gamma', 'gamma_p', 'gamma_q', 'gegenbauer', 'hankel', 'hurwitz_zeta', 'hypergeometric', 'hypergeometric1_f1', 'hypergeometric2_f1', 'incomplete_beta', 'incomplete_gamma', 'inverse_erf', 'jacobi_elliptic', 'lambert_w', 'legendre', 'log_beta', 'log_gamma', 'logarithmic_integral', 'mathieu', 'normal_c_d_f', 'normal_quantile', 'parabolic_cylinder', 'polygamma', 'polylogarithm', 'riemann_zeta', 'scaled_bessel_i', 'scaled_bessel_k', 'sine_integral', 'spherical_bessel_j', 'spherical_bessel_y', 'spherical_harmonic', 'struve', 'trigamma', 'wigner3j', 'wigner6j', 'wigner9j'] + + +from .special_extras import * + +__all__.extend(['sf_error', 'sf_result', 'sf_value']) diff --git a/bindings/python/_hmath_native/special_extras.py b/bindings/python/_hmath_native/special_extras.py new file mode 100644 index 0000000..bbc6e4d --- /dev/null +++ b/bindings/python/_hmath_native/special_extras.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_scalar_extras.py; do not edit. +from ._scalar_extras_base import _invoke + + +def sf_result(value, error): + """HMath.Special.SFResult :: Double -> Double -> SFResult.""" + return _invoke('hmath_special_sf_result', ['Double', 'Double'], [value, error], 'SFResult') + + +def sf_value(value): + """HMath.Special.sfValue :: SFResult -> Double.""" + return _invoke('hmath_special_sf_value', ['SFResult'], [value], 'Double') + + +def sf_error(value): + """HMath.Special.sfError :: SFResult -> Double.""" + return _invoke('hmath_special_sf_error', ['SFResult'], [value], 'Double') + + +__all__ = [ + "sf_error", + "sf_result", + "sf_value" +] diff --git a/bindings/python/_hmath_native/statistics.py b/bindings/python/_hmath_native/statistics.py new file mode 100644 index 0000000..53b2acc --- /dev/null +++ b/bindings/python/_hmath_native/statistics.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call +from ._numeric_objects import _call_value, _uses_value + + +def mean(values, *, dtype='float64'): + """Call HMath.Statistics.mean; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_statistics_mean', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'f', 'float32', '_f32'), + 'float64': (['fs'], 'f', 'float64', '_f64'), + 'rational': (['qs'], 'q', None, '_rational'), + 'complex64': (['cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_statistics_mean', kinds, result, [values], precision, 0, symbol_suffix=suffix) + + +def variance(values, *, dtype='float64'): + """Call HMath.Statistics.variance; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_statistics_variance', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'f', 'float32', '_f32'), + 'float64': (['fs'], 'f', 'float64', '_f64'), + 'rational': (['qs'], 'q', None, '_rational'), + 'complex64': (['cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_statistics_variance', kinds, result, [values], precision, 0, symbol_suffix=suffix) + + +def standard_deviation(values, *, dtype='float64'): + """Call HMath.Statistics.standardDeviation; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_statistics_standard_deviation', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'f', 'float32', '_f32'), + 'float64': (['fs'], 'f', 'float64', '_f64'), + 'complex64': (['cs'], 'c', 'float32', '_c64'), + 'complex128': (['cs'], 'c', 'float64', '_c128'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_statistics_standard_deviation', kinds, result, [values], precision, 0, symbol_suffix=suffix) + + +def median(values, *, dtype='float64'): + """Call HMath.Statistics.median; preserve its argument order, result and errors.""" + if _uses_value([values], dtype, ordered=False): + return _call_value('hmath_statistics_median', ['fs'], [values], dtype) + variants = { + 'float32': (['fs'], 'f', 'float32', '_f32'), + 'float64': (['fs'], 'f', 'float64', '_f64'), + 'rational': (['qs'], 'q', None, '_rational'), + } + if dtype not in variants: + raise ValueError('unsupported dtype for this Haskell function') + kinds, result, precision, suffix = variants[dtype] + return _call('hmath_statistics_median', kinds, result, [values], precision, 0, symbol_suffix=suffix) diff --git a/bindings/python/_hmath_native/statistics_advanced.py b/bindings/python/_hmath_native/statistics_advanced.py new file mode 100644 index 0000000..22bbc73 --- /dev/null +++ b/bindings/python/_hmath_native/statistics_advanced.py @@ -0,0 +1,622 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def arithmetic_mean(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.arithmeticMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_arithmetic_mean', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def weighted_mean(xs, ws, *, dtype='float64'): + """Call HMath.Statistics.Advanced.weightedMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_weighted_mean', + ['fs', 'fs'], + 'f', + [xs, ws], + dtype, + 0, + ) + + +def geometric_mean(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.geometricMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_geometric_mean', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def harmonic_mean(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.harmonicMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_harmonic_mean', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def rms(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.rms; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_rms', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def trimmed_mean(fraction, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.trimmedMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_trimmed_mean', + ['f', 'fs'], + 'f', + [fraction, xs], + dtype, + 0, + ) + + +def winsorized_mean(fraction, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.winsorizedMean; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_winsorized_mean', + ['f', 'fs'], + 'f', + [fraction, xs], + dtype, + 0, + ) + + +def quantile(p, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.quantile; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_quantile', + ['f', 'fs'], + 'f', + [p, xs], + dtype, + 0, + ) + + +def median(argument1, *, dtype='float64'): + """Call HMath.Statistics.Advanced.median; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_median', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def percentile(argument1, argument2, *, dtype='float64'): + """Call HMath.Statistics.Advanced.percentile; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_percentile', + ['f', 'fs'], + 'f', + [argument1, argument2], + dtype, + 0, + ) + + +def modes(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.modes; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_modes', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def interquartile_range(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.interquartileRange; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_interquartile_range', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def median_absolute_deviation(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.medianAbsoluteDeviation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_median_absolute_deviation', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def data_range(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.dataRange; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_data_range', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def central_moment(k, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.centralMoment; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_central_moment', + ['i', 'fs'], + 'f', + [k, xs], + dtype, + 0, + ) + + +def population_variance(argument1, *, dtype='float64'): + """Call HMath.Statistics.Advanced.populationVariance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_population_variance', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def sample_variance(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.sampleVariance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_sample_variance', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def population_s_d(argument1, *, dtype='float64'): + """Call HMath.Statistics.Advanced.populationSD; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_population_s_d', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def sample_s_d(argument1, *, dtype='float64'): + """Call HMath.Statistics.Advanced.sampleSD; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_sample_s_d', + ['fs'], + 'f', + [argument1], + dtype, + 0, + ) + + +def coefficient_of_variation(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.coefficientOfVariation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_coefficient_of_variation', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def skewness(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.skewness; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_skewness', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def kurtosis(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.kurtosis; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_kurtosis', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def covariance(sampleCorrection, xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.covariance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_covariance', + ['b', 'fs', 'fs'], + 'f', + [sampleCorrection, xs, ys], + dtype, + 0, + ) + + +def correlation(xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.correlation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_correlation', + ['fs', 'fs'], + 'f', + [xs, ys], + dtype, + 0, + ) + + +def spearman(xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.spearman; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_spearman', + ['fs', 'fs'], + 'f', + [xs, ys], + dtype, + 0, + ) + + +def kendall(xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.kendall; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_kendall', + ['fs', 'fs'], + 'f', + [xs, ys], + dtype, + 0, + ) + + +def autocorrelation(lag, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.autocorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_autocorrelation', + ['i', 'fs'], + 'f', + [lag, xs], + dtype, + 0, + ) + + +def cross_correlation(lag, xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.crossCorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_cross_correlation', + ['i', 'fs', 'fs'], + 'f', + [lag, xs, ys], + dtype, + 0, + ) + + +def moving_average(window, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.movingAverage; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_moving_average', + ['i', 'fs'], + 'fd', + [window, xs], + dtype, + 0, + ) + + +def moving_variance(window, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.movingVariance; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_moving_variance', + ['i', 'fs'], + 'fd', + [window, xs], + dtype, + 0, + ) + + +def exponential_moving_average(alpha, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.exponentialMovingAverage; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_exponential_moving_average', + ['f', 'fs'], + 'fd', + [alpha, xs], + dtype, + 0, + ) + + +def entropy(ps, *, dtype='float64'): + """Call HMath.Statistics.Advanced.entropy; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_entropy', + ['fs'], + 'f', + [ps], + dtype, + 0, + ) + + +def kl_divergence(p, q, *, dtype='float64'): + """Call HMath.Statistics.Advanced.klDivergence; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_kl_divergence', + ['fs', 'fs'], + 'f', + [p, q], + dtype, + 0, + ) + + +def js_divergence(p, q, *, dtype='float64'): + """Call HMath.Statistics.Advanced.jsDivergence; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_js_divergence', + ['fs', 'fs'], + 'f', + [p, q], + dtype, + 0, + ) + + +def z_scores(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.zScores; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_z_scores', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def standard_error(xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.standardError; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_standard_error', + ['fs'], + 'f', + [xs], + dtype, + 0, + ) + + +def confidence_interval(level, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.confidenceInterval; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_confidence_interval', + ['f', 'fs'], + 'ff', + [level, xs], + dtype, + 0, + ) + + +def bonferroni(ps, *, dtype='float64'): + """Call HMath.Statistics.Advanced.bonferroni; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_bonferroni', + ['fs'], + 'fd', + [ps], + dtype, + 0, + ) + + +def benjamini_hochberg(ps, *, dtype='float64'): + """Call HMath.Statistics.Advanced.benjaminiHochberg; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_benjamini_hochberg', + ['fs'], + 'fd', + [ps], + dtype, + 0, + ) + + +def cohens_d(xs, ys, *, dtype='float64'): + """Call HMath.Statistics.Advanced.cohensD; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_cohens_d', + ['fs', 'fs'], + 'f', + [xs, ys], + dtype, + 0, + ) + + +def normal_test_power(alpha, standardizedEffect, n, *, dtype='float64'): + """Call HMath.Statistics.Advanced.normalTestPower; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_normal_test_power', + ['f', 'f', 'i'], + 'f', + [alpha, standardizedEffect, n], + dtype, + 0, + ) + + +def normal_sample_size(alpha, power, effect, *, dtype='float64'): + """Call HMath.Statistics.Advanced.normalSampleSize; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_normal_sample_size', + ['f', 'f', 'f'], + 'i', + [alpha, power, effect], + dtype, + 0, + ) + + +def tukey_outliers(multiplier, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.tukeyOutliers; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_tukey_outliers', + ['f', 'fs'], + 'id', + [multiplier, xs], + dtype, + 0, + ) + + +def huber_location(tuning, xs, *, dtype='float64'): + """Call HMath.Statistics.Advanced.huberLocation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_statistics_advanced_huber_location', + ['f', 'fs'], + 'f', + [tuning, xs], + dtype, + 0, + ) + + +from .statistics_values import * diff --git a/bindings/python/_hmath_native/statistics_values.py b/bindings/python/_hmath_native/statistics_values.py new file mode 100644 index 0000000..75b4787 --- /dev/null +++ b/bindings/python/_hmath_native/statistics_values.py @@ -0,0 +1,412 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_stochastic_bindings.py. +"""Original HMath.Statistics.Advanced remaining public functions and owned immutable records.""" + +from ._stochastic_base import StochasticValue, _invoke +from ._value import register + + +class Streaming(StochasticValue): + """Original HMath.Statistics.Advanced.Streaming immutable owner.""" + + +register(246, Streaming) + + +class TestResult(StochasticValue): + """Original HMath.Statistics.Advanced.TestResult immutable owner.""" + + def __init__(self, test_statistic, p_value, degrees_of_freedom): + self._initialize( + "hmath_stochastic_statistics_advanced_new_test_result", + [["Double"], ["Double"], ["list", ["Double"]]], + [test_statistic, p_value, degrees_of_freedom], + ) + + @property + def test_statistic(self): + return _invoke( + "hmath_stochastic_statistics_advanced_test_statistic", + [["TestResult"]], + [self], + ) + + @property + def p_value(self): + return _invoke( + "hmath_stochastic_statistics_advanced_p_value", [["TestResult"]], [self] + ) + + @property + def degrees_of_freedom(self): + return _invoke( + "hmath_stochastic_statistics_advanced_degrees_of_freedom", + [["TestResult"]], + [self], + ) + + +register(247, TestResult) + + +def covariance_matrix(argument1, argument2): + "Covariance matrix for variables supplied as columns (each list is one variable). Boolean selects sample correction." + return _invoke( + "hmath_stochastic_statistics_advanced_covariance_matrix", + [["Bool"], ["list", ["list", ["Double"]]]], + [argument1, argument2], + ) + + +def partial_correlation(argument1, argument2, argument3): + "Partial correlation of variable indices i,j conditional on every other supplied column, through the inverse sample covariance." + return _invoke( + "hmath_stochastic_statistics_advanced_partial_correlation", + [["list", ["list", ["Double"]]], ["Int"], ["Int"]], + [argument1, argument2, argument3], + ) + + +def empty_streaming(): + "Zero-count Welford accumulator." + return _invoke("hmath_stochastic_statistics_advanced_empty_streaming", [], []) + + +def update_streaming(argument1, argument2): + "Add one finite observation by Welford recurrence; nonfinite arithmetic is rejected." + return _invoke( + "hmath_stochastic_statistics_advanced_update_streaming", + [["Streaming"], ["Double"]], + [argument1, argument2], + ) + + +def combine_streaming(argument1, argument2): + "Chan parallel merge of two Welford accumulators; empty accumulators are identities." + return _invoke( + "hmath_stochastic_statistics_advanced_combine_streaming", + [["Streaming"], ["Streaming"]], + [argument1, argument2], + ) + + +def streaming_result(argument1, argument2): + "Return count, mean and variance; True uses n-1 correction and requires at least two samples." + return _invoke( + "hmath_stochastic_statistics_advanced_streaming_result", + [["Bool"], ["Streaming"]], + [argument1, argument2], + ) + + +def histogram_nd(argument1, argument2, argument3): + "Histogram edges must increase strictly; intervals are [a,b), with the last interval closed on its right. Points outside any axis are excluded. Flattening is row-major, the last axis varies fastest. Weights need not sum to one." + return _invoke( + "hmath_stochastic_statistics_advanced_histogram_nd", + [ + ["list", ["list", ["Double"]]], + ["list", ["list", ["Double"]]], + ["list", ["Double"]], + ], + [argument1, argument2, argument3], + ) + + +def mutual_information(argument1): + "Mutual information in nats from a rectangular normalized joint-probability table." + return _invoke( + "hmath_stochastic_statistics_advanced_mutual_information", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def bootstrap(argument1, argument2, argument3, argument4): + "Seeded nonparametric resampling with replacement. Returns caller statistic for each replicate and final RNG state." + return _invoke( + "hmath_stochastic_statistics_advanced_bootstrap", + [ + ["Int"], + ["function", ["list", ["Double"]], ["Either", ["MathError"], ["Double"]]], + ["list", ["Double"]], + ["RNG"], + ], + [argument1, argument2, argument3, argument4], + ) + + +def jackknife(argument1, argument2): + "Leave-one-out bias-corrected statistic and jackknife standard error; requires n>=2." + return _invoke( + "hmath_stochastic_statistics_advanced_jackknife", + [ + ["function", ["list", ["Double"]], ["Either", ["MathError"], ["Double"]]], + ["list", ["Double"]], + ], + [argument1, argument2], + ) + + +def one_sample_t(argument1, argument2): + "Two-sided one-sample Student t test against a finite null mean; assumes independent normal observations." + return _invoke( + "hmath_stochastic_statistics_advanced_one_sample_t", + [["Double"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def two_sample_t(argument1, argument2, argument3): + "Two-sided pooled t test when True, Welch unequal-variance test when False; each group requires n>=2 and positive combined variation." + return _invoke( + "hmath_stochastic_statistics_advanced_two_sample_t", + [["Bool"], ["list", ["Double"]], ["list", ["Double"]]], + [argument1, argument2, argument3], + ) + + +def paired_t(argument1, argument2): + "Two-sided one-sample t test on paired differences; matching group lengths required." + return _invoke( + "hmath_stochastic_statistics_advanced_paired_t", + [["list", ["Double"]], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def z_test(argument1, argument2, argument3): + "Two-sided one-sample normal z test with known strictly positive population standard deviation." + return _invoke( + "hmath_stochastic_statistics_advanced_z_test", + [["Double"], ["Double"], ["list", ["Double"]]], + [argument1, argument2, argument3], + ) + + +def chi_square_test(argument1, argument2, argument3): + "Pearson goodness-of-fit chi-square statistic for observed and positive expected counts; first argument is number of fitted nuisance parameters." + return _invoke( + "hmath_stochastic_statistics_advanced_chi_square_test", + [["Int"], ["list", ["Double"]], ["list", ["Double"]]], + [argument1, argument2, argument3], + ) + + +def variance_f_test(argument1, argument2): + "Two-sided normal-population variance-ratio F test, requiring positive sample variances." + return _invoke( + "hmath_stochastic_statistics_advanced_variance_f_test", + [["list", ["Double"]], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def anova(argument1): + "One-way fixed-effects F test on independent normal groups with common variance; each group requires n>=2." + return _invoke( + "hmath_stochastic_statistics_advanced_anova", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def welch_anova(argument1): + "Welch one-way heteroscedastic F test with Satterthwaite denominator degrees of freedom." + return _invoke( + "hmath_stochastic_statistics_advanced_welch_anova", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def kruskal_wallis(argument1): + "Tie-corrected Kruskal--Wallis H statistic with chi-square asymptotic calibration." + return _invoke( + "hmath_stochastic_statistics_advanced_kruskal_wallis", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def mann_whitney(argument1, argument2): + "Mann--Whitney U for the first sample; two-sided tie-corrected normal approximation with continuity correction." + return _invoke( + "hmath_stochastic_statistics_advanced_mann_whitney", + [["list", ["Double"]], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def wilcoxon(argument1): + "Wilcoxon signed-rank test for differences, dropping zeros and using average absolute tied ranks and continuity-corrected normal calibration." + return _invoke( + "hmath_stochastic_statistics_advanced_wilcoxon", + [["list", ["Double"]]], + [argument1], + ) + + +def kolmogorov_smirnov(argument1, argument2): + "Two-sided KS statistic and asymptotic p value against a fully specified continuous distribution. A Jacobi theta transformation handles very small statistics. Fitting parameters from these observations invalidates this null calibration." + return _invoke( + "hmath_stochastic_statistics_advanced_kolmogorov_smirnov", + [["Distribution"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def shapiro_wilk(argument1): + "Royston's AS R94 coefficients and normal-tail approximation, n=3..5000, uncensored samples. Numerical constants are published statistical data. Reference: https://doi.org/10.2307/2986146" + return _invoke( + "hmath_stochastic_statistics_advanced_shapiro_wilk", + [["list", ["Double"]]], + [argument1], + ) + + +def anderson_darling(argument1): + "Anderson--Darling normality test after fitting the sample mean and unbiased sample standard deviation. The returned statistic is raw A²; Stephens' p-value approximation uses A²*(1+0.75/n+2.25/n²). For adjusted A²>13, the published approximation is outside its calibrated range and the extreme tail is reported as zero instead of extrapolating its quadratic back upward." + return _invoke( + "hmath_stochastic_statistics_advanced_anderson_darling", + [["list", ["Double"]]], + [argument1], + ) + + +def levene(argument1, argument2): + "One-way ANOVA on absolute deviations; True chooses group medians (Brown--Forsythe), False chooses means." + return _invoke( + "hmath_stochastic_statistics_advanced_levene", + [["Bool"], ["list", ["list", ["Double"]]]], + [argument1, argument2], + ) + + +def bartlett(argument1): + "Bartlett homogeneity-of-variance test, appropriate for normal samples; positive group variances required." + return _invoke( + "hmath_stochastic_statistics_advanced_bartlett", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def fisher_exact(argument1, argument2, argument3, argument4): + "Two-sided Fisher exact test on nonnegative 2-by-2 counts (a,b;c,d). Enumerates tables with mass no larger than the observed table." + return _invoke( + "hmath_stochastic_statistics_advanced_fisher_exact", + [["Int"], ["Int"], ["Int"], ["Int"]], + [argument1, argument2, argument3, argument4], + ) + + +def permutation_test(argument1, argument2, argument3, argument4, argument5): + "Seeded two-sided random-label permutation p value for a caller statistic, with the (b+1)/(B+1) correction." + return _invoke( + "hmath_stochastic_statistics_advanced_permutation_test", + [ + ["Int"], + [ + "function", + ["list", ["Double"]], + ["list", ["Double"]], + ["Either", ["MathError"], ["Double"]], + ], + ["list", ["Double"]], + ["list", ["Double"]], + ["RNG"], + ], + [argument1, argument2, argument3, argument4, argument5], + ) + + +def eta_squared(argument1): + "One-way ANOVA explained sum of squares divided by total sum of squares." + return _invoke( + "hmath_stochastic_statistics_advanced_eta_squared", + [["list", ["list", ["Double"]]]], + [argument1], + ) + + +def grubbs(argument1, argument2): + "Two-sided single-outlier Grubbs test, returning candidate index, G statistic and rejection decision at alpha; normality assumption required." + return _invoke( + "hmath_stochastic_statistics_advanced_grubbs", + [["Double"], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def masked(argument1, argument2): + "Keep True-mask observations, then validate retained values. Excluded NaN/infinity do not contaminate results." + return _invoke( + "hmath_stochastic_statistics_advanced_masked", + [["list", ["Bool"]], ["list", ["Double"]]], + [argument1, argument2], + ) + + +def test_statistic(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_stochastic_statistics_advanced_test_statistic", + [["TestResult"]], + [argument1], + ) + + +def p_value(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_stochastic_statistics_advanced_p_value", [["TestResult"]], [argument1] + ) + + +def degrees_of_freedom(argument1): + "Read the original immutable public field; no numerical conversion is performed." + return _invoke( + "hmath_stochastic_statistics_advanced_degrees_of_freedom", + [["TestResult"]], + [argument1], + ) + + +__all__ = [ + "Streaming", + "TestResult", + "anderson_darling", + "anova", + "bartlett", + "bootstrap", + "chi_square_test", + "combine_streaming", + "covariance_matrix", + "degrees_of_freedom", + "empty_streaming", + "eta_squared", + "fisher_exact", + "grubbs", + "histogram_nd", + "jackknife", + "kolmogorov_smirnov", + "kruskal_wallis", + "levene", + "mann_whitney", + "masked", + "mutual_information", + "one_sample_t", + "p_value", + "paired_t", + "partial_correlation", + "permutation_test", + "shapiro_wilk", + "streaming_result", + "test_statistic", + "two_sample_t", + "update_streaming", + "variance_f_test", + "welch_anova", + "wilcoxon", + "z_test", +] diff --git a/bindings/python/_hmath_native/symbolic.py b/bindings/python/_hmath_native/symbolic.py new file mode 100644 index 0000000..77ebb88 --- /dev/null +++ b/bindings/python/_hmath_native/symbolic.py @@ -0,0 +1,324 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original HMath.Symbolic public API.""" + +from ._expression_base import ( + Any, + Assumptions, + BinaryPattern, + CallPattern, + Direction, + DoesNotExist, + Equal, + Exactly, + FiniteLimit, + FromLeft, + FromRight, + Greater, + GreaterEqual, + Guarded, + Inconsistent, + Integral, + Less, + LessEqual, + LimitResult, + LinearSolution, + Negative, + NegativeInfinity, + NonNegative, + NonPositive, + NonZero, + NotEqual, + ParametricSolution, + Pattern, + PolynomialFactorization, + Positive, + PositiveInfinity, + Property, + Real, + Relation, + RelationOp, + RelationResult, + RewriteRule, + Series, + SymbolicMatrix, + SymbolicOptions, + Truth, + TwoSided, + UnaryPattern, + Unresolved, + apply_rewrite, + assumptions, + collect_terms, + default_symbolic_options, + differentiate, + exact_polynomial_roots, + expand, + factor_leading, + factor_polynomial, + factor_terms, + formal_power_series, + from_polynomial, + gradient, + guarded_value, + hessian, + integrate_basic, + integrate_by_parts, + integrate_rational, + integrate_substitution, + jacobian, + laurent_series, + logarithmic_simplify, + maclaurin_series, + match_pattern, + matrix_add, + matrix_expressions, + matrix_multiply, + multiply_formal_series, + no_assumptions, + normalize, + numerical_polynomial_roots, + numerical_substitution, + proves, + rational_simplify, + reciprocal_formal_series, + required_conditions, + rewrite_pattern, + rewrite_replacement, + rewrite_requirements, + series_center, + series_minimum_power, + series_terms, + simplify, + simplify_relation, + solve_linear_equations, + solve_linear_inequality, + substitute, + symbolic_assumptions, + symbolic_determinant, + symbolic_eigenvalues, + symbolic_limit, + symbolic_limits, + symbolic_matrix, + taylor_series, + to_la_te_x, + to_math_ml, + to_polynomial, + trigonometric_simplify, +) +from .expression import * + +__all__ = [ + "Abs", + "Acos", + "Add", + "Any", + "Asin", + "Assumptions", + "Atan", + "Binary", + "BinaryOp", + "BinaryPattern", + "Bindings", + "Builtin", + "Call", + "CallPattern", + "Ceiling", + "Compiled", + "Constant", + "Cos", + "Cosh", + "DepthLimit", + "Direction", + "Divide", + "DoesNotExist", + "DomainFailure", + "Equal", + "ErrorKind", + "Euler", + "ExactRational", + "ExactValue", + "Exactly", + "Exp", + "Expr", + "ExprError", + "ExprNode", + "ExpressionCache", + "FiniteLimit", + "Float64", + "FloatValue", + "Floor", + "FromLeft", + "FromRight", + "Greater", + "GreaterEqual", + "Guarded", + "Inconsistent", + "Integral", + "InvalidLimits", + "Less", + "LessEqual", + "Let", + "LimitResult", + "Limits", + "LinearSolution", + "Literal", + "Log", + "Max", + "MemoryLimit", + "Min", + "Multiply", + "NamedConstant", + "Negate", + "Negative", + "NegativeInfinity", + "NonFinite", + "NonNegative", + "NonPositive", + "NonZero", + "NotEqual", + "ParametricSolution", + "Pattern", + "Pi", + "PolynomialFactorization", + "Positive", + "PositiveInfinity", + "Power", + "Precision", + "Property", + "Real", + "Registry", + "Relation", + "RelationOp", + "RelationResult", + "RewriteRule", + "Series", + "Signum", + "Sin", + "Sinh", + "SourcePos", + "Sqrt", + "StepLimit", + "Subtract", + "SymbolicMatrix", + "SymbolicOptions", + "SyntaxError", + "Tan", + "Tanh", + "Tau", + "Truth", + "TwoSided", + "TypeMismatch", + "Unary", + "UnaryOp", + "UnaryPattern", + "UnknownName", + "Unresolved", + "Unsupported", + "Value", + "Variable", + "allowed_functions", + "apply_rewrite", + "assumptions", + "binary", + "cache_size", + "cached_expression", + "call", + "collect_terms", + "compile_expression", + "compiled_node_count", + "constant", + "default_limits", + "default_registry", + "default_symbolic_options", + "deserialize_expression", + "differentiate", + "empty_expression_cache", + "empty_registry", + "error_kind", + "error_message", + "error_position", + "evaluate_compiled", + "evaluate_expression", + "evaluate_text", + "exact_polynomial_roots", + "expand", + "expression_hash", + "expression_node", + "expression_position", + "factor_leading", + "factor_polynomial", + "factor_terms", + "formal_power_series", + "format_radix", + "format_scientific", + "free_variables", + "from_polynomial", + "gradient", + "guarded_value", + "hessian", + "integrate_basic", + "integrate_by_parts", + "integrate_rational", + "integrate_substitution", + "jacobian", + "laurent_series", + "let_in", + "literal", + "logarithmic_simplify", + "maclaurin_series", + "match_pattern", + "matrix_add", + "matrix_expressions", + "matrix_multiply", + "maximum_cache_entries", + "maximum_depth", + "maximum_input_chars", + "maximum_integer_bits", + "maximum_nodes", + "maximum_steps", + "multiply_formal_series", + "no_assumptions", + "normalize", + "numerical_polynomial_roots", + "numerical_substitution", + "optimize_expression", + "parse_expression", + "pretty_expression", + "proves", + "rational_simplify", + "reciprocal_formal_series", + "register_function", + "required_conditions", + "rewrite_pattern", + "rewrite_replacement", + "rewrite_requirements", + "serialize_expression", + "series_center", + "series_minimum_power", + "series_terms", + "simplify", + "simplify_relation", + "solve_linear_equations", + "solve_linear_inequality", + "source_column", + "source_line", + "source_offset", + "substitute", + "symbolic_assumptions", + "symbolic_determinant", + "symbolic_eigenvalues", + "symbolic_limit", + "symbolic_limits", + "symbolic_matrix", + "taylor_series", + "to_la_te_x", + "to_math_ml", + "to_polynomial", + "trigonometric_simplify", + "type_check_expression", + "unary", + "unknown_position", + "validate_expression", + "validate_limits", + "variable", +] diff --git a/bindings/python/_hmath_native/tensor.py b/bindings/python/_hmath_native/tensor.py new file mode 100644 index 0000000..77d5364 --- /dev/null +++ b/bindings/python/_hmath_native/tensor.py @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def shape_size(dims): + """Call HMath.Tensor.shapeSize; preserve its argument order, result and errors.""" + return _call( + 'hmath_tensor_shape_size', + ['is'], + 'i', + [dims], + None, + 0, + ) + + +def infer_broadcast(as_, bs): + """Call HMath.Tensor.inferBroadcast; preserve its argument order, result and errors.""" + return _call( + 'hmath_tensor_infer_broadcast', + ['is', 'is'], + 'id', + [as_, bs], + None, + 0, + ) + + +from ._tensor_core import * diff --git a/bindings/python/_hmath_native/timeseries.py b/bindings/python/_hmath_native/timeseries.py new file mode 100644 index 0000000..9bbceca --- /dev/null +++ b/bindings/python/_hmath_native/timeseries.py @@ -0,0 +1,634 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_timeseries_bindings.py. +"""Original timestamped-series, diagnostics and forecasting functions.""" +from ._timeseries_base import _invoke +from ._value import Value, register + + +class Series(Value): + """Owned immutable original HMath.TimeSeries.Core.Series.""" + + +register(120, Series) + + +class Alignment(Value): + """Owned immutable original HMath.TimeSeries.Core.Alignment.""" + + +register(121, Alignment) + + +class Fill(Value): + """Owned immutable original HMath.TimeSeries.Core.Fill.""" + + +register(122, Fill) + + +class Resampling(Value): + """Owned immutable original HMath.TimeSeries.Core.Resampling.""" + + +register(123, Resampling) + + +class Rolling(Value): + """Owned immutable original HMath.TimeSeries.Core.Rolling.""" + + +register(124, Rolling) + + +class DTWResult(Value): + """Owned immutable original HMath.TimeSeries.Diagnostics.DTWResult.""" + + +register(125, DTWResult) + + +class Deterministic(Value): + """Owned immutable original HMath.TimeSeries.Diagnostics.Deterministic.""" + + +register(126, Deterministic) + + +class ForecastMetric(Value): + """Owned immutable original HMath.TimeSeries.Diagnostics.ForecastMetric.""" + + +register(127, ForecastMetric) + + +class Stationarity(Value): + """Owned immutable original HMath.TimeSeries.Diagnostics.Stationarity.""" + + +register(128, Stationarity) + + +class ARIMAModel(Value): + """Owned immutable original HMath.TimeSeries.Models.ARIMAModel.""" + + +register(129, ARIMAModel) + + +class ARModel(Value): + """Owned immutable original HMath.TimeSeries.Models.ARModel.""" + + +register(130, ARModel) + + +class Decomposition(Value): + """Owned immutable original HMath.TimeSeries.Models.Decomposition.""" + + +register(131, Decomposition) + + +class SARIMAOrder(Value): + """Owned immutable original HMath.TimeSeries.Models.SARIMAOrder.""" + + +register(132, SARIMAOrder) + + +class STLConfig(Value): + """Owned immutable original HMath.TimeSeries.Models.STLConfig.""" + + +register(133, STLConfig) + + +class Smoothing(Value): + """Owned immutable original HMath.TimeSeries.Models.Smoothing.""" + + +register(134, Smoothing) + + +class VARModel(Value): + """Owned immutable original HMath.TimeSeries.Models.VARModel.""" + + +register(135, VARModel) + + +class GaussianState(Value): + """Owned immutable original HMath.Signal.GaussianState.""" + + +register(140, GaussianState) + + +def describe(value): + """Return the original Haskell Show representation of a domain object.""" + return _invoke("hmath_timeseries_describe", [["SeriesObject"]], [value]) + + +def backward_fill(): + """HMath.TimeSeries.Core.BackwardFill :: Fill.""" + return _invoke('hmath_timeseries_backward_fill', [], []) + + +def bin_last(): + """HMath.TimeSeries.Core.BinLast :: Resampling.""" + return _invoke('hmath_timeseries_bin_last', [], []) + + +def bin_mean(): + """HMath.TimeSeries.Core.BinMean :: Resampling.""" + return _invoke('hmath_timeseries_bin_mean', [], []) + + +def forward_fill(): + """HMath.TimeSeries.Core.ForwardFill :: Fill.""" + return _invoke('hmath_timeseries_forward_fill', [], []) + + +def inner(): + """HMath.TimeSeries.Core.Inner :: Alignment.""" + return _invoke('hmath_timeseries_inner', [], []) + + +def left_aligned(): + """HMath.TimeSeries.Core.LeftAligned :: Alignment.""" + return _invoke('hmath_timeseries_left_aligned', [], []) + + +def linear_fill(): + """HMath.TimeSeries.Core.LinearFill :: Fill.""" + return _invoke('hmath_timeseries_linear_fill', [], []) + + +def linear_samples(): + """HMath.TimeSeries.Core.LinearSamples :: Resampling.""" + return _invoke('hmath_timeseries_linear_samples', [], []) + + +def moving_maximum(): + """HMath.TimeSeries.Core.MovingMaximum :: Rolling.""" + return _invoke('hmath_timeseries_moving_maximum', [], []) + + +def moving_mean(): + """HMath.TimeSeries.Core.MovingMean :: Rolling.""" + return _invoke('hmath_timeseries_moving_mean', [], []) + + +def moving_minimum(): + """HMath.TimeSeries.Core.MovingMinimum :: Rolling.""" + return _invoke('hmath_timeseries_moving_minimum', [], []) + + +def moving_sd(): + """HMath.TimeSeries.Core.MovingSD :: Rolling.""" + return _invoke('hmath_timeseries_moving_sd', [], []) + + +def moving_variance(): + """HMath.TimeSeries.Core.MovingVariance :: Rolling.""" + return _invoke('hmath_timeseries_moving_variance', [], []) + + +def outer(): + """HMath.TimeSeries.Core.Outer :: Alignment.""" + return _invoke('hmath_timeseries_outer', [], []) + + +def align(value, value2, value3): + """HMath.TimeSeries.Core.align :: Alignment -> Series -> Series -> Either MathError (Series, Series).""" + return _invoke('hmath_timeseries_align', [['Alignment'], ['Series'], ['Series']], [value, value2, value3]) + + +def autocorrelation(lags, xs): + """HMath.TimeSeries.Core.autocorrelation :: Int -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_autocorrelation', [['Int'], ['list', ['Double']]], [lags, xs]) + + +def cross_correlation(lag, xs, ys): + """HMath.TimeSeries.Core.crossCorrelation :: Int -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_timeseries_cross_correlation', [['Int'], ['list', ['Double']], ['list', ['Double']]], [lag, xs, ys]) + + +def cumulative_returns(xs): + """HMath.TimeSeries.Core.cumulativeReturns :: [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_cumulative_returns', [['list', ['Double']]], [xs]) + + +def difference(order, lag, xs): + """HMath.TimeSeries.Core.difference :: Int -> Int -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_difference', [['Int'], ['Int'], ['list', ['Double']]], [order, lag, xs]) + + +def durbin_levinson(covariance): + """HMath.TimeSeries.Core.durbinLevinson :: [Double] -> Either MathError ([Double], Double, [Double]).""" + return _invoke('hmath_timeseries_durbin_levinson', [['list', ['Double']]], [covariance]) + + +def exponential_average(alpha, xs): + """HMath.TimeSeries.Core.exponentialAverage :: Double -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_exponential_average', [['Double'], ['list', ['Double']]], [alpha, xs]) + + +def fill_missing(value, value2): + """HMath.TimeSeries.Core.fillMissing :: Fill -> Series -> Either MathError Series.""" + return _invoke('hmath_timeseries_fill_missing', [['Fill'], ['Series']], [value, value2]) + + +def is_regular(value, value2): + """HMath.TimeSeries.Core.isRegular :: Double -> Series -> Either MathError Bool.""" + return _invoke('hmath_timeseries_is_regular', [['Double'], ['Series']], [value, value2]) + + +def logarithmic_returns(xs): + """HMath.TimeSeries.Core.logarithmicReturns :: [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_logarithmic_returns', [['list', ['Double']]], [xs]) + + +def observations(value): + """HMath.TimeSeries.Core.observations :: Series -> [(Double, Maybe Double)].""" + return _invoke('hmath_timeseries_observations', [['Series']], [value]) + + +def partial_autocorrelation(order, xs): + """HMath.TimeSeries.Core.partialAutocorrelation :: Int -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_partial_autocorrelation', [['Int'], ['list', ['Double']]], [order, xs]) + + +def regular_series(start, step, xs): + """HMath.TimeSeries.Core.regularSeries :: Double -> Double -> [Maybe Double] -> Either MathError Series.""" + return _invoke('hmath_timeseries_regular_series', [['Double'], ['Double'], ['list', ['maybe', ['Double']]]], [start, step, xs]) + + +def resample(value, value2, value3, value4, value5): + """HMath.TimeSeries.Core.resample :: Resampling -> Double -> Double -> Int -> Series -> Either MathError Series.""" + return _invoke('hmath_timeseries_resample', [['Resampling'], ['Double'], ['Double'], ['Int'], ['Series']], [value, value2, value3, value4, value5]) + + +def rolling(method, width, xs): + """HMath.TimeSeries.Core.rolling :: Rolling -> Int -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_rolling', [['Rolling'], ['Int'], ['list', ['Double']]], [method, width, xs]) + + +def series(xs): + """HMath.TimeSeries.Core.series :: [(Double, Maybe Double)] -> Either MathError Series.""" + return _invoke('hmath_timeseries_series', [['list', ['tuple', ['Double'], ['maybe', ['Double']]]]], [xs]) + + +def series_values(value): + """HMath.TimeSeries.Core.seriesValues :: Series -> Either MathError [Double].""" + return _invoke('hmath_timeseries_series_values', [['Series']], [value]) + + +def weighted_average(ws, xs): + """HMath.TimeSeries.Core.weightedAverage :: [Double] -> [Double] -> Either MathError [Double].""" + return _invoke('hmath_timeseries_weighted_average', [['list', ['Double']], ['list', ['Double']]], [ws, xs]) + + +def yule_walker(order, xs): + """HMath.TimeSeries.Core.yuleWalker :: Int -> [Double] -> Either MathError ([Double], Double, Double).""" + return _invoke('hmath_timeseries_yule_walker', [['Int'], ['list', ['Double']]], [order, xs]) + + +def dtw_result(distance, path): + """HMath.TimeSeries.Diagnostics.DTWResult :: Double -> [(Int, Int)] -> DTWResult.""" + return _invoke('hmath_timeseries_dtw_result', [['Double'], ['list', ['tuple', ['Int'], ['Int']]]], [distance, path]) + + +def level(): + """HMath.TimeSeries.Diagnostics.Level :: Deterministic.""" + return _invoke('hmath_timeseries_level', [], []) + + +def linear_trend(): + """HMath.TimeSeries.Diagnostics.LinearTrend :: Deterministic.""" + return _invoke('hmath_timeseries_linear_trend', [], []) + + +def mae(): + """HMath.TimeSeries.Diagnostics.MAE :: ForecastMetric.""" + return _invoke('hmath_timeseries_mae', [], []) + + +def mape(): + """HMath.TimeSeries.Diagnostics.MAPE :: ForecastMetric.""" + return _invoke('hmath_timeseries_mape', [], []) + + +def mase(period, training): + """HMath.TimeSeries.Diagnostics.MASE :: Int -> [Double] -> ForecastMetric.""" + return _invoke('hmath_timeseries_mase', [['Int'], ['list', ['Double']]], [period, training]) + + +def mse(): + """HMath.TimeSeries.Diagnostics.MSE :: ForecastMetric.""" + return _invoke('hmath_timeseries_mse', [], []) + + +def rmse(): + """HMath.TimeSeries.Diagnostics.RMSE :: ForecastMetric.""" + return _invoke('hmath_timeseries_rmse', [], []) + + +def smape(): + """HMath.TimeSeries.Diagnostics.SMAPE :: ForecastMetric.""" + return _invoke('hmath_timeseries_smape', [], []) + + +def stationarity(statistic, critical_values, observations, null_hypothesis): + """HMath.TimeSeries.Diagnostics.Stationarity :: Double -> [(Double, Double)] -> Int -> String -> Stationarity.""" + return _invoke('hmath_timeseries_stationarity', [['Double'], ['list', ['tuple', ['Double'], ['Double']]], ['Int'], ['String']], [statistic, critical_values, observations, null_hypothesis]) + + +def anomalies(threshold, xs): + """HMath.TimeSeries.Diagnostics.anomalies :: Double -> [Double] -> Either MathError [Int].""" + return _invoke('hmath_timeseries_anomalies', [['Double'], ['list', ['Double']]], [threshold, xs]) + + +def augmented_dickey_fuller(deterministic, lags, xs): + """HMath.TimeSeries.Diagnostics.augmentedDickeyFuller :: Deterministic -> Int -> [Double] -> Either MathError Stationarity.""" + return _invoke('hmath_timeseries_augmented_dickey_fuller', [['Deterministic'], ['Int'], ['list', ['Double']]], [deterministic, lags, xs]) + + +def change_points(penalty, min_segment, xs): + """HMath.TimeSeries.Diagnostics.changePoints :: Double -> Int -> [Double] -> Either MathError [Int].""" + return _invoke('hmath_timeseries_change_points', [['Double'], ['Int'], ['list', ['Double']]], [penalty, min_segment, xs]) + + +def cusum(mean, sd, drift, threshold, xs): + """HMath.TimeSeries.Diagnostics.cusum :: Double -> Double -> Double -> Double -> [Double] -> Either MathError [Int].""" + return _invoke('hmath_timeseries_cusum', [['Double'], ['Double'], ['Double'], ['Double'], ['list', ['Double']]], [mean, sd, drift, threshold, xs]) + + +def dtw_distance(value): + """HMath.TimeSeries.Diagnostics.dtwDistance :: DTWResult -> Double.""" + return _invoke('hmath_timeseries_dtw_distance', [['DTWResult']], [value]) + + +def dtw_path(value): + """HMath.TimeSeries.Diagnostics.dtwPath :: DTWResult -> [(Int, Int)].""" + return _invoke('hmath_timeseries_dtw_path', [['DTWResult']], [value]) + + +def dynamic_time_warping(radius, xs, ys): + """HMath.TimeSeries.Diagnostics.dynamicTimeWarping :: Int -> [Double] -> [Double] -> Either MathError DTWResult.""" + return _invoke('hmath_timeseries_dynamic_time_warping', [['Int'], ['list', ['Double']], ['list', ['Double']]], [radius, xs, ys]) + + +def forecast_error(metric, actual, predicted): + """HMath.TimeSeries.Diagnostics.forecastError :: ForecastMetric -> [Double] -> [Double] -> Either MathError Double.""" + return _invoke('hmath_timeseries_forecast_error', [['ForecastMetric'], ['list', ['Double']], ['list', ['Double']]], [metric, actual, predicted]) + + +def kpss(deterministic, lags, xs): + """HMath.TimeSeries.Diagnostics.kpss :: Deterministic -> Int -> [Double] -> Either MathError Stationarity.""" + return _invoke('hmath_timeseries_kpss', [['Deterministic'], ['Int'], ['list', ['Double']]], [deterministic, lags, xs]) + + +def spectrum(sample_rate, xs): + """HMath.TimeSeries.Diagnostics.spectrum :: Double -> [Double] -> Either MathError [(Double, Double)].""" + return _invoke('hmath_timeseries_spectrum', [['Double'], ['list', ['Double']]], [sample_rate, xs]) + + +def stationarity_critical_values(value): + """HMath.TimeSeries.Diagnostics.stationarityCriticalValues :: Stationarity -> [(Double, Double)].""" + return _invoke('hmath_timeseries_stationarity_critical_values', [['Stationarity']], [value]) + + +def stationarity_null(value): + """HMath.TimeSeries.Diagnostics.stationarityNull :: Stationarity -> String.""" + return _invoke('hmath_timeseries_stationarity_null', [['Stationarity']], [value]) + + +def stationarity_observations(value): + """HMath.TimeSeries.Diagnostics.stationarityObservations :: Stationarity -> Int.""" + return _invoke('hmath_timeseries_stationarity_observations', [['Stationarity']], [value]) + + +def stationarity_statistic(value): + """HMath.TimeSeries.Diagnostics.stationarityStatistic :: Stationarity -> Double.""" + return _invoke('hmath_timeseries_stationarity_statistic', [['Stationarity']], [value]) + + +def decomposition(trend, seasonal, remainder): + """HMath.TimeSeries.Models.Decomposition :: [Double] -> [Double] -> [Double] -> Decomposition.""" + return _invoke('hmath_timeseries_decomposition', [['list', ['Double']], ['list', ['Double']], ['list', ['Double']]], [trend, seasonal, remainder]) + + +def holt(alpha, beta): + """HMath.TimeSeries.Models.Holt :: Double -> Double -> Smoothing.""" + return _invoke('hmath_timeseries_holt', [['Double'], ['Double']], [alpha, beta]) + + +def holt_winters(period, alpha, beta, gamma): + """HMath.TimeSeries.Models.HoltWinters :: Int -> Double -> Double -> Double -> Smoothing.""" + return _invoke('hmath_timeseries_holt_winters', [['Int'], ['Double'], ['Double'], ['Double']], [period, alpha, beta, gamma]) + + +def sarima_order(ar, difference, ma, seasonal_ar, seasonal_difference, seasonal_ma, period): + """HMath.TimeSeries.Models.SARIMAOrder :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> SARIMAOrder.""" + return _invoke('hmath_timeseries_sarima_order', [['Int'], ['Int'], ['Int'], ['Int'], ['Int'], ['Int'], ['Int']], [ar, difference, ma, seasonal_ar, seasonal_difference, seasonal_ma, period]) + + +def stl_config(period, seasonal_window, trend_window, low_pass_window, inner_iterations, robust_iterations): + """HMath.TimeSeries.Models.STLConfig :: Int -> Int -> Int -> Int -> Int -> Int -> STLConfig.""" + return _invoke('hmath_timeseries_stl_config', [['Int'], ['Int'], ['Int'], ['Int'], ['Int'], ['Int']], [period, seasonal_window, trend_window, low_pass_window, inner_iterations, robust_iterations]) + + +def simple(alpha): + """HMath.TimeSeries.Models.Simple :: Double -> Smoothing.""" + return _invoke('hmath_timeseries_simple', [['Double']], [alpha]) + + +def ar_coefficients(value): + """HMath.TimeSeries.Models.arCoefficients :: ARModel -> [Double].""" + return _invoke('hmath_timeseries_ar_coefficients', [['ARModel']], [value]) + + +def ar_order(value): + """HMath.TimeSeries.Models.arOrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_ar_order', [['SARIMAOrder']], [value]) + + +def arima_innovation_variance(value): + """HMath.TimeSeries.Models.arimaInnovationVariance :: ARIMAModel -> Double.""" + return _invoke('hmath_timeseries_arima_innovation_variance', [['ARIMAModel']], [value]) + + +def arima_parameters(value): + """HMath.TimeSeries.Models.arimaParameters :: ARIMAModel -> [Double].""" + return _invoke('hmath_timeseries_arima_parameters', [['ARIMAModel']], [value]) + + +def arima_residuals(value): + """HMath.TimeSeries.Models.arimaResiduals :: ARIMAModel -> [Double].""" + return _invoke('hmath_timeseries_arima_residuals', [['ARIMAModel']], [value]) + + +def decompose(period, xs): + """HMath.TimeSeries.Models.decompose :: Int -> [Double] -> Either MathError Decomposition.""" + return _invoke('hmath_timeseries_decompose', [['Int'], ['list', ['Double']]], [period, xs]) + + +def default_stl_config(period): + """HMath.TimeSeries.Models.defaultSTLConfig :: Int -> STLConfig.""" + return _invoke('hmath_timeseries_default_stl_config', [['Int']], [period]) + + +def difference_order(value): + """HMath.TimeSeries.Models.differenceOrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_difference_order', [['SARIMAOrder']], [value]) + + +def fit_ar(order, xs): + """HMath.TimeSeries.Models.fitAR :: Int -> [Double] -> Either MathError ARModel.""" + return _invoke('hmath_timeseries_fit_ar', [['Int'], ['list', ['Double']]], [order, xs]) + + +def fit_arima(value, value2, value3, value4, value5): + """HMath.TimeSeries.Models.fitARIMA :: OptimizeOptions -> Int -> Int -> Int -> [Double] -> Either MathError ARIMAModel.""" + return _invoke('hmath_timeseries_fit_arima', [['OptimizeOptions'], ['Int'], ['Int'], ['Int'], ['list', ['Double']]], [value, value2, value3, value4, value5]) + + +def fit_arma(value, value2, value3, value4): + """HMath.TimeSeries.Models.fitARMA :: OptimizeOptions -> Int -> Int -> [Double] -> Either MathError ARIMAModel.""" + return _invoke('hmath_timeseries_fit_arma', [['OptimizeOptions'], ['Int'], ['Int'], ['list', ['Double']]], [value, value2, value3, value4]) + + +def fit_ma(value, value2, value3): + """HMath.TimeSeries.Models.fitMA :: OptimizeOptions -> Int -> [Double] -> Either MathError ARIMAModel.""" + return _invoke('hmath_timeseries_fit_ma', [['OptimizeOptions'], ['Int'], ['list', ['Double']]], [value, value2, value3]) + + +def fit_sarima(options, order, xs): + """HMath.TimeSeries.Models.fitSARIMA :: OptimizeOptions -> SARIMAOrder -> [Double] -> Either MathError ARIMAModel.""" + return _invoke('hmath_timeseries_fit_sarima', [['OptimizeOptions'], ['SARIMAOrder'], ['list', ['Double']]], [options, order, xs]) + + +def fit_var(order, xs): + """HMath.TimeSeries.Models.fitVAR :: Int -> [[Double]] -> Either MathError VARModel.""" + return _invoke('hmath_timeseries_fit_var', [['Int'], ['list', ['list', ['Double']]]], [order, xs]) + + +def forecast_ar(value, value2): + """HMath.TimeSeries.Models.forecastAR :: Int -> ARModel -> Either MathError [Double].""" + return _invoke('hmath_timeseries_forecast_ar', [['Int'], ['ARModel']], [value, value2]) + + +def forecast_arima(value, value2): + """HMath.TimeSeries.Models.forecastARIMA :: Int -> ARIMAModel -> Either MathError [Double].""" + return _invoke('hmath_timeseries_forecast_arima', [['Int'], ['ARIMAModel']], [value, value2]) + + +def forecast_var(value, value2): + """HMath.TimeSeries.Models.forecastVAR :: Int -> VARModel -> Either MathError [[Double]].""" + return _invoke('hmath_timeseries_forecast_var', [['Int'], ['VARModel']], [value, value2]) + + +def kalman_series(transition, observation, q, r, initial, measured): + """HMath.TimeSeries.Models.kalmanSeries :: [[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> GaussianState -> [[Double]] -> Either MathError [GaussianState].""" + return _invoke('hmath_timeseries_kalman_series', [['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['list', ['list', ['Double']]], ['GaussianState'], ['list', ['list', ['Double']]]], [transition, observation, q, r, initial, measured]) + + +def ma_order(value): + """HMath.TimeSeries.Models.maOrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_ma_order', [['SARIMAOrder']], [value]) + + +def remainder_component(value): + """HMath.TimeSeries.Models.remainderComponent :: Decomposition -> [Double].""" + return _invoke('hmath_timeseries_remainder_component', [['Decomposition']], [value]) + + +def seasonal_ar_order(value): + """HMath.TimeSeries.Models.seasonalAROrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_seasonal_ar_order', [['SARIMAOrder']], [value]) + + +def seasonal_component(value): + """HMath.TimeSeries.Models.seasonalComponent :: Decomposition -> [Double].""" + return _invoke('hmath_timeseries_seasonal_component', [['Decomposition']], [value]) + + +def seasonal_difference_order(value): + """HMath.TimeSeries.Models.seasonalDifferenceOrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_seasonal_difference_order', [['SARIMAOrder']], [value]) + + +def seasonal_ma_order(value): + """HMath.TimeSeries.Models.seasonalMAOrder :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_seasonal_ma_order', [['SARIMAOrder']], [value]) + + +def seasonal_period(value): + """HMath.TimeSeries.Models.seasonalPeriod :: SARIMAOrder -> Int.""" + return _invoke('hmath_timeseries_seasonal_period', [['SARIMAOrder']], [value]) + + +def smooth_forecast(method, horizon, xs): + """HMath.TimeSeries.Models.smoothForecast :: Smoothing -> Int -> [Double] -> Either MathError ([Double], [Double]).""" + return _invoke('hmath_timeseries_smooth_forecast', [['Smoothing'], ['Int'], ['list', ['Double']]], [method, horizon, xs]) + + +def stl(config, xs): + """HMath.TimeSeries.Models.stl :: STLConfig -> [Double] -> Either MathError Decomposition.""" + return _invoke('hmath_timeseries_stl', [['STLConfig'], ['list', ['Double']]], [config, xs]) + + +def stl_inner_iterations(value): + """HMath.TimeSeries.Models.stlInnerIterations :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_inner_iterations', [['STLConfig']], [value]) + + +def stl_low_pass_window(value): + """HMath.TimeSeries.Models.stlLowPassWindow :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_low_pass_window', [['STLConfig']], [value]) + + +def stl_period(value): + """HMath.TimeSeries.Models.stlPeriod :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_period', [['STLConfig']], [value]) + + +def stl_robust_iterations(value): + """HMath.TimeSeries.Models.stlRobustIterations :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_robust_iterations', [['STLConfig']], [value]) + + +def stl_seasonal_window(value): + """HMath.TimeSeries.Models.stlSeasonalWindow :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_seasonal_window', [['STLConfig']], [value]) + + +def stl_trend_window(value): + """HMath.TimeSeries.Models.stlTrendWindow :: STLConfig -> Int.""" + return _invoke('hmath_timeseries_stl_trend_window', [['STLConfig']], [value]) + + +def trend_component(value): + """HMath.TimeSeries.Models.trendComponent :: Decomposition -> [Double].""" + return _invoke('hmath_timeseries_trend_component', [['Decomposition']], [value]) + + +def var_coefficients(value): + """HMath.TimeSeries.Models.varCoefficients :: VARModel -> [[Double]].""" + return _invoke('hmath_timeseries_var_coefficients', [['VARModel']], [value]) + + +def gaussian_state(mean, covariance): + """HMath.Signal.gaussianState :: [Double] -> [[Double]] -> Either MathError GaussianState.""" + return _invoke('hmath_timeseries_gaussian_state', [['list', ['Double']], ['list', ['list', ['Double']]]], [mean, covariance]) + + +def state_mean(value): + """HMath.Signal.stateMean :: GaussianState -> [Double].""" + return _invoke('hmath_timeseries_state_mean', [['GaussianState']], [value]) + + +def state_covariance(value): + """HMath.Signal.stateCovariance :: GaussianState -> [[Double]].""" + return _invoke('hmath_timeseries_state_covariance', [['GaussianState']], [value]) diff --git a/bindings/python/_hmath_native/timeseries_core.py b/bindings/python/_hmath_native/timeseries_core.py new file mode 100644 index 0000000..5dd489a --- /dev/null +++ b/bindings/python/_hmath_native/timeseries_core.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def exponential_average(alpha, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.exponentialAverage; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_exponential_average', + ['f', 'fs'], + 'fd', + [alpha, xs], + dtype, + 0, + ) + + +def weighted_average(ws, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.weightedAverage; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_weighted_average', + ['fs', 'fs'], + 'fd', + [ws, xs], + dtype, + 0, + ) + + +def cumulative_returns(xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.cumulativeReturns; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_cumulative_returns', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def logarithmic_returns(xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.logarithmicReturns; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_logarithmic_returns', + ['fs'], + 'fd', + [xs], + dtype, + 0, + ) + + +def difference(order, lag, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.difference; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_difference', + ['i', 'i', 'fs'], + 'fd', + [order, lag, xs], + dtype, + 0, + ) + + +def autocorrelation(lags, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.autocorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_autocorrelation', + ['i', 'fs'], + 'fd', + [lags, xs], + dtype, + 0, + ) + + +def cross_correlation(lag, xs, ys, *, dtype='float64'): + """Call HMath.TimeSeries.Core.crossCorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_cross_correlation', + ['i', 'fs', 'fs'], + 'f', + [lag, xs, ys], + dtype, + 0, + ) + + +def partial_autocorrelation(order, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Core.partialAutocorrelation; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_core_partial_autocorrelation', + ['i', 'fs'], + 'fd', + [order, xs], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/timeseries_diagnostics.py b/bindings/python/_hmath_native/timeseries_diagnostics.py new file mode 100644 index 0000000..3fb5f75 --- /dev/null +++ b/bindings/python/_hmath_native/timeseries_diagnostics.py @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def change_points(penalty, minSegment, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Diagnostics.changePoints; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_diagnostics_change_points', + ['f', 'i', 'fs'], + 'id', + [penalty, minSegment, xs], + dtype, + 0, + ) + + +def cusum(mean, sd, drift, threshold, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Diagnostics.cusum; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_diagnostics_cusum', + ['f', 'f', 'f', 'f', 'fs'], + 'id', + [mean, sd, drift, threshold, xs], + dtype, + 0, + ) + + +def anomalies(threshold, xs, *, dtype='float64'): + """Call HMath.TimeSeries.Diagnostics.anomalies; preserve its argument order, result and errors.""" + if dtype != "float64": + raise ValueError("this Haskell function uses Double; dtype must be 'float64'") + return _call( + 'hmath_timeseries_diagnostics_anomalies', + ['f', 'fs'], + 'id', + [threshold, xs], + dtype, + 0, + ) diff --git a/bindings/python/_hmath_native/trigonometry.py b/bindings/python/_hmath_native/trigonometry.py new file mode 100644 index 0000000..0dfc6d4 --- /dev/null +++ b/bindings/python/_hmath_native/trigonometry.py @@ -0,0 +1,654 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def sin_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.sinChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sin_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def cos_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.cosChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_cos_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def tan_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.tanChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_tan_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def asin_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.asinChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_asin_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acos_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.acosChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acos_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def atan_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.atanChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_atan_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def sec(x, *, dtype='float64'): + """Call HMath.Trigonometry.sec; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sec', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def csc(x, *, dtype='float64'): + """Call HMath.Trigonometry.csc; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_csc', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def cot(x, *, dtype='float64'): + """Call HMath.Trigonometry.cot; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_cot', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def asec(x, *, dtype='float64'): + """Call HMath.Trigonometry.asec; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_asec', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acsc(x, *, dtype='float64'): + """Call HMath.Trigonometry.acsc; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acsc', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acot(x, *, dtype='float64'): + """Call HMath.Trigonometry.acot; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acot', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def sinh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.sinhChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sinh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def cosh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.coshChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_cosh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def tanh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.tanhChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_tanh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def asinh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.asinhChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_asinh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acosh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.acoshChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acosh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def atanh_checked(x, *, dtype='float64'): + """Call HMath.Trigonometry.atanhChecked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_atanh_checked', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def sech(x, *, dtype='float64'): + """Call HMath.Trigonometry.sech; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sech', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def csch(x, *, dtype='float64'): + """Call HMath.Trigonometry.csch; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_csch', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def coth(x, *, dtype='float64'): + """Call HMath.Trigonometry.coth; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_coth', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def asech(x, *, dtype='float64'): + """Call HMath.Trigonometry.asech; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_asech', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acsch(x, *, dtype='float64'): + """Call HMath.Trigonometry.acsch; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acsch', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def acoth(x, *, dtype='float64'): + """Call HMath.Trigonometry.acoth; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_acoth', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def normalize_angle(x, *, dtype='float64'): + """Call HMath.Trigonometry.normalizeAngle; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_normalize_angle', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def normalize_signed_angle(x, *, dtype='float64'): + """Call HMath.Trigonometry.normalizeSignedAngle; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_normalize_signed_angle', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def versine(x, *, dtype='float64'): + """Call HMath.Trigonometry.versine; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_versine', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def haversine(x, *, dtype='float64'): + """Call HMath.Trigonometry.haversine; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_haversine', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def sinc(x, *, dtype='float64'): + """Call HMath.Trigonometry.sinc; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sinc', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def cosc(x, *, dtype='float64'): + """Call HMath.Trigonometry.cosc; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_cosc', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def atan2_checked(y, x, *, dtype='float64'): + """Call HMath.Trigonometry.atan2Checked; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_atan2_checked', + ['f', 'f'], + 'f', + [y, x], + dtype, + 0, + ) + + +def sincos(x, *, dtype='float64'): + """Call HMath.Trigonometry.sincos; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_sincos', + ['f'], + 'ff', + [x], + dtype, + 0, + ) + + +def wrap(low, high, x, *, dtype='float64'): + """Call HMath.Trigonometry.wrap; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_wrap', + ['f', 'f', 'f'], + 'f', + [low, high, x], + dtype, + 0, + ) + + +def angle_difference(a, b, *, dtype='float64'): + """Call HMath.Trigonometry.angleDifference; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_angle_difference', + ['f', 'f'], + 'f', + [a, b], + dtype, + 0, + ) + + +def great_circle_angle(a, b, *, dtype='float64'): + """Call HMath.Trigonometry.greatCircleAngle; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_great_circle_angle', + ['p', 'p'], + 'f', + [a, b], + dtype, + 0, + ) + + +def great_circle_distance(radius, a, b, *, dtype='float64'): + """Call HMath.Trigonometry.greatCircleDistance; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_great_circle_distance', + ['f', 'p', 'p'], + 'f', + [radius, a, b], + dtype, + 0, + ) + + +def spherical_side(a, b, included, *, dtype='float64'): + """Call HMath.Trigonometry.sphericalSide; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_spherical_side', + ['f', 'f', 'f'], + 'f', + [a, b, included], + dtype, + 0, + ) + + +def spherical_angles(a, b, c, *, dtype='float64'): + """Call HMath.Trigonometry.sphericalAngles; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_spherical_angles', + ['f', 'f', 'f'], + 'fff', + [a, b, c], + dtype, + 0, + ) + + +def spherical_excess(a, b, c, *, dtype='float64'): + """Call HMath.Trigonometry.sphericalExcess; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_spherical_excess', + ['f', 'f', 'f'], + 'f', + [a, b, c], + dtype, + 0, + ) + + +def complex_sin(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexSin; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_sin', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_cos(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexCos; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_cos', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_tan(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexTan; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_tan', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_asin(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAsin; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_asin', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_acos(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAcos; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_acos', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_atan(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAtan; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_atan', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_sinh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexSinh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_sinh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_cosh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexCosh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_cosh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_tanh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexTanh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_tanh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_asinh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAsinh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_asinh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_acosh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAcosh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_acosh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def complex_atanh(z, *, dtype='float64'): + """Call HMath.Trigonometry.complexAtanh; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_complex_atanh', + ['c'], + 'c', + [z], + dtype, + 0, + ) + + +def periodic_sawtooth(period, x, *, dtype='float64'): + """Call HMath.Trigonometry.periodicSawtooth; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_periodic_sawtooth', + ['f', 'f'], + 'f', + [period, x], + dtype, + 0, + ) + + +def periodic_triangle(period, x, *, dtype='float64'): + """Call HMath.Trigonometry.periodicTriangle; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_periodic_triangle', + ['f', 'f'], + 'f', + [period, x], + dtype, + 0, + ) + + +def periodic_square(period, x, *, dtype='float64'): + """Call HMath.Trigonometry.periodicSquare; preserve its argument order, result and errors.""" + return _call( + 'hmath_trigonometry_periodic_square', + ['f', 'f'], + 'f', + [period, x], + dtype, + 0, + ) + + +from .trigonometry_extras import * diff --git a/bindings/python/_hmath_native/trigonometry_extras.py b/bindings/python/_hmath_native/trigonometry_extras.py new file mode 100644 index 0000000..2564c4c --- /dev/null +++ b/bindings/python/_hmath_native/trigonometry_extras.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_scalar_extras.py; do not edit. +from ._scalar_extras_base import ComplexFunction, _invoke + + +def c_sin(): + """HMath.Trigonometry.CSin :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_sin', [], [], 'ComplexFunction') + + +def c_cos(): + """HMath.Trigonometry.CCos :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_cos', [], [], 'ComplexFunction') + + +def c_tan(): + """HMath.Trigonometry.CTan :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_tan', [], [], 'ComplexFunction') + + +def c_asin(): + """HMath.Trigonometry.CAsin :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_asin', [], [], 'ComplexFunction') + + +def c_acos(): + """HMath.Trigonometry.CAcos :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_acos', [], [], 'ComplexFunction') + + +def c_atan(): + """HMath.Trigonometry.CAtan :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_atan', [], [], 'ComplexFunction') + + +def c_sinh(): + """HMath.Trigonometry.CSinh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_sinh', [], [], 'ComplexFunction') + + +def c_cosh(): + """HMath.Trigonometry.CCosh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_cosh', [], [], 'ComplexFunction') + + +def c_tanh(): + """HMath.Trigonometry.CTanh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_tanh', [], [], 'ComplexFunction') + + +def c_asinh(): + """HMath.Trigonometry.CAsinh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_asinh', [], [], 'ComplexFunction') + + +def c_acosh(): + """HMath.Trigonometry.CAcosh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_acosh', [], [], 'ComplexFunction') + + +def c_atanh(): + """HMath.Trigonometry.CAtanh :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_atanh', [], [], 'ComplexFunction') + + +def c_sec(): + """HMath.Trigonometry.CSec :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_sec', [], [], 'ComplexFunction') + + +def c_csc(): + """HMath.Trigonometry.CCsc :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_csc', [], [], 'ComplexFunction') + + +def c_cot(): + """HMath.Trigonometry.CCot :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_cot', [], [], 'ComplexFunction') + + +def c_sech(): + """HMath.Trigonometry.CSech :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_sech', [], [], 'ComplexFunction') + + +def c_csch(): + """HMath.Trigonometry.CCsch :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_csch', [], [], 'ComplexFunction') + + +def c_coth(): + """HMath.Trigonometry.CCoth :: ComplexFunction.""" + return _invoke('hmath_trigonometry_c_coth', [], [], 'ComplexFunction') + + +def complex_function(operation, value, *, dtype=None): + """HMath.Trigonometry.complexFunction :: RealFloat a => ComplexFunction -> Complex a -> Either MathError (Complex a).""" + return _invoke('hmath_trigonometry_complex_function', ['ComplexFunction', 'TypedComplex'], [operation, value], 'TypedComplex', dtype=dtype) + + +__all__ = [ + "ComplexFunction", + "c_acos", + "c_acosh", + "c_asin", + "c_asinh", + "c_atan", + "c_atanh", + "c_cos", + "c_cosh", + "c_cot", + "c_coth", + "c_csc", + "c_csch", + "c_sec", + "c_sech", + "c_sin", + "c_sinh", + "c_tan", + "c_tanh", + "complex_function" +] diff --git a/bindings/python/_hmath_native/units.py b/bindings/python/_hmath_native/units.py new file mode 100644 index 0000000..bb5e7e9 --- /dev/null +++ b/bindings/python/_hmath_native/units.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_numeric_bindings.py; do not edit. +from ._numeric import _call + + +def radians_to_degrees(x, *, dtype='float64'): + """Call HMath.Units.radiansToDegrees; preserve its argument order, result and errors.""" + return _call( + 'hmath_units_radians_to_degrees', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def degrees_to_radians(x, *, dtype='float64'): + """Call HMath.Units.degreesToRadians; preserve its argument order, result and errors.""" + return _call( + 'hmath_units_degrees_to_radians', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def radians_to_gradians(x, *, dtype='float64'): + """Call HMath.Units.radiansToGradians; preserve its argument order, result and errors.""" + return _call( + 'hmath_units_radians_to_gradians', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +def gradians_to_radians(x, *, dtype='float64'): + """Call HMath.Units.gradiansToRadians; preserve its argument order, result and errors.""" + return _call( + 'hmath_units_gradians_to_radians', + ['f'], + 'f', + [x], + dtype, + 0, + ) + + +from .units_values import * diff --git a/bindings/python/_hmath_native/units_values.py b/bindings/python/_hmath_native/units_values.py new file mode 100644 index 0000000..3ff033c --- /dev/null +++ b/bindings/python/_hmath_native/units_values.py @@ -0,0 +1,508 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_units_bindings.py. +"""Exact original HMath.Units operations and owned catalog values.""" + +from ._units_base import Dimension, Quantity, SIPrefix, Unit, _call + +__all__ = [ + "Dimension", + "Quantity", + "SIPrefix", + "Unit", + "add_quantity", + "angle_dimension", + "atmosphere", + "bar", + "bit", + "byte", + "celsius", + "centimetre", + "convert", + "cubic_metre", + "data_dimension", + "day", + "degree", + "dimension", + "dimension_exponents", + "dimensionless", + "divide_quantity", + "fahrenheit", + "foot", + "gigabyte", + "gradian", + "gram", + "hectare", + "hertz", + "hour", + "in_unit", + "inch", + "joule", + "kelvin", + "kibibyte", + "kilogram", + "kilometre", + "kilometres_per_hour", + "length_dimension", + "litre", + "mass_dimension", + "mebibyte", + "metre", + "metres_per_second", + "metres_per_second_squared", + "mile", + "miles_per_hour", + "millilitre", + "millimetre", + "minute", + "multiply_quantity", + "nautical_mile", + "newton", + "pascal", + "pound", + "prefix_exponent", + "prefix_name", + "prefix_symbol", + "prefixed", + "quantity", + "quantity_dimension", + "radian", + "second", + "si_prefix", + "si_prefixes", + "si_value", + "square_metre", + "subtract_quantity", + "temperature_difference", + "temperature_dimension", + "time_dimension", + "tonne", + "unit", + "unit_dimension", + "unit_name", + "unit_offset", + "unit_power", + "unit_product", + "unit_quotient", + "unit_scale", + "watt", + "yard", +] + + +def dimension(exponents): + "HMath.Units.dimension: Exponents in order length, mass, time, current, temperature, amount, luminous intensity, data, plane angle. Require exactly nine exponents." + return _call("hmath_units_value_dimension", ["[Integer]"], exponents) + + +def dimension_exponents(dimension): + "HMath.Units.dimensionExponents: Return nine exact integer exponents ordered as length, mass, time, current, temperature, amount, luminous intensity, data, plane angle." + return _call("hmath_units_value_dimension_exponents", ["Dimension"], dimension) + + +def dimensionless(): + "HMath.Units.dimensionless: Dimension witness with all nine exponents zero; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_dimensionless", []) + + +def length_dimension(): + "HMath.Units.lengthDimension: Dimension witness with length exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_length_dimension", []) + + +def mass_dimension(): + "HMath.Units.massDimension: Dimension witness with mass exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_mass_dimension", []) + + +def time_dimension(): + "HMath.Units.timeDimension: Dimension witness with time exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_time_dimension", []) + + +def temperature_dimension(): + "HMath.Units.temperatureDimension: Dimension witness with temperature exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_temperature_dimension", []) + + +def angle_dimension(): + "HMath.Units.angleDimension: Dimension witness with plane-angle tag exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_angle_dimension", []) + + +def data_dimension(): + "HMath.Units.dataDimension: Dimension witness with data tag exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities." + return _call("hmath_units_value_data_dimension", []) + + +def unit(name, dimension, scale, offset): + "HMath.Units.unit: SI = value * scale + offset. Only temperature units may have an offset." + return _call( + "hmath_units_value_unit", + ["String", "Dimension", "Rational", "Rational"], + name, + dimension, + scale, + offset, + ) + + +def unit_name(unit): + 'HMath.Units.unitName: Return the display name/symbol of a Unit, for example "m". No conversion is performed.' + return _call("hmath_units_value_unit_name", ["Unit"], unit) + + +def unit_dimension(unit): + "HMath.Units.unitDimension: Return the dimensional-exponent witness of a Unit. Compatible conversions require equal dimensions." + return _call("hmath_units_value_unit_dimension", ["Unit"], unit) + + +def unit_scale(unit): + "HMath.Units.unitScale: Return exact Rational scale in the conversion SI = value*scale + offset. All public Unit constructors require a positive scale." + return _call("hmath_units_value_unit_scale", ["Unit"], unit) + + +def unit_offset(unit): + "HMath.Units.unitOffset: Return exact Rational affine offset in SI = value*scale + offset. Only temperature units may have a nonzero offset." + return _call("hmath_units_value_unit_offset", ["Unit"], unit) + + +def unit_product(left, right): + "HMath.Units.unitProduct: Multiply two zero-offset units: add dimension exponents and multiply Rational scales. Any affine offset returns Left DomainError. This constructs a Unit, not a Quantity." + return _call("hmath_units_value_unit_product", ["Unit", "Unit"], left, right) + + +def unit_quotient(numerator, denominator): + "HMath.Units.unitQuotient: Divide two zero-offset units: subtract dimension exponents and divide their positive scales. Affine units fail with DomainError." + return _call( + "hmath_units_value_unit_quotient", ["Unit", "Unit"], numerator, denominator + ) + + +def unit_power(unit, exponent): + "HMath.Units.unitPower: Given zero-offset Unit then Integer exponent, multiply its exponents and raise its positive scale to that power. Negative powers are valid; affine units fail." + return _call("hmath_units_value_unit_power", ["Unit", "Integer"], unit, exponent) + + +def quantity(unit, value): + "HMath.Units.quantity: Given Unit then Rational value, construct an exact SI-valued Quantity using its scale and offset. A temperature unit constructs an absolute temperature; use temperatureDifference for differences." + return _call("hmath_units_value_quantity", ["Unit", "Rational"], unit, value) + + +def temperature_difference(unit, value): + "HMath.Units.temperatureDifference: Given Unit then Rational value, construct an exact SI-valued Quantity using its scale and offset. A temperature unit constructs an absolute temperature; use" + return _call( + "hmath_units_value_temperature_difference", ["Unit", "Rational"], unit, value + ) + + +def quantity_dimension(quantity): + "HMath.Units.quantityDimension: Return a Quantity's dimensional-exponent witness, without changing its SI value or absolute-temperature tag." + return _call("hmath_units_value_quantity_dimension", ["Quantity"], quantity) + + +def si_value(quantity): + "HMath.Units.siValue: Return exact Rational SI value of a Quantity. For absolute temperature this is an absolute kelvin value; preserve quantityDimension when interpreting the number." + return _call("hmath_units_value_si_value", ["Quantity"], quantity) + + +def in_unit(unit, quantity): + "HMath.Units.inUnit: Given destination Unit then Quantity, convert its SI value to that unit. Reject incompatible dimensions. Apply affine offsets only for absolute temperatures, not differences." + return _call("hmath_units_value_in_unit", ["Unit", "Quantity"], unit, quantity) + + +def convert(source, destination, value): + "HMath.Units.convert: Given source Unit, destination Unit, then Rational value, convert exactly through SI. Incompatible dimensions fail. Example: convert kilometre metre 2 == Right 2000." + return _call( + "hmath_units_value_convert", + ["Unit", "Unit", "Rational"], + source, + destination, + value, + ) + + +def add_quantity(left, right): + "HMath.Units.addQuantity: Original public HMath.Units constructor or field." + return _call( + "hmath_units_value_add_quantity", ["Quantity", "Quantity"], left, right + ) + + +def subtract_quantity(left, right): + "HMath.Units.subtractQuantity: Original public HMath.Units constructor or field." + return _call( + "hmath_units_value_subtract_quantity", ["Quantity", "Quantity"], left, right + ) + + +def multiply_quantity(left, right): + "HMath.Units.multiplyQuantity: Original public HMath.Units constructor or field." + return _call( + "hmath_units_value_multiply_quantity", ["Quantity", "Quantity"], left, right + ) + + +def divide_quantity(numerator, denominator): + "HMath.Units.divideQuantity: Original public HMath.Units constructor or field." + return _call( + "hmath_units_value_divide_quantity", + ["Quantity", "Quantity"], + numerator, + denominator, + ) + + +def si_prefix(name, symbol, exponent): + "HMath.Units.SIPrefix: Original public HMath.Units constructor or field." + return _call( + "hmath_units_value_si_prefix", + ["String", "String", "Int"], + name, + symbol, + exponent, + ) + + +def si_prefixes(): + "HMath.Units.siPrefixes: BIPM prefixes through the 2022 quetta/ronna and ronto/quecto additions. Source: https://www.bipm.org/en/measurement-units/si-prefixes" + return _call("hmath_units_value_si_prefixes", []) + + +def prefixed(prefix, unit): + "HMath.Units.prefixed: Given SIPrefix then zero-offset Unit, multiply its scale by 10^prefixExponent and prepend its symbol. Reject affine units or absolute exponent above 10000." + return _call("hmath_units_value_prefixed", ["SIPrefix", "Unit"], prefix, unit) + + +def metre(): + "HMath.Units.metre: The metre Unit: 1 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_metre", []) + + +def kilometre(): + "HMath.Units.kilometre: The kilometre Unit: 1000 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_kilometre", []) + + +def centimetre(): + "HMath.Units.centimetre: The centimetre Unit: 0.01 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_centimetre", []) + + +def millimetre(): + "HMath.Units.millimetre: The millimetre Unit: 0.001 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_millimetre", []) + + +def inch(): + "HMath.Units.inch: The inch Unit: 0.0254 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_inch", []) + + +def foot(): + "HMath.Units.foot: The foot Unit: 0.3048 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_foot", []) + + +def yard(): + "HMath.Units.yard: The yard Unit: 0.9144 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_yard", []) + + +def mile(): + "HMath.Units.mile: The mile Unit: 1609.344 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_mile", []) + + +def nautical_mile(): + "HMath.Units.nauticalMile: The nauticalMile Unit: 1852 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_nautical_mile", []) + + +def square_metre(): + "HMath.Units.squareMetre: The squareMetre Unit: 1 square metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_square_metre", []) + + +def hectare(): + "HMath.Units.hectare: The hectare Unit: 10000 square metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_hectare", []) + + +def cubic_metre(): + "HMath.Units.cubicMetre: The cubicMetre Unit: 1 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_cubic_metre", []) + + +def litre(): + "HMath.Units.litre: The litre Unit: 0.001 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_litre", []) + + +def millilitre(): + "HMath.Units.millilitre: The millilitre Unit: 0.000001 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_millilitre", []) + + +def kilogram(): + "HMath.Units.kilogram: The kilogram Unit: 1 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_kilogram", []) + + +def gram(): + "HMath.Units.gram: The gram Unit: 0.001 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_gram", []) + + +def tonne(): + "HMath.Units.tonne: The tonne Unit: 1000 kilograms. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_tonne", []) + + +def pound(): + "HMath.Units.pound: The pound Unit: 0.45359237 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_pound", []) + + +def second(): + "HMath.Units.second: The second Unit: 1 second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_second", []) + + +def minute(): + "HMath.Units.minute: The minute Unit: 60 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_minute", []) + + +def hour(): + "HMath.Units.hour: The hour Unit: 3600 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_hour", []) + + +def day(): + "HMath.Units.day: The day Unit: 86400 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_day", []) + + +def metres_per_second(): + "HMath.Units.metresPerSecond: The metresPerSecond Unit: 1 metre per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_metres_per_second", []) + + +def kilometres_per_hour(): + "HMath.Units.kilometresPerHour: The kilometresPerHour Unit: 1000/3600 metres per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_kilometres_per_hour", []) + + +def miles_per_hour(): + "HMath.Units.milesPerHour: The milesPerHour Unit: 1609.344/3600 metres per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_miles_per_hour", []) + + +def metres_per_second_squared(): + "HMath.Units.metresPerSecondSquared: The metresPerSecondSquared Unit: 1 metre per second squared. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_metres_per_second_squared", []) + + +def newton(): + "HMath.Units.newton: The newton Unit: 1 kg*m/s^2. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_newton", []) + + +def joule(): + "HMath.Units.joule: The joule Unit: 1 newton metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_joule", []) + + +def watt(): + "HMath.Units.watt: The watt Unit: 1 joule per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_watt", []) + + +def pascal(): + "HMath.Units.pascal: The pascal Unit: 1 newton per square metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_pascal", []) + + +def bar(): + "HMath.Units.bar: The bar Unit: 100000 pascals. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_bar", []) + + +def atmosphere(): + "HMath.Units.atmosphere: The atmosphere Unit: 101325 pascals. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_atmosphere", []) + + +def kelvin(): + "HMath.Units.kelvin: The kelvin Unit: absolute temperature with SI=value. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_kelvin", []) + + +def celsius(): + "HMath.Units.celsius: The celsius Unit: absolute temperature with SI=value+273.15 kelvin. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_celsius", []) + + +def fahrenheit(): + "HMath.Units.fahrenheit: The fahrenheit Unit: absolute temperature with SI=(value-32)*5/9+273.15 kelvin. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_fahrenheit", []) + + +def hertz(): + "HMath.Units.hertz: The hertz Unit: 1 inverse second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_hertz", []) + + +def bit(): + "HMath.Units.bit: The bit Unit: 1 data bit. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_bit", []) + + +def byte(): + "HMath.Units.byte: The byte Unit: 8 data bits. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_byte", []) + + +def kibibyte(): + "HMath.Units.kibibyte: The kibibyte Unit: 8192 data bits (1024 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_kibibyte", []) + + +def mebibyte(): + "HMath.Units.mebibyte: The mebibyte Unit: 8388608 data bits (1024^2 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_mebibyte", []) + + +def gigabyte(): + "HMath.Units.gigabyte: The gigabyte Unit: 8000000000 data bits (10^9 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_gigabyte", []) + + +def radian(): + "HMath.Units.radian: The radian Unit: 1 radian. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_radian", []) + + +def degree(): + "HMath.Units.degree: The degree Unit: pi/180 radian, using the stored 50-place Rational pi approximation. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_degree", []) + + +def gradian(): + "HMath.Units.gradian: The gradian Unit: pi/200 radian, using the stored Rational pi approximation. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference." + return _call("hmath_units_value_gradian", []) + + +def prefix_name(prefix): + "HMath.Units.prefixName: Original public HMath.Units constructor or field." + return _call("hmath_units_value_prefix_name", ["SIPrefix"], prefix) + + +def prefix_symbol(prefix): + "HMath.Units.prefixSymbol: Original public HMath.Units constructor or field." + return _call("hmath_units_value_prefix_symbol", ["SIPrefix"], prefix) + + +def prefix_exponent(prefix): + "HMath.Units.prefixExponent: Original public HMath.Units constructor or field." + return _call("hmath_units_value_prefix_exponent", ["SIPrefix"], prefix) diff --git a/bindings/python/_hmath_native/vector.py b/bindings/python/_hmath_native/vector.py new file mode 100644 index 0000000..59e4998 --- /dev/null +++ b/bindings/python/_hmath_native/vector.py @@ -0,0 +1,394 @@ +# SPDX-License-Identifier: MPL-2.0 +# Generated by tools/generate_linear_bindings.py. +"""Original HMath.Vector public operations and owned records.""" + +from ._linear_base import LinearValue, _invoke, register + + +class Vector(LinearValue): + """Original HMath.Vector.Vector immutable owner.""" + + _source_type = "HMath.Vector.Vector" + + def __init__(self, values, *, dtype=None): + self._initialize( + "hmath_linear_vector_vector", True, [["list", ["a"]]], [values], dtype + ) + + +register("HMath.Vector.Vector", Vector) + + +class FixedVector(LinearValue): + """Original HMath.Vector.FixedVector immutable owner.""" + + _source_type = "HMath.Vector.FixedVector" + + def __init__(self, dimension, values, *, dtype=None): + self._initialize( + "hmath_linear_vector_fixed_vector", + True, + [["Int"], ["list", ["a"]]], + [dimension, values], + dtype, + ) + + +register("HMath.Vector.FixedVector", FixedVector) + + +class SparseVector(LinearValue): + """Original HMath.Vector.SparseVector immutable owner.""" + + _source_type = "HMath.Vector.SparseVector" + + def __init__(self, dimension, entries, *, dtype=None): + self._initialize( + "hmath_linear_vector_sparse_vector", + True, + [["Int"], ["list", ["tuple", ["Int"], ["a"]]]], + [dimension, entries], + dtype, + ) + + +register("HMath.Vector.SparseVector", SparseVector) + + +def vector(values1, *, dtype=None): + "Wrap a list as an immutable dynamic vector without numeric validation. The list order is preserved. Example: vectorValues (vector [1,2]) == [1,2]. Call original HMath.Vector.vector :: [a] -> Vector a" + return _invoke( + "hmath_linear_vector_vector", True, [["list", ["a"]]], [values1], dtype=dtype + ) + + +def vector_values(vector1, *, dtype=None): + "Extract the immutable list of vector values in order; no shape conversion or numeric validation occurs. Call original HMath.Vector.vectorValues :: Vector a -> [a]" + return _invoke( + "hmath_linear_vector_vector_values", + True, + [["Vector", ["a"]]], + [vector1], + dtype=dtype, + ) + + +def vector_dimension(vector1, *, dtype=None): + "Return the number of coordinates in a dynamic vector. Empty vectors have dimension zero. Call original HMath.Vector.vectorDimension :: Vector a -> Int" + return _invoke( + "hmath_linear_vector_vector_dimension", + True, + [["Vector", ["a"]]], + [vector1], + dtype=dtype, + ) + + +def fixed_vector(index1, values2, *, dtype=None): + "Construct a vector whose list length equals the type-level KnownNat size. A mismatch returns Left InvalidArgument. For example, fixedVector `3 requires exactly three values. Call original HMath.Vector.fixedVector :: [a] -> Either MathError (FixedVector n a)" + return _invoke( + "hmath_linear_vector_fixed_vector", + True, + [["Int"], ["list", ["a"]]], + [index1, values2], + dtype=dtype, + ) + + +def fixed_values(fixed_vector1, *, dtype=None): + "Extract the ordered coordinates of a type-indexed vector; its length is the type-level size. Call original HMath.Vector.fixedValues :: FixedVector n a -> [a]" + return _invoke( + "hmath_linear_vector_fixed_values", + True, + [["FixedVector", ["n"], ["a"]]], + [fixed_vector1], + dtype=dtype, + ) + + +def sparse_vector(index1, values2, *, dtype=None): + "Given nonnegative dimension and (zero-based index,value) entries, sum duplicate indices and remove explicit zeros. Reject out-of-range indices or negative dimension. Call original HMath.Vector.sparseVector :: Int -> [(Int, a)] -> Either MathError (SparseVector a)" + return _invoke( + "hmath_linear_vector_sparse_vector", + True, + [["Int"], ["list", ["tuple", ["Int"], ["a"]]]], + [index1, values2], + dtype=dtype, + ) + + +def sparse_vector_values(sparse_vector1, *, dtype=None): + "Expand a sparse vector to a dense list of its declared dimension, filling absent entries with zero. Call original HMath.Vector.sparseVectorValues :: SparseVector a -> [a]" + return _invoke( + "hmath_linear_vector_sparse_vector_values", + True, + [["SparseVector", ["a"]]], + [sparse_vector1], + dtype=dtype, + ) + + +def vector_slice(index1, index2, vector3, *, dtype=None): + "Given start, count, then vector, return the half-open slice [start,start+count). Reject negative or out-of-range bounds; an empty end slice is valid. Call original HMath.Vector.vectorSlice :: Int -> Int -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_vector_slice", + True, + [["Int"], ["Int"], ["Vector", ["a"]]], + [index1, index2, vector3], + dtype=dtype, + ) + + +def vector_concat(values1, *, dtype=None): + "Concatenate a list of vectors in order. Return Left InvalidArgument if the combined dimension would overflow Int; an empty list gives an empty vector. Call original HMath.Vector.vectorConcat :: [Vector a] -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_vector_concat", + True, + [["list", ["Vector", ["a"]]]], + [values1], + dtype=dtype, + ) + + +def vector_add(vector1, vector2, *, dtype=None): + "Add corresponding values of equally sized vectors, returning a new vector. Unequal dimensions return VectorLengthMismatch. Generic Num arithmetic is unchecked. Call original HMath.Vector.vectorAdd :: Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_vector_add", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def vector_subtract(vector1, vector2, *, dtype=None): + "Subtract corresponding right-hand coordinates from left-hand coordinates. Unequal dimensions return VectorLengthMismatch; Num arithmetic is unchecked. Call original HMath.Vector.vectorSubtract :: Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_vector_subtract", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def vector_scale(scalar1, vector2, *, dtype=None): + "Given scalar then vector, multiply every coordinate by the scalar. Return a new vector, retaining the original dimension and Num arithmetic behavior. Call original HMath.Vector.vectorScale :: a -> Vector a -> Vector a" + return _invoke( + "hmath_linear_vector_vector_scale", + True, + [["a"], ["Vector", ["a"]]], + [scalar1, vector2], + dtype=dtype, + ) + + +def vector_dot(vector1, vector2, *, dtype=None): + "Sum coordinatewise products of equally sized vectors. Empty vectors give zero; unequal dimensions return VectorLengthMismatch. No floating-point finiteness check is added. Call original HMath.Vector.vectorDot :: Vector a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_vector_dot", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def cross(vector1, vector2, *, dtype=None): + "Compute the right-handed cross product of two three-dimensional vectors. Any other dimension returns Left InvalidArgument. Call original HMath.Vector.cross :: Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_cross", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def outer(vector1, vector2, *, dtype=None): + "Return the matrix of pairwise products a[i]*b[j], with shape (dimension a,dimension b). Matrix construction can return shape/count errors. Call original HMath.Vector.outer :: Vector a -> Vector a -> Either MathError (Matrix a)" + return _invoke( + "hmath_linear_vector_outer", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def triple(vector1, vector2, vector3, *, dtype=None): + "Given a,b,c, compute scalar triple product a dot (b cross c). All three vectors must have dimension three; dimension errors propagate. Call original HMath.Vector.triple :: Vector a -> Vector a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_triple", + True, + [["Vector", ["a"]], ["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2, vector3], + dtype=dtype, + ) + + +def norm0(vector1, *, dtype=None): + "Count nonzero coordinates, returning Int. This is the usual sparsity count rather than a norm satisfying homogeneity. Call original HMath.Vector.norm0 :: Vector a -> Int" + return _invoke( + "hmath_linear_vector_norm0", True, [["Vector", ["a"]]], [vector1], dtype=dtype + ) + + +def norm1(vector1, *, dtype=None): + "Sum absolute coordinate values. Empty vector returns zero; arithmetic follows the chosen Num type. Call original HMath.Vector.norm1 :: Vector a -> a" + return _invoke( + "hmath_linear_vector_norm1", True, [["Vector", ["a"]]], [vector1], dtype=dtype + ) + + +def norm2(vector1, *, dtype=None): + "Compute Euclidean length using a scaled stable norm to reduce intermediate overflow/underflow. Empty vector returns zero; the result itself is not wrapped in Either. Call original HMath.Vector.norm2 :: Vector a -> a" + return _invoke( + "hmath_linear_vector_norm2", True, [["Vector", ["a"]]], [vector1], dtype=dtype + ) + + +def norm_infinity(vector1, *, dtype=None): + "Return maximum absolute coordinate, or zero for an empty vector. NaN coordinates propagate rather than being silently discarded. Call original HMath.Vector.normInfinity :: Vector a -> a" + return _invoke( + "hmath_linear_vector_norm_infinity", + True, + [["Vector", ["a"]]], + [vector1], + dtype=dtype, + ) + + +def norm_p(scalar1, vector2, *, dtype=None): + "Given positive exponent p then finite vector, compute the scaled p-norm. Positive infinity selects normInfinity. NaN/nonpositive p or non-finite coordinates fail; p\\<1 is accepted as a quasi-norm. Call original HMath.Vector.normP :: a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_norm_p", + True, + [["a"], ["Vector", ["a"]]], + [scalar1, vector2], + dtype=dtype, + ) + + +def normalize_vector(vector1, *, dtype=None): + "Return a unit-length vector in the same direction. Reject non-finite coordinates, zero norm, or non-finite resulting norm. Empty input is a zero vector and fails. Call original HMath.Vector.normalizeVector :: Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_normalize_vector", + True, + [["Vector", ["a"]]], + [vector1], + dtype=dtype, + ) + + +def project(vector1, vector2, *, dtype=None): + "Given a then b, return the projection of a onto b. Dimensions must agree and b must have nonzero finite norm; non-finite input/result fails. Call original HMath.Vector.project :: Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_project", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def reflect(vector1, vector2, *, dtype=None): + "Given incident vector then surface normal, return incident minus twice its projection onto the normal. The normal is normalized internally; invalid dimensions, zero normal, or non-finite values fail. Call original HMath.Vector.reflect :: Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_reflect", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def refract(scalar1, vector2, vector3, *, dtype=None): + "Given positive finite refractive-index ratio, incident vector, then normal, return the refracted unit-direction expression. Normalize both inputs; reject invalid dimensions, zero vectors, non-finite values, or total internal reflection. Call original HMath.Vector.refract :: a -> Vector a -> Vector a -> Either MathError (Vector a)" + return _invoke( + "hmath_linear_vector_refract", + True, + [["a"], ["Vector", ["a"]], ["Vector", ["a"]]], + [scalar1, vector2, vector3], + dtype=dtype, + ) + + +def distance(vector1, vector2, *, dtype=None): + "Return Euclidean distance between equal-sized finite vectors. Dimension mismatch and non-finite input/intermediate/result return Left MathError. Call original HMath.Vector.distance :: Vector a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_distance", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def cosine_similarity(vector1, vector2, *, dtype=None): + "Return normalized dot product clamped to [-1,1]. Equal dimensions and nonzero finite vectors are required; validation errors propagate. Call original HMath.Vector.cosineSimilarity :: Vector a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_cosine_similarity", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def angle(vector1, vector2, *, dtype=None): + "Return the angle in radians, acos of cosineSimilarity, between two nonzero finite equally sized vectors. Invalid dimensions or zero/non-finite vectors fail. Call original HMath.Vector.angle :: Vector a -> Vector a -> Either MathError a" + return _invoke( + "hmath_linear_vector_angle", + True, + [["Vector", ["a"]], ["Vector", ["a"]]], + [vector1, vector2], + dtype=dtype, + ) + + +def gram_schmidt(scalar1, values2, *, dtype=None): + "Given finite nonnegative relative tolerance then vectors, perform two-pass modified Gram-Schmidt, returning an orthonormal basis in input order. Reject unequal dimensions, zero/dependent vectors (RankDeficient), invalid tolerance, or non-finite data. Call original HMath.Vector.gramSchmidt :: a -> [Vector a] -> Either MathError [Vector a]" + return _invoke( + "hmath_linear_vector_gram_schmidt", + True, + [["a"], ["list", ["Vector", ["a"]]]], + [scalar1, values2], + dtype=dtype, + ) + + +__all__ = [ + "FixedVector", + "SparseVector", + "Vector", + "angle", + "cosine_similarity", + "cross", + "distance", + "fixed_values", + "fixed_vector", + "gram_schmidt", + "norm0", + "norm1", + "norm2", + "norm_infinity", + "norm_p", + "normalize_vector", + "outer", + "project", + "reflect", + "refract", + "sparse_vector", + "sparse_vector_values", + "triple", + "vector", + "vector_add", + "vector_concat", + "vector_dimension", + "vector_dot", + "vector_scale", + "vector_slice", + "vector_subtract", + "vector_values", +] diff --git a/bindings/python/hmath.py b/bindings/python/hmath.py index 64fea39..015bac1 100644 --- a/bindings/python/hmath.py +++ b/bindings/python/hmath.py @@ -1,5 +1,7 @@ # SPDX-License-Identifier: MPL-2.0 -"""Binary64 HMath ABI 1, with its native library included in binary wheels. +"""HMath ABI 1, with its native library included in binary wheels. + +Tensor uses binary64. Numeric namespaces also provide binary32 scalar APIs. Tensor owns one native reference. close()/with provide deterministic cleanup; __del__ is a fallback. Arrays are copied by default. from_numpy(copy=False) @@ -14,7 +16,152 @@ import weakref from itertools import islice -from _hmath_native import library_path +from _hmath_native import ( + buffer_values as buffer, + algebra, + algebra_api, + convergence_values as convergence, + shape_values as shape, + deeplearning_layers, + machinelearning, + interchange, + algorithms, + vector, + matrix_advanced, + decomposition, + iterative, + lapack, + sparse, + sparse_spectral, + backend, + calculus, + root, + ode, + pde, + api_algebra, + autodiff, + basic, + combinatorics, + complex, + constants, + datastructure, + deeplearning_core, + deeplearning_metrics, + deeplearning_precision, + discrete, + errors, + execution, + expression, + fourier, + geometry, + geometry_primitives, + graph_core, + graph, + image, + image_color, + interpolation, + library_path, + linear, + matrix, + numbertheory, + numeric, + numeric_types, + optimization, + optimization_common, + polynomial, + probability, + quaternion, + random, + rotation, + scalar, + signal, + special, + statistics, + statistics_advanced, + symbolic, + tensor, + timeseries, + timeseries_core, + timeseries_diagnostics, + trigonometry, + units, +) + +__all__ = [ + "buffer", + "algebra", + "algebra_api", + "convergence", + "shape", + "deeplearning_layers", + "machinelearning", + "interchange", + "HMathError", + "Tensor", + "add", + "algorithms", + "vector", + "matrix_advanced", + "decomposition", + "iterative", + "lapack", + "sparse", + "sparse_spectral", + "backend", + "calculus", + "root", + "ode", + "pde", + "api_algebra", + "autodiff", + "basic", + "combinatorics", + "complex", + "constants", + "datastructure", + "deeplearning_core", + "deeplearning_metrics", + "deeplearning_precision", + "discrete", + "errors", + "execution", + "expression", + "fourier", + "geometry", + "geometry_primitives", + "graph_core", + "graph", + "image", + "image_color", + "initialize", + "interpolation", + "linear", + "matrix", + "numbertheory", + "numeric", + "numeric_types", + "optimization", + "optimization_common", + "polynomial", + "probability", + "quaternion", + "random", + "rotation", + "scalar", + "shutdown", + "signal", + "special", + "statistics", + "statistics_advanced", + "symbolic", + "tensor", + "timeseries", + "timeseries_core", + "timeseries_diagnostics", + "trigonometry", + "units", +] + _lib = C.CDLL(library_path()) P, Z, D = C.c_void_p, C.c_size_t, C.c_double @@ -68,6 +215,21 @@ def _sig(name, result, *args): class HMathError(RuntimeError): def __init__(self, status): self.status = status + self.math_error = None + self.expression_error = None + self.interchange_error = None + if status == 11: + from _hmath_native._math_error import last_math_error + + self.math_error = last_math_error(_lib) + elif status == 12: + from _hmath_native._expression_error import last_expression_error + + self.expression_error = last_expression_error(_lib) + elif status == 13: + from _hmath_native._interchange_error import last_interchange_error + + self.interchange_error = last_interchange_error(_lib) super().__init__(_lib.hmath_last_error_message().decode("utf-8", "replace")) diff --git a/bindings/schema/algebra-functions.json b/bindings/schema/algebra-functions.json new file mode 100644 index 0000000..b528111 --- /dev/null +++ b/bindings/schema/algebra-functions.json @@ -0,0 +1,1496 @@ +{ + "functions": [ + { + "module": "HMath.Algebra", + "name": "linearCombination", + "args": [ + [ + "v" + ], + [ + "list", + [ + "tuple", + [ + "s" + ], + [ + "v" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "v" + ] + ], + "constraints": "(Module s v)", + "signature": "v -> [(s, v)] -> Either MathError v", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "semiringLaws", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ], + "constraints": "(Eq a, Semiring a)", + "signature": "[a] -> [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "ringLaws", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ], + "constraints": "(Eq a, Ring a)", + "signature": "[a] -> [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldLaws", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ], + "constraints": "(Eq a, Field a)", + "signature": "[a] -> [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "groupLaws", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ], + "constraints": "(Eq a, Group a)", + "signature": "[a] -> [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "moduleLaws", + "args": [ + [ + "list", + [ + "s" + ] + ], + [ + "list", + [ + "v" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ], + "constraints": "(Eq v, Module s v)", + "signature": "[s] -> [v] -> [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "modular", + "args": [ + [ + "Integer" + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Integer -> Integer -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "modularValue", + "args": [ + [ + "Modular" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "Modular -> Integer", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "modularModulus", + "args": [ + [ + "Modular" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "Modular -> Integer", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "addModular", + "args": [ + [ + "Modular" + ], + [ + "Modular" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Modular -> Modular -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "subtractModular", + "args": [ + [ + "Modular" + ], + [ + "Modular" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Modular -> Modular -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "multiplyModular", + "args": [ + [ + "Modular" + ], + [ + "Modular" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Modular -> Modular -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "inverseModular", + "args": [ + [ + "Modular" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Modular -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "powerModular", + "args": [ + [ + "Modular" + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Modular" + ] + ], + "constraints": "", + "signature": "Modular -> Integer -> Either MathError Modular", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "finiteField", + "args": [ + [ + "Int" + ], + [ + "Integer" + ], + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FiniteField" + ] + ], + "constraints": "", + "signature": "Int -> Integer -> [Integer] -> Either MathError FiniteField", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "primeField", + "args": [ + [ + "Int" + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FiniteField" + ] + ], + "constraints": "", + "signature": "Int -> Integer -> Either MathError FiniteField", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldCharacteristic", + "args": [ + [ + "FiniteField" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "FiniteField -> Integer", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldDegree", + "args": [ + [ + "FiniteField" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "FiniteField -> Int", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldCardinality", + "args": [ + [ + "FiniteField" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "FiniteField -> Integer", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldModulus", + "args": [ + [ + "FiniteField" + ] + ], + "result": [ + "list", + [ + "Integer" + ] + ], + "constraints": "", + "signature": "FiniteField -> [Integer]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldElement", + "args": [ + [ + "FiniteField" + ], + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "FieldElement" + ], + "constraints": "", + "signature": "FiniteField -> [Integer] -> FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldElementCoefficients", + "args": [ + [ + "FieldElement" + ] + ], + "result": [ + "list", + [ + "Integer" + ] + ], + "constraints": "", + "signature": "FieldElement -> [Integer]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "fieldElements", + "args": [ + [ + "Int" + ], + [ + "FiniteField" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "FieldElement" + ] + ] + ], + "constraints": "", + "signature": "Int -> FiniteField -> Either MathError [FieldElement]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "addField", + "args": [ + [ + "FieldElement" + ], + [ + "FieldElement" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FieldElement" + ] + ], + "constraints": "", + "signature": "FieldElement -> FieldElement -> Either MathError FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "negateField", + "args": [ + [ + "FieldElement" + ] + ], + "result": [ + "FieldElement" + ], + "constraints": "", + "signature": "FieldElement -> FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "subtractField", + "args": [ + [ + "FieldElement" + ], + [ + "FieldElement" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FieldElement" + ] + ], + "constraints": "", + "signature": "FieldElement -> FieldElement -> Either MathError FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "multiplyField", + "args": [ + [ + "FieldElement" + ], + [ + "FieldElement" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FieldElement" + ] + ], + "constraints": "", + "signature": "FieldElement -> FieldElement -> Either MathError FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "inverseFieldElement", + "args": [ + [ + "FieldElement" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FieldElement" + ] + ], + "constraints": "", + "signature": "FieldElement -> Either MathError FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "powerField", + "args": [ + [ + "FieldElement" + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FieldElement" + ] + ], + "constraints": "", + "signature": "FieldElement -> Integer -> Either MathError FieldElement", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "finiteFieldLaws", + "args": [ + [ + "Int" + ], + [ + "FiniteField" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "tuple", + [ + "String" + ], + [ + "Bool" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> FiniteField -> Either MathError [(String, Bool)]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "getAdditive", + "args": [ + [ + "Additive", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "Additive -> field", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "Additive", + "args": [ + [ + "a" + ] + ], + "result": [ + "Additive", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Algebra", + "name": "horner", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "(Ring a)", + "signature": "[a] -> a -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "innerProduct", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(Scalar a)", + "signature": "[a] -> [a] -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "getExact", + "args": [ + [ + "Exact" + ] + ], + "result": [ + "Rational" + ], + "constraints": "", + "signature": "Exact -> field", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "Exact", + "args": [ + [ + "Rational" + ] + ], + "result": [ + "Exact" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Algebra", + "name": "zero", + "args": [], + "result": [ + "a" + ], + "constraints": "Semiring (original instances only)", + "signature": "a", + "wire_signature": "a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "one", + "args": [], + "result": [ + "a" + ], + "constraints": "Semiring (original instances only)", + "signature": "a", + "wire_signature": "a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "plus", + "args": [ + [ + "a" + ], + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Semiring (original instances only)", + "signature": "a -> a -> a", + "wire_signature": "a -> a -> a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "times", + "args": [ + [ + "a" + ], + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Semiring (original instances only)", + "signature": "a -> a -> a", + "wire_signature": "a -> a -> a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "negateRing", + "args": [ + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a -> a", + "wire_signature": "a -> a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "inverseField", + "args": [ + [ + "a" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "Field (original instances only)", + "signature": "a -> Either MathError a", + "wire_signature": "a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "groupIdentity", + "args": [], + "result": [ + "Additive", + [ + "a" + ] + ], + "constraints": "Group (original instances only)", + "signature": "a", + "wire_signature": "Additive a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "groupCombine", + "args": [ + [ + "Additive", + [ + "a" + ] + ], + [ + "Additive", + [ + "a" + ] + ] + ], + "result": [ + "Additive", + [ + "a" + ] + ], + "constraints": "Group (original instances only)", + "signature": "a -> a -> a", + "wire_signature": "Additive a -> Additive a -> Additive a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "groupInverse", + "args": [ + [ + "Additive", + [ + "a" + ] + ] + ], + "result": [ + "Additive", + [ + "a" + ] + ], + "constraints": "Group (original instances only)", + "signature": "a -> a", + "wire_signature": "Additive a -> Additive a", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "moduleScale", + "args": [ + [ + "a" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "Module (original instances only)", + "signature": "scalar -> vector -> vector", + "wire_signature": "a -> [a] -> [a]", + "constructor": false + }, + { + "module": "HMath.Algebra", + "name": "moduleAdd", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "Module (original instances only)", + "signature": "vector -> vector -> Either MathError vector", + "wire_signature": "[a] -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "zero", + "args": [], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a", + "wire_signature": "a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "one", + "args": [], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a", + "wire_signature": "a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "plus", + "args": [ + [ + "a" + ], + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a -> a -> a", + "wire_signature": "a -> a -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "times", + "args": [ + [ + "a" + ], + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a -> a -> a", + "wire_signature": "a -> a -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "negative", + "args": [ + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "a -> a", + "wire_signature": "a -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "integer", + "args": [ + [ + "Integer" + ] + ], + "result": [ + "a" + ], + "constraints": "Ring (original instances only)", + "signature": "Integer -> a", + "wire_signature": "Integer -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "invert", + "args": [ + [ + "a" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "Field (original instances only)", + "signature": "a -> Either MathError a", + "wire_signature": "a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "conjugateScalar", + "args": [ + [ + "a" + ] + ], + "result": [ + "a" + ], + "constraints": "Scalar (original instances only)", + "signature": "a -> a", + "wire_signature": "a -> a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "machineEpsilon", + "args": [], + "result": [ + "Double" + ], + "constraints": "FloatingPoint (original instances only)", + "signature": "proxy a -> Double", + "wire_signature": "Double", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "finiteScalar", + "args": [ + [ + "a" + ] + ], + "result": [ + "Bool" + ], + "constraints": "FloatingPoint (original instances only)", + "signature": "a -> Bool", + "wire_signature": "a -> Bool", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "rational", + "args": [ + [ + "Rational" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "Numeric (original instances only)", + "signature": "Rational -> Either MathError a", + "wire_signature": "Rational -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "matrixDimensions", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "tuple", + [ + "Int" + ], + [ + "Int" + ] + ], + "constraints": "MatrixLike (original instances only)", + "signature": "m a -> (Int, Int)", + "wire_signature": "Matrix a -> (Int,Int)", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "matrixElements", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "MatrixLike (original instances only)", + "signature": "m a -> [a]", + "wire_signature": "Matrix a -> [a]", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "matrixConstruct", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "MatrixLike (original instances only)", + "signature": "Int -> Int -> [a] -> Either MathError (m a)", + "wire_signature": "Int -> Int -> [a] -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "tensorDimensions", + "args": [ + [ + "Tensor", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "Int" + ] + ], + "constraints": "TensorLike (original instances only)", + "signature": "t a -> [Int]", + "wire_signature": "Tensor a -> [Int]", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "tensorElements", + "args": [ + [ + "Tensor", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "TensorLike (original instances only)", + "signature": "t a -> [a]", + "wire_signature": "Tensor a -> [a]", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "tensorConstruct", + "args": [ + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Tensor", + [ + "a" + ] + ] + ], + "constraints": "TensorLike (original instances only)", + "signature": "[Int] -> [a] -> Either MathError (t a)", + "wire_signature": "[Int] -> [a] -> Either MathError (Tensor a)", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "vectorPlus", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "VectorSpace (original instances only)", + "signature": "(Num a) => v a -> v a -> Either MathError (v a)", + "wire_signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "vectorScale", + "args": [ + [ + "a" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Vector", + [ + "a" + ] + ], + "constraints": "VectorSpace (original instances only)", + "signature": "(Num a) => a -> v a -> v a", + "wire_signature": "a -> Vector a -> Vector a", + "constructor": false + }, + { + "module": "HMath.API.Algebra", + "name": "differential", + "args": [ + [ + "Dual", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "Differentiable (original instances only)", + "signature": "a -> Differential a", + "wire_signature": "Dual a -> a", + "constructor": false + } + ], + "types": { + "Additive": { + "module": "HMath.Algebra", + "alias": "A", + "namespace": "algebra", + "name": "Additive", + "params": [ + "a" + ] + }, + "Modular": { + "module": "HMath.Algebra", + "alias": "A", + "namespace": "algebra", + "name": "Modular", + "params": [] + }, + "FiniteField": { + "module": "HMath.Algebra", + "alias": "A", + "namespace": "algebra", + "name": "FiniteField", + "params": [] + }, + "FieldElement": { + "module": "HMath.Algebra", + "alias": "A", + "namespace": "algebra", + "name": "FieldElement", + "params": [] + }, + "Exact": { + "module": "HMath.API.Algebra", + "alias": "P", + "namespace": "algebra_api", + "name": "Exact", + "params": [] + } + } +} diff --git a/bindings/schema/algebra-objects.json b/bindings/schema/algebra-objects.json new file mode 100644 index 0000000..ed8b5b7 --- /dev/null +++ b/bindings/schema/algebra-objects.json @@ -0,0 +1,877 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.API.Algebra.Differentiable", + "c": [ + "hmath_algebra_api_differential" + ], + "python": "hmath.algebra_api.Differentiable", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Differential", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.algebra_api.Differential", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Exact", + "c": [ + "hmath_algebra_api_new_exact" + ], + "python": "hmath.algebra_api.Exact", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Field", + "c": [ + "hmath_algebra_api_invert" + ], + "python": "hmath.algebra_api.Field", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.FloatingPoint", + "c": [ + "hmath_algebra_api_machine_epsilon", + "hmath_algebra_api_finite_scalar" + ], + "python": "hmath.algebra_api.FloatingPoint", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.MatrixLike", + "c": [ + "hmath_algebra_api_matrix_dimensions", + "hmath_algebra_api_matrix_elements", + "hmath_algebra_api_matrix_construct" + ], + "python": "hmath.algebra_api.MatrixLike", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Numeric", + "c": [ + "hmath_algebra_api_rational" + ], + "python": "hmath.algebra_api.Numeric", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Ring", + "c": [ + "hmath_algebra_api_zero", + "hmath_algebra_api_one", + "hmath_algebra_api_plus", + "hmath_algebra_api_times", + "hmath_algebra_api_negative", + "hmath_algebra_api_integer" + ], + "python": "hmath.algebra_api.Ring", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.Scalar", + "c": [ + "hmath_algebra_api_conjugate_scalar" + ], + "python": "hmath.algebra_api.Scalar", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.TensorLike", + "c": [ + "hmath_algebra_api_tensor_dimensions", + "hmath_algebra_api_tensor_elements", + "hmath_algebra_api_tensor_construct" + ], + "python": "hmath.algebra_api.TensorLike", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.VectorSpace", + "c": [ + "hmath_algebra_api_vector_plus", + "hmath_algebra_api_vector_scale" + ], + "python": "hmath.algebra_api.VectorSpace", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.API.Algebra.conjugateScalar", + "c": [ + "hmath_algebra_api_conjugate_scalar" + ], + "python": "hmath.algebra_api.conjugate_scalar", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.differential", + "c": [ + "hmath_algebra_api_differential" + ], + "python": "hmath.algebra_api.differential", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.finiteScalar", + "c": [ + "hmath_algebra_api_finite_scalar" + ], + "python": "hmath.algebra_api.finite_scalar", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.getExact", + "c": [ + "hmath_algebra_api_get_exact" + ], + "python": "hmath.algebra_api.get_exact", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.horner", + "c": [ + "hmath_algebra_api_horner" + ], + "python": "hmath.algebra_api.horner", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.integer", + "c": [ + "hmath_algebra_api_integer" + ], + "python": "hmath.algebra_api.integer", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.invert", + "c": [ + "hmath_algebra_api_invert" + ], + "python": "hmath.algebra_api.invert", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.machineEpsilon", + "c": [ + "hmath_algebra_api_machine_epsilon" + ], + "python": "hmath.algebra_api.machine_epsilon", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixConstruct", + "c": [ + "hmath_algebra_api_matrix_construct" + ], + "python": "hmath.algebra_api.matrix_construct", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixDimensions", + "c": [ + "hmath_algebra_api_matrix_dimensions" + ], + "python": "hmath.algebra_api.matrix_dimensions", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixElements", + "c": [ + "hmath_algebra_api_matrix_elements" + ], + "python": "hmath.algebra_api.matrix_elements", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.negative", + "c": [ + "hmath_algebra_api_negative" + ], + "python": "hmath.algebra_api.negative", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.one", + "c": [ + "hmath_algebra_api_one" + ], + "python": "hmath.algebra_api.one", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.plus", + "c": [ + "hmath_algebra_api_plus" + ], + "python": "hmath.algebra_api.plus", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.rational", + "c": [ + "hmath_algebra_api_rational" + ], + "python": "hmath.algebra_api.rational", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorConstruct", + "c": [ + "hmath_algebra_api_tensor_construct" + ], + "python": "hmath.algebra_api.tensor_construct", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorDimensions", + "c": [ + "hmath_algebra_api_tensor_dimensions" + ], + "python": "hmath.algebra_api.tensor_dimensions", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorElements", + "c": [ + "hmath_algebra_api_tensor_elements" + ], + "python": "hmath.algebra_api.tensor_elements", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.times", + "c": [ + "hmath_algebra_api_times" + ], + "python": "hmath.algebra_api.times", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.vectorPlus", + "c": [ + "hmath_algebra_api_vector_plus" + ], + "python": "hmath.algebra_api.vector_plus", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.vectorScale", + "c": [ + "hmath_algebra_api_vector_scale" + ], + "python": "hmath.algebra_api.vector_scale", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.API.Algebra.zero", + "c": [ + "hmath_algebra_api_zero" + ], + "python": "hmath.algebra_api.zero", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.Additive", + "c": [ + "hmath_algebra_core_new_additive" + ], + "python": "hmath.algebra.Additive", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.Field", + "c": [ + "hmath_algebra_core_inverse_field" + ], + "python": "hmath.algebra.Field", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.FieldElement", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.algebra.FieldElement", + "specializations": [ + "original opaque owned type" + ] + }, + { + "symbol": "HMath.Algebra.FiniteField", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.algebra.FiniteField", + "specializations": [ + "original opaque owned type" + ] + }, + { + "symbol": "HMath.Algebra.Group", + "c": [ + "hmath_algebra_core_group_identity", + "hmath_algebra_core_group_combine", + "hmath_algebra_core_group_inverse" + ], + "python": "hmath.algebra.Group", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.Modular", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.algebra.Modular", + "specializations": [ + "original opaque owned type" + ] + }, + { + "symbol": "HMath.Algebra.Module", + "c": [ + "hmath_algebra_core_module_scale", + "hmath_algebra_core_module_add" + ], + "python": "hmath.algebra.Module", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.Ring", + "c": [ + "hmath_algebra_core_negate_ring" + ], + "python": "hmath.algebra.Ring", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.Semiring", + "c": [ + "hmath_algebra_core_zero", + "hmath_algebra_core_one", + "hmath_algebra_core_plus", + "hmath_algebra_core_times" + ], + "python": "hmath.algebra.Semiring", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.VectorSpace", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.algebra.VectorSpace", + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ] + }, + { + "symbol": "HMath.Algebra.addField", + "c": [ + "hmath_algebra_core_add_field" + ], + "python": "hmath.algebra.add_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.addModular", + "c": [ + "hmath_algebra_core_add_modular" + ], + "python": "hmath.algebra.add_modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldCardinality", + "c": [ + "hmath_algebra_core_field_cardinality" + ], + "python": "hmath.algebra.field_cardinality", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldCharacteristic", + "c": [ + "hmath_algebra_core_field_characteristic" + ], + "python": "hmath.algebra.field_characteristic", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldDegree", + "c": [ + "hmath_algebra_core_field_degree" + ], + "python": "hmath.algebra.field_degree", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldElement", + "c": [ + "hmath_algebra_core_field_element" + ], + "python": "hmath.algebra.field_element", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldElementCoefficients", + "c": [ + "hmath_algebra_core_field_element_coefficients" + ], + "python": "hmath.algebra.field_element_coefficients", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldElements", + "c": [ + "hmath_algebra_core_field_elements" + ], + "python": "hmath.algebra.field_elements", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldLaws", + "c": [ + "hmath_algebra_core_field_laws" + ], + "python": "hmath.algebra.field_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.fieldModulus", + "c": [ + "hmath_algebra_core_field_modulus" + ], + "python": "hmath.algebra.field_modulus", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.finiteField", + "c": [ + "hmath_algebra_core_finite_field" + ], + "python": "hmath.algebra.finite_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.finiteFieldLaws", + "c": [ + "hmath_algebra_core_finite_field_laws" + ], + "python": "hmath.algebra.finite_field_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.getAdditive", + "c": [ + "hmath_algebra_core_get_additive" + ], + "python": "hmath.algebra.get_additive", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.groupCombine", + "c": [ + "hmath_algebra_core_group_combine" + ], + "python": "hmath.algebra.group_combine", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.groupIdentity", + "c": [ + "hmath_algebra_core_group_identity" + ], + "python": "hmath.algebra.group_identity", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.groupInverse", + "c": [ + "hmath_algebra_core_group_inverse" + ], + "python": "hmath.algebra.group_inverse", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.groupLaws", + "c": [ + "hmath_algebra_core_group_laws" + ], + "python": "hmath.algebra.group_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.inverseField", + "c": [ + "hmath_algebra_core_inverse_field" + ], + "python": "hmath.algebra.inverse_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.inverseFieldElement", + "c": [ + "hmath_algebra_core_inverse_field_element" + ], + "python": "hmath.algebra.inverse_field_element", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.inverseModular", + "c": [ + "hmath_algebra_core_inverse_modular" + ], + "python": "hmath.algebra.inverse_modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.linearCombination", + "c": [ + "hmath_algebra_core_linear_combination" + ], + "python": "hmath.algebra.linear_combination", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.modular", + "c": [ + "hmath_algebra_core_modular" + ], + "python": "hmath.algebra.modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.modularModulus", + "c": [ + "hmath_algebra_core_modular_modulus" + ], + "python": "hmath.algebra.modular_modulus", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.modularValue", + "c": [ + "hmath_algebra_core_modular_value" + ], + "python": "hmath.algebra.modular_value", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.moduleAdd", + "c": [ + "hmath_algebra_core_module_add" + ], + "python": "hmath.algebra.module_add", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.moduleLaws", + "c": [ + "hmath_algebra_core_module_laws" + ], + "python": "hmath.algebra.module_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.moduleScale", + "c": [ + "hmath_algebra_core_module_scale" + ], + "python": "hmath.algebra.module_scale", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.multiplyField", + "c": [ + "hmath_algebra_core_multiply_field" + ], + "python": "hmath.algebra.multiply_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.multiplyModular", + "c": [ + "hmath_algebra_core_multiply_modular" + ], + "python": "hmath.algebra.multiply_modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.negateField", + "c": [ + "hmath_algebra_core_negate_field" + ], + "python": "hmath.algebra.negate_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.negateRing", + "c": [ + "hmath_algebra_core_negate_ring" + ], + "python": "hmath.algebra.negate_ring", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.one", + "c": [ + "hmath_algebra_core_one" + ], + "python": "hmath.algebra.one", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.plus", + "c": [ + "hmath_algebra_core_plus" + ], + "python": "hmath.algebra.plus", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.powerField", + "c": [ + "hmath_algebra_core_power_field" + ], + "python": "hmath.algebra.power_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.powerModular", + "c": [ + "hmath_algebra_core_power_modular" + ], + "python": "hmath.algebra.power_modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.primeField", + "c": [ + "hmath_algebra_core_prime_field" + ], + "python": "hmath.algebra.prime_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.ringLaws", + "c": [ + "hmath_algebra_core_ring_laws" + ], + "python": "hmath.algebra.ring_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.semiringLaws", + "c": [ + "hmath_algebra_core_semiring_laws" + ], + "python": "hmath.algebra.semiring_laws", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.subtractField", + "c": [ + "hmath_algebra_core_subtract_field" + ], + "python": "hmath.algebra.subtract_field", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.subtractModular", + "c": [ + "hmath_algebra_core_subtract_modular" + ], + "python": "hmath.algebra.subtract_modular", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.times", + "c": [ + "hmath_algebra_core_times" + ], + "python": "hmath.algebra.times", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + }, + { + "symbol": "HMath.Algebra.zero", + "c": [ + "hmath_algebra_core_zero" + ], + "python": "hmath.algebra.zero", + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ] + } + ] +} diff --git a/bindings/schema/autodiff-objects.json b/bindings/schema/autodiff-objects.json new file mode 100644 index 0000000..8434a40 --- /dev/null +++ b/bindings/schema/autodiff-objects.json @@ -0,0 +1,533 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Autodiff.Expr", + "c": [ + "hmath_ad_expr" + ], + "python": "hmath.autodiff.Expr", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.CompiledGraph", + "c": [ + "hmath_ad_graph" + ], + "python": "hmath.autodiff.CompiledGraph", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.Dual", + "c": [ + "hmath_ad_dual_create", + "hmath_ad_dual_nested", + "hmath_ad_dual_depth", + "hmath_ad_dual_parts", + "hmath_ad_dual_create_f32", + "hmath_ad_dual_create_integer", + "hmath_ad_dual_create_rational", + "hmath_ad_dual_kind", + "hmath_ad_scalar_text", + "hmath_ad_value_import", + "hmath_ad_value_export" + ], + "python": "hmath.autodiff.Dual", + "specializations": [ + "Double", + "Float", + "Integer", + "Rational", + "Complex Double", + "Complex Float", + "Int8/Int16/Int32/Int64/Int", + "Word8/Word16/Word32/Word64/Word", + "Nested original Numeric.Dual coefficient towers", + "Original Numeric.Quaternion Float/Double", + "Arbitrary original Autodiff.Dual nesting over those leaves" + ] + }, + { + "symbol": "HMath.Autodiff.GradientState", + "c": [ + "hmath_ad_gradient_state_create" + ], + "python": "hmath.autodiff.GradientState", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.ADTensor", + "c": [ + "hmath_ad_tensor_create" + ], + "python": "hmath.autodiff.ADTensor", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.variable", + "c": [ + "hmath_ad_variable" + ], + "python": "hmath.autodiff.variable", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.constant", + "c": [ + "hmath_ad_constant" + ], + "python": "hmath.autodiff.constant", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.compileGraph", + "c": [ + "hmath_ad_compile_graph" + ], + "python": "hmath.autodiff.compile_graph", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.evaluateGraph", + "c": [ + "hmath_ad_evaluate_graph" + ], + "python": "hmath.autodiff.evaluate_graph", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.differentiate", + "c": [ + "hmath_ad_differentiate" + ], + "python": "hmath.autodiff.differentiate", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.detach", + "c": [ + "hmath_ad_unary" + ], + "python": "hmath.autodiff.detach", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.stopGradient", + "c": [ + "hmath_ad_unary" + ], + "python": "hmath.autodiff.stop_gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.valueAndGradient", + "c": [ + "hmath_ad_value_and_gradient" + ], + "python": "hmath.autodiff.value_and_gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.gradient", + "c": [ + "hmath_ad_gradient" + ], + "python": "hmath.autodiff.gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.hessian", + "c": [ + "hmath_ad_hessian" + ], + "python": "hmath.autodiff.hessian", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.jacobian", + "c": [ + "hmath_ad_jacobian" + ], + "python": "hmath.autodiff.jacobian", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.jvp", + "c": [ + "hmath_ad_jvp" + ], + "python": "hmath.autodiff.jvp", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.vjp", + "c": [ + "hmath_ad_vjp" + ], + "python": "hmath.autodiff.vjp", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.hvp", + "c": [ + "hmath_ad_hvp" + ], + "python": "hmath.autodiff.hvp", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.gradientCheck", + "c": [ + "hmath_ad_gradient_check" + ], + "python": "hmath.autodiff.gradient_check", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.complexGradient", + "c": [ + "hmath_ad_complex_gradient" + ], + "python": "hmath.autodiff.complex_gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.differentiableStep", + "c": [ + "hmath_ad_differentiable_step" + ], + "python": "hmath.autodiff.differentiable_step", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.primal", + "c": [ + "hmath_ad_values_copy", + "hmath_ad_dual_nested", + "hmath_ad_dual_depth", + "hmath_ad_dual_parts", + "hmath_ad_dual_create_f32", + "hmath_ad_dual_create_integer", + "hmath_ad_dual_create_rational", + "hmath_ad_dual_kind", + "hmath_ad_scalar_text", + "hmath_ad_value_import", + "hmath_ad_value_export" + ], + "python": "hmath.autodiff.primal", + "specializations": [ + "Double", + "Float", + "Integer", + "Rational", + "Complex Double", + "Complex Float", + "Int8/Int16/Int32/Int64/Int", + "Word8/Word16/Word32/Word64/Word", + "Nested original Numeric.Dual coefficient towers", + "Original Numeric.Quaternion Float/Double", + "Arbitrary original Autodiff.Dual nesting over those leaves" + ] + }, + { + "symbol": "HMath.Autodiff.tangent", + "c": [ + "hmath_ad_values_copy", + "hmath_ad_dual_nested", + "hmath_ad_dual_depth", + "hmath_ad_dual_parts", + "hmath_ad_dual_create_f32", + "hmath_ad_dual_create_integer", + "hmath_ad_dual_create_rational", + "hmath_ad_dual_kind", + "hmath_ad_scalar_text", + "hmath_ad_value_import", + "hmath_ad_value_export" + ], + "python": "hmath.autodiff.tangent", + "specializations": [ + "Double", + "Float", + "Integer", + "Rational", + "Complex Double", + "Complex Float", + "Int8/Int16/Int32/Int64/Int", + "Word8/Word16/Word32/Word64/Word", + "Nested original Numeric.Dual coefficient towers", + "Original Numeric.Quaternion Float/Double", + "Arbitrary original Autodiff.Dual nesting over those leaves" + ] + }, + { + "symbol": "HMath.Autodiff.forward", + "c": [ + "hmath_ad_dual_create", + "hmath_ad_unary", + "hmath_ad_binary", + "hmath_ad_values_copy", + "hmath_ad_dual_nested", + "hmath_ad_dual_depth", + "hmath_ad_dual_parts", + "hmath_ad_dual_create_f32", + "hmath_ad_dual_create_integer", + "hmath_ad_dual_create_rational", + "hmath_ad_dual_kind", + "hmath_ad_scalar_text", + "hmath_ad_value_import", + "hmath_ad_value_export" + ], + "python": "hmath.autodiff.forward", + "specializations": [ + "Double", + "Float", + "Integer", + "Rational", + "Complex Double", + "Complex Float", + "Int8/Int16/Int32/Int64/Int", + "Word8/Word16/Word32/Word64/Word", + "Nested original Numeric.Dual coefficient towers", + "Original Numeric.Quaternion Float/Double", + "Arbitrary original Autodiff.Dual nesting over those leaves" + ], + "c_representation": "Compose caller function using native primitives/result adapter as documented." + }, + { + "symbol": "HMath.Autodiff.forwardJVP", + "c": [ + "hmath_ad_forward_jvp_result" + ], + "python": "hmath.autodiff.forward_jvp", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.zeroGradients", + "c": [ + "hmath_ad_zero_gradients" + ], + "python": "hmath.autodiff.zero_gradients", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.accumulateGradients", + "c": [ + "hmath_ad_accumulate_gradients" + ], + "python": "hmath.autodiff.accumulate_gradients", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.accumulatedGradient", + "c": [ + "hmath_ad_values_copy" + ], + "python": "hmath.autodiff.GradientState.accumulated_gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.resetGradients", + "c": [ + "hmath_ad_reset_gradients" + ], + "python": "hmath.autodiff.reset_gradients", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.gradientHook", + "c": [ + "hmath_ad_gradient_hook_result" + ], + "python": "hmath.autodiff.gradient_hook", + "specializations": [ + "Double" + ], + "c_representation": "Compose caller function using native primitives/result adapter as documented." + }, + { + "symbol": "HMath.Autodiff.clipGradient", + "c": [ + "hmath_ad_clip_gradient" + ], + "python": "hmath.autodiff.clip_gradient", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adTensor", + "c": [ + "hmath_ad_tensor_create" + ], + "python": "hmath.autodiff.ad_tensor", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adValues", + "c": [ + "hmath_ad_tensor_values" + ], + "python": "hmath.autodiff.ad_values", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adShape", + "c": [ + "hmath_ad_shape_copy" + ], + "python": "hmath.autodiff.ad_shape", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adBroadcast", + "c": [ + "hmath_ad_broadcast" + ], + "python": "hmath.autodiff.ad_broadcast", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adAdd", + "c": [ + "hmath_ad_tensor_add" + ], + "python": "hmath.autodiff.ad_add", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adMultiply", + "c": [ + "hmath_ad_tensor_multiply" + ], + "python": "hmath.autodiff.ad_multiply", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adMatmul", + "c": [ + "hmath_ad_matmul" + ], + "python": "hmath.autodiff.ad_matmul", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adContract", + "c": [ + "hmath_ad_contract" + ], + "python": "hmath.autodiff.ad_contract", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.adSum", + "c": [ + "hmath_ad_sum" + ], + "python": "hmath.autodiff.ad_sum", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.customOperation", + "c": [ + "hmath_ad_custom_operation", + "hmath_ad_custom_operation_checked" + ], + "python": "hmath.autodiff.custom_operation", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.customUnary", + "c": [ + "hmath_ad_custom_unary", + "hmath_ad_custom_unary_checked" + ], + "python": "hmath.autodiff.custom_unary", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Autodiff.checkpoint", + "c": [ + "hmath_ad_checkpoint", + "hmath_ad_checkpoint_checked" + ], + "python": "hmath.autodiff.checkpoint", + "specializations": [ + "Double" + ] + } + ] +} diff --git a/bindings/schema/buffer-objects.json b/bindings/schema/buffer-objects.json new file mode 100644 index 0000000..978d665 --- /dev/null +++ b/bindings/schema/buffer-objects.json @@ -0,0 +1,255 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.API.Buffer.Boxed", + "c": [ + "hmath_buffer_boxed_object" + ], + "python": "hmath.buffer.Boxed", + "specializations": [ + "actual original container; generic owned elements or actual standard Storable witnesses" + ] + }, + { + "symbol": "HMath.API.Buffer.UnboxedDouble", + "c": [ + "hmath_buffer_unboxed_double_object" + ], + "python": "hmath.buffer.UnboxedDouble", + "specializations": [ + "actual original container; generic owned elements or actual standard Storable witnesses" + ] + }, + { + "symbol": "HMath.API.Buffer.STBuffer", + "c": [ + "hmath_buffer_st_buffer_object" + ], + "python": "hmath.buffer.STBuffer", + "specializations": [ + "actual original container; generic owned elements or actual standard Storable witnesses" + ] + }, + { + "symbol": "HMath.API.Buffer.IOBuffer", + "c": [ + "hmath_buffer_io_buffer_object" + ], + "python": "hmath.buffer.IOBuffer", + "specializations": [ + "actual original container; generic owned elements or actual standard Storable witnesses" + ] + }, + { + "symbol": "HMath.API.Buffer.lazyBoxed", + "c": [ + "hmath_buffer_lazy_boxed" + ], + "python": "hmath.buffer.lazy_boxed", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.strictBoxed", + "c": [ + "hmath_buffer_strict_boxed" + ], + "python": "hmath.buffer.strict_boxed", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedValues", + "c": [ + "hmath_buffer_boxed_values" + ], + "python": "hmath.buffer.boxed_values", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedLength", + "c": [ + "hmath_buffer_boxed_length" + ], + "python": "hmath.buffer.boxed_length", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.mapStrict", + "c": [ + "hmath_buffer_map_strict" + ], + "python": "hmath.buffer.map_strict", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedDouble", + "c": [ + "hmath_buffer_unboxed_double" + ], + "python": "hmath.buffer.unboxed_double", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedValues", + "c": [ + "hmath_buffer_unboxed_values" + ], + "python": "hmath.buffer.unboxed_values", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.runSTBuffer", + "c": [ + "hmath_buffer_run_st_buffer" + ], + "python": "hmath.buffer.run_st_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.thawSTBuffer", + "c": [ + "hmath_buffer_thaw_st_buffer" + ], + "python": "hmath.buffer.thaw_st_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.freezeSTBuffer", + "c": [ + "hmath_buffer_freeze_st_buffer" + ], + "python": "hmath.buffer.freeze_st_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.readSTBuffer", + "c": [ + "hmath_buffer_read_st_buffer" + ], + "python": "hmath.buffer.read_st_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.writeSTBuffer", + "c": [ + "hmath_buffer_write_st_buffer" + ], + "python": "hmath.buffer.write_st_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.newIOBuffer", + "c": [ + "hmath_buffer_new_io_buffer" + ], + "python": "hmath.buffer.new_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.thawIOBuffer", + "c": [ + "hmath_buffer_thaw_io_buffer" + ], + "python": "hmath.buffer.thaw_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.freezeIOBuffer", + "c": [ + "hmath_buffer_freeze_io_buffer" + ], + "python": "hmath.buffer.freeze_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.ioBufferLength", + "c": [ + "hmath_buffer_io_buffer_length" + ], + "python": "hmath.buffer.io_buffer_length", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.readIOBuffer", + "c": [ + "hmath_buffer_read_io_buffer" + ], + "python": "hmath.buffer.read_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.writeIOBuffer", + "c": [ + "hmath_buffer_write_io_buffer" + ], + "python": "hmath.buffer.write_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.withIOBuffer", + "c": [ + "hmath_buffer_with_io_buffer" + ], + "python": "hmath.buffer.with_io_buffer", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedToBoxed", + "c": [ + "hmath_buffer_unboxed_to_boxed" + ], + "python": "hmath.buffer.unboxed_to_boxed", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedToUnboxed", + "c": [ + "hmath_buffer_boxed_to_unboxed" + ], + "python": "hmath.buffer.boxed_to_unboxed", + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ] + } + ] +} diff --git a/bindings/schema/buffer-symbols.txt b/bindings/schema/buffer-symbols.txt new file mode 100644 index 0000000..004a185 --- /dev/null +++ b/bindings/schema/buffer-symbols.txt @@ -0,0 +1,28 @@ +hmath_buffer_lazy_boxed +hmath_buffer_strict_boxed +hmath_buffer_boxed_values +hmath_buffer_boxed_length +hmath_buffer_map_strict +hmath_buffer_unboxed_double +hmath_buffer_unboxed_values +hmath_buffer_run_st_buffer +hmath_buffer_thaw_st_buffer +hmath_buffer_freeze_st_buffer +hmath_buffer_read_st_buffer +hmath_buffer_write_st_buffer +hmath_buffer_new_io_buffer +hmath_buffer_thaw_io_buffer +hmath_buffer_freeze_io_buffer +hmath_buffer_io_buffer_length +hmath_buffer_read_io_buffer +hmath_buffer_write_io_buffer +hmath_buffer_with_io_buffer +hmath_buffer_unboxed_to_boxed +hmath_buffer_boxed_to_unboxed +hmath_buffer_storage_info +hmath_buffer_pointer_info +hmath_buffer_pointer_read +hmath_buffer_pointer_write +hmath_buffer_pointer_address +hmath_buffer_st_active +hmath_buffer_pointer_active diff --git a/bindings/schema/deeplearning-objects.json b/bindings/schema/deeplearning-objects.json new file mode 100644 index 0000000..67e7314 --- /dev/null +++ b/bindings/schema/deeplearning-objects.json @@ -0,0 +1,1295 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.DeepLearning.Core.Sigmoid", + "c": [ + "hmath_neural_core_sigmoid_create" + ], + "python": "hmath.deeplearning_core.Sigmoid", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Tanh", + "c": [ + "hmath_neural_core_tanh_create" + ], + "python": "hmath.deeplearning_core.Tanh", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ReLU", + "c": [ + "hmath_neural_core_relu_create" + ], + "python": "hmath.deeplearning_core.ReLU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SELU", + "c": [ + "hmath_neural_core_selu_create" + ], + "python": "hmath.deeplearning_core.SELU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.GELU", + "c": [ + "hmath_neural_core_gelu_create" + ], + "python": "hmath.deeplearning_core.GELU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SiLU", + "c": [ + "hmath_neural_core_silu_create" + ], + "python": "hmath.deeplearning_core.SiLU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Mish", + "c": [ + "hmath_neural_core_mish_create" + ], + "python": "hmath.deeplearning_core.Mish", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Softplus", + "c": [ + "hmath_neural_core_softplus_create" + ], + "python": "hmath.deeplearning_core.Softplus", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Softsign", + "c": [ + "hmath_neural_core_softsign_create" + ], + "python": "hmath.deeplearning_core.Softsign", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.HardSigmoid", + "c": [ + "hmath_neural_core_hard_sigmoid_create" + ], + "python": "hmath.deeplearning_core.HardSigmoid", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.HardSwish", + "c": [ + "hmath_neural_core_hard_swish_create" + ], + "python": "hmath.deeplearning_core.HardSwish", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.LeakyReLU", + "c": [ + "hmath_neural_core_leaky_relu_create" + ], + "python": "hmath.deeplearning_core.LeakyReLU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.PReLU", + "c": [ + "hmath_neural_core_prelu_create" + ], + "python": "hmath.deeplearning_core.PReLU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ELU", + "c": [ + "hmath_neural_core_elu_create" + ], + "python": "hmath.deeplearning_core.ELU", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Sum", + "c": [ + "hmath_neural_core_sum_create" + ], + "python": "hmath.deeplearning_core.Sum", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Mean", + "c": [ + "hmath_neural_core_mean_create" + ], + "python": "hmath.deeplearning_core.Mean", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.MeanSquaredError", + "c": [ + "hmath_neural_core_mean_squared_error_create" + ], + "python": "hmath.deeplearning_core.MeanSquaredError", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.MeanAbsoluteError", + "c": [ + "hmath_neural_core_mean_absolute_error_create" + ], + "python": "hmath.deeplearning_core.MeanAbsoluteError", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.BinaryCrossEntropy", + "c": [ + "hmath_neural_core_binary_cross_entropy_create" + ], + "python": "hmath.deeplearning_core.BinaryCrossEntropy", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.CategoricalCrossEntropy", + "c": [ + "hmath_neural_core_categorical_cross_entropy_create" + ], + "python": "hmath.deeplearning_core.CategoricalCrossEntropy", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.NegativeLogLikelihood", + "c": [ + "hmath_neural_core_negative_log_likelihood_create" + ], + "python": "hmath.deeplearning_core.NegativeLogLikelihood", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.KLDivergence", + "c": [ + "hmath_neural_core_kl_divergence_create" + ], + "python": "hmath.deeplearning_core.KLDivergence", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.CosineLoss", + "c": [ + "hmath_neural_core_cosine_loss_create" + ], + "python": "hmath.deeplearning_core.CosineLoss", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Huber", + "c": [ + "hmath_neural_core_huber_create" + ], + "python": "hmath.deeplearning_core.Huber", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SmoothL1", + "c": [ + "hmath_neural_core_smooth_l1_create" + ], + "python": "hmath.deeplearning_core.SmoothL1", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Hinge", + "c": [ + "hmath_neural_core_hinge_create" + ], + "python": "hmath.deeplearning_core.Hinge", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activation", + "c": [ + "hmath_neural_core_activation" + ], + "python": "hmath.deeplearning_core.activation", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activationDerivative", + "c": [ + "hmath_neural_core_activation_derivative" + ], + "python": "hmath.deeplearning_core.activation_derivative", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activationExpr", + "c": [ + "hmath_neural_core_activation_expr" + ], + "python": "hmath.deeplearning_core.activation_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.softmaxExpr", + "c": [ + "hmath_neural_core_softmax_expr" + ], + "python": "hmath.deeplearning_core.softmax_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.logSoftmaxExpr", + "c": [ + "hmath_neural_core_log_softmax_expr" + ], + "python": "hmath.deeplearning_core.log_softmax_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.sparsemaxExpr", + "c": [ + "hmath_neural_core_sparsemax_expr" + ], + "python": "hmath.deeplearning_core.sparsemax_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.loss", + "c": [ + "hmath_neural_core_loss" + ], + "python": "hmath.deeplearning_core.loss", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.lossGradient", + "c": [ + "hmath_neural_core_loss_gradient" + ], + "python": "hmath.deeplearning_core.loss_gradient", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.lossExpr", + "c": [ + "hmath_neural_core_loss_expr" + ], + "python": "hmath.deeplearning_core.loss_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.binaryCrossEntropyLogits", + "c": [ + "hmath_neural_core_binary_cross_entropy_logits" + ], + "python": "hmath.deeplearning_core.binary_cross_entropy_logits", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLoss", + "c": [ + "hmath_neural_core_ctc_loss" + ], + "python": "hmath.deeplearning_core.ctc_loss", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLossGradient", + "c": [ + "hmath_neural_core_ctc_loss_gradient" + ], + "python": "hmath.deeplearning_core.ctc_loss_gradient", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLossExpr", + "c": [ + "hmath_neural_core_ctc_loss_expr" + ], + "python": "hmath.deeplearning_core.ctc_loss_expr", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Training", + "c": [ + "hmath_neural_layers_training_create" + ], + "python": "hmath.deeplearning_layers.Training.TRAINING", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Inference", + "c": [ + "hmath_neural_layers_inference_create" + ], + "python": "hmath.deeplearning_layers.Inference", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.dropout", + "c": [ + "hmath_neural_layers_dropout" + ], + "python": "hmath.deeplearning_layers.dropout", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.spatialDropout", + "c": [ + "hmath_neural_layers_spatial_dropout" + ], + "python": "hmath.deeplearning_layers.spatial_dropout", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.BatchNormState", + "c": [ + "hmath_neural_layers_batch_norm_state_create" + ], + "python": "hmath.deeplearning_layers.BatchNormState", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.runningMean", + "c": [ + "hmath_neural_layers_running_mean" + ], + "python": "hmath.deeplearning_layers.running_mean", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.runningVariance", + "c": [ + "hmath_neural_layers_running_variance" + ], + "python": "hmath.deeplearning_layers.running_variance", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.batchesSeen", + "c": [ + "hmath_neural_layers_batches_seen" + ], + "python": "hmath.deeplearning_layers.batches_seen", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.batchNorm", + "c": [ + "hmath_neural_layers_batch_norm" + ], + "python": "hmath.deeplearning_layers.batch_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.layerNorm", + "c": [ + "hmath_neural_layers_layer_norm" + ], + "python": "hmath.deeplearning_layers.layer_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rmsNorm", + "c": [ + "hmath_neural_layers_rms_norm" + ], + "python": "hmath.deeplearning_layers.rms_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.instanceNorm", + "c": [ + "hmath_neural_layers_instance_norm" + ], + "python": "hmath.deeplearning_layers.instance_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.groupNorm", + "c": [ + "hmath_neural_layers_group_norm" + ], + "python": "hmath.deeplearning_layers.group_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.weightNorm", + "c": [ + "hmath_neural_layers_weight_norm" + ], + "python": "hmath.deeplearning_layers.weight_norm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.XavierUniform", + "c": [ + "hmath_neural_layers_xavier_uniform_create" + ], + "python": "hmath.deeplearning_layers.XavierUniform", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.XavierNormal", + "c": [ + "hmath_neural_layers_xavier_normal_create" + ], + "python": "hmath.deeplearning_layers.XavierNormal", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KaimingUniform", + "c": [ + "hmath_neural_layers_kaiming_uniform_create" + ], + "python": "hmath.deeplearning_layers.KaimingUniform", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KaimingNormal", + "c": [ + "hmath_neural_layers_kaiming_normal_create" + ], + "python": "hmath.deeplearning_layers.KaimingNormal", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Orthogonal", + "c": [ + "hmath_neural_layers_orthogonal_create" + ], + "python": "hmath.deeplearning_layers.Orthogonal", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.TruncatedNormal", + "c": [ + "hmath_neural_layers_truncated_normal_create" + ], + "python": "hmath.deeplearning_layers.TruncatedNormal", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.initializeWeights", + "c": [ + "hmath_neural_layers_initialize_weights" + ], + "python": "hmath.deeplearning_layers.initialize_weights", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.embedding", + "c": [ + "hmath_neural_layers_embedding" + ], + "python": "hmath.deeplearning_layers.embedding", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.dense", + "c": [ + "hmath_neural_layers_dense" + ], + "python": "hmath.deeplearning_layers.dense", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.denseAD", + "c": [ + "hmath_neural_layers_dense_ad" + ], + "python": "hmath.deeplearning_layers.dense_ad", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.ConvOptions", + "c": [ + "hmath_neural_layers_conv_options_create" + ], + "python": "hmath.deeplearning_layers.ConvOptions", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionStride", + "c": [ + "hmath_neural_layers_convolution_stride" + ], + "python": "hmath.deeplearning_layers.convolution_stride", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionPadding", + "c": [ + "hmath_neural_layers_convolution_padding" + ], + "python": "hmath.deeplearning_layers.convolution_padding", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionDilation", + "c": [ + "hmath_neural_layers_convolution_dilation" + ], + "python": "hmath.deeplearning_layers.convolution_dilation", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionGroups", + "c": [ + "hmath_neural_layers_convolution_groups" + ], + "python": "hmath.deeplearning_layers.convolution_groups", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolution", + "c": [ + "hmath_neural_layers_convolution" + ], + "python": "hmath.deeplearning_layers.convolution", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.depthwiseConvolution", + "c": [ + "hmath_neural_layers_depthwise_convolution" + ], + "python": "hmath.deeplearning_layers.depthwise_convolution", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionAD", + "c": [ + "hmath_neural_layers_convolution_ad" + ], + "python": "hmath.deeplearning_layers.convolution_ad", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.transposedConvolution", + "c": [ + "hmath_neural_layers_transposed_convolution" + ], + "python": "hmath.deeplearning_layers.transposed_convolution", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.MaxPool", + "c": [ + "hmath_neural_layers_max_pool_create" + ], + "python": "hmath.deeplearning_layers.MaxPool", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.AveragePool", + "c": [ + "hmath_neural_layers_average_pool_create" + ], + "python": "hmath.deeplearning_layers.AveragePool", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.pooling", + "c": [ + "hmath_neural_layers_pooling" + ], + "python": "hmath.deeplearning_layers.pooling", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.adaptivePooling", + "c": [ + "hmath_neural_layers_adaptive_pooling" + ], + "python": "hmath.deeplearning_layers.adaptive_pooling", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.globalPooling", + "c": [ + "hmath_neural_layers_global_pooling" + ], + "python": "hmath.deeplearning_layers.global_pooling", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.scaledDotProductAttention", + "c": [ + "hmath_neural_layers_scaled_dot_product_attention" + ], + "python": "hmath.deeplearning_layers.scaled_dot_product_attention", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.multiheadAttention", + "c": [ + "hmath_neural_layers_multihead_attention" + ], + "python": "hmath.deeplearning_layers.multihead_attention", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.causalMask", + "c": [ + "hmath_neural_layers_causal_mask" + ], + "python": "hmath.deeplearning_layers.causal_mask", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rotaryEmbedding", + "c": [ + "hmath_neural_layers_rotary_embedding" + ], + "python": "hmath.deeplearning_layers.rotary_embedding", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.sinusoidalEncoding", + "c": [ + "hmath_neural_layers_sinusoidal_encoding" + ], + "python": "hmath.deeplearning_layers.sinusoidal_encoding", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.alibiBias", + "c": [ + "hmath_neural_layers_alibi_bias" + ], + "python": "hmath.deeplearning_layers.alibi_bias", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.emptyCache", + "c": [ + "hmath_neural_layers_empty_cache" + ], + "python": "hmath.deeplearning_layers.empty_cache", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.appendCache", + "c": [ + "hmath_neural_layers_append_cache" + ], + "python": "hmath.deeplearning_layers.append_cache", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.cacheValues", + "c": [ + "hmath_neural_layers_cache_values" + ], + "python": "hmath.deeplearning_layers.cache_values", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.transformerFeedForward", + "c": [ + "hmath_neural_layers_transformer_feed_forward" + ], + "python": "hmath.deeplearning_layers.transformer_feed_forward", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.layerNormAD", + "c": [ + "hmath_neural_layers_layer_norm_ad" + ], + "python": "hmath.deeplearning_layers.layer_norm_ad", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rmsNormAD", + "c": [ + "hmath_neural_layers_rms_norm_ad" + ], + "python": "hmath.deeplearning_layers.rms_norm_ad", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.scaledDotProductAttentionAD", + "c": [ + "hmath_neural_layers_scaled_dot_product_attention_ad" + ], + "python": "hmath.deeplearning_layers.scaled_dot_product_attention_ad", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Symmetric", + "c": [ + "hmath_neural_precision_symmetric_create" + ], + "python": "hmath.deeplearning_precision.Symmetric", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Asymmetric", + "c": [ + "hmath_neural_precision_asymmetric_create" + ], + "python": "hmath.deeplearning_precision.Asymmetric", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantize", + "c": [ + "hmath_neural_precision_quantize" + ], + "python": "hmath.deeplearning_precision.quantize", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.dequantize", + "c": [ + "hmath_neural_precision_dequantize" + ], + "python": "hmath.deeplearning_precision.dequantize", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizedValues", + "c": [ + "hmath_neural_precision_quantized_values" + ], + "python": "hmath.deeplearning_precision.quantized_values", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizationScales", + "c": [ + "hmath_neural_precision_quantization_scales" + ], + "python": "hmath.deeplearning_precision.quantization_scales", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizationZeroPoints", + "c": [ + "hmath_neural_precision_quantization_zero_points" + ], + "python": "hmath.deeplearning_precision.quantization_zero_points", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.int8Gemm", + "c": [ + "hmath_neural_precision_int8_gemm" + ], + "python": "hmath.deeplearning_precision.int8_gemm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.FP16", + "c": [ + "hmath_neural_precision_fp16_create" + ], + "python": "hmath.deeplearning_precision.FP16", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.BF16", + "c": [ + "hmath_neural_precision_bf16_create" + ], + "python": "hmath.deeplearning_precision.BF16", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.reducedGemm", + "c": [ + "hmath_neural_precision_reduced_gemm" + ], + "python": "hmath.deeplearning_precision.reduced_gemm", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.LossScaler", + "c": [ + "hmath_neural_precision_loss_scaler_create" + ], + "python": "hmath.deeplearning_precision.LossScaler", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.lossScale", + "c": [ + "hmath_neural_precision_loss_scale" + ], + "python": "hmath.deeplearning_precision.loss_scale", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.scaleGrowthInterval", + "c": [ + "hmath_neural_precision_scale_growth_interval" + ], + "python": "hmath.deeplearning_precision.scale_growth_interval", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.finiteSteps", + "c": [ + "hmath_neural_precision_finite_steps" + ], + "python": "hmath.deeplearning_precision.finite_steps", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.initialLossScaler", + "c": [ + "hmath_neural_precision_initial_loss_scaler" + ], + "python": "hmath.deeplearning_precision.initial_loss_scaler", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.scaleLoss", + "c": [ + "hmath_neural_precision_scale_loss" + ], + "python": "hmath.deeplearning_precision.scale_loss", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.unscaleGradients", + "c": [ + "hmath_neural_precision_unscale_gradients" + ], + "python": "hmath.deeplearning_precision.unscale_gradients", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.updateLossScaler", + "c": [ + "hmath_neural_precision_update_loss_scaler" + ], + "python": "hmath.deeplearning_precision.update_loss_scaler", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.ClassificationMetrics", + "c": [ + "hmath_neural_metrics_classification_metrics_create" + ], + "python": "hmath.deeplearning_metrics.ClassificationMetrics", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.accuracy", + "c": [ + "hmath_neural_metrics_accuracy" + ], + "python": "hmath.deeplearning_metrics.accuracy", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.precisionByClass", + "c": [ + "hmath_neural_metrics_precision_by_class" + ], + "python": "hmath.deeplearning_metrics.precision_by_class", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.recallByClass", + "c": [ + "hmath_neural_metrics_recall_by_class" + ], + "python": "hmath.deeplearning_metrics.recall_by_class", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.f1ByClass", + "c": [ + "hmath_neural_metrics_f1_by_class" + ], + "python": "hmath.deeplearning_metrics.f1_by_class", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.confusionMatrix", + "c": [ + "hmath_neural_metrics_confusion_matrix" + ], + "python": "hmath.deeplearning_metrics.confusion_matrix", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.classificationMetrics", + "c": [ + "hmath_neural_metrics_classification_metrics" + ], + "python": "hmath.deeplearning_metrics.classification_metrics", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.topKAccuracy", + "c": [ + "hmath_neural_metrics_top_k_accuracy" + ], + "python": "hmath.deeplearning_metrics.top_k_accuracy", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.rocAUC", + "c": [ + "hmath_neural_metrics_roc_auc" + ], + "python": "hmath.deeplearning_metrics.roc_auc", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.prAUC", + "c": [ + "hmath_neural_metrics_pr_auc" + ], + "python": "hmath.deeplearning_metrics.pr_auc", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.cosineSimilarityMatrix", + "c": [ + "hmath_neural_metrics_cosine_similarity_matrix" + ], + "python": "hmath.deeplearning_metrics.cosine_similarity_matrix", + "specializations": [ + "original fixed Double/INT8/FP16/BF16/AD graph rules as declared; full original RNG state and all result diagnostics" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Activation", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_core.Activation", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Loss", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_core.Loss", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Reduction", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_core.Reduction", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Initializer", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_layers.Initializer", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KVCache", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_layers.KVCache", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.PoolMode", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_layers.PoolMode", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Precision", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_precision.Precision", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Quantization", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_precision.Quantization", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.QuantizedTensor", + "c": [ + "hmath_value" + ], + "python": "hmath.deeplearning_precision.QuantizedTensor", + "specializations": [ + "actual original closed selector, state or opaque object; no reconstructed numerical approximation" + ] + } + ] +} diff --git a/bindings/schema/deeplearning.json b/bindings/schema/deeplearning.json new file mode 100644 index 0000000..bd5f21e --- /dev/null +++ b/bindings/schema/deeplearning.json @@ -0,0 +1,2351 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.DeepLearning.Core", + "name": "Sigmoid", + "arguments": [], + "result": "Activation", + "python": "sigmoid", + "c": "hmath_neural_core_sigmoid_create", + "expression": "C.Sigmoid" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Tanh", + "arguments": [], + "result": "Activation", + "python": "tanh", + "c": "hmath_neural_core_tanh_create", + "expression": "C.Tanh" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "ReLU", + "arguments": [], + "result": "Activation", + "python": "relu", + "c": "hmath_neural_core_relu_create", + "expression": "C.ReLU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "SELU", + "arguments": [], + "result": "Activation", + "python": "selu", + "c": "hmath_neural_core_selu_create", + "expression": "C.SELU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "GELU", + "arguments": [], + "result": "Activation", + "python": "gelu", + "c": "hmath_neural_core_gelu_create", + "expression": "C.GELU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "SiLU", + "arguments": [], + "result": "Activation", + "python": "silu", + "c": "hmath_neural_core_silu_create", + "expression": "C.SiLU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Mish", + "arguments": [], + "result": "Activation", + "python": "mish", + "c": "hmath_neural_core_mish_create", + "expression": "C.Mish" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Softplus", + "arguments": [], + "result": "Activation", + "python": "softplus", + "c": "hmath_neural_core_softplus_create", + "expression": "C.Softplus" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Softsign", + "arguments": [], + "result": "Activation", + "python": "softsign", + "c": "hmath_neural_core_softsign_create", + "expression": "C.Softsign" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "HardSigmoid", + "arguments": [], + "result": "Activation", + "python": "hard_sigmoid", + "c": "hmath_neural_core_hard_sigmoid_create", + "expression": "C.HardSigmoid" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "HardSwish", + "arguments": [], + "result": "Activation", + "python": "hard_swish", + "c": "hmath_neural_core_hard_swish_create", + "expression": "C.HardSwish" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "LeakyReLU", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Activation", + "python": "leaky_relu", + "c": "hmath_neural_core_leaky_relu_create", + "expression": "C.LeakyReLU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "PReLU", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Activation", + "python": "prelu", + "c": "hmath_neural_core_prelu_create", + "expression": "C.PReLU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "ELU", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Activation", + "python": "elu", + "c": "hmath_neural_core_elu_create", + "expression": "C.ELU" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Sum", + "arguments": [], + "result": "Reduction", + "python": "sum", + "c": "hmath_neural_core_sum_create", + "expression": "C.Sum" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Mean", + "arguments": [], + "result": "Reduction", + "python": "mean", + "c": "hmath_neural_core_mean_create", + "expression": "C.Mean" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "MeanSquaredError", + "arguments": [], + "result": "Loss", + "python": "mean_squared_error", + "c": "hmath_neural_core_mean_squared_error_create", + "expression": "C.MeanSquaredError" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "MeanAbsoluteError", + "arguments": [], + "result": "Loss", + "python": "mean_absolute_error", + "c": "hmath_neural_core_mean_absolute_error_create", + "expression": "C.MeanAbsoluteError" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "BinaryCrossEntropy", + "arguments": [], + "result": "Loss", + "python": "binary_cross_entropy", + "c": "hmath_neural_core_binary_cross_entropy_create", + "expression": "C.BinaryCrossEntropy" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "CategoricalCrossEntropy", + "arguments": [], + "result": "Loss", + "python": "categorical_cross_entropy", + "c": "hmath_neural_core_categorical_cross_entropy_create", + "expression": "C.CategoricalCrossEntropy" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "NegativeLogLikelihood", + "arguments": [], + "result": "Loss", + "python": "negative_log_likelihood", + "c": "hmath_neural_core_negative_log_likelihood_create", + "expression": "C.NegativeLogLikelihood" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "KLDivergence", + "arguments": [], + "result": "Loss", + "python": "kl_divergence", + "c": "hmath_neural_core_kl_divergence_create", + "expression": "C.KLDivergence" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "CosineLoss", + "arguments": [], + "result": "Loss", + "python": "cosine_loss", + "c": "hmath_neural_core_cosine_loss_create", + "expression": "C.CosineLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Huber", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Loss", + "python": "huber", + "c": "hmath_neural_core_huber_create", + "expression": "C.Huber" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "SmoothL1", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Loss", + "python": "smooth_l1", + "c": "hmath_neural_core_smooth_l1_create", + "expression": "C.SmoothL1" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "Hinge", + "arguments": [ + [ + "parameter", + "Double" + ] + ], + "result": "Loss", + "python": "hinge", + "c": "hmath_neural_core_hinge_create", + "expression": "C.Hinge" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "activation", + "arguments": [ + [ + "method", + "Activation" + ], + [ + "value", + "Double" + ] + ], + "result": "Double", + "python": "activation", + "c": "hmath_neural_core_activation", + "expression": "C.activation" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "activationDerivative", + "arguments": [ + [ + "method", + "Activation" + ], + [ + "value", + "Double" + ] + ], + "result": "Double", + "python": "activation_derivative", + "c": "hmath_neural_core_activation_derivative", + "expression": "C.activationDerivative" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "activationExpr", + "arguments": [ + [ + "method", + "Activation" + ], + [ + "value", + "ADExpr" + ] + ], + "result": "ADExpr", + "python": "activation_expr", + "c": "hmath_neural_core_activation_expr", + "expression": "C.activationExpr" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "softmax", + "arguments": [ + [ + "values", + "[Double]" + ] + ], + "result": "[Double]", + "python": "softmax", + "c": "hmath_neural_core_softmax", + "expression": "C.softmax" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "logSoftmax", + "arguments": [ + [ + "values", + "[Double]" + ] + ], + "result": "[Double]", + "python": "log_softmax", + "c": "hmath_neural_core_log_softmax", + "expression": "C.logSoftmax" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "sparsemax", + "arguments": [ + [ + "values", + "[Double]" + ] + ], + "result": "[Double]", + "python": "sparsemax", + "c": "hmath_neural_core_sparsemax", + "expression": "C.sparsemax" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "gatedLinearUnit", + "arguments": [ + [ + "values", + "[Double]" + ], + [ + "gate", + "[Double]" + ] + ], + "result": "[Double]", + "python": "gated_linear_unit", + "c": "hmath_neural_core_gated_linear_unit", + "expression": "C.gatedLinearUnit" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "softmaxExpr", + "arguments": [ + [ + "values", + "[ADExpr]" + ] + ], + "result": "[ADExpr]", + "python": "softmax_expr", + "c": "hmath_neural_core_softmax_expr", + "expression": "C.softmaxExpr" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "logSoftmaxExpr", + "arguments": [ + [ + "values", + "[ADExpr]" + ] + ], + "result": "[ADExpr]", + "python": "log_softmax_expr", + "c": "hmath_neural_core_log_softmax_expr", + "expression": "C.logSoftmaxExpr" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "sparsemaxExpr", + "arguments": [ + [ + "values", + "[ADExpr]" + ] + ], + "result": "[ADExpr]", + "python": "sparsemax_expr", + "c": "hmath_neural_core_sparsemax_expr", + "expression": "C.sparsemaxExpr" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "loss", + "arguments": [ + [ + "method", + "Loss" + ], + [ + "reduction", + "Reduction" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[Double]" + ] + ], + "result": "Double", + "python": "loss", + "c": "hmath_neural_core_loss", + "expression": "C.loss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "lossGradient", + "arguments": [ + [ + "method", + "Loss" + ], + [ + "reduction", + "Reduction" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[Double]" + ] + ], + "result": "[Double]", + "python": "loss_gradient", + "c": "hmath_neural_core_loss_gradient", + "expression": "C.lossGradient" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "lossExpr", + "arguments": [ + [ + "method", + "Loss" + ], + [ + "reduction", + "Reduction" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[ADExpr]" + ] + ], + "result": "ADExpr", + "python": "loss_expr", + "c": "hmath_neural_core_loss_expr", + "expression": "C.lossExpr" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "binaryCrossEntropyLogits", + "arguments": [ + [ + "reduction", + "Reduction" + ], + [ + "target", + "[Double]" + ], + [ + "logits", + "[Double]" + ] + ], + "result": "Double", + "python": "binary_cross_entropy_logits", + "c": "hmath_neural_core_binary_cross_entropy_logits", + "expression": "C.binaryCrossEntropyLogits" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "categoricalCrossEntropyLogits", + "arguments": [ + [ + "target", + "[Double]" + ], + [ + "logits", + "[Double]" + ] + ], + "result": "Double", + "python": "categorical_cross_entropy_logits", + "c": "hmath_neural_core_categorical_cross_entropy_logits", + "expression": "C.categoricalCrossEntropyLogits" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "regularization", + "arguments": [ + [ + "l1", + "Double" + ], + [ + "l2", + "Double" + ], + [ + "weights", + "[Double]" + ] + ], + "result": "Double", + "python": "regularization", + "c": "hmath_neural_core_regularization", + "expression": "C.regularization" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "contrastiveLoss", + "arguments": [ + [ + "margin", + "Double" + ], + [ + "similar", + "Bool" + ], + [ + "left", + "[Double]" + ], + [ + "right", + "[Double]" + ] + ], + "result": "Double", + "python": "contrastive_loss", + "c": "hmath_neural_core_contrastive_loss", + "expression": "C.contrastiveLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "tripletLoss", + "arguments": [ + [ + "margin", + "Double" + ], + [ + "anchor", + "[Double]" + ], + [ + "positive", + "[Double]" + ], + [ + "negative", + "[Double]" + ] + ], + "result": "Double", + "python": "triplet_loss", + "c": "hmath_neural_core_triplet_loss", + "expression": "C.tripletLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "focalLoss", + "arguments": [ + [ + "alpha", + "Double" + ], + [ + "gamma", + "Double" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[Double]" + ] + ], + "result": "Double", + "python": "focal_loss", + "c": "hmath_neural_core_focal_loss", + "expression": "C.focalLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "diceLoss", + "arguments": [ + [ + "smooth", + "Double" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[Double]" + ] + ], + "result": "Double", + "python": "dice_loss", + "c": "hmath_neural_core_dice_loss", + "expression": "C.diceLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "iouLoss", + "arguments": [ + [ + "smooth", + "Double" + ], + [ + "target", + "[Double]" + ], + [ + "prediction", + "[Double]" + ] + ], + "result": "Double", + "python": "iou_loss", + "c": "hmath_neural_core_iou_loss", + "expression": "C.iouLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "ctcLoss", + "arguments": [ + [ + "blank", + "Int" + ], + [ + "labels", + "[Int]" + ], + [ + "log_probabilities", + "[[Double]]" + ] + ], + "result": "Double", + "python": "ctc_loss", + "c": "hmath_neural_core_ctc_loss", + "expression": "C.ctcLoss" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "ctcLossGradient", + "arguments": [ + [ + "blank", + "Int" + ], + [ + "labels", + "[Int]" + ], + [ + "log_probabilities", + "[[Double]]" + ] + ], + "result": "(Double,[[Double]])", + "python": "ctc_loss_gradient", + "c": "hmath_neural_core_ctc_loss_gradient", + "expression": "C.ctcLossGradient" + }, + { + "module": "HMath.DeepLearning.Core", + "name": "ctcLossExpr", + "arguments": [ + [ + "blank", + "Int" + ], + [ + "labels", + "[Int]" + ], + [ + "log_probabilities", + "[[ADExpr]]" + ] + ], + "result": "ADExpr", + "python": "ctc_loss_expr", + "c": "hmath_neural_core_ctc_loss_expr", + "expression": "C.ctcLossExpr" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "Training", + "arguments": [], + "result": "Training", + "python": "training", + "c": "hmath_neural_layers_training_create", + "expression": "L.Training" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "Inference", + "arguments": [], + "result": "Training", + "python": "inference", + "c": "hmath_neural_layers_inference_create", + "expression": "L.Inference" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "dropout", + "arguments": [ + [ + "mode", + "Training" + ], + [ + "probability", + "Double" + ], + [ + "rng", + "RNG" + ], + [ + "input", + "Tensor" + ] + ], + "result": "(Tensor,Tensor,RNG)", + "python": "dropout", + "c": "hmath_neural_layers_dropout", + "expression": "L.dropout" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "spatialDropout", + "arguments": [ + [ + "mode", + "Training" + ], + [ + "probability", + "Double" + ], + [ + "rng", + "RNG" + ], + [ + "input", + "Tensor" + ] + ], + "result": "(Tensor,Tensor,RNG)", + "python": "spatial_dropout", + "c": "hmath_neural_layers_spatial_dropout", + "expression": "L.spatialDropout" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "BatchNormState", + "arguments": [ + [ + "running_mean", + "[Double]" + ], + [ + "running_variance", + "[Double]" + ], + [ + "batches_seen", + "Int" + ] + ], + "result": "BatchNormState", + "python": "batch_norm_state", + "c": "hmath_neural_layers_batch_norm_state_create", + "expression": "L.BatchNormState" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "runningMean", + "arguments": [ + [ + "state", + "BatchNormState" + ] + ], + "result": "[Double]", + "python": "running_mean", + "c": "hmath_neural_layers_running_mean", + "expression": "L.runningMean" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "runningVariance", + "arguments": [ + [ + "state", + "BatchNormState" + ] + ], + "result": "[Double]", + "python": "running_variance", + "c": "hmath_neural_layers_running_variance", + "expression": "L.runningVariance" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "batchesSeen", + "arguments": [ + [ + "state", + "BatchNormState" + ] + ], + "result": "Int", + "python": "batches_seen", + "c": "hmath_neural_layers_batches_seen", + "expression": "L.batchesSeen" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "batchNorm", + "arguments": [ + [ + "mode", + "Training" + ], + [ + "momentum", + "Double" + ], + [ + "epsilon", + "Double" + ], + [ + "gamma", + "[Double]" + ], + [ + "beta", + "[Double]" + ], + [ + "state", + "BatchNormState" + ], + [ + "input", + "Tensor" + ] + ], + "result": "(Tensor,BatchNormState)", + "python": "batch_norm", + "c": "hmath_neural_layers_batch_norm", + "expression": "L.batchNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "layerNorm", + "arguments": [ + [ + "axes", + "Int" + ], + [ + "epsilon", + "Double" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "layer_norm", + "c": "hmath_neural_layers_layer_norm", + "expression": "L.layerNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "rmsNorm", + "arguments": [ + [ + "axes", + "Int" + ], + [ + "epsilon", + "Double" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "rms_norm", + "c": "hmath_neural_layers_rms_norm", + "expression": "L.rmsNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "instanceNorm", + "arguments": [ + [ + "epsilon", + "Double" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "instance_norm", + "c": "hmath_neural_layers_instance_norm", + "expression": "L.instanceNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "groupNorm", + "arguments": [ + [ + "groups", + "Int" + ], + [ + "epsilon", + "Double" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "group_norm", + "c": "hmath_neural_layers_group_norm", + "expression": "L.groupNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "weightNorm", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "scales", + "[Double]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "weight_norm", + "c": "hmath_neural_layers_weight_norm", + "expression": "L.weightNorm" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "XavierUniform", + "arguments": [], + "result": "Initializer", + "python": "xavier_uniform", + "c": "hmath_neural_layers_xavier_uniform_create", + "expression": "L.XavierUniform" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "XavierNormal", + "arguments": [], + "result": "Initializer", + "python": "xavier_normal", + "c": "hmath_neural_layers_xavier_normal_create", + "expression": "L.XavierNormal" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "KaimingUniform", + "arguments": [], + "result": "Initializer", + "python": "kaiming_uniform", + "c": "hmath_neural_layers_kaiming_uniform_create", + "expression": "L.KaimingUniform" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "KaimingNormal", + "arguments": [], + "result": "Initializer", + "python": "kaiming_normal", + "c": "hmath_neural_layers_kaiming_normal_create", + "expression": "L.KaimingNormal" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "Orthogonal", + "arguments": [ + [ + "scale", + "Double" + ] + ], + "result": "Initializer", + "python": "orthogonal", + "c": "hmath_neural_layers_orthogonal_create", + "expression": "L.Orthogonal" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "TruncatedNormal", + "arguments": [ + [ + "mean", + "Double" + ], + [ + "standard_deviation", + "Double" + ], + [ + "bound", + "Double" + ] + ], + "result": "Initializer", + "python": "truncated_normal", + "c": "hmath_neural_layers_truncated_normal_create", + "expression": "L.TruncatedNormal" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "initializeWeights", + "arguments": [ + [ + "method", + "Initializer" + ], + [ + "fan_in", + "Int" + ], + [ + "fan_out", + "Int" + ], + [ + "shape", + "[Int]" + ], + [ + "rng", + "RNG" + ] + ], + "result": "(Tensor,RNG)", + "python": "initialize_weights", + "c": "hmath_neural_layers_initialize_weights", + "expression": "L.initializeWeights" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "embedding", + "arguments": [ + [ + "weights", + "Tensor" + ], + [ + "indices", + "[Int]" + ] + ], + "result": "Tensor", + "python": "embedding", + "c": "hmath_neural_layers_embedding", + "expression": "L.embedding" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "dense", + "arguments": [ + [ + "input", + "Tensor" + ], + [ + "weights", + "Tensor" + ], + [ + "bias", + "[Double]" + ] + ], + "result": "Tensor", + "python": "dense", + "c": "hmath_neural_layers_dense", + "expression": "L.dense" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "denseAD", + "arguments": [ + [ + "input", + "ADTensor" + ], + [ + "weights", + "ADTensor" + ], + [ + "bias", + "[ADExpr]" + ] + ], + "result": "ADTensor", + "python": "dense_ad", + "c": "hmath_neural_layers_dense_ad", + "expression": "L.denseAD" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "ConvOptions", + "arguments": [ + [ + "stride", + "[Int]" + ], + [ + "padding", + "[Int]" + ], + [ + "dilation", + "[Int]" + ], + [ + "groups", + "Int" + ] + ], + "result": "ConvOptions", + "python": "conv_options", + "c": "hmath_neural_layers_conv_options_create", + "expression": "L.ConvOptions" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolutionStride", + "arguments": [ + [ + "options", + "ConvOptions" + ] + ], + "result": "[Int]", + "python": "convolution_stride", + "c": "hmath_neural_layers_convolution_stride", + "expression": "L.convolutionStride" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolutionPadding", + "arguments": [ + [ + "options", + "ConvOptions" + ] + ], + "result": "[Int]", + "python": "convolution_padding", + "c": "hmath_neural_layers_convolution_padding", + "expression": "L.convolutionPadding" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolutionDilation", + "arguments": [ + [ + "options", + "ConvOptions" + ] + ], + "result": "[Int]", + "python": "convolution_dilation", + "c": "hmath_neural_layers_convolution_dilation", + "expression": "L.convolutionDilation" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolutionGroups", + "arguments": [ + [ + "options", + "ConvOptions" + ] + ], + "result": "Int", + "python": "convolution_groups", + "c": "hmath_neural_layers_convolution_groups", + "expression": "L.convolutionGroups" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolution", + "arguments": [ + [ + "options", + "ConvOptions" + ], + [ + "input", + "Tensor" + ], + [ + "weights", + "Tensor" + ], + [ + "bias", + "[Double]" + ] + ], + "result": "Tensor", + "python": "convolution", + "c": "hmath_neural_layers_convolution", + "expression": "L.convolution" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "depthwiseConvolution", + "arguments": [ + [ + "options", + "ConvOptions" + ], + [ + "input", + "Tensor" + ], + [ + "weights", + "Tensor" + ], + [ + "bias", + "[Double]" + ] + ], + "result": "Tensor", + "python": "depthwise_convolution", + "c": "hmath_neural_layers_depthwise_convolution", + "expression": "L.depthwiseConvolution" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "convolutionAD", + "arguments": [ + [ + "options", + "ConvOptions" + ], + [ + "input", + "ADTensor" + ], + [ + "weights", + "ADTensor" + ], + [ + "bias", + "[ADExpr]" + ] + ], + "result": "ADTensor", + "python": "convolution_ad", + "c": "hmath_neural_layers_convolution_ad", + "expression": "L.convolutionAD" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "transposedConvolution", + "arguments": [ + [ + "output_padding", + "[Int]" + ], + [ + "options", + "ConvOptions" + ], + [ + "input", + "Tensor" + ], + [ + "weights", + "Tensor" + ], + [ + "bias", + "[Double]" + ] + ], + "result": "Tensor", + "python": "transposed_convolution", + "c": "hmath_neural_layers_transposed_convolution", + "expression": "L.transposedConvolution" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "MaxPool", + "arguments": [], + "result": "PoolMode", + "python": "max_pool", + "c": "hmath_neural_layers_max_pool_create", + "expression": "L.MaxPool" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "AveragePool", + "arguments": [], + "result": "PoolMode", + "python": "average_pool", + "c": "hmath_neural_layers_average_pool_create", + "expression": "L.AveragePool" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "pooling", + "arguments": [ + [ + "mode", + "PoolMode" + ], + [ + "kernel", + "[Int]" + ], + [ + "stride", + "[Int]" + ], + [ + "padding", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "pooling", + "c": "hmath_neural_layers_pooling", + "expression": "L.pooling" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "adaptivePooling", + "arguments": [ + [ + "mode", + "PoolMode" + ], + [ + "shape", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "adaptive_pooling", + "c": "hmath_neural_layers_adaptive_pooling", + "expression": "L.adaptivePooling" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "globalPooling", + "arguments": [ + [ + "mode", + "PoolMode" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "global_pooling", + "c": "hmath_neural_layers_global_pooling", + "expression": "L.globalPooling" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "scaledDotProductAttention", + "arguments": [ + [ + "query", + "Tensor" + ], + [ + "key", + "Tensor" + ], + [ + "value", + "Tensor" + ], + [ + "mask", + "Maybe[[Bool]]" + ], + [ + "bias", + "Maybe[[Double]]" + ] + ], + "result": "(Tensor,Tensor)", + "python": "scaled_dot_product_attention", + "c": "hmath_neural_layers_scaled_dot_product_attention", + "expression": "L.scaledDotProductAttention" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "multiheadAttention", + "arguments": [ + [ + "heads", + "Int" + ], + [ + "query", + "Tensor" + ], + [ + "key", + "Tensor" + ], + [ + "value", + "Tensor" + ], + [ + "mask", + "Maybe[[Bool]]" + ] + ], + "result": "Tensor", + "python": "multihead_attention", + "c": "hmath_neural_layers_multihead_attention", + "expression": "L.multiheadAttention" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "causalMask", + "arguments": [ + [ + "queries", + "Int" + ], + [ + "keys", + "Int" + ], + [ + "offset", + "Int" + ] + ], + "result": "[[Bool]]", + "python": "causal_mask", + "c": "hmath_neural_layers_causal_mask", + "expression": "L.causalMask" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "rotaryEmbedding", + "arguments": [ + [ + "base", + "Double" + ], + [ + "offset", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor", + "python": "rotary_embedding", + "c": "hmath_neural_layers_rotary_embedding", + "expression": "L.rotaryEmbedding" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "sinusoidalEncoding", + "arguments": [ + [ + "length", + "Int" + ], + [ + "dimensions", + "Int" + ], + [ + "offset", + "Int" + ] + ], + "result": "Tensor", + "python": "sinusoidal_encoding", + "c": "hmath_neural_layers_sinusoidal_encoding", + "expression": "L.sinusoidalEncoding" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "alibiBias", + "arguments": [ + [ + "slope", + "Double" + ], + [ + "queries", + "Int" + ], + [ + "keys", + "Int" + ], + [ + "offset", + "Int" + ] + ], + "result": "[[Double]]", + "python": "alibi_bias", + "c": "hmath_neural_layers_alibi_bias", + "expression": "L.alibiBias" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "emptyCache", + "arguments": [ + [ + "capacity", + "Int" + ], + [ + "key_dimensions", + "Int" + ], + [ + "value_dimensions", + "Int" + ] + ], + "result": "KVCache", + "python": "empty_cache", + "c": "hmath_neural_layers_empty_cache", + "expression": "L.emptyCache" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "appendCache", + "arguments": [ + [ + "cache", + "KVCache" + ], + [ + "key", + "Tensor" + ], + [ + "value", + "Tensor" + ] + ], + "result": "KVCache", + "python": "append_cache", + "c": "hmath_neural_layers_append_cache", + "expression": "L.appendCache" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "cacheValues", + "arguments": [ + [ + "cache", + "KVCache" + ] + ], + "result": "(Tensor,Tensor)", + "python": "cache_values", + "c": "hmath_neural_layers_cache_values", + "expression": "L.cacheValues" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "transformerFeedForward", + "arguments": [ + [ + "activation", + "Activation" + ], + [ + "input", + "Tensor" + ], + [ + "first_weights", + "Tensor" + ], + [ + "first_bias", + "[Double]" + ], + [ + "second_weights", + "Tensor" + ], + [ + "second_bias", + "[Double]" + ] + ], + "result": "Tensor", + "python": "transformer_feed_forward", + "c": "hmath_neural_layers_transformer_feed_forward", + "expression": "L.transformerFeedForward" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "layerNormAD", + "arguments": [ + [ + "axes", + "Int" + ], + [ + "epsilon", + "Double" + ], + [ + "input", + "ADTensor" + ] + ], + "result": "ADTensor", + "python": "layer_norm_ad", + "c": "hmath_neural_layers_layer_norm_ad", + "expression": "L.layerNormAD" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "rmsNormAD", + "arguments": [ + [ + "axes", + "Int" + ], + [ + "epsilon", + "Double" + ], + [ + "input", + "ADTensor" + ] + ], + "result": "ADTensor", + "python": "rms_norm_ad", + "c": "hmath_neural_layers_rms_norm_ad", + "expression": "L.rmsNormAD" + }, + { + "module": "HMath.DeepLearning.Layers", + "name": "scaledDotProductAttentionAD", + "arguments": [ + [ + "query", + "ADTensor" + ], + [ + "key", + "ADTensor" + ], + [ + "value", + "ADTensor" + ], + [ + "mask", + "Maybe[[Bool]]" + ] + ], + "result": "ADTensor", + "python": "scaled_dot_product_attention_ad", + "c": "hmath_neural_layers_scaled_dot_product_attention_ad", + "expression": "L.scaledDotProductAttentionAD" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "Symmetric", + "arguments": [], + "result": "Quantization", + "python": "symmetric", + "c": "hmath_neural_precision_symmetric_create", + "expression": "P.Symmetric" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "Asymmetric", + "arguments": [], + "result": "Quantization", + "python": "asymmetric", + "c": "hmath_neural_precision_asymmetric_create", + "expression": "P.Asymmetric" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "quantize", + "arguments": [ + [ + "scheme", + "Quantization" + ], + [ + "axis", + "MaybeInt" + ], + [ + "input", + "Tensor" + ] + ], + "result": "QuantizedTensor", + "python": "quantize", + "c": "hmath_neural_precision_quantize", + "expression": "P.quantize" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "dequantize", + "arguments": [ + [ + "quantized", + "QuantizedTensor" + ] + ], + "result": "Tensor", + "python": "dequantize", + "c": "hmath_neural_precision_dequantize", + "expression": "P.dequantize" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "quantizedValues", + "arguments": [ + [ + "quantized", + "QuantizedTensor" + ] + ], + "result": "[Int8]", + "python": "quantized_values", + "c": "hmath_neural_precision_quantized_values", + "expression": "P.quantizedValues" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "quantizationScales", + "arguments": [ + [ + "quantized", + "QuantizedTensor" + ] + ], + "result": "[Double]", + "python": "quantization_scales", + "c": "hmath_neural_precision_quantization_scales", + "expression": "P.quantizationScales" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "quantizationZeroPoints", + "arguments": [ + [ + "quantized", + "QuantizedTensor" + ] + ], + "result": "[Int]", + "python": "quantization_zero_points", + "c": "hmath_neural_precision_quantization_zero_points", + "expression": "P.quantizationZeroPoints" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "int8Gemm", + "arguments": [ + [ + "left", + "QuantizedTensor" + ], + [ + "right", + "QuantizedTensor" + ] + ], + "result": "Tensor", + "python": "int8_gemm", + "c": "hmath_neural_precision_int8_gemm", + "expression": "P.int8Gemm" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "FP16", + "arguments": [], + "result": "Precision", + "python": "fp16", + "c": "hmath_neural_precision_fp16_create", + "expression": "P.FP16" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "BF16", + "arguments": [], + "result": "Precision", + "python": "bf16", + "c": "hmath_neural_precision_bf16_create", + "expression": "P.BF16" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "reducedGemm", + "arguments": [ + [ + "precision", + "Precision" + ], + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "Tensor", + "python": "reduced_gemm", + "c": "hmath_neural_precision_reduced_gemm", + "expression": "P.reducedGemm" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "LossScaler", + "arguments": [ + [ + "scale", + "Double" + ], + [ + "growth_interval", + "Int" + ], + [ + "finite_steps", + "Int" + ] + ], + "result": "LossScaler", + "python": "loss_scaler", + "c": "hmath_neural_precision_loss_scaler_create", + "expression": "P.LossScaler" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "lossScale", + "arguments": [ + [ + "state", + "LossScaler" + ] + ], + "result": "Double", + "python": "loss_scale", + "c": "hmath_neural_precision_loss_scale", + "expression": "P.lossScale" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "scaleGrowthInterval", + "arguments": [ + [ + "state", + "LossScaler" + ] + ], + "result": "Int", + "python": "scale_growth_interval", + "c": "hmath_neural_precision_scale_growth_interval", + "expression": "P.scaleGrowthInterval" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "finiteSteps", + "arguments": [ + [ + "state", + "LossScaler" + ] + ], + "result": "Int", + "python": "finite_steps", + "c": "hmath_neural_precision_finite_steps", + "expression": "P.finiteSteps" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "initialLossScaler", + "arguments": [ + [ + "scale", + "Double" + ], + [ + "growth_interval", + "Int" + ] + ], + "result": "LossScaler", + "python": "initial_loss_scaler", + "c": "hmath_neural_precision_initial_loss_scaler", + "expression": "P.initialLossScaler" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "scaleLoss", + "arguments": [ + [ + "state", + "LossScaler" + ], + [ + "loss", + "Double" + ] + ], + "result": "Double", + "python": "scale_loss", + "c": "hmath_neural_precision_scale_loss", + "expression": "P.scaleLoss" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "unscaleGradients", + "arguments": [ + [ + "state", + "LossScaler" + ], + [ + "gradients", + "[Double]" + ] + ], + "result": "(Bool,[Double])", + "python": "unscale_gradients", + "c": "hmath_neural_precision_unscale_gradients", + "expression": "P.unscaleGradients" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "updateLossScaler", + "arguments": [ + [ + "finite", + "Bool" + ], + [ + "state", + "LossScaler" + ] + ], + "result": "LossScaler", + "python": "update_loss_scaler", + "c": "hmath_neural_precision_update_loss_scaler", + "expression": "P.updateLossScaler" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "gradientNorm", + "arguments": [ + [ + "gradient", + "[Double]" + ] + ], + "result": "Double", + "python": "gradient_norm", + "c": "hmath_neural_precision_gradient_norm", + "expression": "P.gradientNorm" + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "clipGradients", + "arguments": [ + [ + "maximum", + "Double" + ], + [ + "gradient", + "[Double]" + ] + ], + "result": "[Double]", + "python": "clip_gradients", + "c": "hmath_neural_precision_clip_gradients", + "expression": "P.clipGradients" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "ClassificationMetrics", + "arguments": [ + [ + "accuracy", + "Double" + ], + [ + "precision", + "[Double]" + ], + [ + "recall", + "[Double]" + ], + [ + "f1", + "[Double]" + ] + ], + "result": "ClassificationMetrics", + "python": "classification_metrics", + "c": "hmath_neural_metrics_classification_metrics_create", + "expression": "M.ClassificationMetrics" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "accuracy", + "arguments": [ + [ + "metrics", + "ClassificationMetrics" + ] + ], + "result": "Double", + "python": "accuracy", + "c": "hmath_neural_metrics_accuracy", + "expression": "M.accuracy" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "precisionByClass", + "arguments": [ + [ + "metrics", + "ClassificationMetrics" + ] + ], + "result": "[Double]", + "python": "precision_by_class", + "c": "hmath_neural_metrics_precision_by_class", + "expression": "M.precisionByClass" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "recallByClass", + "arguments": [ + [ + "metrics", + "ClassificationMetrics" + ] + ], + "result": "[Double]", + "python": "recall_by_class", + "c": "hmath_neural_metrics_recall_by_class", + "expression": "M.recallByClass" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "f1ByClass", + "arguments": [ + [ + "metrics", + "ClassificationMetrics" + ] + ], + "result": "[Double]", + "python": "f1_by_class", + "c": "hmath_neural_metrics_f1_by_class", + "expression": "M.f1ByClass" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "confusionMatrix", + "arguments": [ + [ + "classes", + "Int" + ], + [ + "truth", + "[Int]" + ], + [ + "prediction", + "[Int]" + ] + ], + "result": "[[Int]]", + "python": "confusion_matrix", + "c": "hmath_neural_metrics_confusion_matrix", + "expression": "M.confusionMatrix" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "classificationMetrics", + "arguments": [ + [ + "classes", + "Int" + ], + [ + "truth", + "[Int]" + ], + [ + "prediction", + "[Int]" + ] + ], + "result": "ClassificationMetrics", + "python": "classification_metrics", + "c": "hmath_neural_metrics_classification_metrics", + "expression": "M.classificationMetrics" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "topKAccuracy", + "arguments": [ + [ + "k", + "Int" + ], + [ + "truth", + "[Int]" + ], + [ + "scores", + "[[Double]]" + ] + ], + "result": "Double", + "python": "top_k_accuracy", + "c": "hmath_neural_metrics_top_k_accuracy", + "expression": "M.topKAccuracy" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "rocAUC", + "arguments": [ + [ + "truth", + "[Bool]" + ], + [ + "scores", + "[Double]" + ] + ], + "result": "Double", + "python": "roc_auc", + "c": "hmath_neural_metrics_roc_auc", + "expression": "M.rocAUC" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "prAUC", + "arguments": [ + [ + "truth", + "[Bool]" + ], + [ + "scores", + "[Double]" + ] + ], + "result": "Double", + "python": "pr_auc", + "c": "hmath_neural_metrics_pr_auc", + "expression": "M.prAUC" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "perplexity", + "arguments": [ + [ + "negative_log_probabilities", + "[Double]" + ] + ], + "result": "Double", + "python": "perplexity", + "c": "hmath_neural_metrics_perplexity", + "expression": "M.perplexity" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "cosineSimilarityMatrix", + "arguments": [ + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "Tensor", + "python": "cosine_similarity_matrix", + "c": "hmath_neural_metrics_cosine_similarity_matrix", + "expression": "M.cosineSimilarityMatrix" + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "marginRankingLoss", + "arguments": [ + [ + "margin", + "Double" + ], + [ + "left", + "[Double]" + ], + [ + "right", + "[Double]" + ], + [ + "labels", + "[Double]" + ] + ], + "result": "Double", + "python": "margin_ranking_loss", + "c": "hmath_neural_metrics_margin_ranking_loss", + "expression": "M.marginRankingLoss" + } + ] +} diff --git a/bindings/schema/errors-objects.json b/bindings/schema/errors-objects.json new file mode 100644 index 0000000..07466cc --- /dev/null +++ b/bindings/schema/errors-objects.json @@ -0,0 +1,226 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Error.MathError", + "c": [ + "hmath_math_error", + "hmath_last_math_error" + ], + "python": "hmath.errors.MathError", + "specializations": [ + "all 21 original constructors; Int and full Char string payloads" + ] + }, + { + "symbol": "HMath.Error.NegativeDimensions", + "c": [ + "HMATH_MATH_NEGATIVE_DIMENSIONS" + ], + "python": "hmath.errors.NegativeDimensions", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.ElementCountOverflow", + "c": [ + "HMATH_MATH_ELEMENT_COUNT_OVERFLOW" + ], + "python": "hmath.errors.ElementCountOverflow", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.ElementCountMismatch", + "c": [ + "HMATH_MATH_ELEMENT_COUNT_MISMATCH" + ], + "python": "hmath.errors.ElementCountMismatch", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.ShapeMismatch", + "c": [ + "HMATH_MATH_SHAPE_MISMATCH" + ], + "python": "hmath.errors.ShapeMismatch", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.InnerDimensionMismatch", + "c": [ + "HMATH_MATH_INNER_DIMENSION_MISMATCH" + ], + "python": "hmath.errors.InnerDimensionMismatch", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.IndexOutOfBounds", + "c": [ + "HMATH_MATH_INDEX_OUT_OF_BOUNDS" + ], + "python": "hmath.errors.IndexOutOfBounds", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.SliceOutOfBounds", + "c": [ + "HMATH_MATH_SLICE_OUT_OF_BOUNDS" + ], + "python": "hmath.errors.SliceOutOfBounds", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.VectorLengthMismatch", + "c": [ + "HMATH_MATH_VECTOR_LENGTH_MISMATCH" + ], + "python": "hmath.errors.VectorLengthMismatch", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NonSquareMatrix", + "c": [ + "HMATH_MATH_NON_SQUARE_MATRIX" + ], + "python": "hmath.errors.NonSquareMatrix", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.InvalidTolerance", + "c": [ + "HMATH_MATH_INVALID_TOLERANCE" + ], + "python": "hmath.errors.InvalidTolerance", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.SingularMatrix", + "c": [ + "HMATH_MATH_SINGULAR_MATRIX" + ], + "python": "hmath.errors.SingularMatrix", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NearSingularMatrix", + "c": [ + "HMATH_MATH_NEAR_SINGULAR_MATRIX" + ], + "python": "hmath.errors.NearSingularMatrix", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NonFiniteMatrixEntry", + "c": [ + "HMATH_MATH_NON_FINITE_MATRIX_ENTRY" + ], + "python": "hmath.errors.NonFiniteMatrixEntry", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NonFiniteVectorEntry", + "c": [ + "HMATH_MATH_NON_FINITE_VECTOR_ENTRY" + ], + "python": "hmath.errors.NonFiniteVectorEntry", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NonFiniteResult", + "c": [ + "HMATH_MATH_NON_FINITE_RESULT" + ], + "python": "hmath.errors.NonFiniteResult", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.RightHandSideMismatch", + "c": [ + "HMATH_MATH_RIGHT_HAND_SIDE_MISMATCH" + ], + "python": "hmath.errors.RightHandSideMismatch", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.DomainError", + "c": [ + "HMATH_MATH_DOMAIN_ERROR" + ], + "python": "hmath.errors.DomainError", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.InvalidArgument", + "c": [ + "HMATH_MATH_INVALID_ARGUMENT" + ], + "python": "hmath.errors.InvalidArgument", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NonConvergence", + "c": [ + "HMATH_MATH_NON_CONVERGENCE" + ], + "python": "hmath.errors.NonConvergence", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.RankDeficient", + "c": [ + "HMATH_MATH_RANK_DEFICIENT" + ], + "python": "hmath.errors.RankDeficient", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + }, + { + "symbol": "HMath.Error.NotPositiveDefinite", + "c": [ + "HMATH_MATH_NOT_POSITIVE_DEFINITE" + ], + "python": "hmath.errors.NotPositiveDefinite", + "specializations": [ + "original constructor payloads; checked callback Left and queried errors" + ] + } + ] +} diff --git a/bindings/schema/execution-api.json b/bindings/schema/execution-api.json new file mode 100644 index 0000000..9aac6f8 --- /dev/null +++ b/bindings/schema/execution-api.json @@ -0,0 +1,11 @@ +{ + "schema": 1, + "kind": "new-buffer-execution-api", + "note": "Not counted as full coverage of HMath.Backend.gemm or its Backend/Transpose APIs.", + "c": ["hmath_execution_create", "hmath_execution_retain", "hmath_execution_release", "hmath_execution_gemm_f32", "hmath_execution_gemm_f64"], + "python": ["hmath.execution.Execution", "hmath.execution.Execution.gemm", "hmath.execution.Execution.matmul"], + "reference_arithmetic": ["HMath.Matrix.multiplyChecked", "HMath.Matrix.scaleMatrix", "HMath.Matrix.addMatrixChecked"], + "precisions": ["Float", "Double"], + "layouts": ["row-major consecutive columns with optional row padding"], + "unsupported": ["negative strides", "non-consecutive columns", "transpose flags"] +} diff --git a/bindings/schema/expression-objects.json b/bindings/schema/expression-objects.json new file mode 100644 index 0000000..8689e5e --- /dev/null +++ b/bindings/schema/expression-objects.json @@ -0,0 +1,2135 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Expression.SourcePos", + "c": [ + "hmath_expression_source_pos_create" + ], + "python": "hmath.expression.SourcePos", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.unknownPosition", + "c": [ + "hmath_expression_unknown_position" + ], + "python": "hmath.expression.unknown_position", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.sourceOffset", + "c": [ + "hmath_expression_source_offset" + ], + "python": "hmath.expression.source_offset", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.sourceLine", + "c": [ + "hmath_expression_source_line" + ], + "python": "hmath.expression.source_line", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.sourceColumn", + "c": [ + "hmath_expression_source_column" + ], + "python": "hmath.expression.source_column", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Negate", + "c": [ + "hmath_expression_negate_create" + ], + "python": "hmath.expression.Negate", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Add", + "c": [ + "hmath_expression_add_create" + ], + "python": "hmath.expression.Add", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Subtract", + "c": [ + "hmath_expression_subtract_create" + ], + "python": "hmath.expression.Subtract", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Multiply", + "c": [ + "hmath_expression_multiply_create" + ], + "python": "hmath.expression.Multiply", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Divide", + "c": [ + "hmath_expression_divide_create" + ], + "python": "hmath.expression.Divide", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Power", + "c": [ + "hmath_expression_power_create" + ], + "python": "hmath.expression.Power", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Pi", + "c": [ + "hmath_expression_pi_create" + ], + "python": "hmath.expression.Pi", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Euler", + "c": [ + "hmath_expression_euler_create" + ], + "python": "hmath.expression.Euler", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Tau", + "c": [ + "hmath_expression_tau_create" + ], + "python": "hmath.expression.Tau", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.ExactRational", + "c": [ + "hmath_expression_exact_rational_create" + ], + "python": "hmath.expression.ExactRational", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Float64", + "c": [ + "hmath_expression_float64_create" + ], + "python": "hmath.expression.Float64", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.SyntaxError", + "c": [ + "hmath_expression_syntax_error_create" + ], + "python": "hmath.expression.SyntaxError", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.UnknownName", + "c": [ + "hmath_expression_unknown_name_create" + ], + "python": "hmath.expression.UnknownName", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.TypeMismatch", + "c": [ + "hmath_expression_type_mismatch_create" + ], + "python": "hmath.expression.TypeMismatch", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.DomainFailure", + "c": [ + "hmath_expression_domain_failure_create" + ], + "python": "hmath.expression.DomainFailure", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.NonFinite", + "c": [ + "hmath_expression_non_finite_create" + ], + "python": "hmath.expression.NonFinite", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.StepLimit", + "c": [ + "hmath_expression_step_limit_create" + ], + "python": "hmath.expression.StepLimit", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.DepthLimit", + "c": [ + "hmath_expression_depth_limit_create" + ], + "python": "hmath.expression.DepthLimit", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.MemoryLimit", + "c": [ + "hmath_expression_memory_limit_create" + ], + "python": "hmath.expression.MemoryLimit", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.InvalidLimits", + "c": [ + "hmath_expression_invalid_limits_create" + ], + "python": "hmath.expression.InvalidLimits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Unsupported", + "c": [ + "hmath_expression_unsupported_create" + ], + "python": "hmath.expression.Unsupported", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Sin", + "c": [ + "hmath_expression_sin_create" + ], + "python": "hmath.expression.Sin", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Cos", + "c": [ + "hmath_expression_cos_create" + ], + "python": "hmath.expression.Cos", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Tan", + "c": [ + "hmath_expression_tan_create" + ], + "python": "hmath.expression.Tan", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Exp", + "c": [ + "hmath_expression_exp_create" + ], + "python": "hmath.expression.Exp", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Log", + "c": [ + "hmath_expression_log_create" + ], + "python": "hmath.expression.Log", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Sqrt", + "c": [ + "hmath_expression_sqrt_create" + ], + "python": "hmath.expression.Sqrt", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Abs", + "c": [ + "hmath_expression_abs_create" + ], + "python": "hmath.expression.Abs", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Signum", + "c": [ + "hmath_expression_signum_create" + ], + "python": "hmath.expression.Signum", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Floor", + "c": [ + "hmath_expression_floor_create" + ], + "python": "hmath.expression.Floor", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Ceiling", + "c": [ + "hmath_expression_ceiling_create" + ], + "python": "hmath.expression.Ceiling", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Min", + "c": [ + "hmath_expression_min_create" + ], + "python": "hmath.expression.Min", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Max", + "c": [ + "hmath_expression_max_create" + ], + "python": "hmath.expression.Max", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Asin", + "c": [ + "hmath_expression_asin_create" + ], + "python": "hmath.expression.Asin", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Acos", + "c": [ + "hmath_expression_acos_create" + ], + "python": "hmath.expression.Acos", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Atan", + "c": [ + "hmath_expression_atan_create" + ], + "python": "hmath.expression.Atan", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Sinh", + "c": [ + "hmath_expression_sinh_create" + ], + "python": "hmath.expression.Sinh", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Cosh", + "c": [ + "hmath_expression_cosh_create" + ], + "python": "hmath.expression.Cosh", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Tanh", + "c": [ + "hmath_expression_tanh_create" + ], + "python": "hmath.expression.Tanh", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Expr", + "c": [ + "hmath_expression_expr_create" + ], + "python": "hmath.expression.Expr", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.expressionPosition", + "c": [ + "hmath_expression_expression_position" + ], + "python": "hmath.expression.expression_position", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.expressionNode", + "c": [ + "hmath_expression_expression_node" + ], + "python": "hmath.expression.expression_node", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Literal", + "c": [ + "hmath_expression_literal_create" + ], + "python": "hmath.expression.Literal", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Variable", + "c": [ + "hmath_expression_variable_create" + ], + "python": "hmath.expression.Variable", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Constant", + "c": [ + "hmath_expression_constant_create" + ], + "python": "hmath.expression.Constant", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Unary", + "c": [ + "hmath_expression_unary_create" + ], + "python": "hmath.expression.Unary", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Binary", + "c": [ + "hmath_expression_binary_create" + ], + "python": "hmath.expression.Binary", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Call", + "c": [ + "hmath_expression_call_create" + ], + "python": "hmath.expression.Call", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Let", + "c": [ + "hmath_expression_let_create" + ], + "python": "hmath.expression.Let", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.literal", + "c": [ + "hmath_expression_literal" + ], + "python": "hmath.expression.literal", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.variable", + "c": [ + "hmath_expression_variable" + ], + "python": "hmath.expression.variable", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.constant", + "c": [ + "hmath_expression_constant" + ], + "python": "hmath.expression.constant", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.unary", + "c": [ + "hmath_expression_unary" + ], + "python": "hmath.expression.unary", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.binary", + "c": [ + "hmath_expression_binary" + ], + "python": "hmath.expression.binary", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.call", + "c": [ + "hmath_expression_call" + ], + "python": "hmath.expression.call", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.letIn", + "c": [ + "hmath_expression_let_in" + ], + "python": "hmath.expression.let_in", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.Limits", + "c": [ + "hmath_expression_limits_create" + ], + "python": "hmath.expression.Limits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.defaultLimits", + "c": [ + "hmath_expression_default_limits" + ], + "python": "hmath.expression.default_limits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumSteps", + "c": [ + "hmath_expression_maximum_steps" + ], + "python": "hmath.expression.maximum_steps", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumDepth", + "c": [ + "hmath_expression_maximum_depth" + ], + "python": "hmath.expression.maximum_depth", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumNodes", + "c": [ + "hmath_expression_maximum_nodes" + ], + "python": "hmath.expression.maximum_nodes", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumInputChars", + "c": [ + "hmath_expression_maximum_input_chars" + ], + "python": "hmath.expression.maximum_input_chars", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumIntegerBits", + "c": [ + "hmath_expression_maximum_integer_bits" + ], + "python": "hmath.expression.maximum_integer_bits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.maximumCacheEntries", + "c": [ + "hmath_expression_maximum_cache_entries" + ], + "python": "hmath.expression.maximum_cache_entries", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.ExprError", + "c": [ + "hmath_expression_expr_error_create" + ], + "python": "hmath.expression.ExprError", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.errorKind", + "c": [ + "hmath_expression_error_kind_get" + ], + "python": "hmath.expression.error_kind", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.errorPosition", + "c": [ + "hmath_expression_error_position" + ], + "python": "hmath.expression.error_position", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.errorMessage", + "c": [ + "hmath_expression_error_message" + ], + "python": "hmath.expression.error_message", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.validateLimits", + "c": [ + "hmath_expression_validate_limits" + ], + "python": "hmath.expression.validate_limits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.validateExpression", + "c": [ + "hmath_expression_validate_expression" + ], + "python": "hmath.expression.validate_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.parseExpression", + "c": [ + "hmath_expression_parse_expression" + ], + "python": "hmath.expression.parse_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.prettyExpression", + "c": [ + "hmath_expression_pretty_expression" + ], + "python": "hmath.expression.pretty_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.freeVariables", + "c": [ + "hmath_expression_free_variables" + ], + "python": "hmath.expression.free_variables", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.ExactValue", + "c": [ + "hmath_expression_exact_value_create" + ], + "python": "hmath.expression.ExactValue", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.FloatValue", + "c": [ + "hmath_expression_float_value_create" + ], + "python": "hmath.expression.FloatValue", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.defaultRegistry", + "c": [ + "hmath_expression_default_registry" + ], + "python": "hmath.expression.default_registry", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.emptyRegistry", + "c": [ + "hmath_expression_empty_registry" + ], + "python": "hmath.expression.empty_registry", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.registerFunction", + "c": [ + "hmath_expression_register_function" + ], + "python": "hmath.expression.register_function", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.allowedFunctions", + "c": [ + "hmath_expression_allowed_functions" + ], + "python": "hmath.expression.allowed_functions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.typeCheckExpression", + "c": [ + "hmath_expression_type_check_expression" + ], + "python": "hmath.expression.type_check_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.evaluateExpression", + "c": [ + "hmath_expression_evaluate_expression" + ], + "python": "hmath.expression.evaluate_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.evaluateText", + "c": [ + "hmath_expression_evaluate_text" + ], + "python": "hmath.expression.evaluate_text", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.evaluateCompiled", + "c": [ + "hmath_expression_evaluate_compiled" + ], + "python": "hmath.expression.evaluate_compiled", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.compileExpression", + "c": [ + "hmath_expression_compile_expression" + ], + "python": "hmath.expression.compile_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.compiledNodeCount", + "c": [ + "hmath_expression_compiled_node_count" + ], + "python": "hmath.expression.compiled_node_count", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.optimizeExpression", + "c": [ + "hmath_expression_optimize_expression" + ], + "python": "hmath.expression.optimize_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.emptyExpressionCache", + "c": [ + "hmath_expression_empty_expression_cache" + ], + "python": "hmath.expression.empty_expression_cache", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.cacheSize", + "c": [ + "hmath_expression_cache_size" + ], + "python": "hmath.expression.cache_size", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.cachedExpression", + "c": [ + "hmath_expression_cached_expression" + ], + "python": "hmath.expression.cached_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.formatScientific", + "c": [ + "hmath_expression_format_scientific" + ], + "python": "hmath.expression.format_scientific", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.formatRadix", + "c": [ + "hmath_expression_format_radix" + ], + "python": "hmath.expression.format_radix", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.serializeExpression", + "c": [ + "hmath_expression_serialize_expression" + ], + "python": "hmath.expression.serialize_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.deserializeExpression", + "c": [ + "hmath_expression_deserialize_expression" + ], + "python": "hmath.expression.deserialize_expression", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.expressionHash", + "c": [ + "hmath_expression_expression_hash" + ], + "python": "hmath.expression.expression_hash", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Real", + "c": [ + "hmath_symbolic_real_create" + ], + "python": "hmath.symbolic.Real", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.NonZero", + "c": [ + "hmath_symbolic_non_zero_create" + ], + "python": "hmath.symbolic.NonZero", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Positive", + "c": [ + "hmath_symbolic_positive_create" + ], + "python": "hmath.symbolic.Positive", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.NonNegative", + "c": [ + "hmath_symbolic_non_negative_create" + ], + "python": "hmath.symbolic.NonNegative", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Integral", + "c": [ + "hmath_symbolic_integral_create" + ], + "python": "hmath.symbolic.Integral", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Negative", + "c": [ + "hmath_symbolic_negative_create" + ], + "python": "hmath.symbolic.Negative", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.NonPositive", + "c": [ + "hmath_symbolic_non_positive_create" + ], + "python": "hmath.symbolic.NonPositive", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.FromLeft", + "c": [ + "hmath_symbolic_from_left_create" + ], + "python": "hmath.symbolic.FromLeft", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.FromRight", + "c": [ + "hmath_symbolic_from_right_create" + ], + "python": "hmath.symbolic.FromRight", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.TwoSided", + "c": [ + "hmath_symbolic_two_sided_create" + ], + "python": "hmath.symbolic.TwoSided", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Equal", + "c": [ + "hmath_symbolic_equal_create" + ], + "python": "hmath.symbolic.Equal", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.NotEqual", + "c": [ + "hmath_symbolic_not_equal_create" + ], + "python": "hmath.symbolic.NotEqual", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Less", + "c": [ + "hmath_symbolic_less_create" + ], + "python": "hmath.symbolic.Less", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.LessEqual", + "c": [ + "hmath_symbolic_less_equal_create" + ], + "python": "hmath.symbolic.LessEqual", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Greater", + "c": [ + "hmath_symbolic_greater_create" + ], + "python": "hmath.symbolic.Greater", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.GreaterEqual", + "c": [ + "hmath_symbolic_greater_equal_create" + ], + "python": "hmath.symbolic.GreaterEqual", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.assumptions", + "c": [ + "hmath_symbolic_assumptions" + ], + "python": "hmath.symbolic.assumptions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.noAssumptions", + "c": [ + "hmath_symbolic_no_assumptions" + ], + "python": "hmath.symbolic.no_assumptions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.proves", + "c": [ + "hmath_symbolic_proves" + ], + "python": "hmath.symbolic.proves", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.SymbolicOptions", + "c": [ + "hmath_symbolic_symbolic_options_create" + ], + "python": "hmath.symbolic.SymbolicOptions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.defaultSymbolicOptions", + "c": [ + "hmath_symbolic_default_symbolic_options" + ], + "python": "hmath.symbolic.default_symbolic_options", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicLimits", + "c": [ + "hmath_symbolic_symbolic_limits" + ], + "python": "hmath.symbolic.symbolic_limits", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicAssumptions", + "c": [ + "hmath_symbolic_symbolic_assumptions" + ], + "python": "hmath.symbolic.symbolic_assumptions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.normalize", + "c": [ + "hmath_symbolic_normalize" + ], + "python": "hmath.symbolic.normalize", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.simplify", + "c": [ + "hmath_symbolic_simplify" + ], + "python": "hmath.symbolic.simplify", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.expand", + "c": [ + "hmath_symbolic_expand" + ], + "python": "hmath.symbolic.expand", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.collectTerms", + "c": [ + "hmath_symbolic_collect_terms" + ], + "python": "hmath.symbolic.collect_terms", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.trigonometricSimplify", + "c": [ + "hmath_symbolic_trigonometric_simplify" + ], + "python": "hmath.symbolic.trigonometric_simplify", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.logarithmicSimplify", + "c": [ + "hmath_symbolic_logarithmic_simplify" + ], + "python": "hmath.symbolic.logarithmic_simplify", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.factorPolynomial", + "c": [ + "hmath_symbolic_factor_polynomial" + ], + "python": "hmath.symbolic.factor_polynomial", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.rationalSimplify", + "c": [ + "hmath_symbolic_rational_simplify" + ], + "python": "hmath.symbolic.rational_simplify", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.differentiate", + "c": [ + "hmath_symbolic_differentiate" + ], + "python": "hmath.symbolic.differentiate", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.integrateBasic", + "c": [ + "hmath_symbolic_integrate_basic" + ], + "python": "hmath.symbolic.integrate_basic", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.toPolynomial", + "c": [ + "hmath_symbolic_to_polynomial" + ], + "python": "hmath.symbolic.to_polynomial", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.exactPolynomialRoots", + "c": [ + "hmath_symbolic_exact_polynomial_roots" + ], + "python": "hmath.symbolic.exact_polynomial_roots", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.numericalPolynomialRoots", + "c": [ + "hmath_symbolic_numerical_polynomial_roots" + ], + "python": "hmath.symbolic.numerical_polynomial_roots", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.PolynomialFactorization", + "c": [ + "hmath_symbolic_polynomial_factorization_create" + ], + "python": "hmath.symbolic.PolynomialFactorization", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.factorLeading", + "c": [ + "hmath_symbolic_factor_leading" + ], + "python": "hmath.symbolic.factor_leading", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.factorTerms", + "c": [ + "hmath_symbolic_factor_terms" + ], + "python": "hmath.symbolic.factor_terms", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.substitute", + "c": [ + "hmath_symbolic_substitute" + ], + "python": "hmath.symbolic.substitute", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Any", + "c": [ + "hmath_symbolic_any_create" + ], + "python": "hmath.symbolic.Any", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Exactly", + "c": [ + "hmath_symbolic_exactly_create" + ], + "python": "hmath.symbolic.Exactly", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.UnaryPattern", + "c": [ + "hmath_symbolic_unary_pattern_create" + ], + "python": "hmath.symbolic.UnaryPattern", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.BinaryPattern", + "c": [ + "hmath_symbolic_binary_pattern_create" + ], + "python": "hmath.symbolic.BinaryPattern", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.CallPattern", + "c": [ + "hmath_symbolic_call_pattern_create" + ], + "python": "hmath.symbolic.CallPattern", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.matchPattern", + "c": [ + "hmath_symbolic_match_pattern" + ], + "python": "hmath.symbolic.match_pattern", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.RewriteRule", + "c": [ + "hmath_symbolic_rewrite_rule_create" + ], + "python": "hmath.symbolic.RewriteRule", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.rewritePattern", + "c": [ + "hmath_symbolic_rewrite_pattern" + ], + "python": "hmath.symbolic.rewrite_pattern", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.rewriteReplacement", + "c": [ + "hmath_symbolic_rewrite_replacement" + ], + "python": "hmath.symbolic.rewrite_replacement", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.rewriteRequirements", + "c": [ + "hmath_symbolic_rewrite_requirements" + ], + "python": "hmath.symbolic.rewrite_requirements", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.applyRewrite", + "c": [ + "hmath_symbolic_apply_rewrite" + ], + "python": "hmath.symbolic.apply_rewrite", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.gradient", + "c": [ + "hmath_symbolic_gradient" + ], + "python": "hmath.symbolic.gradient", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.hessian", + "c": [ + "hmath_symbolic_hessian" + ], + "python": "hmath.symbolic.hessian", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.jacobian", + "c": [ + "hmath_symbolic_jacobian" + ], + "python": "hmath.symbolic.jacobian", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.integrateByParts", + "c": [ + "hmath_symbolic_integrate_by_parts" + ], + "python": "hmath.symbolic.integrate_by_parts", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.integrateSubstitution", + "c": [ + "hmath_symbolic_integrate_substitution" + ], + "python": "hmath.symbolic.integrate_substitution", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.integrateRational", + "c": [ + "hmath_symbolic_integrate_rational" + ], + "python": "hmath.symbolic.integrate_rational", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.FiniteLimit", + "c": [ + "hmath_symbolic_finite_limit_create" + ], + "python": "hmath.symbolic.FiniteLimit", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.PositiveInfinity", + "c": [ + "hmath_symbolic_positive_infinity_create" + ], + "python": "hmath.symbolic.PositiveInfinity", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.NegativeInfinity", + "c": [ + "hmath_symbolic_negative_infinity_create" + ], + "python": "hmath.symbolic.NegativeInfinity", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.DoesNotExist", + "c": [ + "hmath_symbolic_does_not_exist_create" + ], + "python": "hmath.symbolic.DoesNotExist", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicLimit", + "c": [ + "hmath_symbolic_symbolic_limit" + ], + "python": "hmath.symbolic.symbolic_limit", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Series", + "c": [ + "hmath_symbolic_series_create" + ], + "python": "hmath.symbolic.Series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.seriesCenter", + "c": [ + "hmath_symbolic_series_center" + ], + "python": "hmath.symbolic.series_center", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.seriesMinimumPower", + "c": [ + "hmath_symbolic_series_minimum_power" + ], + "python": "hmath.symbolic.series_minimum_power", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.seriesTerms", + "c": [ + "hmath_symbolic_series_terms" + ], + "python": "hmath.symbolic.series_terms", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.taylorSeries", + "c": [ + "hmath_symbolic_taylor_series" + ], + "python": "hmath.symbolic.taylor_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.laurentSeries", + "c": [ + "hmath_symbolic_laurent_series" + ], + "python": "hmath.symbolic.laurent_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.maclaurinSeries", + "c": [ + "hmath_symbolic_maclaurin_series" + ], + "python": "hmath.symbolic.maclaurin_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.formalPowerSeries", + "c": [ + "hmath_symbolic_formal_power_series" + ], + "python": "hmath.symbolic.formal_power_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.multiplyFormalSeries", + "c": [ + "hmath_symbolic_multiply_formal_series" + ], + "python": "hmath.symbolic.multiply_formal_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.reciprocalFormalSeries", + "c": [ + "hmath_symbolic_reciprocal_formal_series" + ], + "python": "hmath.symbolic.reciprocal_formal_series", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.fromPolynomial", + "c": [ + "hmath_symbolic_from_polynomial" + ], + "python": "hmath.symbolic.from_polynomial", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Relation", + "c": [ + "hmath_symbolic_relation_create" + ], + "python": "hmath.symbolic.Relation", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Truth", + "c": [ + "hmath_symbolic_truth_create" + ], + "python": "hmath.symbolic.Truth", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Unresolved", + "c": [ + "hmath_symbolic_unresolved_create" + ], + "python": "hmath.symbolic.Unresolved", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.simplifyRelation", + "c": [ + "hmath_symbolic_simplify_relation" + ], + "python": "hmath.symbolic.simplify_relation", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.solveLinearInequality", + "c": [ + "hmath_symbolic_solve_linear_inequality" + ], + "python": "hmath.symbolic.solve_linear_inequality", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Inconsistent", + "c": [ + "hmath_symbolic_inconsistent_create" + ], + "python": "hmath.symbolic.Inconsistent", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.ParametricSolution", + "c": [ + "hmath_symbolic_parametric_solution_create" + ], + "python": "hmath.symbolic.ParametricSolution", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.solveLinearEquations", + "c": [ + "hmath_symbolic_solve_linear_equations" + ], + "python": "hmath.symbolic.solve_linear_equations", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicMatrix", + "c": [ + "hmath_symbolic_symbolic_matrix" + ], + "python": "hmath.symbolic.symbolic_matrix", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.matrixExpressions", + "c": [ + "hmath_symbolic_matrix_expressions" + ], + "python": "hmath.symbolic.matrix_expressions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.matrixAdd", + "c": [ + "hmath_symbolic_matrix_add" + ], + "python": "hmath.symbolic.matrix_add", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.matrixMultiply", + "c": [ + "hmath_symbolic_matrix_multiply" + ], + "python": "hmath.symbolic.matrix_multiply", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicDeterminant", + "c": [ + "hmath_symbolic_symbolic_determinant" + ], + "python": "hmath.symbolic.symbolic_determinant", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.Guarded", + "c": [ + "hmath_symbolic_guarded_create" + ], + "python": "hmath.symbolic.Guarded", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.guardedValue", + "c": [ + "hmath_symbolic_guarded_value" + ], + "python": "hmath.symbolic.guarded_value", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.requiredConditions", + "c": [ + "hmath_symbolic_required_conditions" + ], + "python": "hmath.symbolic.required_conditions", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicEigenvalues", + "c": [ + "hmath_symbolic_symbolic_eigenvalues" + ], + "python": "hmath.symbolic.symbolic_eigenvalues", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.numericalSubstitution", + "c": [ + "hmath_symbolic_numerical_substitution" + ], + "python": "hmath.symbolic.numerical_substitution", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.toLaTeX", + "c": [ + "hmath_symbolic_to_la_te_x" + ], + "python": "hmath.symbolic.to_la_te_x", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Symbolic.toMathML", + "c": [ + "hmath_symbolic_to_math_ml" + ], + "python": "hmath.symbolic.to_math_ml", + "specializations": [ + "original exact Rational/Double expression domain; lossless positioned AST and original ExprError" + ] + }, + { + "symbol": "HMath.Expression.BinaryOp", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.BinaryOp", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Bindings", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Bindings", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Builtin", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Builtin", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Compiled", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Compiled", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.ErrorKind", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.ErrorKind", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.ExprNode", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.ExprNode", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.ExpressionCache", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.ExpressionCache", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.NamedConstant", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.NamedConstant", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Precision", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Precision", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Registry", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Registry", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.UnaryOp", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.UnaryOp", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Expression.Value", + "c": [ + "hmath_value" + ], + "python": "hmath.expression.Value", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.Assumptions", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.Assumptions", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.Direction", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.Direction", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.LimitResult", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.LimitResult", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.LinearSolution", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.LinearSolution", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.Pattern", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.Pattern", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.Property", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.Property", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.RelationOp", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.RelationOp", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.RelationResult", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.RelationResult", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + }, + { + "symbol": "HMath.Symbolic.SymbolicMatrix", + "c": [ + "hmath_value" + ], + "python": "hmath.symbolic.SymbolicMatrix", + "specializations": [ + "original typed record/sum/opaque value; explicit closed enum or shared Value representation" + ] + } + ] +} diff --git a/bindings/schema/expression.json b/bindings/schema/expression.json new file mode 100644 index 0000000..9ea4e25 --- /dev/null +++ b/bindings/schema/expression.json @@ -0,0 +1,2955 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Expression", + "name": "SourcePos", + "arguments": [ + [ + "offset", + "Int" + ], + [ + "line", + "Int" + ], + [ + "column", + "Int" + ] + ], + "result": "SourcePos", + "expression": "E.SourcePos", + "python": "source_pos", + "c": "hmath_expression_source_pos_create" + }, + { + "module": "HMath.Expression", + "name": "unknownPosition", + "arguments": [], + "result": "SourcePos", + "expression": "E.unknownPosition", + "python": "unknown_position", + "c": "hmath_expression_unknown_position" + }, + { + "module": "HMath.Expression", + "name": "sourceOffset", + "arguments": [ + [ + "position", + "SourcePos" + ] + ], + "result": "Int", + "expression": "E.sourceOffset", + "python": "source_offset", + "c": "hmath_expression_source_offset" + }, + { + "module": "HMath.Expression", + "name": "sourceLine", + "arguments": [ + [ + "position", + "SourcePos" + ] + ], + "result": "Int", + "expression": "E.sourceLine", + "python": "source_line", + "c": "hmath_expression_source_line" + }, + { + "module": "HMath.Expression", + "name": "sourceColumn", + "arguments": [ + [ + "position", + "SourcePos" + ] + ], + "result": "Int", + "expression": "E.sourceColumn", + "python": "source_column", + "c": "hmath_expression_source_column" + }, + { + "module": "HMath.Expression", + "name": "Negate", + "arguments": [], + "result": "UnaryOp", + "expression": "E.Negate", + "python": "negate", + "c": "hmath_expression_negate_create" + }, + { + "module": "HMath.Expression", + "name": "Add", + "arguments": [], + "result": "BinaryOp", + "expression": "E.Add", + "python": "add", + "c": "hmath_expression_add_create" + }, + { + "module": "HMath.Expression", + "name": "Subtract", + "arguments": [], + "result": "BinaryOp", + "expression": "E.Subtract", + "python": "subtract", + "c": "hmath_expression_subtract_create" + }, + { + "module": "HMath.Expression", + "name": "Multiply", + "arguments": [], + "result": "BinaryOp", + "expression": "E.Multiply", + "python": "multiply", + "c": "hmath_expression_multiply_create" + }, + { + "module": "HMath.Expression", + "name": "Divide", + "arguments": [], + "result": "BinaryOp", + "expression": "E.Divide", + "python": "divide", + "c": "hmath_expression_divide_create" + }, + { + "module": "HMath.Expression", + "name": "Power", + "arguments": [], + "result": "BinaryOp", + "expression": "E.Power", + "python": "power", + "c": "hmath_expression_power_create" + }, + { + "module": "HMath.Expression", + "name": "Pi", + "arguments": [], + "result": "NamedConstant", + "expression": "E.Pi", + "python": "pi", + "c": "hmath_expression_pi_create" + }, + { + "module": "HMath.Expression", + "name": "Euler", + "arguments": [], + "result": "NamedConstant", + "expression": "E.Euler", + "python": "euler", + "c": "hmath_expression_euler_create" + }, + { + "module": "HMath.Expression", + "name": "Tau", + "arguments": [], + "result": "NamedConstant", + "expression": "E.Tau", + "python": "tau", + "c": "hmath_expression_tau_create" + }, + { + "module": "HMath.Expression", + "name": "ExactRational", + "arguments": [], + "result": "Precision", + "expression": "E.ExactRational", + "python": "exact_rational", + "c": "hmath_expression_exact_rational_create" + }, + { + "module": "HMath.Expression", + "name": "Float64", + "arguments": [], + "result": "Precision", + "expression": "E.Float64", + "python": "float64", + "c": "hmath_expression_float64_create" + }, + { + "module": "HMath.Expression", + "name": "SyntaxError", + "arguments": [], + "result": "ErrorKind", + "expression": "E.SyntaxError", + "python": "syntax_error", + "c": "hmath_expression_syntax_error_create" + }, + { + "module": "HMath.Expression", + "name": "UnknownName", + "arguments": [], + "result": "ErrorKind", + "expression": "E.UnknownName", + "python": "unknown_name", + "c": "hmath_expression_unknown_name_create" + }, + { + "module": "HMath.Expression", + "name": "TypeMismatch", + "arguments": [], + "result": "ErrorKind", + "expression": "E.TypeMismatch", + "python": "type_mismatch", + "c": "hmath_expression_type_mismatch_create" + }, + { + "module": "HMath.Expression", + "name": "DomainFailure", + "arguments": [], + "result": "ErrorKind", + "expression": "E.DomainFailure", + "python": "domain_failure", + "c": "hmath_expression_domain_failure_create" + }, + { + "module": "HMath.Expression", + "name": "NonFinite", + "arguments": [], + "result": "ErrorKind", + "expression": "E.NonFinite", + "python": "non_finite", + "c": "hmath_expression_non_finite_create" + }, + { + "module": "HMath.Expression", + "name": "StepLimit", + "arguments": [], + "result": "ErrorKind", + "expression": "E.StepLimit", + "python": "step_limit", + "c": "hmath_expression_step_limit_create" + }, + { + "module": "HMath.Expression", + "name": "DepthLimit", + "arguments": [], + "result": "ErrorKind", + "expression": "E.DepthLimit", + "python": "depth_limit", + "c": "hmath_expression_depth_limit_create" + }, + { + "module": "HMath.Expression", + "name": "MemoryLimit", + "arguments": [], + "result": "ErrorKind", + "expression": "E.MemoryLimit", + "python": "memory_limit", + "c": "hmath_expression_memory_limit_create" + }, + { + "module": "HMath.Expression", + "name": "InvalidLimits", + "arguments": [], + "result": "ErrorKind", + "expression": "E.InvalidLimits", + "python": "invalid_limits", + "c": "hmath_expression_invalid_limits_create" + }, + { + "module": "HMath.Expression", + "name": "Unsupported", + "arguments": [], + "result": "ErrorKind", + "expression": "E.Unsupported", + "python": "unsupported", + "c": "hmath_expression_unsupported_create" + }, + { + "module": "HMath.Expression", + "name": "Sin", + "arguments": [], + "result": "Builtin", + "expression": "E.Sin", + "python": "sin", + "c": "hmath_expression_sin_create" + }, + { + "module": "HMath.Expression", + "name": "Cos", + "arguments": [], + "result": "Builtin", + "expression": "E.Cos", + "python": "cos", + "c": "hmath_expression_cos_create" + }, + { + "module": "HMath.Expression", + "name": "Tan", + "arguments": [], + "result": "Builtin", + "expression": "E.Tan", + "python": "tan", + "c": "hmath_expression_tan_create" + }, + { + "module": "HMath.Expression", + "name": "Exp", + "arguments": [], + "result": "Builtin", + "expression": "E.Exp", + "python": "exp", + "c": "hmath_expression_exp_create" + }, + { + "module": "HMath.Expression", + "name": "Log", + "arguments": [], + "result": "Builtin", + "expression": "E.Log", + "python": "log", + "c": "hmath_expression_log_create" + }, + { + "module": "HMath.Expression", + "name": "Sqrt", + "arguments": [], + "result": "Builtin", + "expression": "E.Sqrt", + "python": "sqrt", + "c": "hmath_expression_sqrt_create" + }, + { + "module": "HMath.Expression", + "name": "Abs", + "arguments": [], + "result": "Builtin", + "expression": "E.Abs", + "python": "abs", + "c": "hmath_expression_abs_create" + }, + { + "module": "HMath.Expression", + "name": "Signum", + "arguments": [], + "result": "Builtin", + "expression": "E.Signum", + "python": "signum", + "c": "hmath_expression_signum_create" + }, + { + "module": "HMath.Expression", + "name": "Floor", + "arguments": [], + "result": "Builtin", + "expression": "E.Floor", + "python": "floor", + "c": "hmath_expression_floor_create" + }, + { + "module": "HMath.Expression", + "name": "Ceiling", + "arguments": [], + "result": "Builtin", + "expression": "E.Ceiling", + "python": "ceiling", + "c": "hmath_expression_ceiling_create" + }, + { + "module": "HMath.Expression", + "name": "Min", + "arguments": [], + "result": "Builtin", + "expression": "E.Min", + "python": "min", + "c": "hmath_expression_min_create" + }, + { + "module": "HMath.Expression", + "name": "Max", + "arguments": [], + "result": "Builtin", + "expression": "E.Max", + "python": "max", + "c": "hmath_expression_max_create" + }, + { + "module": "HMath.Expression", + "name": "Asin", + "arguments": [], + "result": "Builtin", + "expression": "E.Asin", + "python": "asin", + "c": "hmath_expression_asin_create" + }, + { + "module": "HMath.Expression", + "name": "Acos", + "arguments": [], + "result": "Builtin", + "expression": "E.Acos", + "python": "acos", + "c": "hmath_expression_acos_create" + }, + { + "module": "HMath.Expression", + "name": "Atan", + "arguments": [], + "result": "Builtin", + "expression": "E.Atan", + "python": "atan", + "c": "hmath_expression_atan_create" + }, + { + "module": "HMath.Expression", + "name": "Sinh", + "arguments": [], + "result": "Builtin", + "expression": "E.Sinh", + "python": "sinh", + "c": "hmath_expression_sinh_create" + }, + { + "module": "HMath.Expression", + "name": "Cosh", + "arguments": [], + "result": "Builtin", + "expression": "E.Cosh", + "python": "cosh", + "c": "hmath_expression_cosh_create" + }, + { + "module": "HMath.Expression", + "name": "Tanh", + "arguments": [], + "result": "Builtin", + "expression": "E.Tanh", + "python": "tanh", + "c": "hmath_expression_tanh_create" + }, + { + "module": "HMath.Expression", + "name": "Expr", + "arguments": [ + [ + "position", + "SourcePos" + ], + [ + "node", + "ExprNode" + ] + ], + "result": "Expr", + "expression": "E.Expr", + "python": "expr", + "c": "hmath_expression_expr_create" + }, + { + "module": "HMath.Expression", + "name": "expressionPosition", + "arguments": [ + [ + "expression", + "Expr" + ] + ], + "result": "SourcePos", + "expression": "E.expressionPosition", + "python": "expression_position", + "c": "hmath_expression_expression_position" + }, + { + "module": "HMath.Expression", + "name": "expressionNode", + "arguments": [ + [ + "expression", + "Expr" + ] + ], + "result": "ExprNode", + "expression": "E.expressionNode", + "python": "expression_node", + "c": "hmath_expression_expression_node" + }, + { + "module": "HMath.Expression", + "name": "Literal", + "arguments": [ + [ + "value", + "Rational" + ] + ], + "result": "ExprNode", + "expression": "E.Literal", + "python": "literal", + "c": "hmath_expression_literal_create" + }, + { + "module": "HMath.Expression", + "name": "Variable", + "arguments": [ + [ + "name", + "String" + ] + ], + "result": "ExprNode", + "expression": "E.Variable", + "python": "variable", + "c": "hmath_expression_variable_create" + }, + { + "module": "HMath.Expression", + "name": "Constant", + "arguments": [ + [ + "constant", + "NamedConstant" + ] + ], + "result": "ExprNode", + "expression": "E.Constant", + "python": "constant", + "c": "hmath_expression_constant_create" + }, + { + "module": "HMath.Expression", + "name": "Unary", + "arguments": [ + [ + "operator", + "UnaryOp" + ], + [ + "child", + "Expr" + ] + ], + "result": "ExprNode", + "expression": "E.Unary", + "python": "unary", + "c": "hmath_expression_unary_create" + }, + { + "module": "HMath.Expression", + "name": "Binary", + "arguments": [ + [ + "operator", + "BinaryOp" + ], + [ + "left", + "Expr" + ], + [ + "right", + "Expr" + ] + ], + "result": "ExprNode", + "expression": "E.Binary", + "python": "binary", + "c": "hmath_expression_binary_create" + }, + { + "module": "HMath.Expression", + "name": "Call", + "arguments": [ + [ + "name", + "String" + ], + [ + "arguments", + "[Expr]" + ] + ], + "result": "ExprNode", + "expression": "E.Call", + "python": "call", + "c": "hmath_expression_call_create" + }, + { + "module": "HMath.Expression", + "name": "Let", + "arguments": [ + [ + "name", + "String" + ], + [ + "value", + "Expr" + ], + [ + "body", + "Expr" + ] + ], + "result": "ExprNode", + "expression": "E.Let", + "python": "let", + "c": "hmath_expression_let_create" + }, + { + "module": "HMath.Expression", + "name": "literal", + "arguments": [ + [ + "value", + "Rational" + ] + ], + "result": "Expr", + "expression": "E.literal", + "python": "literal", + "c": "hmath_expression_literal" + }, + { + "module": "HMath.Expression", + "name": "variable", + "arguments": [ + [ + "name", + "String" + ] + ], + "result": "Expr", + "expression": "E.variable", + "python": "variable", + "c": "hmath_expression_variable" + }, + { + "module": "HMath.Expression", + "name": "constant", + "arguments": [ + [ + "constant", + "NamedConstant" + ] + ], + "result": "Expr", + "expression": "E.constant", + "python": "constant", + "c": "hmath_expression_constant" + }, + { + "module": "HMath.Expression", + "name": "unary", + "arguments": [ + [ + "operator", + "UnaryOp" + ], + [ + "child", + "Expr" + ] + ], + "result": "Expr", + "expression": "E.unary", + "python": "unary", + "c": "hmath_expression_unary" + }, + { + "module": "HMath.Expression", + "name": "binary", + "arguments": [ + [ + "operator", + "BinaryOp" + ], + [ + "left", + "Expr" + ], + [ + "right", + "Expr" + ] + ], + "result": "Expr", + "expression": "E.binary", + "python": "binary", + "c": "hmath_expression_binary" + }, + { + "module": "HMath.Expression", + "name": "call", + "arguments": [ + [ + "name", + "String" + ], + [ + "arguments", + "[Expr]" + ] + ], + "result": "Expr", + "expression": "E.call", + "python": "call", + "c": "hmath_expression_call" + }, + { + "module": "HMath.Expression", + "name": "letIn", + "arguments": [ + [ + "name", + "String" + ], + [ + "value", + "Expr" + ], + [ + "body", + "Expr" + ] + ], + "result": "Expr", + "expression": "E.letIn", + "python": "let_in", + "c": "hmath_expression_let_in" + }, + { + "module": "HMath.Expression", + "name": "Limits", + "arguments": [ + [ + "maximum_steps", + "Int" + ], + [ + "maximum_depth", + "Int" + ], + [ + "maximum_nodes", + "Int" + ], + [ + "maximum_input_chars", + "Int" + ], + [ + "maximum_integer_bits", + "Int" + ], + [ + "maximum_cache_entries", + "Int" + ] + ], + "result": "Limits", + "expression": "E.Limits", + "python": "limits", + "c": "hmath_expression_limits_create" + }, + { + "module": "HMath.Expression", + "name": "defaultLimits", + "arguments": [], + "result": "Limits", + "expression": "E.defaultLimits", + "python": "default_limits", + "c": "hmath_expression_default_limits" + }, + { + "module": "HMath.Expression", + "name": "maximumSteps", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumSteps", + "python": "maximum_steps", + "c": "hmath_expression_maximum_steps" + }, + { + "module": "HMath.Expression", + "name": "maximumDepth", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumDepth", + "python": "maximum_depth", + "c": "hmath_expression_maximum_depth" + }, + { + "module": "HMath.Expression", + "name": "maximumNodes", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumNodes", + "python": "maximum_nodes", + "c": "hmath_expression_maximum_nodes" + }, + { + "module": "HMath.Expression", + "name": "maximumInputChars", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumInputChars", + "python": "maximum_input_chars", + "c": "hmath_expression_maximum_input_chars" + }, + { + "module": "HMath.Expression", + "name": "maximumIntegerBits", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumIntegerBits", + "python": "maximum_integer_bits", + "c": "hmath_expression_maximum_integer_bits" + }, + { + "module": "HMath.Expression", + "name": "maximumCacheEntries", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Int", + "expression": "E.maximumCacheEntries", + "python": "maximum_cache_entries", + "c": "hmath_expression_maximum_cache_entries" + }, + { + "module": "HMath.Expression", + "name": "ExprError", + "arguments": [ + [ + "kind", + "ErrorKind" + ], + [ + "position", + "SourcePos" + ], + [ + "message", + "String" + ] + ], + "result": "ExprError", + "expression": "E.ExprError", + "python": "expr_error", + "c": "hmath_expression_expr_error_create" + }, + { + "module": "HMath.Expression", + "name": "errorKind", + "arguments": [ + [ + "error", + "ExprError" + ] + ], + "result": "ErrorKind", + "expression": "E.errorKind", + "python": "error_kind", + "c": "hmath_expression_error_kind_get" + }, + { + "module": "HMath.Expression", + "name": "errorPosition", + "arguments": [ + [ + "error", + "ExprError" + ] + ], + "result": "SourcePos", + "expression": "E.errorPosition", + "python": "error_position", + "c": "hmath_expression_error_position" + }, + { + "module": "HMath.Expression", + "name": "errorMessage", + "arguments": [ + [ + "error", + "ExprError" + ] + ], + "result": "String", + "expression": "E.errorMessage", + "python": "error_message", + "c": "hmath_expression_error_message" + }, + { + "module": "HMath.Expression", + "name": "validateLimits", + "arguments": [ + [ + "limits", + "Limits" + ] + ], + "result": "Unit", + "expression": "E.validateLimits", + "python": "validate_limits", + "c": "hmath_expression_validate_limits" + }, + { + "module": "HMath.Expression", + "name": "validateExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Unit", + "expression": "E.validateExpression", + "python": "validate_expression", + "c": "hmath_expression_validate_expression" + }, + { + "module": "HMath.Expression", + "name": "parseExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "source", + "String" + ] + ], + "result": "Expr", + "expression": "E.parseExpression", + "python": "parse_expression", + "c": "hmath_expression_parse_expression" + }, + { + "module": "HMath.Expression", + "name": "prettyExpression", + "arguments": [ + [ + "expression", + "Expr" + ] + ], + "result": "String", + "expression": "E.prettyExpression", + "python": "pretty_expression", + "c": "hmath_expression_pretty_expression" + }, + { + "module": "HMath.Expression", + "name": "freeVariables", + "arguments": [ + [ + "expression", + "Expr" + ] + ], + "result": "[String]", + "expression": "E.freeVariables", + "python": "free_variables", + "c": "hmath_expression_free_variables" + }, + { + "module": "HMath.Expression", + "name": "ExactValue", + "arguments": [ + [ + "value", + "Rational" + ] + ], + "result": "ExpressionValue", + "expression": "E.ExactValue", + "python": "exact_value", + "c": "hmath_expression_exact_value_create" + }, + { + "module": "HMath.Expression", + "name": "FloatValue", + "arguments": [ + [ + "value", + "Double" + ] + ], + "result": "ExpressionValue", + "expression": "E.FloatValue", + "python": "float_value", + "c": "hmath_expression_float_value_create" + }, + { + "module": "HMath.Expression", + "name": "defaultRegistry", + "arguments": [], + "result": "Registry", + "expression": "E.defaultRegistry", + "python": "default_registry", + "c": "hmath_expression_default_registry" + }, + { + "module": "HMath.Expression", + "name": "emptyRegistry", + "arguments": [], + "result": "Registry", + "expression": "E.emptyRegistry", + "python": "empty_registry", + "c": "hmath_expression_empty_registry" + }, + { + "module": "HMath.Expression", + "name": "registerFunction", + "arguments": [ + [ + "name", + "String" + ], + [ + "builtin", + "Builtin" + ], + [ + "registry", + "Registry" + ] + ], + "result": "Registry", + "expression": "E.registerFunction", + "python": "register_function", + "c": "hmath_expression_register_function" + }, + { + "module": "HMath.Expression", + "name": "allowedFunctions", + "arguments": [ + [ + "registry", + "Registry" + ] + ], + "result": "[String]", + "expression": "E.allowedFunctions", + "python": "allowed_functions", + "c": "hmath_expression_allowed_functions" + }, + { + "module": "HMath.Expression", + "name": "typeCheckExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "precision", + "Precision" + ], + [ + "registry", + "Registry" + ], + [ + "bindings", + "Bindings" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Precision", + "expression": "E.typeCheckExpression", + "python": "type_check_expression", + "c": "hmath_expression_type_check_expression" + }, + { + "module": "HMath.Expression", + "name": "evaluateExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "precision", + "Precision" + ], + [ + "registry", + "Registry" + ], + [ + "bindings", + "Bindings" + ], + [ + "expression", + "Expr" + ] + ], + "result": "ExpressionValue", + "expression": "E.evaluateExpression", + "python": "evaluate_expression", + "c": "hmath_expression_evaluate_expression" + }, + { + "module": "HMath.Expression", + "name": "evaluateText", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "precision", + "Precision" + ], + [ + "registry", + "Registry" + ], + [ + "bindings", + "Bindings" + ], + [ + "source", + "String" + ] + ], + "result": "ExpressionValue", + "expression": "E.evaluateText", + "python": "evaluate_text", + "c": "hmath_expression_evaluate_text" + }, + { + "module": "HMath.Expression", + "name": "evaluateCompiled", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "precision", + "Precision" + ], + [ + "registry", + "Registry" + ], + [ + "bindings", + "Bindings" + ], + [ + "compiled", + "Compiled" + ] + ], + "result": "ExpressionValue", + "expression": "E.evaluateCompiled", + "python": "evaluate_compiled", + "c": "hmath_expression_evaluate_compiled" + }, + { + "module": "HMath.Expression", + "name": "compileExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Compiled", + "expression": "E.compileExpression", + "python": "compile_expression", + "c": "hmath_expression_compile_expression" + }, + { + "module": "HMath.Expression", + "name": "compiledNodeCount", + "arguments": [ + [ + "compiled", + "Compiled" + ] + ], + "result": "Int", + "expression": "E.compiledNodeCount", + "python": "compiled_node_count", + "c": "hmath_expression_compiled_node_count" + }, + { + "module": "HMath.Expression", + "name": "optimizeExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "precision", + "Precision" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "E.optimizeExpression", + "python": "optimize_expression", + "c": "hmath_expression_optimize_expression" + }, + { + "module": "HMath.Expression", + "name": "emptyExpressionCache", + "arguments": [], + "result": "ExpressionCache", + "expression": "E.emptyExpressionCache", + "python": "empty_expression_cache", + "c": "hmath_expression_empty_expression_cache" + }, + { + "module": "HMath.Expression", + "name": "cacheSize", + "arguments": [ + [ + "cache", + "ExpressionCache" + ] + ], + "result": "Int", + "expression": "E.cacheSize", + "python": "cache_size", + "c": "hmath_expression_cache_size" + }, + { + "module": "HMath.Expression", + "name": "cachedExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "source", + "String" + ], + [ + "cache", + "ExpressionCache" + ] + ], + "result": "(Compiled,ExpressionCache)", + "expression": "E.cachedExpression", + "python": "cached_expression", + "c": "hmath_expression_cached_expression" + }, + { + "module": "HMath.Expression", + "name": "formatScientific", + "arguments": [ + [ + "digits", + "Int" + ], + [ + "value", + "ExpressionValue" + ] + ], + "result": "String", + "expression": "E.formatScientific", + "python": "format_scientific", + "c": "hmath_expression_format_scientific" + }, + { + "module": "HMath.Expression", + "name": "formatRadix", + "arguments": [ + [ + "radix", + "Int" + ], + [ + "value", + "ExpressionValue" + ] + ], + "result": "String", + "expression": "E.formatRadix", + "python": "format_radix", + "c": "hmath_expression_format_radix" + }, + { + "module": "HMath.Expression", + "name": "serializeExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "String", + "expression": "E.serializeExpression", + "python": "serialize_expression", + "c": "hmath_expression_serialize_expression" + }, + { + "module": "HMath.Expression", + "name": "deserializeExpression", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "serialized", + "String" + ] + ], + "result": "Expr", + "expression": "E.deserializeExpression", + "python": "deserialize_expression", + "c": "hmath_expression_deserialize_expression" + }, + { + "module": "HMath.Expression", + "name": "expressionHash", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Word64", + "expression": "E.expressionHash", + "python": "expression_hash", + "c": "hmath_expression_expression_hash" + }, + { + "module": "HMath.Symbolic", + "name": "Real", + "arguments": [], + "result": "Property", + "expression": "S.Real", + "python": "real", + "c": "hmath_symbolic_real_create" + }, + { + "module": "HMath.Symbolic", + "name": "NonZero", + "arguments": [], + "result": "Property", + "expression": "S.NonZero", + "python": "non_zero", + "c": "hmath_symbolic_non_zero_create" + }, + { + "module": "HMath.Symbolic", + "name": "Positive", + "arguments": [], + "result": "Property", + "expression": "S.Positive", + "python": "positive", + "c": "hmath_symbolic_positive_create" + }, + { + "module": "HMath.Symbolic", + "name": "NonNegative", + "arguments": [], + "result": "Property", + "expression": "S.NonNegative", + "python": "non_negative", + "c": "hmath_symbolic_non_negative_create" + }, + { + "module": "HMath.Symbolic", + "name": "Integral", + "arguments": [], + "result": "Property", + "expression": "S.Integral", + "python": "integral", + "c": "hmath_symbolic_integral_create" + }, + { + "module": "HMath.Symbolic", + "name": "Negative", + "arguments": [], + "result": "Property", + "expression": "S.Negative", + "python": "negative", + "c": "hmath_symbolic_negative_create" + }, + { + "module": "HMath.Symbolic", + "name": "NonPositive", + "arguments": [], + "result": "Property", + "expression": "S.NonPositive", + "python": "non_positive", + "c": "hmath_symbolic_non_positive_create" + }, + { + "module": "HMath.Symbolic", + "name": "FromLeft", + "arguments": [], + "result": "Direction", + "expression": "S.FromLeft", + "python": "from_left", + "c": "hmath_symbolic_from_left_create" + }, + { + "module": "HMath.Symbolic", + "name": "FromRight", + "arguments": [], + "result": "Direction", + "expression": "S.FromRight", + "python": "from_right", + "c": "hmath_symbolic_from_right_create" + }, + { + "module": "HMath.Symbolic", + "name": "TwoSided", + "arguments": [], + "result": "Direction", + "expression": "S.TwoSided", + "python": "two_sided", + "c": "hmath_symbolic_two_sided_create" + }, + { + "module": "HMath.Symbolic", + "name": "Equal", + "arguments": [], + "result": "RelationOp", + "expression": "S.Equal", + "python": "equal", + "c": "hmath_symbolic_equal_create" + }, + { + "module": "HMath.Symbolic", + "name": "NotEqual", + "arguments": [], + "result": "RelationOp", + "expression": "S.NotEqual", + "python": "not_equal", + "c": "hmath_symbolic_not_equal_create" + }, + { + "module": "HMath.Symbolic", + "name": "Less", + "arguments": [], + "result": "RelationOp", + "expression": "S.Less", + "python": "less", + "c": "hmath_symbolic_less_create" + }, + { + "module": "HMath.Symbolic", + "name": "LessEqual", + "arguments": [], + "result": "RelationOp", + "expression": "S.LessEqual", + "python": "less_equal", + "c": "hmath_symbolic_less_equal_create" + }, + { + "module": "HMath.Symbolic", + "name": "Greater", + "arguments": [], + "result": "RelationOp", + "expression": "S.Greater", + "python": "greater", + "c": "hmath_symbolic_greater_create" + }, + { + "module": "HMath.Symbolic", + "name": "GreaterEqual", + "arguments": [], + "result": "RelationOp", + "expression": "S.GreaterEqual", + "python": "greater_equal", + "c": "hmath_symbolic_greater_equal_create" + }, + { + "module": "HMath.Symbolic", + "name": "assumptions", + "arguments": [ + [ + "entries", + "[(String,[Property])]" + ] + ], + "result": "Assumptions", + "expression": "S.assumptions", + "python": "assumptions", + "c": "hmath_symbolic_assumptions" + }, + { + "module": "HMath.Symbolic", + "name": "noAssumptions", + "arguments": [], + "result": "Assumptions", + "expression": "S.noAssumptions", + "python": "no_assumptions", + "c": "hmath_symbolic_no_assumptions" + }, + { + "module": "HMath.Symbolic", + "name": "proves", + "arguments": [ + [ + "assumptions", + "Assumptions" + ], + [ + "property", + "Property" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Bool", + "expression": "S.proves", + "python": "proves", + "c": "hmath_symbolic_proves" + }, + { + "module": "HMath.Symbolic", + "name": "SymbolicOptions", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "assumptions", + "Assumptions" + ] + ], + "result": "SymbolicOptions", + "expression": "S.SymbolicOptions", + "python": "symbolic_options", + "c": "hmath_symbolic_symbolic_options_create" + }, + { + "module": "HMath.Symbolic", + "name": "defaultSymbolicOptions", + "arguments": [], + "result": "SymbolicOptions", + "expression": "S.defaultSymbolicOptions", + "python": "default_symbolic_options", + "c": "hmath_symbolic_default_symbolic_options" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicLimits", + "arguments": [ + [ + "options", + "SymbolicOptions" + ] + ], + "result": "Limits", + "expression": "S.symbolicLimits", + "python": "symbolic_limits", + "c": "hmath_symbolic_symbolic_limits" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicAssumptions", + "arguments": [ + [ + "options", + "SymbolicOptions" + ] + ], + "result": "Assumptions", + "expression": "S.symbolicAssumptions", + "python": "symbolic_assumptions", + "c": "hmath_symbolic_symbolic_assumptions" + }, + { + "module": "HMath.Symbolic", + "name": "normalize", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.normalize", + "python": "normalize", + "c": "hmath_symbolic_normalize" + }, + { + "module": "HMath.Symbolic", + "name": "simplify", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.simplify", + "python": "simplify", + "c": "hmath_symbolic_simplify" + }, + { + "module": "HMath.Symbolic", + "name": "expand", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.expand", + "python": "expand", + "c": "hmath_symbolic_expand" + }, + { + "module": "HMath.Symbolic", + "name": "collectTerms", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.collectTerms", + "python": "collect_terms", + "c": "hmath_symbolic_collect_terms" + }, + { + "module": "HMath.Symbolic", + "name": "trigonometricSimplify", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.trigonometricSimplify", + "python": "trigonometric_simplify", + "c": "hmath_symbolic_trigonometric_simplify" + }, + { + "module": "HMath.Symbolic", + "name": "logarithmicSimplify", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.logarithmicSimplify", + "python": "logarithmic_simplify", + "c": "hmath_symbolic_logarithmic_simplify" + }, + { + "module": "HMath.Symbolic", + "name": "factorPolynomial", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "PolynomialFactorization", + "expression": "S.factorPolynomial", + "python": "factor_polynomial", + "c": "hmath_symbolic_factor_polynomial" + }, + { + "module": "HMath.Symbolic", + "name": "rationalSimplify", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.rationalSimplify", + "python": "rational_simplify", + "c": "hmath_symbolic_rational_simplify" + }, + { + "module": "HMath.Symbolic", + "name": "differentiate", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.differentiate", + "python": "differentiate", + "c": "hmath_symbolic_differentiate" + }, + { + "module": "HMath.Symbolic", + "name": "integrateBasic", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.integrateBasic", + "python": "integrate_basic", + "c": "hmath_symbolic_integrate_basic" + }, + { + "module": "HMath.Symbolic", + "name": "toPolynomial", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Polynomial", + "expression": "S.toPolynomial", + "python": "to_polynomial", + "c": "hmath_symbolic_to_polynomial" + }, + { + "module": "HMath.Symbolic", + "name": "exactPolynomialRoots", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "([(Rational,Int)],Expr)", + "expression": "S.exactPolynomialRoots", + "python": "exact_polynomial_roots", + "c": "hmath_symbolic_exact_polynomial_roots" + }, + { + "module": "HMath.Symbolic", + "name": "numericalPolynomialRoots", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "expression", + "Expr" + ] + ], + "result": "[Complex]", + "expression": "S.numericalPolynomialRoots", + "python": "numerical_polynomial_roots", + "c": "hmath_symbolic_numerical_polynomial_roots" + }, + { + "module": "HMath.Symbolic", + "name": "PolynomialFactorization", + "arguments": [ + [ + "leading", + "Rational" + ], + [ + "terms", + "[(Expr,Int)]" + ] + ], + "result": "PolynomialFactorization", + "expression": "S.PolynomialFactorization", + "python": "polynomial_factorization", + "c": "hmath_symbolic_polynomial_factorization_create" + }, + { + "module": "HMath.Symbolic", + "name": "factorLeading", + "arguments": [ + [ + "factorization", + "PolynomialFactorization" + ] + ], + "result": "Rational", + "expression": "S.factorLeading", + "python": "factor_leading", + "c": "hmath_symbolic_factor_leading" + }, + { + "module": "HMath.Symbolic", + "name": "factorTerms", + "arguments": [ + [ + "factorization", + "PolynomialFactorization" + ] + ], + "result": "[(Expr,Int)]", + "expression": "S.factorTerms", + "python": "factor_terms", + "c": "hmath_symbolic_factor_terms" + }, + { + "module": "HMath.Symbolic", + "name": "substitute", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "bindings", + "[(String,Expr)]" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.substitute", + "python": "substitute", + "c": "hmath_symbolic_substitute" + }, + { + "module": "HMath.Symbolic", + "name": "Any", + "arguments": [ + [ + "name", + "String" + ] + ], + "result": "Pattern", + "expression": "S.Any", + "python": "any", + "c": "hmath_symbolic_any_create" + }, + { + "module": "HMath.Symbolic", + "name": "Exactly", + "arguments": [ + [ + "expression", + "Expr" + ] + ], + "result": "Pattern", + "expression": "S.Exactly", + "python": "exactly", + "c": "hmath_symbolic_exactly_create" + }, + { + "module": "HMath.Symbolic", + "name": "UnaryPattern", + "arguments": [ + [ + "operator", + "UnaryOp" + ], + [ + "child", + "Pattern" + ] + ], + "result": "Pattern", + "expression": "S.UnaryPattern", + "python": "unary_pattern", + "c": "hmath_symbolic_unary_pattern_create" + }, + { + "module": "HMath.Symbolic", + "name": "BinaryPattern", + "arguments": [ + [ + "operator", + "BinaryOp" + ], + [ + "left", + "Pattern" + ], + [ + "right", + "Pattern" + ] + ], + "result": "Pattern", + "expression": "S.BinaryPattern", + "python": "binary_pattern", + "c": "hmath_symbolic_binary_pattern_create" + }, + { + "module": "HMath.Symbolic", + "name": "CallPattern", + "arguments": [ + [ + "name", + "String" + ], + [ + "arguments", + "[Pattern]" + ] + ], + "result": "Pattern", + "expression": "S.CallPattern", + "python": "call_pattern", + "c": "hmath_symbolic_call_pattern_create" + }, + { + "module": "HMath.Symbolic", + "name": "matchPattern", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "pattern", + "Pattern" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Maybe[(String,Expr)]", + "expression": "S.matchPattern", + "python": "match_pattern", + "c": "hmath_symbolic_match_pattern" + }, + { + "module": "HMath.Symbolic", + "name": "RewriteRule", + "arguments": [ + [ + "pattern", + "Pattern" + ], + [ + "replacement", + "Expr" + ], + [ + "requirements", + "[(String,Property)]" + ] + ], + "result": "RewriteRule", + "expression": "S.RewriteRule", + "python": "rewrite_rule", + "c": "hmath_symbolic_rewrite_rule_create" + }, + { + "module": "HMath.Symbolic", + "name": "rewritePattern", + "arguments": [ + [ + "rule", + "RewriteRule" + ] + ], + "result": "Pattern", + "expression": "S.rewritePattern", + "python": "rewrite_pattern", + "c": "hmath_symbolic_rewrite_pattern" + }, + { + "module": "HMath.Symbolic", + "name": "rewriteReplacement", + "arguments": [ + [ + "rule", + "RewriteRule" + ] + ], + "result": "Expr", + "expression": "S.rewriteReplacement", + "python": "rewrite_replacement", + "c": "hmath_symbolic_rewrite_replacement" + }, + { + "module": "HMath.Symbolic", + "name": "rewriteRequirements", + "arguments": [ + [ + "rule", + "RewriteRule" + ] + ], + "result": "[(String,Property)]", + "expression": "S.rewriteRequirements", + "python": "rewrite_requirements", + "c": "hmath_symbolic_rewrite_requirements" + }, + { + "module": "HMath.Symbolic", + "name": "applyRewrite", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "rule", + "RewriteRule" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.applyRewrite", + "python": "apply_rewrite", + "c": "hmath_symbolic_apply_rewrite" + }, + { + "module": "HMath.Symbolic", + "name": "gradient", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variables", + "[String]" + ], + [ + "expression", + "Expr" + ] + ], + "result": "[Expr]", + "expression": "S.gradient", + "python": "gradient", + "c": "hmath_symbolic_gradient" + }, + { + "module": "HMath.Symbolic", + "name": "hessian", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variables", + "[String]" + ], + [ + "expression", + "Expr" + ] + ], + "result": "[[Expr]]", + "expression": "S.hessian", + "python": "hessian", + "c": "hmath_symbolic_hessian" + }, + { + "module": "HMath.Symbolic", + "name": "jacobian", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variables", + "[String]" + ], + [ + "expressions", + "[Expr]" + ] + ], + "result": "[[Expr]]", + "expression": "S.jacobian", + "python": "jacobian", + "c": "hmath_symbolic_jacobian" + }, + { + "module": "HMath.Symbolic", + "name": "integrateByParts", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "u", + "Expr" + ], + [ + "dv", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.integrateByParts", + "python": "integrate_by_parts", + "c": "hmath_symbolic_integrate_by_parts" + }, + { + "module": "HMath.Symbolic", + "name": "integrateSubstitution", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "temporary", + "String" + ], + [ + "inner", + "Expr" + ], + [ + "outer", + "Expr" + ], + [ + "integrand", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.integrateSubstitution", + "python": "integrate_substitution", + "c": "hmath_symbolic_integrate_substitution" + }, + { + "module": "HMath.Symbolic", + "name": "integrateRational", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "numerator", + "Expr" + ], + [ + "denominator", + "Expr" + ] + ], + "result": "Expr", + "expression": "S.integrateRational", + "python": "integrate_rational", + "c": "hmath_symbolic_integrate_rational" + }, + { + "module": "HMath.Symbolic", + "name": "FiniteLimit", + "arguments": [ + [ + "value", + "Rational" + ] + ], + "result": "LimitResult", + "expression": "S.FiniteLimit", + "python": "finite_limit", + "c": "hmath_symbolic_finite_limit_create" + }, + { + "module": "HMath.Symbolic", + "name": "PositiveInfinity", + "arguments": [], + "result": "LimitResult", + "expression": "S.PositiveInfinity", + "python": "positive_infinity", + "c": "hmath_symbolic_positive_infinity_create" + }, + { + "module": "HMath.Symbolic", + "name": "NegativeInfinity", + "arguments": [], + "result": "LimitResult", + "expression": "S.NegativeInfinity", + "python": "negative_infinity", + "c": "hmath_symbolic_negative_infinity_create" + }, + { + "module": "HMath.Symbolic", + "name": "DoesNotExist", + "arguments": [], + "result": "LimitResult", + "expression": "S.DoesNotExist", + "python": "does_not_exist", + "c": "hmath_symbolic_does_not_exist_create" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicLimit", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "center", + "Rational" + ], + [ + "direction", + "Direction" + ], + [ + "expression", + "Expr" + ] + ], + "result": "LimitResult", + "expression": "S.symbolicLimit", + "python": "symbolic_limit", + "c": "hmath_symbolic_symbolic_limit" + }, + { + "module": "HMath.Symbolic", + "name": "Series", + "arguments": [ + [ + "center", + "Rational" + ], + [ + "minimum_power", + "Int" + ], + [ + "terms", + "[Expr]" + ] + ], + "result": "Series", + "expression": "S.Series", + "python": "series", + "c": "hmath_symbolic_series_create" + }, + { + "module": "HMath.Symbolic", + "name": "seriesCenter", + "arguments": [ + [ + "series", + "Series" + ] + ], + "result": "Rational", + "expression": "S.seriesCenter", + "python": "series_center", + "c": "hmath_symbolic_series_center" + }, + { + "module": "HMath.Symbolic", + "name": "seriesMinimumPower", + "arguments": [ + [ + "series", + "Series" + ] + ], + "result": "Int", + "expression": "S.seriesMinimumPower", + "python": "series_minimum_power", + "c": "hmath_symbolic_series_minimum_power" + }, + { + "module": "HMath.Symbolic", + "name": "seriesTerms", + "arguments": [ + [ + "series", + "Series" + ] + ], + "result": "[Expr]", + "expression": "S.seriesTerms", + "python": "series_terms", + "c": "hmath_symbolic_series_terms" + }, + { + "module": "HMath.Symbolic", + "name": "taylorSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "center", + "Rational" + ], + [ + "order", + "Int" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Series", + "expression": "S.taylorSeries", + "python": "taylor_series", + "c": "hmath_symbolic_taylor_series" + }, + { + "module": "HMath.Symbolic", + "name": "laurentSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "center", + "Rational" + ], + [ + "order", + "Int" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Series", + "expression": "S.laurentSeries", + "python": "laurent_series", + "c": "hmath_symbolic_laurent_series" + }, + { + "module": "HMath.Symbolic", + "name": "maclaurinSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "order", + "Int" + ], + [ + "expression", + "Expr" + ] + ], + "result": "Series", + "expression": "S.maclaurinSeries", + "python": "maclaurin_series", + "c": "hmath_symbolic_maclaurin_series" + }, + { + "module": "HMath.Symbolic", + "name": "formalPowerSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "coefficients", + "[Rational]" + ] + ], + "result": "PowerSeries", + "expression": "S.formalPowerSeries", + "python": "formal_power_series", + "c": "hmath_symbolic_formal_power_series" + }, + { + "module": "HMath.Symbolic", + "name": "multiplyFormalSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "left", + "PowerSeries" + ], + [ + "right", + "PowerSeries" + ] + ], + "result": "PowerSeries", + "expression": "S.multiplyFormalSeries", + "python": "multiply_formal_series", + "c": "hmath_symbolic_multiply_formal_series" + }, + { + "module": "HMath.Symbolic", + "name": "reciprocalFormalSeries", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "series", + "PowerSeries" + ] + ], + "result": "PowerSeries", + "expression": "S.reciprocalFormalSeries", + "python": "reciprocal_formal_series", + "c": "hmath_symbolic_reciprocal_formal_series" + }, + { + "module": "HMath.Symbolic", + "name": "fromPolynomial", + "arguments": [ + [ + "variable", + "String" + ], + [ + "polynomial", + "Polynomial" + ] + ], + "result": "Expr", + "expression": "S.fromPolynomial", + "python": "from_polynomial", + "c": "hmath_symbolic_from_polynomial" + }, + { + "module": "HMath.Symbolic", + "name": "Relation", + "arguments": [ + [ + "operator", + "RelationOp" + ], + [ + "left", + "Expr" + ], + [ + "right", + "Expr" + ] + ], + "result": "Relation", + "expression": "S.Relation", + "python": "relation", + "c": "hmath_symbolic_relation_create" + }, + { + "module": "HMath.Symbolic", + "name": "Truth", + "arguments": [ + [ + "value", + "Bool" + ] + ], + "result": "RelationResult", + "expression": "S.Truth", + "python": "truth", + "c": "hmath_symbolic_truth_create" + }, + { + "module": "HMath.Symbolic", + "name": "Unresolved", + "arguments": [ + [ + "relation", + "Relation" + ] + ], + "result": "RelationResult", + "expression": "S.Unresolved", + "python": "unresolved", + "c": "hmath_symbolic_unresolved_create" + }, + { + "module": "HMath.Symbolic", + "name": "simplifyRelation", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "relation", + "Relation" + ] + ], + "result": "RelationResult", + "expression": "S.simplifyRelation", + "python": "simplify_relation", + "c": "hmath_symbolic_simplify_relation" + }, + { + "module": "HMath.Symbolic", + "name": "solveLinearInequality", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variable", + "String" + ], + [ + "relation", + "Relation" + ] + ], + "result": "RelationResult", + "expression": "S.solveLinearInequality", + "python": "solve_linear_inequality", + "c": "hmath_symbolic_solve_linear_inequality" + }, + { + "module": "HMath.Symbolic", + "name": "Inconsistent", + "arguments": [], + "result": "LinearSolution", + "expression": "S.Inconsistent", + "python": "inconsistent", + "c": "hmath_symbolic_inconsistent_create" + }, + { + "module": "HMath.Symbolic", + "name": "ParametricSolution", + "arguments": [ + [ + "bindings", + "[(String,Expr)]" + ], + [ + "free_variables", + "[String]" + ] + ], + "result": "LinearSolution", + "expression": "S.ParametricSolution", + "python": "parametric_solution", + "c": "hmath_symbolic_parametric_solution_create" + }, + { + "module": "HMath.Symbolic", + "name": "solveLinearEquations", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "variables", + "[String]" + ], + [ + "equations", + "[(Expr,Expr)]" + ] + ], + "result": "LinearSolution", + "expression": "S.solveLinearEquations", + "python": "solve_linear_equations", + "c": "hmath_symbolic_solve_linear_equations" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicMatrix", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "rows", + "[[Expr]]" + ] + ], + "result": "SymbolicMatrix", + "expression": "S.symbolicMatrix", + "python": "symbolic_matrix", + "c": "hmath_symbolic_symbolic_matrix" + }, + { + "module": "HMath.Symbolic", + "name": "matrixExpressions", + "arguments": [ + [ + "matrix", + "SymbolicMatrix" + ] + ], + "result": "[[Expr]]", + "expression": "S.matrixExpressions", + "python": "matrix_expressions", + "c": "hmath_symbolic_matrix_expressions" + }, + { + "module": "HMath.Symbolic", + "name": "matrixAdd", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "left", + "SymbolicMatrix" + ], + [ + "right", + "SymbolicMatrix" + ] + ], + "result": "SymbolicMatrix", + "expression": "S.matrixAdd", + "python": "matrix_add", + "c": "hmath_symbolic_matrix_add" + }, + { + "module": "HMath.Symbolic", + "name": "matrixMultiply", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "left", + "SymbolicMatrix" + ], + [ + "right", + "SymbolicMatrix" + ] + ], + "result": "SymbolicMatrix", + "expression": "S.matrixMultiply", + "python": "matrix_multiply", + "c": "hmath_symbolic_matrix_multiply" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicDeterminant", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "matrix", + "SymbolicMatrix" + ] + ], + "result": "Expr", + "expression": "S.symbolicDeterminant", + "python": "symbolic_determinant", + "c": "hmath_symbolic_symbolic_determinant" + }, + { + "module": "HMath.Symbolic", + "name": "Guarded", + "arguments": [ + [ + "value", + "Generic" + ], + [ + "conditions", + "[(Expr,Property)]" + ] + ], + "result": "Guarded", + "expression": "(S.Guarded :: Value -> [(E.Expr,S.Property)] -> S.Guarded Value)", + "python": "guarded", + "c": "hmath_symbolic_guarded_create" + }, + { + "module": "HMath.Symbolic", + "name": "guardedValue", + "arguments": [ + [ + "guarded", + "Guarded" + ] + ], + "result": "Generic", + "expression": "(S.guardedValue :: S.Guarded Value -> Value)", + "python": "guarded_value", + "c": "hmath_symbolic_guarded_value" + }, + { + "module": "HMath.Symbolic", + "name": "requiredConditions", + "arguments": [ + [ + "guarded", + "Guarded" + ] + ], + "result": "[(Expr,Property)]", + "expression": "(S.requiredConditions :: S.Guarded Value -> [(E.Expr,S.Property)])", + "python": "required_conditions", + "c": "hmath_symbolic_required_conditions" + }, + { + "module": "HMath.Symbolic", + "name": "symbolicEigenvalues", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "matrix", + "SymbolicMatrix" + ] + ], + "result": "Guarded[Expr]", + "expression": "S.symbolicEigenvalues", + "python": "symbolic_eigenvalues", + "c": "hmath_symbolic_symbolic_eigenvalues" + }, + { + "module": "HMath.Symbolic", + "name": "numericalSubstitution", + "arguments": [ + [ + "options", + "SymbolicOptions" + ], + [ + "precision", + "Precision" + ], + [ + "bindings", + "[(String,ExpressionValue)]" + ], + [ + "expression", + "Expr" + ] + ], + "result": "ExpressionValue", + "expression": "S.numericalSubstitution", + "python": "numerical_substitution", + "c": "hmath_symbolic_numerical_substitution" + }, + { + "module": "HMath.Symbolic", + "name": "toLaTeX", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "String", + "expression": "S.toLaTeX", + "python": "to_la_te_x", + "c": "hmath_symbolic_to_la_te_x" + }, + { + "module": "HMath.Symbolic", + "name": "toMathML", + "arguments": [ + [ + "limits", + "Limits" + ], + [ + "expression", + "Expr" + ] + ], + "result": "String", + "expression": "S.toMathML", + "python": "to_math_ml", + "c": "hmath_symbolic_to_math_ml" + } + ] +} diff --git a/bindings/schema/foundation-functions.json b/bindings/schema/foundation-functions.json new file mode 100644 index 0000000..abe2a18 --- /dev/null +++ b/bindings/schema/foundation-functions.json @@ -0,0 +1,3416 @@ +{ + "functions": [ + { + "module": "HMath.DataStructure", + "name": "fenwick", + "args": [ + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Fenwick" + ] + ], + "constraints": "", + "signature": "[Integer] -> Either MathError Fenwick", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "fenwickAdd", + "args": [ + [ + "Int" + ], + [ + "Integer" + ], + [ + "Fenwick" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Fenwick" + ] + ], + "constraints": "", + "signature": "Int -> Integer -> Fenwick -> Either MathError Fenwick", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "fenwickPrefix", + "args": [ + [ + "Int" + ], + [ + "Fenwick" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Fenwick -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "fenwickRange", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Fenwick" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Int -> Fenwick -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "segmentTree", + "args": [ + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SegmentTree" + ] + ], + "constraints": "", + "signature": "[Integer] -> Either MathError SegmentTree", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "segmentSet", + "args": [ + [ + "Int" + ], + [ + "Integer" + ], + [ + "SegmentTree" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SegmentTree" + ] + ], + "constraints": "", + "signature": "Int -> Integer -> SegmentTree -> Either MathError SegmentTree", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "segmentRange", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "SegmentTree" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Int -> SegmentTree -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "sparseTable", + "args": [ + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseTable" + ] + ], + "constraints": "", + "signature": "[Integer] -> Either MathError SparseTable", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "sparseMinimum", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "SparseTable" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Int -> SparseTable -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "disjointSparseTable", + "args": [ + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "DisjointSparseTable" + ] + ], + "constraints": "", + "signature": "[Integer] -> Either MathError DisjointSparseTable", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "disjointRange", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "DisjointSparseTable" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Int -> DisjointSparseTable -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "nextGreater", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "Maybe", + [ + "Int" + ] + ] + ], + "constraints": "(Ord a)", + "signature": "[a] -> [Maybe Int]", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "emptyHeap", + "args": [], + "result": [ + "Heap", + [ + "a" + ] + ], + "constraints": "", + "signature": "Heap a", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "heapInsert", + "args": [ + [ + "a" + ], + [ + "Heap", + [ + "a" + ] + ] + ], + "result": [ + "Heap", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "a -> Heap a -> Heap a", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "heapPop", + "args": [ + [ + "Heap", + [ + "a" + ] + ] + ], + "result": [ + "Maybe", + [ + "tuple", + [ + "a" + ], + [ + "Heap", + [ + "a" + ] + ] + ] + ], + "constraints": "(Ord a)", + "signature": "Heap a -> Maybe (a, Heap a)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "heapFromList", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Heap", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "[a] -> Heap a", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "binaryHeap", + "args": [ + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BinaryHeap" + ] + ], + "constraints": "", + "signature": "[Integer] -> Either MathError BinaryHeap", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "binaryInsert", + "args": [ + [ + "Integer" + ], + [ + "BinaryHeap" + ] + ], + "result": [ + "BinaryHeap" + ], + "constraints": "", + "signature": "Integer -> BinaryHeap -> BinaryHeap", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "binaryPop", + "args": [ + [ + "BinaryHeap" + ] + ], + "result": [ + "Maybe", + [ + "tuple", + [ + "Integer" + ], + [ + "BinaryHeap" + ] + ] + ], + "constraints": "", + "signature": "BinaryHeap -> Maybe (Integer, BinaryHeap)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "indexedHeap", + "args": [], + "result": [ + "IndexedHeap" + ], + "constraints": "", + "signature": "IndexedHeap", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "indexedSet", + "args": [ + [ + "Int" + ], + [ + "Integer" + ], + [ + "IndexedHeap" + ] + ], + "result": [ + "IndexedHeap" + ], + "constraints": "", + "signature": "Int -> Integer -> IndexedHeap -> IndexedHeap", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "indexedPop", + "args": [ + [ + "IndexedHeap" + ] + ], + "result": [ + "Maybe", + [ + "tuple", + [ + "tuple", + [ + "Int" + ], + [ + "Integer" + ] + ], + [ + "IndexedHeap" + ] + ] + ], + "constraints": "", + "signature": "IndexedHeap -> Maybe ((Int, Integer), IndexedHeap)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "unionFind", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "UnionFind" + ] + ], + "constraints": "", + "signature": "Int -> Either MathError UnionFind", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "findRoot", + "args": [ + [ + "Int" + ], + [ + "UnionFind" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Int" + ] + ], + "constraints": "", + "signature": "Int -> UnionFind -> Either MathError Int", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "union", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "UnionFind" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "UnionFind" + ] + ], + "constraints": "", + "signature": "Int -> Int -> UnionFind -> Either MathError UnionFind", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "connected", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "UnionFind" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bool" + ] + ], + "constraints": "", + "signature": "Int -> Int -> UnionFind -> Either MathError Bool", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "components", + "args": [ + [ + "UnionFind" + ] + ], + "result": [ + "list", + [ + "list", + [ + "Int" + ] + ] + ], + "constraints": "", + "signature": "UnionFind -> [[Int]]", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "bloom", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bloom" + ] + ], + "constraints": "", + "signature": "Int -> Int -> Either MathError Bloom", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "bloomInsert", + "args": [ + [ + "Word64" + ], + [ + "Bloom" + ] + ], + "result": [ + "Bloom" + ], + "constraints": "", + "signature": "Word64 -> Bloom -> Bloom", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "bloomMember", + "args": [ + [ + "Word64" + ], + [ + "Bloom" + ] + ], + "result": [ + "Bool" + ], + "constraints": "", + "signature": "Word64 -> Bloom -> Bool", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "bloomFalsePositiveBound", + "args": [ + [ + "Bloom" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "Bloom -> Double", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "countMin", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "CountMin" + ] + ], + "constraints": "", + "signature": "Int -> Int -> Either MathError CountMin", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "countMinAdd", + "args": [ + [ + "Word64" + ], + [ + "Integer" + ], + [ + "CountMin" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "CountMin" + ] + ], + "constraints": "", + "signature": "Word64 -> Integer -> CountMin -> Either MathError CountMin", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "countMinEstimate", + "args": [ + [ + "Word64" + ], + [ + "CountMin" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "Word64 -> CountMin -> Integer", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "countMinErrorBound", + "args": [ + [ + "CountMin" + ] + ], + "result": [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "CountMin -> (Double, Double)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "hyperLogLog", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "HyperLogLog" + ] + ], + "constraints": "", + "signature": "Int -> Either MathError HyperLogLog", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "hllAdd", + "args": [ + [ + "Word64" + ], + [ + "HyperLogLog" + ] + ], + "result": [ + "HyperLogLog" + ], + "constraints": "", + "signature": "Word64 -> HyperLogLog -> HyperLogLog", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "hllEstimate", + "args": [ + [ + "HyperLogLog" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "HyperLogLog -> Double", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "reservoir", + "args": [ + [ + "Int" + ], + [ + "Word64" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Reservoir", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Int -> Word64 -> Either MathError (Reservoir a)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "reservoirAdd", + "args": [ + [ + "a" + ], + [ + "Reservoir", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Reservoir", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "a -> Reservoir a -> Either MathError (Reservoir a)", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "reservoirValues", + "args": [ + [ + "Reservoir", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "Reservoir a -> [a]", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "onlineQuantiles", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "OnlineQuantiles" + ] + ], + "constraints": "", + "signature": "Int -> Either MathError OnlineQuantiles", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "quantileAdd", + "args": [ + [ + "Double" + ], + [ + "OnlineQuantiles" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "OnlineQuantiles" + ] + ], + "constraints": "", + "signature": "Double -> OnlineQuantiles -> Either MathError OnlineQuantiles", + "constructor": false + }, + { + "module": "HMath.DataStructure", + "name": "onlineQuantile", + "args": [ + [ + "Double" + ], + [ + "OnlineQuantiles" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Double -> OnlineQuantiles -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multiset", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "[a] -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multiplicity", + "args": [ + [ + "a" + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "Integer" + ], + "constraints": "(Ord a)", + "signature": "a -> MultiSet a -> Integer", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetEntries", + "args": [ + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "Integer" + ] + ] + ], + "constraints": "", + "signature": "MultiSet a -> [(a, Integer)]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetInsert", + "args": [ + [ + "a" + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "a -> MultiSet a -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetDelete", + "args": [ + [ + "a" + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "a -> MultiSet a -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetUnion", + "args": [ + [ + "MultiSet", + [ + "a" + ] + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "MultiSet a -> MultiSet a -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetIntersection", + "args": [ + [ + "MultiSet", + [ + "a" + ] + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "MultiSet a -> MultiSet a -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "multisetDifference", + "args": [ + [ + "MultiSet", + [ + "a" + ] + ], + [ + "MultiSet", + [ + "a" + ] + ] + ], + "result": [ + "MultiSet", + [ + "a" + ] + ], + "constraints": "(Ord a)", + "signature": "MultiSet a -> MultiSet a -> MultiSet a", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitSet", + "args": [ + [ + "Int" + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "Int -> Integer -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitWidth", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "BitSet -> Int", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitValue", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "BitSet -> Integer", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitMember", + "args": [ + [ + "BitSet" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bool" + ] + ], + "constraints": "", + "signature": "BitSet -> Int -> Either MathError Bool", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitInsert", + "args": [ + [ + "BitSet" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "BitSet -> Int -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitDelete", + "args": [ + [ + "BitSet" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "BitSet -> Int -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitUnion", + "args": [ + [ + "BitSet" + ], + [ + "BitSet" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "BitSet -> BitSet -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitIntersection", + "args": [ + [ + "BitSet" + ], + [ + "BitSet" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "BitSet -> BitSet -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "bitDifference", + "args": [ + [ + "BitSet" + ], + [ + "BitSet" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "BitSet -> BitSet -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "resizeBitSet", + "args": [ + [ + "Int" + ], + [ + "BitSet" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "BitSet" + ] + ], + "constraints": "", + "signature": "Int -> BitSet -> Either MathError BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "populationCount", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "BitSet -> Int", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "leadingZeros", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "BitSet -> Int", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "trailingZeros", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "BitSet -> Int", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "rotateBits", + "args": [ + [ + "Int" + ], + [ + "BitSet" + ] + ], + "result": [ + "BitSet" + ], + "constraints": "", + "signature": "Int -> BitSet -> BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "reverseBits", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "BitSet" + ], + "constraints": "", + "signature": "BitSet -> BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "grayEncode", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "BitSet" + ], + "constraints": "", + "signature": "BitSet -> BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "grayDecode", + "args": [ + [ + "BitSet" + ] + ], + "result": [ + "BitSet" + ], + "constraints": "", + "signature": "BitSet -> BitSet", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "hammingDistance", + "args": [ + [ + "BitSet" + ], + [ + "BitSet" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Int" + ] + ], + "constraints": "", + "signature": "BitSet -> BitSet -> Either MathError Int", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "transitiveClosure", + "args": [ + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "constraints": "", + "signature": "[[Bool]] -> Either MathError [[Bool]]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "equivalenceClosure", + "args": [ + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "constraints": "", + "signature": "[[Bool]] -> Either MathError [[Bool]]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "isEquivalence", + "args": [ + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bool" + ] + ], + "constraints": "", + "signature": "[[Bool]] -> Either MathError Bool", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "booleanMultiply", + "args": [ + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ], + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Bool" + ] + ] + ] + ], + "constraints": "", + "signature": "[[Bool]] -> [[Bool]] -> Either MathError [[Bool]]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "evaluateProp", + "args": [ + [ + "list", + [ + "Bool" + ] + ], + [ + "Prop" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bool" + ] + ], + "constraints": "", + "signature": "[Bool] -> Prop -> Either MathError Bool", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "truthTable", + "args": [ + [ + "Int" + ], + [ + "Prop" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "tuple", + [ + "list", + [ + "Bool" + ] + ], + [ + "Bool" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Prop -> Either MathError [([Bool], Bool)]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "implicantCovers", + "args": [ + [ + "Implicant" + ], + [ + "Integer" + ] + ], + "result": [ + "Bool" + ], + "constraints": "", + "signature": "Implicant -> Integer -> Bool", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "quineMcCluskey", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Integer" + ] + ], + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Implicant" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> [Integer] -> [Integer] -> Either MathError [Implicant]", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "Literal", + "args": [ + [ + "Bool" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Variable", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Not", + "args": [ + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "And", + "args": [ + [ + "Prop" + ], + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Or", + "args": [ + [ + "Prop" + ], + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Xor", + "args": [ + [ + "Prop" + ], + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Implies", + "args": [ + [ + "Prop" + ], + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "Iff", + "args": [ + [ + "Prop" + ], + [ + "Prop" + ] + ], + "result": [ + "Prop" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Discrete", + "name": "implicantValue", + "args": [ + [ + "Implicant" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "Implicant -> field", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "implicantMask", + "args": [ + [ + "Implicant" + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "Implicant -> field", + "constructor": false + }, + { + "module": "HMath.Discrete", + "name": "Implicant", + "args": [ + [ + "Integer" + ], + [ + "Integer" + ] + ], + "result": [ + "Implicant" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Algorithms", + "name": "binarySearch", + "args": [ + [ + "a" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Maybe", + [ + "Int" + ] + ] + ], + "constraints": "(Ord a)", + "signature": "a -> [a] -> Either MathError (Maybe Int)", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "interpolationSearch", + "args": [ + [ + "Integer" + ], + [ + "list", + [ + "Integer" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Maybe", + [ + "Int" + ] + ] + ], + "constraints": "", + "signature": "Integer -> [Integer] -> Either MathError (Maybe Int)", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "exponentialSearch", + "args": [ + [ + "a" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Maybe", + [ + "Int" + ] + ] + ], + "constraints": "(Ord a)", + "signature": "a -> [a] -> Either MathError (Maybe Int)", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "ternarySearch", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Int -> (Double -> Double) -> Double -> Double -> Either MathError (Double, Double)", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "numericGroups", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "Int" + ] + ] + ], + "constraints": "(Ord a)", + "signature": "[a] -> [(a, Int)]", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "runLengthEncode", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "Int" + ] + ] + ], + "constraints": "(Eq a)", + "signature": "[a] -> [(a, Int)]", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "runLengthDecode", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "Int" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Int -> [(a, Int)] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "coordinateCompression", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "Int" + ] + ] + ], + "constraints": "(Ord a)", + "signature": "[a] -> ([a], [Int])", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "intervalSweep", + "args": [ + [ + "list", + [ + "tuple", + [ + "Integer" + ], + [ + "Integer" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Integer" + ], + [ + "Int" + ] + ] + ], + "constraints": "", + "signature": "[(Integer, Integer)] -> Either MathError (Integer, Int)", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "divideConquerDP", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "function", + [ + "Int" + ], + [ + "Int" + ], + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "[Double] -> (Int -> Int -> Double) -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "tabulateDP", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "Integer" + ] + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Integer" + ] + ] + ], + "constraints": "", + "signature": "Int -> (Int -> [(Int, Integer)]) -> Either MathError [Integer]", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "memoizedDP", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "Int" + ], + [ + "tuple", + [ + "Integer" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "Integer" + ] + ] + ] + ] + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> (Int -> (Integer, [(Int, Integer)])) -> Int -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.Algorithms", + "name": "integerMatrixPower", + "args": [ + [ + "list", + [ + "list", + [ + "Integer" + ] + ] + ], + [ + "Integer" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Integer" + ] + ] + ] + ], + "constraints": "", + "signature": "[[Integer]] -> Integer -> Either MathError [[Integer]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "permutationsOf", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> [a] -> Either MathError [[a]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "combinationsOf", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> [a] -> Either MathError [[a]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "derangements", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Int" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> Either MathError [[Int]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "integerPartitions", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Int" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> Either MathError [[Int]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "setPartitions", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "list", + [ + "Int" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> Either MathError [[[Int]]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "pascalTriangle", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Integer" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> Either MathError [[Integer]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "subsets", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> [a] -> Either MathError [[a]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "cartesianProduct", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "", + "signature": "Int -> [[a]] -> Either MathError [[a]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "multisetPermutations", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "(Ord a)", + "signature": "Int -> [a] -> Either MathError [[a]]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "generatingCoefficients", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "Rational" + ] + ], + [ + "list", + [ + "Rational" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Rational" + ] + ] + ], + "constraints": "", + "signature": "Int -> [Rational] -> [Rational] -> Either MathError [Rational]", + "constructor": false + }, + { + "module": "HMath.Combinatorics", + "name": "finiteDifferences", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "[a] -> [[a]]", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "defaultIterationOptions", + "args": [], + "result": [ + "IterationOptions" + ], + "constraints": "", + "signature": "IterationOptions", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "iterateUntil", + "args": [ + [ + "IterationOptions" + ], + [ + "function", + [ + "a" + ], + [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ] + ], + [ + "function", + [ + "a" + ], + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + [ + "function", + [ + "a" + ], + [ + "a" + ], + [ + "Bool" + ] + ], + [ + "a" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Convergence", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "IterationOptions -> (a -> Either MathError a) -> (a -> Either MathError Double) -> (a -> a -> Bool) -> a -> Either MathError (Convergence a)", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "requireConvergence", + "args": [ + [ + "String" + ], + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "", + "signature": "String -> Convergence a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "resultMaybe", + "args": [ + [ + "Either", + [ + "e" + ], + [ + "a" + ] + ] + ], + "result": [ + "Maybe", + [ + "a" + ] + ], + "constraints": "", + "signature": "Either e a -> Maybe a", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "fromMaybeError", + "args": [ + [ + "e" + ], + [ + "Maybe", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "e" + ], + [ + "a" + ] + ], + "constraints": "", + "signature": "e -> Maybe a -> Either e a", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "ResidualSatisfied", + "args": [], + "result": [ + "StopReason" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Convergence", + "name": "IterationLimit", + "args": [], + "result": [ + "StopReason" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Convergence", + "name": "Stagnation", + "args": [], + "result": [ + "StopReason" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Convergence", + "name": "estimate", + "args": [ + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "Convergence -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "iterationCount", + "args": [ + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "Convergence -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "finalResidual", + "args": [ + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "Convergence -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "stopReason", + "args": [ + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "StopReason" + ], + "constraints": "", + "signature": "Convergence -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "Convergence", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Double" + ], + [ + "StopReason" + ] + ], + "result": [ + "Convergence", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Convergence", + "name": "maximumIterations", + "args": [ + [ + "IterationOptions" + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "IterationOptions -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "absoluteTolerance", + "args": [ + [ + "IterationOptions" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "IterationOptions -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "relativeTolerance", + "args": [ + [ + "IterationOptions" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "IterationOptions -> field", + "constructor": false + }, + { + "module": "HMath.API.Convergence", + "name": "IterationOptions", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "IterationOptions" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.API.Convergence", + "name": "Converged", + "args": [ + [ + "Convergence", + [ + "a" + ] + ] + ], + "result": [ + "Maybe", + [ + "a" + ] + ], + "constraints": "", + "signature": "Convergence a -> Maybe a (read-only source pattern)", + "constructor": false + } + ], + "types": { + "Fenwick": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "Fenwick", + "params": [] + }, + "SegmentTree": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "SegmentTree", + "params": [] + }, + "SparseTable": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "SparseTable", + "params": [] + }, + "DisjointSparseTable": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "DisjointSparseTable", + "params": [] + }, + "Heap": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "Heap", + "params": [ + "a" + ] + }, + "BinaryHeap": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "BinaryHeap", + "params": [] + }, + "IndexedHeap": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "IndexedHeap", + "params": [] + }, + "UnionFind": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "UnionFind", + "params": [] + }, + "Bloom": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "Bloom", + "params": [] + }, + "CountMin": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "CountMin", + "params": [] + }, + "HyperLogLog": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "HyperLogLog", + "params": [] + }, + "Reservoir": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "Reservoir", + "params": [ + "a" + ] + }, + "OnlineQuantiles": { + "module": "HMath.DataStructure", + "alias": "D", + "namespace": "data_structures", + "name": "OnlineQuantiles", + "params": [] + }, + "MultiSet": { + "module": "HMath.Discrete", + "alias": "S", + "namespace": "discrete_values", + "name": "MultiSet", + "params": [ + "a" + ] + }, + "BitSet": { + "module": "HMath.Discrete", + "alias": "S", + "namespace": "discrete_values", + "name": "BitSet", + "params": [] + }, + "Prop": { + "module": "HMath.Discrete", + "alias": "S", + "namespace": "discrete_values", + "name": "Prop", + "params": [] + }, + "Implicant": { + "module": "HMath.Discrete", + "alias": "S", + "namespace": "discrete_values", + "name": "Implicant", + "params": [] + }, + "StopReason": { + "module": "HMath.API.Convergence", + "alias": "V", + "namespace": "convergence_values", + "name": "StopReason", + "params": [] + }, + "Convergence": { + "module": "HMath.API.Convergence", + "alias": "V", + "namespace": "convergence_values", + "name": "Convergence", + "params": [ + "a" + ] + }, + "IterationOptions": { + "module": "HMath.API.Convergence", + "alias": "V", + "namespace": "convergence_values", + "name": "IterationOptions", + "params": [] + } + }, + "fields": { + "Fenwick": [], + "SegmentTree": [], + "SparseTable": [], + "DisjointSparseTable": [], + "Heap": [], + "BinaryHeap": [], + "IndexedHeap": [], + "UnionFind": [], + "Bloom": [], + "CountMin": [], + "HyperLogLog": [], + "Reservoir": [], + "OnlineQuantiles": [], + "MultiSet": [], + "BitSet": [], + "Prop": [], + "Implicant": [ + [ + "implicantValue", + [ + "Integer" + ] + ], + [ + "implicantMask", + [ + "Integer" + ] + ] + ], + "StopReason": [], + "Convergence": [ + [ + "estimate", + [ + "a" + ] + ], + [ + "iterationCount", + [ + "Int" + ] + ], + [ + "finalResidual", + [ + "Double" + ] + ], + [ + "stopReason", + [ + "StopReason" + ] + ] + ], + "IterationOptions": [ + [ + "maximumIterations", + [ + "Int" + ] + ], + [ + "absoluteTolerance", + [ + "Double" + ] + ], + [ + "relativeTolerance", + [ + "Double" + ] + ] + ] + } +} diff --git a/bindings/schema/foundation-objects.json b/bindings/schema/foundation-objects.json new file mode 100644 index 0000000..6fe8c72 --- /dev/null +++ b/bindings/schema/foundation-objects.json @@ -0,0 +1,1510 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.API.Convergence.Converged", + "c": [ + "hmath_foundation_convergence_converged" + ], + "python": "hmath.convergence.converged", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.Convergence", + "c": [ + "hmath_foundation_convergence_new_convergence" + ], + "python": "hmath.convergence.Convergence", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.IterationLimit", + "c": [ + "hmath_foundation_convergence_new_iteration_limit" + ], + "python": "hmath.convergence.iteration_limit", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.IterationOptions", + "c": [ + "hmath_foundation_convergence_new_iteration_options" + ], + "python": "hmath.convergence.IterationOptions", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.ResidualSatisfied", + "c": [ + "hmath_foundation_convergence_new_residual_satisfied" + ], + "python": "hmath.convergence.residual_satisfied", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.Stagnation", + "c": [ + "hmath_foundation_convergence_new_stagnation" + ], + "python": "hmath.convergence.stagnation", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.StopReason", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.convergence.StopReason", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.API.Convergence.absoluteTolerance", + "c": [ + "hmath_foundation_convergence_absolute_tolerance" + ], + "python": "hmath.convergence.absolute_tolerance", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.defaultIterationOptions", + "c": [ + "hmath_foundation_convergence_default_iteration_options" + ], + "python": "hmath.convergence.default_iteration_options", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.estimate", + "c": [ + "hmath_foundation_convergence_estimate" + ], + "python": "hmath.convergence.estimate", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.finalResidual", + "c": [ + "hmath_foundation_convergence_final_residual" + ], + "python": "hmath.convergence.final_residual", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.fromMaybeError", + "c": [ + "hmath_foundation_convergence_from_maybe_error" + ], + "python": "hmath.convergence.from_maybe_error", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.iterateUntil", + "c": [ + "hmath_foundation_convergence_iterate_until" + ], + "python": "hmath.convergence.iterate_until", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.iterationCount", + "c": [ + "hmath_foundation_convergence_iteration_count" + ], + "python": "hmath.convergence.iteration_count", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.maximumIterations", + "c": [ + "hmath_foundation_convergence_maximum_iterations" + ], + "python": "hmath.convergence.maximum_iterations", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.relativeTolerance", + "c": [ + "hmath_foundation_convergence_relative_tolerance" + ], + "python": "hmath.convergence.relative_tolerance", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.requireConvergence", + "c": [ + "hmath_foundation_convergence_require_convergence" + ], + "python": "hmath.convergence.require_convergence", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.resultMaybe", + "c": [ + "hmath_foundation_convergence_result_maybe" + ], + "python": "hmath.convergence.result_maybe", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.API.Convergence.stopReason", + "c": [ + "hmath_foundation_convergence_stop_reason" + ], + "python": "hmath.convergence.stop_reason", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.binarySearch", + "c": [ + "hmath_foundation_algorithms_binary_search", + "hmath_foundation_algorithms_binary_search_typed" + ], + "python": "hmath.algorithms.binary_search", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.coordinateCompression", + "c": [ + "hmath_foundation_algorithms_coordinate_compression", + "hmath_foundation_algorithms_coordinate_compression_typed" + ], + "python": "hmath.algorithms.coordinate_compression", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.divideConquerDP", + "c": [ + "hmath_foundation_algorithms_divide_conquer_dp" + ], + "python": "hmath.algorithms.divide_conquer_dp", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.exponentialSearch", + "c": [ + "hmath_foundation_algorithms_exponential_search", + "hmath_foundation_algorithms_exponential_search_typed" + ], + "python": "hmath.algorithms.exponential_search", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.integerMatrixPower", + "c": [ + "hmath_foundation_algorithms_integer_matrix_power" + ], + "python": "hmath.algorithms.integer_matrix_power", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.interpolationSearch", + "c": [ + "hmath_foundation_algorithms_interpolation_search" + ], + "python": "hmath.algorithms.interpolation_search", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.intervalSweep", + "c": [ + "hmath_foundation_algorithms_interval_sweep" + ], + "python": "hmath.algorithms.interval_sweep", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.memoizedDP", + "c": [ + "hmath_foundation_algorithms_memoized_dp" + ], + "python": "hmath.algorithms.memoized_dp", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.numericGroups", + "c": [ + "hmath_foundation_algorithms_numeric_groups", + "hmath_foundation_algorithms_numeric_groups_typed" + ], + "python": "hmath.algorithms.numeric_groups", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.runLengthDecode", + "c": [ + "hmath_foundation_algorithms_run_length_decode" + ], + "python": "hmath.algorithms.run_length_decode", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.runLengthEncode", + "c": [ + "hmath_foundation_algorithms_run_length_encode" + ], + "python": "hmath.algorithms.run_length_encode", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.tabulateDP", + "c": [ + "hmath_foundation_algorithms_tabulate_dp" + ], + "python": "hmath.algorithms.tabulate_dp", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Algorithms.ternarySearch", + "c": [ + "hmath_foundation_algorithms_ternary_search" + ], + "python": "hmath.algorithms.ternary_search", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.cartesianProduct", + "c": [ + "hmath_foundation_combinatorics_cartesian_product" + ], + "python": "hmath.combinatorics.cartesian_product", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.combinationsOf", + "c": [ + "hmath_foundation_combinatorics_combinations_of" + ], + "python": "hmath.combinatorics.combinations_of", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.derangements", + "c": [ + "hmath_foundation_combinatorics_derangements" + ], + "python": "hmath.combinatorics.derangements", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.finiteDifferences", + "c": [ + "hmath_foundation_combinatorics_finite_differences" + ], + "python": "hmath.combinatorics.finite_differences", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.generatingCoefficients", + "c": [ + "hmath_foundation_combinatorics_generating_coefficients" + ], + "python": "hmath.combinatorics.generating_coefficients", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.integerPartitions", + "c": [ + "hmath_foundation_combinatorics_integer_partitions" + ], + "python": "hmath.combinatorics.integer_partitions", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.multisetPermutations", + "c": [ + "hmath_foundation_combinatorics_multiset_permutations", + "hmath_foundation_combinatorics_multiset_permutations_typed" + ], + "python": "hmath.combinatorics.multiset_permutations", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.pascalTriangle", + "c": [ + "hmath_foundation_combinatorics_pascal_triangle" + ], + "python": "hmath.combinatorics.pascal_triangle", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.permutationsOf", + "c": [ + "hmath_foundation_combinatorics_permutations_of" + ], + "python": "hmath.combinatorics.permutations_of", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.setPartitions", + "c": [ + "hmath_foundation_combinatorics_set_partitions" + ], + "python": "hmath.combinatorics.set_partitions", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Combinatorics.subsets", + "c": [ + "hmath_foundation_combinatorics_subsets" + ], + "python": "hmath.combinatorics.subsets", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.BinaryHeap", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.BinaryHeap", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.Bloom", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.Bloom", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.CountMin", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.CountMin", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.DisjointSparseTable", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.DisjointSparseTable", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.Fenwick", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.Fenwick", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.Heap", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.Heap", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.HyperLogLog", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.HyperLogLog", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.IndexedHeap", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.IndexedHeap", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.OnlineQuantiles", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.OnlineQuantiles", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.Reservoir", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.Reservoir", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.SegmentTree", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.SegmentTree", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.SparseTable", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.SparseTable", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.UnionFind", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.datastructure.UnionFind", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.DataStructure.binaryHeap", + "c": [ + "hmath_foundation_datastructure_binary_heap" + ], + "python": "hmath.datastructure.binary_heap", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.binaryInsert", + "c": [ + "hmath_foundation_datastructure_binary_insert" + ], + "python": "hmath.datastructure.binary_insert", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.binaryPop", + "c": [ + "hmath_foundation_datastructure_binary_pop" + ], + "python": "hmath.datastructure.binary_pop", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.bloom", + "c": [ + "hmath_foundation_datastructure_bloom" + ], + "python": "hmath.datastructure.bloom", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.bloomFalsePositiveBound", + "c": [ + "hmath_foundation_datastructure_bloom_false_positive_bound" + ], + "python": "hmath.datastructure.bloom_false_positive_bound", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.bloomInsert", + "c": [ + "hmath_foundation_datastructure_bloom_insert" + ], + "python": "hmath.datastructure.bloom_insert", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.bloomMember", + "c": [ + "hmath_foundation_datastructure_bloom_member" + ], + "python": "hmath.datastructure.bloom_member", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.components", + "c": [ + "hmath_foundation_datastructure_components" + ], + "python": "hmath.datastructure.components", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.connected", + "c": [ + "hmath_foundation_datastructure_connected" + ], + "python": "hmath.datastructure.connected", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.countMin", + "c": [ + "hmath_foundation_datastructure_count_min" + ], + "python": "hmath.datastructure.count_min", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.countMinAdd", + "c": [ + "hmath_foundation_datastructure_count_min_add" + ], + "python": "hmath.datastructure.count_min_add", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.countMinErrorBound", + "c": [ + "hmath_foundation_datastructure_count_min_error_bound" + ], + "python": "hmath.datastructure.count_min_error_bound", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.countMinEstimate", + "c": [ + "hmath_foundation_datastructure_count_min_estimate" + ], + "python": "hmath.datastructure.count_min_estimate", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.disjointRange", + "c": [ + "hmath_foundation_datastructure_disjoint_range" + ], + "python": "hmath.datastructure.disjoint_range", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.disjointSparseTable", + "c": [ + "hmath_foundation_datastructure_disjoint_sparse_table" + ], + "python": "hmath.datastructure.disjoint_sparse_table", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.emptyHeap", + "c": [ + "hmath_foundation_datastructure_empty_heap" + ], + "python": "hmath.datastructure.empty_heap", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.fenwick", + "c": [ + "hmath_foundation_datastructure_fenwick" + ], + "python": "hmath.datastructure.fenwick", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickAdd", + "c": [ + "hmath_foundation_datastructure_fenwick_add" + ], + "python": "hmath.datastructure.fenwick_add", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickPrefix", + "c": [ + "hmath_foundation_datastructure_fenwick_prefix" + ], + "python": "hmath.datastructure.fenwick_prefix", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickRange", + "c": [ + "hmath_foundation_datastructure_fenwick_range" + ], + "python": "hmath.datastructure.fenwick_range", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.findRoot", + "c": [ + "hmath_foundation_datastructure_find_root" + ], + "python": "hmath.datastructure.find_root", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.heapFromList", + "c": [ + "hmath_foundation_datastructure_heap_from_list", + "hmath_foundation_heap_from_list_typed" + ], + "python": "hmath.datastructure.heap_from_list", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.heapInsert", + "c": [ + "hmath_foundation_datastructure_heap_insert" + ], + "python": "hmath.datastructure.heap_insert", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.heapPop", + "c": [ + "hmath_foundation_datastructure_heap_pop" + ], + "python": "hmath.datastructure.heap_pop", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.hllAdd", + "c": [ + "hmath_foundation_datastructure_hll_add" + ], + "python": "hmath.datastructure.hll_add", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.hllEstimate", + "c": [ + "hmath_foundation_datastructure_hll_estimate" + ], + "python": "hmath.datastructure.hll_estimate", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.hyperLogLog", + "c": [ + "hmath_foundation_datastructure_hyper_log_log" + ], + "python": "hmath.datastructure.hyper_log_log", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.indexedHeap", + "c": [ + "hmath_foundation_datastructure_indexed_heap" + ], + "python": "hmath.datastructure.indexed_heap", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.indexedPop", + "c": [ + "hmath_foundation_datastructure_indexed_pop" + ], + "python": "hmath.datastructure.indexed_pop", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.indexedSet", + "c": [ + "hmath_foundation_datastructure_indexed_set" + ], + "python": "hmath.datastructure.indexed_set", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.nextGreater", + "c": [ + "hmath_foundation_datastructure_next_greater", + "hmath_foundation_datastructure_next_greater_typed" + ], + "python": "hmath.datastructure.next_greater", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.onlineQuantile", + "c": [ + "hmath_foundation_datastructure_online_quantile" + ], + "python": "hmath.datastructure.online_quantile", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.onlineQuantiles", + "c": [ + "hmath_foundation_datastructure_online_quantiles" + ], + "python": "hmath.datastructure.online_quantiles", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.quantileAdd", + "c": [ + "hmath_foundation_datastructure_quantile_add" + ], + "python": "hmath.datastructure.quantile_add", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.reservoir", + "c": [ + "hmath_foundation_datastructure_reservoir" + ], + "python": "hmath.datastructure.reservoir", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.reservoirAdd", + "c": [ + "hmath_foundation_datastructure_reservoir_add" + ], + "python": "hmath.datastructure.reservoir_add", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.reservoirValues", + "c": [ + "hmath_foundation_datastructure_reservoir_values" + ], + "python": "hmath.datastructure.reservoir_values", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.segmentRange", + "c": [ + "hmath_foundation_datastructure_segment_range" + ], + "python": "hmath.datastructure.segment_range", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.segmentSet", + "c": [ + "hmath_foundation_datastructure_segment_set" + ], + "python": "hmath.datastructure.segment_set", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.segmentTree", + "c": [ + "hmath_foundation_datastructure_segment_tree" + ], + "python": "hmath.datastructure.segment_tree", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.sparseMinimum", + "c": [ + "hmath_foundation_datastructure_sparse_minimum" + ], + "python": "hmath.datastructure.sparse_minimum", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.sparseTable", + "c": [ + "hmath_foundation_datastructure_sparse_table" + ], + "python": "hmath.datastructure.sparse_table", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.union", + "c": [ + "hmath_foundation_datastructure_union" + ], + "python": "hmath.datastructure.union", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.DataStructure.unionFind", + "c": [ + "hmath_foundation_datastructure_union_find" + ], + "python": "hmath.datastructure.union_find", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.And", + "c": [ + "hmath_foundation_discrete_new_and" + ], + "python": "hmath.discrete.logical_and", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.BitSet", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.discrete.BitSet", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.Discrete.Iff", + "c": [ + "hmath_foundation_discrete_new_iff" + ], + "python": "hmath.discrete.iff", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Implicant", + "c": [ + "hmath_foundation_discrete_new_implicant" + ], + "python": "hmath.discrete.Implicant", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Implies", + "c": [ + "hmath_foundation_discrete_new_implies" + ], + "python": "hmath.discrete.implies", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Literal", + "c": [ + "hmath_foundation_discrete_new_literal" + ], + "python": "hmath.discrete.literal", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.MultiSet", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.discrete.MultiSet", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.Discrete.Not", + "c": [ + "hmath_foundation_discrete_new_not" + ], + "python": "hmath.discrete.logical_not", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Or", + "c": [ + "hmath_foundation_discrete_new_or" + ], + "python": "hmath.discrete.logical_or", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Prop", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.discrete.Prop", + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ] + }, + { + "symbol": "HMath.Discrete.Variable", + "c": [ + "hmath_foundation_discrete_new_variable" + ], + "python": "hmath.discrete.variable", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.Xor", + "c": [ + "hmath_foundation_discrete_new_xor" + ], + "python": "hmath.discrete.xor", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitDelete", + "c": [ + "hmath_foundation_discrete_bit_delete" + ], + "python": "hmath.discrete.bit_delete", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitDifference", + "c": [ + "hmath_foundation_discrete_bit_difference" + ], + "python": "hmath.discrete.bit_difference", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitInsert", + "c": [ + "hmath_foundation_discrete_bit_insert" + ], + "python": "hmath.discrete.bit_insert", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitIntersection", + "c": [ + "hmath_foundation_discrete_bit_intersection" + ], + "python": "hmath.discrete.bit_intersection", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitMember", + "c": [ + "hmath_foundation_discrete_bit_member" + ], + "python": "hmath.discrete.bit_member", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitSet", + "c": [ + "hmath_foundation_discrete_bit_set" + ], + "python": "hmath.discrete.bit_set", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitUnion", + "c": [ + "hmath_foundation_discrete_bit_union" + ], + "python": "hmath.discrete.bit_union", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitValue", + "c": [ + "hmath_foundation_discrete_bit_value" + ], + "python": "hmath.discrete.bit_value", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.bitWidth", + "c": [ + "hmath_foundation_discrete_bit_width" + ], + "python": "hmath.discrete.bit_width", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.booleanMultiply", + "c": [ + "hmath_foundation_discrete_boolean_multiply" + ], + "python": "hmath.discrete.boolean_multiply", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.equivalenceClosure", + "c": [ + "hmath_foundation_discrete_equivalence_closure" + ], + "python": "hmath.discrete.equivalence_closure", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.evaluateProp", + "c": [ + "hmath_foundation_discrete_evaluate_prop" + ], + "python": "hmath.discrete.evaluate_prop", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.grayDecode", + "c": [ + "hmath_foundation_discrete_gray_decode" + ], + "python": "hmath.discrete.gray_decode", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.grayEncode", + "c": [ + "hmath_foundation_discrete_gray_encode" + ], + "python": "hmath.discrete.gray_encode", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.hammingDistance", + "c": [ + "hmath_foundation_discrete_hamming_distance" + ], + "python": "hmath.discrete.hamming_distance", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.implicantCovers", + "c": [ + "hmath_foundation_discrete_implicant_covers" + ], + "python": "hmath.discrete.implicant_covers", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.implicantMask", + "c": [ + "hmath_foundation_discrete_implicant_mask" + ], + "python": "hmath.discrete.implicant_mask", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.implicantValue", + "c": [ + "hmath_foundation_discrete_implicant_value" + ], + "python": "hmath.discrete.implicant_value", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.isEquivalence", + "c": [ + "hmath_foundation_discrete_is_equivalence" + ], + "python": "hmath.discrete.is_equivalence", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.leadingZeros", + "c": [ + "hmath_foundation_discrete_leading_zeros" + ], + "python": "hmath.discrete.leading_zeros", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multiplicity", + "c": [ + "hmath_foundation_discrete_multiplicity" + ], + "python": "hmath.discrete.multiplicity", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multiset", + "c": [ + "hmath_foundation_discrete_multiset", + "hmath_foundation_multiset_typed" + ], + "python": "hmath.discrete.multiset", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetDelete", + "c": [ + "hmath_foundation_discrete_multiset_delete" + ], + "python": "hmath.discrete.multiset_delete", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetDifference", + "c": [ + "hmath_foundation_discrete_multiset_difference" + ], + "python": "hmath.discrete.multiset_difference", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetEntries", + "c": [ + "hmath_foundation_discrete_multiset_entries" + ], + "python": "hmath.discrete.multiset_entries", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetInsert", + "c": [ + "hmath_foundation_discrete_multiset_insert" + ], + "python": "hmath.discrete.multiset_insert", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetIntersection", + "c": [ + "hmath_foundation_discrete_multiset_intersection" + ], + "python": "hmath.discrete.multiset_intersection", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.multisetUnion", + "c": [ + "hmath_foundation_discrete_multiset_union" + ], + "python": "hmath.discrete.multiset_union", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.populationCount", + "c": [ + "hmath_foundation_discrete_population_count" + ], + "python": "hmath.discrete.population_count", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.quineMcCluskey", + "c": [ + "hmath_foundation_discrete_quine_mc_cluskey" + ], + "python": "hmath.discrete.quine_mc_cluskey", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.resizeBitSet", + "c": [ + "hmath_foundation_discrete_resize_bit_set" + ], + "python": "hmath.discrete.resize_bit_set", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.reverseBits", + "c": [ + "hmath_foundation_discrete_reverse_bits" + ], + "python": "hmath.discrete.reverse_bits", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.rotateBits", + "c": [ + "hmath_foundation_discrete_rotate_bits" + ], + "python": "hmath.discrete.rotate_bits", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.trailingZeros", + "c": [ + "hmath_foundation_discrete_trailing_zeros" + ], + "python": "hmath.discrete.trailing_zeros", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.transitiveClosure", + "c": [ + "hmath_foundation_discrete_transitive_closure" + ], + "python": "hmath.discrete.transitive_closure", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + }, + { + "symbol": "HMath.Discrete.truthTable", + "c": [ + "hmath_foundation_discrete_truth_table" + ], + "python": "hmath.discrete.truth_table", + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ] + } + ] +} diff --git a/bindings/schema/geometry-functions.json b/bindings/schema/geometry-functions.json new file mode 100644 index 0000000..466b518 --- /dev/null +++ b/bindings/schema/geometry-functions.json @@ -0,0 +1,645 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Geometry.Collision", + "name": "Penetration", + "signature": "Double -> Point2 -> Double -> Int -> Penetration" + }, + { + "module": "HMath.Geometry.Collision", + "name": "epa", + "signature": "Int -> Double -> [Point2] -> [Point2] -> Either MathError (Maybe Penetration)" + }, + { + "module": "HMath.Geometry.Collision", + "name": "gjk", + "signature": "Int -> [Point2] -> [Point2] -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Collision", + "name": "penetrationDepth", + "signature": "Penetration -> Double" + }, + { + "module": "HMath.Geometry.Collision", + "name": "penetrationError", + "signature": "Penetration -> Double" + }, + { + "module": "HMath.Geometry.Collision", + "name": "penetrationIterations", + "signature": "Penetration -> Int" + }, + { + "module": "HMath.Geometry.Collision", + "name": "penetrationNormal", + "signature": "Penetration -> Point2" + }, + { + "module": "HMath.Geometry.Collision", + "name": "separatingAxis", + "signature": "[Point2] -> [Point2] -> Either MathError (Maybe Penetration)" + }, + { + "module": "HMath.Geometry.Internal", + "name": "AABB", + "signature": "PointND -> PointND -> AABB" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Boundary", + "signature": "Location" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Capsule", + "signature": "Point3 -> Point3 -> Double -> Capsule" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Circle", + "signature": "Point2 -> Double -> Circle" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Clockwise", + "signature": "Orientation" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Collinear", + "signature": "Orientation" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Cone", + "signature": "Point3 -> Point3 -> Double -> Cone" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Counterclockwise", + "signature": "Orientation" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Cylinder", + "signature": "Point3 -> Point3 -> Double -> Cylinder" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Ellipse", + "signature": "Point2 -> Double -> Double -> Double -> Ellipse" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Frustum", + "signature": "[Plane] -> Frustum" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Inside", + "signature": "Location" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Line", + "signature": "PointND -> PointND -> Line" + }, + { + "module": "HMath.Geometry.Internal", + "name": "OBB", + "signature": "Point3 -> [Point3] -> Point3 -> OBB" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Outside", + "signature": "Location" + }, + { + "module": "HMath.Geometry.Internal", + "name": "P2", + "signature": "Double -> Double -> Point2" + }, + { + "module": "HMath.Geometry.Internal", + "name": "P3", + "signature": "Double -> Double -> Double -> Point3" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Plane", + "signature": "Point3 -> Double -> Plane" + }, + { + "module": "HMath.Geometry.Internal", + "name": "PointND", + "signature": "[Double] -> PointND" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Polygon", + "signature": "[Point2] -> Polygon" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Ray", + "signature": "Point3 -> Point3 -> Ray" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Rectangle", + "signature": "Point2 -> Point2 -> Rectangle" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Segment", + "signature": "PointND -> PointND -> Segment" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Sphere", + "signature": "Point3 -> Double -> Sphere" + }, + { + "module": "HMath.Geometry.Internal", + "name": "Triangle", + "signature": "Point2 -> Point2 -> Point2 -> Triangle" + }, + { + "module": "HMath.Geometry.Internal", + "name": "point2", + "signature": "Double -> Double -> Either MathError Point2" + }, + { + "module": "HMath.Geometry.Internal", + "name": "point3", + "signature": "Double -> Double -> Double -> Either MathError Point3" + }, + { + "module": "HMath.Geometry.Internal", + "name": "pointND", + "signature": "[Double] -> Either MathError PointND" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "Difference", + "signature": "BooleanOperation" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "GiftWrapping", + "signature": "HullAlgorithm" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "GrahamScan", + "signature": "HullAlgorithm" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "Intersection", + "signature": "BooleanOperation" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "MonotoneChain", + "signature": "HullAlgorithm" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "Quickhull", + "signature": "HullAlgorithm" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "Union", + "signature": "BooleanOperation" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "clipPolygon", + "signature": "Polygon -> Polygon -> Either MathError [Point2]" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "convexHull", + "signature": "HullAlgorithm -> [Point2] -> Either MathError [Point2]" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "minimumBoundingCircle", + "signature": "[Point2] -> Either MathError Circle" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "minimumBoundingRectangle", + "signature": "[Point2] -> Either MathError [Point2]" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "minkowskiSum", + "signature": "[Point2] -> [Point2] -> Either MathError [Point2]" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "polygonArea", + "signature": "Polygon -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "polygonBoolean", + "signature": "BooleanOperation -> Polygon -> Polygon -> Either MathError [Polygon]" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "polygonCentroid", + "signature": "Polygon -> Either MathError Point2" + }, + { + "module": "HMath.Geometry.Polygon", + "name": "shoelace", + "signature": "Polygon -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "Chebyshev", + "signature": "Metric" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "CirclePoints", + "signature": "[Point2] -> CircleIntersection" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "CoincidentCircles", + "signature": "CircleIntersection" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "CoincidentLine", + "signature": "Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "DisjointCircles", + "signature": "CircleIntersection" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "Euclidean", + "signature": "Metric" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "IntersectionPoint", + "signature": "Point2 -> Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "Manhattan", + "signature": "Metric" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "Minkowski", + "signature": "Double -> Metric" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "NoIntersection", + "signature": "Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "OverlapSegment", + "signature": "Point2 -> Point2 -> Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "boxContains", + "signature": "AABB -> PointND -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "boxSDF", + "signature": "AABB -> PointND -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "capsuleSDF", + "signature": "Capsule -> Point3 -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "circleIntersection", + "signature": "Circle -> Circle -> Either MathError CircleIntersection" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "circumcenter", + "signature": "Triangle -> Either MathError Point2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "coneSDF", + "signature": "Cone -> Point3 -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "cosineDistance", + "signature": "PointND -> PointND -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "cylinderSDF", + "signature": "Cylinder -> Point3 -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "distance", + "signature": "Metric -> PointND -> PointND -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "ellipseContains", + "signature": "Ellipse -> Point2 -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "hammingDistance", + "signature": "Eq a => [a] -> [a] -> Either MathError Int" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "hausdorffDistance", + "signature": "[PointND] -> [PointND] -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "incenter", + "signature": "Triangle -> Either MathError Point2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "incircle", + "signature": "Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Ordering" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "jaccardDistance", + "signature": "Eq a => [a] -> [a] -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "lineIntersection", + "signature": "Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "linePlaneIntersection", + "signature": "Line -> Plane -> Either MathError (Maybe (Maybe Point3))" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "mahalanobisDistance", + "signature": "[[Double]] -> PointND -> PointND -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "obbSDF", + "signature": "OBB -> Point3 -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "orientation", + "signature": "Point2 -> Point2 -> Point2 -> Either MathError Orientation" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "planeIntersection", + "signature": "Plane -> Plane -> Either MathError (Maybe (Maybe Line))" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "pointLineDistance", + "signature": "PointND -> Line -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "pointPlaneDistance", + "signature": "Point3 -> Plane -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "pointSegmentDistance", + "signature": "PointND -> Segment -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "polygonLocation", + "signature": "Polygon -> Point2 -> Either MathError Location" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "rayBox", + "signature": "Ray -> AABB -> Either MathError (Maybe (Double, Double))" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "raySphere", + "signature": "Ray -> Sphere -> Either MathError (Maybe (Double, Double))" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "rayTriangle", + "signature": "Ray -> (Point3, Point3, Point3) -> Either MathError (Maybe Double)" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "segmentIntersection", + "signature": "Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "sphereContains", + "signature": "Sphere -> Point3 -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "sphereSDF", + "signature": "Sphere -> Point3 -> Either MathError Double" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "triangleBarycentric", + "signature": "Triangle -> Point2 -> Either MathError [Double]" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "triangleIntersection", + "signature": "Triangle -> Triangle -> Either MathError [Point2]" + }, + { + "module": "HMath.Geometry.Primitives", + "name": "triangleLocation", + "signature": "Triangle -> Point2 -> Either MathError Location" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "BVH", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "BallTree", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "KDTree", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "NeighborQuery", + "signature": "[(Int, Double)] -> Int -> Bool -> NeighborQuery" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "Octree", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "Quadtree", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "RTree", + "signature": "SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "SpatialHash", + "signature": "Double -> SpatialKind" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "buildSpatialIndex", + "signature": "SpatialKind -> PointCloud -> Either MathError SpatialIndex" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "cloudPoints", + "signature": "PointCloud -> [PointND]" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "nearestQuery", + "signature": "Int -> Int -> SpatialIndex -> PointND -> Either MathError NeighborQuery" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "pointCloud", + "signature": "[PointND] -> Either MathError PointCloud" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "queryExhaustive", + "signature": "NeighborQuery -> Bool" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "queryLeaves", + "signature": "NeighborQuery -> Int" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "queryNeighbors", + "signature": "NeighborQuery -> [(Int, Double)]" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "radiusQuery", + "signature": "SpatialIndex -> PointND -> Double -> Either MathError [Int]" + }, + { + "module": "HMath.Geometry.Spatial", + "name": "rangeQuery", + "signature": "SpatialIndex -> AABB -> Either MathError [Int]" + }, + { + "module": "HMath.Geometry.Transform", + "name": "affineTransform", + "signature": "Matrix Double -> PointND -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Transform", + "name": "applyTransform", + "signature": "Matrix Double -> PointND -> Either MathError PointND" + }, + { + "module": "HMath.Geometry.Transform", + "name": "composeTransforms", + "signature": "Matrix Double -> Matrix Double -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Transform", + "name": "cullBox", + "signature": "Frustum -> AABB -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Transform", + "name": "cullSphere", + "signature": "Frustum -> Sphere -> Either MathError Bool" + }, + { + "module": "HMath.Geometry.Transform", + "name": "extractFrustum", + "signature": "Matrix Double -> Either MathError Frustum" + }, + { + "module": "HMath.Geometry.Transform", + "name": "inverseTransform", + "signature": "Matrix Double -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Transform", + "name": "lookAt", + "signature": "Point3 -> Point3 -> Point3 -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Transform", + "name": "orthographic", + "signature": "Double -> Double -> Double -> Double -> Double -> Double -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Transform", + "name": "perspective", + "signature": "Double -> Double -> Double -> Double -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Geometry.Triangulation", + "name": "constrainedDelaunay", + "signature": "[Point2] -> [(Int, Int)] -> Either MathError [IndexedTriangle]" + }, + { + "module": "HMath.Geometry.Triangulation", + "name": "delaunay", + "signature": "[Point2] -> Either MathError [IndexedTriangle]" + }, + { + "module": "HMath.Geometry.Triangulation", + "name": "earClip", + "signature": "Polygon -> Either MathError [IndexedTriangle]" + }, + { + "module": "HMath.Geometry.Triangulation", + "name": "voronoi", + "signature": "Rectangle -> [Point2] -> Either MathError [[Point2]]" + } + ] +} diff --git a/bindings/schema/geometry-objects.json b/bindings/schema/geometry-objects.json new file mode 100644 index 0000000..4e8ea95 --- /dev/null +++ b/bindings/schema/geometry-objects.json @@ -0,0 +1,1395 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Geometry.Internal.Point2", + "c": [ + "hmath_geometry_point2_object" + ], + "python": "hmath.geometry.Point2", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Point3", + "c": [ + "hmath_geometry_point3_object" + ], + "python": "hmath.geometry.Point3", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Orientation", + "c": [ + "hmath_geometry_orientation_object" + ], + "python": "hmath.geometry.Orientation", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Location", + "c": [ + "hmath_geometry_location_object" + ], + "python": "hmath.geometry.Location", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.HullAlgorithm", + "c": [ + "hmath_geometry_hull_algorithm_object" + ], + "python": "hmath.geometry.HullAlgorithm", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.BooleanOperation", + "c": [ + "hmath_geometry_boolean_operation_object" + ], + "python": "hmath.geometry.BooleanOperation", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Metric", + "c": [ + "hmath_geometry_metric_object" + ], + "python": "hmath.geometry.Metric", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Intersection2", + "c": [ + "hmath_geometry_intersection2_object" + ], + "python": "hmath.geometry.Intersection2", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CircleIntersection", + "c": [ + "hmath_geometry_circle_intersection_object" + ], + "python": "hmath.geometry.CircleIntersection", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialKind", + "c": [ + "hmath_geometry_spatial_kind_object" + ], + "python": "hmath.geometry.SpatialKind", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.PointCloud", + "c": [ + "hmath_geometry_point_cloud_object" + ], + "python": "hmath.geometry.PointCloud", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialIndex", + "c": [ + "hmath_geometry_spatial_index_object" + ], + "python": "hmath.geometry.SpatialIndex", + "specializations": [ + "original opaque type" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.IndexedTriangle", + "c": [ + "hmath_geometry_indexed_triangle_object" + ], + "python": "hmath.geometry.IndexedTriangle", + "specializations": [ + "exact original Int triple" + ] + }, + { + "symbol": "HMath.Geometry.Collision.Penetration", + "c": [ + "hmath_geometry_penetration" + ], + "python": "hmath.geometry.penetration", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.epa", + "c": [ + "hmath_geometry_epa" + ], + "python": "hmath.geometry.epa", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.gjk", + "c": [ + "hmath_geometry_gjk" + ], + "python": "hmath.geometry.gjk", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationDepth", + "c": [ + "hmath_geometry_penetration_depth" + ], + "python": "hmath.geometry.penetration_depth", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationError", + "c": [ + "hmath_geometry_penetration_error" + ], + "python": "hmath.geometry.penetration_error", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationIterations", + "c": [ + "hmath_geometry_penetration_iterations" + ], + "python": "hmath.geometry.penetration_iterations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationNormal", + "c": [ + "hmath_geometry_penetration_normal" + ], + "python": "hmath.geometry.penetration_normal", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Collision.separatingAxis", + "c": [ + "hmath_geometry_separating_axis" + ], + "python": "hmath.geometry.separating_axis", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.AABB", + "c": [ + "hmath_geometry_aabb" + ], + "python": "hmath.geometry.aabb", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Boundary", + "c": [ + "hmath_geometry_boundary" + ], + "python": "hmath.geometry.boundary", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Capsule", + "c": [ + "hmath_geometry_capsule" + ], + "python": "hmath.geometry.capsule", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Circle", + "c": [ + "hmath_geometry_circle" + ], + "python": "hmath.geometry.circle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Clockwise", + "c": [ + "hmath_geometry_clockwise" + ], + "python": "hmath.geometry.clockwise", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Collinear", + "c": [ + "hmath_geometry_collinear" + ], + "python": "hmath.geometry.collinear", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Cone", + "c": [ + "hmath_geometry_cone" + ], + "python": "hmath.geometry.cone", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Counterclockwise", + "c": [ + "hmath_geometry_counterclockwise" + ], + "python": "hmath.geometry.counterclockwise", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Cylinder", + "c": [ + "hmath_geometry_cylinder" + ], + "python": "hmath.geometry.cylinder", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Ellipse", + "c": [ + "hmath_geometry_ellipse" + ], + "python": "hmath.geometry.ellipse", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Frustum", + "c": [ + "hmath_geometry_frustum" + ], + "python": "hmath.geometry.frustum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Inside", + "c": [ + "hmath_geometry_inside" + ], + "python": "hmath.geometry.inside", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Line", + "c": [ + "hmath_geometry_line" + ], + "python": "hmath.geometry.line", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.OBB", + "c": [ + "hmath_geometry_obb" + ], + "python": "hmath.geometry.obb", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Outside", + "c": [ + "hmath_geometry_outside" + ], + "python": "hmath.geometry.outside", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.P2", + "c": [ + "hmath_geometry_p2" + ], + "python": "hmath.geometry.p2", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.P3", + "c": [ + "hmath_geometry_p3" + ], + "python": "hmath.geometry.p3", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Plane", + "c": [ + "hmath_geometry_plane" + ], + "python": "hmath.geometry.plane", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.PointND", + "c": [ + "hmath_geometry_point_nd_raw" + ], + "python": "hmath.geometry.point_nd_raw", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Polygon", + "c": [ + "hmath_geometry_polygon" + ], + "python": "hmath.geometry.polygon", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Ray", + "c": [ + "hmath_geometry_ray" + ], + "python": "hmath.geometry.ray", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Rectangle", + "c": [ + "hmath_geometry_rectangle" + ], + "python": "hmath.geometry.rectangle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Segment", + "c": [ + "hmath_geometry_segment" + ], + "python": "hmath.geometry.segment", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Sphere", + "c": [ + "hmath_geometry_sphere" + ], + "python": "hmath.geometry.sphere", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Triangle", + "c": [ + "hmath_geometry_triangle" + ], + "python": "hmath.geometry.triangle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.point2", + "c": [ + "hmath_geometry_point2" + ], + "python": "hmath.geometry.point2", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.point3", + "c": [ + "hmath_geometry_point3" + ], + "python": "hmath.geometry.point3", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Internal.pointND", + "c": [ + "hmath_geometry_point_nd" + ], + "python": "hmath.geometry.point_nd", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Difference", + "c": [ + "hmath_geometry_difference" + ], + "python": "hmath.geometry.difference", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.GiftWrapping", + "c": [ + "hmath_geometry_gift_wrapping" + ], + "python": "hmath.geometry.gift_wrapping", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.GrahamScan", + "c": [ + "hmath_geometry_graham_scan" + ], + "python": "hmath.geometry.graham_scan", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Intersection", + "c": [ + "hmath_geometry_intersection" + ], + "python": "hmath.geometry.intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.MonotoneChain", + "c": [ + "hmath_geometry_monotone_chain" + ], + "python": "hmath.geometry.monotone_chain", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Quickhull", + "c": [ + "hmath_geometry_quickhull" + ], + "python": "hmath.geometry.quickhull", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Union", + "c": [ + "hmath_geometry_union" + ], + "python": "hmath.geometry.union", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.clipPolygon", + "c": [ + "hmath_geometry_clip_polygon" + ], + "python": "hmath.geometry.clip_polygon", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.convexHull", + "c": [ + "hmath_geometry_convex_hull" + ], + "python": "hmath.geometry.convex_hull", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minimumBoundingCircle", + "c": [ + "hmath_geometry_minimum_bounding_circle" + ], + "python": "hmath.geometry.minimum_bounding_circle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minimumBoundingRectangle", + "c": [ + "hmath_geometry_minimum_bounding_rectangle" + ], + "python": "hmath.geometry.minimum_bounding_rectangle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minkowskiSum", + "c": [ + "hmath_geometry_minkowski_sum" + ], + "python": "hmath.geometry.minkowski_sum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonArea", + "c": [ + "hmath_geometry_polygon_area" + ], + "python": "hmath.geometry.polygon_area", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonBoolean", + "c": [ + "hmath_geometry_polygon_boolean" + ], + "python": "hmath.geometry.polygon_boolean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonCentroid", + "c": [ + "hmath_geometry_polygon_centroid" + ], + "python": "hmath.geometry.polygon_centroid", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.shoelace", + "c": [ + "hmath_geometry_shoelace" + ], + "python": "hmath.geometry.shoelace", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Chebyshev", + "c": [ + "hmath_geometry_chebyshev" + ], + "python": "hmath.geometry.chebyshev", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CirclePoints", + "c": [ + "hmath_geometry_circle_points" + ], + "python": "hmath.geometry.circle_points", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CoincidentCircles", + "c": [ + "hmath_geometry_coincident_circles" + ], + "python": "hmath.geometry.coincident_circles", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CoincidentLine", + "c": [ + "hmath_geometry_coincident_line" + ], + "python": "hmath.geometry.coincident_line", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.DisjointCircles", + "c": [ + "hmath_geometry_disjoint_circles" + ], + "python": "hmath.geometry.disjoint_circles", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Euclidean", + "c": [ + "hmath_geometry_euclidean" + ], + "python": "hmath.geometry.euclidean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.IntersectionPoint", + "c": [ + "hmath_geometry_intersection_point" + ], + "python": "hmath.geometry.intersection_point", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Manhattan", + "c": [ + "hmath_geometry_manhattan" + ], + "python": "hmath.geometry.manhattan", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Minkowski", + "c": [ + "hmath_geometry_minkowski" + ], + "python": "hmath.geometry.minkowski", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.NoIntersection", + "c": [ + "hmath_geometry_no_intersection" + ], + "python": "hmath.geometry.no_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.OverlapSegment", + "c": [ + "hmath_geometry_overlap_segment" + ], + "python": "hmath.geometry.overlap_segment", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.boxContains", + "c": [ + "hmath_geometry_box_contains" + ], + "python": "hmath.geometry.box_contains", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.boxSDF", + "c": [ + "hmath_geometry_box_sdf" + ], + "python": "hmath.geometry.box_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.capsuleSDF", + "c": [ + "hmath_geometry_capsule_sdf" + ], + "python": "hmath.geometry.capsule_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.circleIntersection", + "c": [ + "hmath_geometry_circle_intersection" + ], + "python": "hmath.geometry.circle_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.circumcenter", + "c": [ + "hmath_geometry_circumcenter" + ], + "python": "hmath.geometry.circumcenter", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.coneSDF", + "c": [ + "hmath_geometry_cone_sdf" + ], + "python": "hmath.geometry.cone_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.cosineDistance", + "c": [ + "hmath_geometry_cosine_distance" + ], + "python": "hmath.geometry.cosine_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.cylinderSDF", + "c": [ + "hmath_geometry_cylinder_sdf" + ], + "python": "hmath.geometry.cylinder_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.distance", + "c": [ + "hmath_geometry_distance" + ], + "python": "hmath.geometry.distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.ellipseContains", + "c": [ + "hmath_geometry_ellipse_contains" + ], + "python": "hmath.geometry.ellipse_contains", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.hausdorffDistance", + "c": [ + "hmath_geometry_hausdorff_distance" + ], + "python": "hmath.geometry.hausdorff_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.incenter", + "c": [ + "hmath_geometry_incenter" + ], + "python": "hmath.geometry.incenter", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.incircle", + "c": [ + "hmath_geometry_incircle" + ], + "python": "hmath.geometry.incircle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.lineIntersection", + "c": [ + "hmath_geometry_line_intersection" + ], + "python": "hmath.geometry.line_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.linePlaneIntersection", + "c": [ + "hmath_geometry_line_plane_intersection" + ], + "python": "hmath.geometry.line_plane_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.mahalanobisDistance", + "c": [ + "hmath_geometry_mahalanobis_distance" + ], + "python": "hmath.geometry.mahalanobis_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.obbSDF", + "c": [ + "hmath_geometry_obb_sdf" + ], + "python": "hmath.geometry.obb_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.orientation", + "c": [ + "hmath_geometry_orientation" + ], + "python": "hmath.geometry.orientation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.planeIntersection", + "c": [ + "hmath_geometry_plane_intersection" + ], + "python": "hmath.geometry.plane_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointLineDistance", + "c": [ + "hmath_geometry_point_line_distance" + ], + "python": "hmath.geometry.point_line_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointPlaneDistance", + "c": [ + "hmath_geometry_point_plane_distance" + ], + "python": "hmath.geometry.point_plane_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointSegmentDistance", + "c": [ + "hmath_geometry_point_segment_distance" + ], + "python": "hmath.geometry.point_segment_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.polygonLocation", + "c": [ + "hmath_geometry_polygon_location" + ], + "python": "hmath.geometry.polygon_location", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.rayBox", + "c": [ + "hmath_geometry_ray_box" + ], + "python": "hmath.geometry.ray_box", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.raySphere", + "c": [ + "hmath_geometry_ray_sphere" + ], + "python": "hmath.geometry.ray_sphere", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.rayTriangle", + "c": [ + "hmath_geometry_ray_triangle" + ], + "python": "hmath.geometry.ray_triangle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.segmentIntersection", + "c": [ + "hmath_geometry_segment_intersection" + ], + "python": "hmath.geometry.segment_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.sphereContains", + "c": [ + "hmath_geometry_sphere_contains" + ], + "python": "hmath.geometry.sphere_contains", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.sphereSDF", + "c": [ + "hmath_geometry_sphere_sdf" + ], + "python": "hmath.geometry.sphere_sdf", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleBarycentric", + "c": [ + "hmath_geometry_triangle_barycentric" + ], + "python": "hmath.geometry.triangle_barycentric", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleIntersection", + "c": [ + "hmath_geometry_triangle_intersection" + ], + "python": "hmath.geometry.triangle_intersection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleLocation", + "c": [ + "hmath_geometry_triangle_location" + ], + "python": "hmath.geometry.triangle_location", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.BVH", + "c": [ + "hmath_geometry_bvh" + ], + "python": "hmath.geometry.bvh", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.BallTree", + "c": [ + "hmath_geometry_ball_tree" + ], + "python": "hmath.geometry.ball_tree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.KDTree", + "c": [ + "hmath_geometry_kd_tree" + ], + "python": "hmath.geometry.kd_tree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.NeighborQuery", + "c": [ + "hmath_geometry_neighbor_query" + ], + "python": "hmath.geometry.neighbor_query", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.Octree", + "c": [ + "hmath_geometry_octree" + ], + "python": "hmath.geometry.octree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.Quadtree", + "c": [ + "hmath_geometry_quadtree" + ], + "python": "hmath.geometry.quadtree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.RTree", + "c": [ + "hmath_geometry_r_tree" + ], + "python": "hmath.geometry.r_tree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialHash", + "c": [ + "hmath_geometry_spatial_hash" + ], + "python": "hmath.geometry.spatial_hash", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.buildSpatialIndex", + "c": [ + "hmath_geometry_build_spatial_index" + ], + "python": "hmath.geometry.build_spatial_index", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.cloudPoints", + "c": [ + "hmath_geometry_cloud_points" + ], + "python": "hmath.geometry.cloud_points", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.nearestQuery", + "c": [ + "hmath_geometry_nearest_query" + ], + "python": "hmath.geometry.nearest_query", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.pointCloud", + "c": [ + "hmath_geometry_point_cloud" + ], + "python": "hmath.geometry.point_cloud", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryExhaustive", + "c": [ + "hmath_geometry_query_exhaustive" + ], + "python": "hmath.geometry.query_exhaustive", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryLeaves", + "c": [ + "hmath_geometry_query_leaves" + ], + "python": "hmath.geometry.query_leaves", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryNeighbors", + "c": [ + "hmath_geometry_query_neighbors" + ], + "python": "hmath.geometry.query_neighbors", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.radiusQuery", + "c": [ + "hmath_geometry_radius_query" + ], + "python": "hmath.geometry.radius_query", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.rangeQuery", + "c": [ + "hmath_geometry_range_query" + ], + "python": "hmath.geometry.range_query", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.affineTransform", + "c": [ + "hmath_geometry_affine_transform" + ], + "python": "hmath.geometry.affine_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.applyTransform", + "c": [ + "hmath_geometry_apply_transform" + ], + "python": "hmath.geometry.apply_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.composeTransforms", + "c": [ + "hmath_geometry_compose_transforms" + ], + "python": "hmath.geometry.compose_transforms", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.cullBox", + "c": [ + "hmath_geometry_cull_box" + ], + "python": "hmath.geometry.cull_box", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.cullSphere", + "c": [ + "hmath_geometry_cull_sphere" + ], + "python": "hmath.geometry.cull_sphere", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.extractFrustum", + "c": [ + "hmath_geometry_extract_frustum" + ], + "python": "hmath.geometry.extract_frustum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.inverseTransform", + "c": [ + "hmath_geometry_inverse_transform" + ], + "python": "hmath.geometry.inverse_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.lookAt", + "c": [ + "hmath_geometry_look_at" + ], + "python": "hmath.geometry.look_at", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.orthographic", + "c": [ + "hmath_geometry_orthographic" + ], + "python": "hmath.geometry.orthographic", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Transform.perspective", + "c": [ + "hmath_geometry_perspective" + ], + "python": "hmath.geometry.perspective", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.constrainedDelaunay", + "c": [ + "hmath_geometry_constrained_delaunay" + ], + "python": "hmath.geometry.constrained_delaunay", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.delaunay", + "c": [ + "hmath_geometry_delaunay" + ], + "python": "hmath.geometry.delaunay", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.earClip", + "c": [ + "hmath_geometry_ear_clip" + ], + "python": "hmath.geometry.ear_clip", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.voronoi", + "c": [ + "hmath_geometry_voronoi" + ], + "python": "hmath.geometry.voronoi", + "specializations": [ + "original concrete types" + ] + } + ] +} diff --git a/bindings/schema/geometry-symbols.txt b/bindings/schema/geometry-symbols.txt new file mode 100644 index 0000000..68c130f --- /dev/null +++ b/bindings/schema/geometry-symbols.txt @@ -0,0 +1,129 @@ +hmath_geometry_parts +hmath_geometry_describe +hmath_geometry_equal +hmath_geometry_penetration +hmath_geometry_epa +hmath_geometry_gjk +hmath_geometry_penetration_depth +hmath_geometry_penetration_error +hmath_geometry_penetration_iterations +hmath_geometry_penetration_normal +hmath_geometry_separating_axis +hmath_geometry_aabb +hmath_geometry_boundary +hmath_geometry_capsule +hmath_geometry_circle +hmath_geometry_clockwise +hmath_geometry_collinear +hmath_geometry_cone +hmath_geometry_counterclockwise +hmath_geometry_cylinder +hmath_geometry_ellipse +hmath_geometry_frustum +hmath_geometry_inside +hmath_geometry_line +hmath_geometry_obb +hmath_geometry_outside +hmath_geometry_p2 +hmath_geometry_p3 +hmath_geometry_plane +hmath_geometry_point_nd_raw +hmath_geometry_polygon +hmath_geometry_ray +hmath_geometry_rectangle +hmath_geometry_segment +hmath_geometry_sphere +hmath_geometry_triangle +hmath_geometry_point2 +hmath_geometry_point3 +hmath_geometry_point_nd +hmath_geometry_difference +hmath_geometry_gift_wrapping +hmath_geometry_graham_scan +hmath_geometry_intersection +hmath_geometry_monotone_chain +hmath_geometry_quickhull +hmath_geometry_union +hmath_geometry_clip_polygon +hmath_geometry_convex_hull +hmath_geometry_minimum_bounding_circle +hmath_geometry_minimum_bounding_rectangle +hmath_geometry_minkowski_sum +hmath_geometry_polygon_area +hmath_geometry_polygon_boolean +hmath_geometry_polygon_centroid +hmath_geometry_shoelace +hmath_geometry_chebyshev +hmath_geometry_circle_points +hmath_geometry_coincident_circles +hmath_geometry_coincident_line +hmath_geometry_disjoint_circles +hmath_geometry_euclidean +hmath_geometry_intersection_point +hmath_geometry_manhattan +hmath_geometry_minkowski +hmath_geometry_no_intersection +hmath_geometry_overlap_segment +hmath_geometry_box_contains +hmath_geometry_box_sdf +hmath_geometry_capsule_sdf +hmath_geometry_circle_intersection +hmath_geometry_circumcenter +hmath_geometry_cone_sdf +hmath_geometry_cosine_distance +hmath_geometry_cylinder_sdf +hmath_geometry_distance +hmath_geometry_ellipse_contains +hmath_geometry_hausdorff_distance +hmath_geometry_incenter +hmath_geometry_incircle +hmath_geometry_line_intersection +hmath_geometry_line_plane_intersection +hmath_geometry_mahalanobis_distance +hmath_geometry_obb_sdf +hmath_geometry_orientation +hmath_geometry_plane_intersection +hmath_geometry_point_line_distance +hmath_geometry_point_plane_distance +hmath_geometry_point_segment_distance +hmath_geometry_polygon_location +hmath_geometry_ray_box +hmath_geometry_ray_sphere +hmath_geometry_ray_triangle +hmath_geometry_segment_intersection +hmath_geometry_sphere_contains +hmath_geometry_sphere_sdf +hmath_geometry_triangle_barycentric +hmath_geometry_triangle_intersection +hmath_geometry_triangle_location +hmath_geometry_bvh +hmath_geometry_ball_tree +hmath_geometry_kd_tree +hmath_geometry_neighbor_query +hmath_geometry_octree +hmath_geometry_quadtree +hmath_geometry_r_tree +hmath_geometry_spatial_hash +hmath_geometry_build_spatial_index +hmath_geometry_cloud_points +hmath_geometry_nearest_query +hmath_geometry_point_cloud +hmath_geometry_query_exhaustive +hmath_geometry_query_leaves +hmath_geometry_query_neighbors +hmath_geometry_radius_query +hmath_geometry_range_query +hmath_geometry_affine_transform +hmath_geometry_apply_transform +hmath_geometry_compose_transforms +hmath_geometry_cull_box +hmath_geometry_cull_sphere +hmath_geometry_extract_frustum +hmath_geometry_inverse_transform +hmath_geometry_look_at +hmath_geometry_orthographic +hmath_geometry_perspective +hmath_geometry_constrained_delaunay +hmath_geometry_delaunay +hmath_geometry_ear_clip +hmath_geometry_voronoi diff --git a/bindings/schema/graph-functions.json b/bindings/schema/graph-functions.json new file mode 100644 index 0000000..77ad314 --- /dev/null +++ b/bindings/schema/graph-functions.json @@ -0,0 +1,540 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Graph.Analysis", + "name": "betweennessCentrality", + "signature": "Graph -> [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "bipartiteColors", + "signature": "Graph -> Maybe [Bool]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "closenessCentrality", + "signature": "Graph -> [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "clusteringCoefficients", + "signature": "Graph -> Either MathError [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "degreeCentrality", + "signature": "Graph -> [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "density", + "signature": "Graph -> Double" + }, + { + "module": "HMath.Graph.Analysis", + "name": "diameterRadius", + "signature": "Graph -> Maybe (Int, Int)" + }, + { + "module": "HMath.Graph.Analysis", + "name": "eigenvectorCentrality", + "signature": "Int -> Double -> Graph -> Either MathError [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "eulerianPath", + "signature": "Graph -> Either MathError (Maybe ([Int], [Int]))" + }, + { + "module": "HMath.Graph.Analysis", + "name": "exactColoring", + "signature": "Int -> Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "graphEditDistance", + "signature": "Int -> Graph -> Graph -> Either MathError Int" + }, + { + "module": "HMath.Graph.Analysis", + "name": "graphLaplacian", + "signature": "Bool -> Graph -> Either MathError [[Double]]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "graphSimilarity", + "signature": "Graph -> Graph -> Either MathError Double" + }, + { + "module": "HMath.Graph.Analysis", + "name": "greedyColoring", + "signature": "Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "hamiltonianPath", + "signature": "Int -> Graph -> Either MathError (Maybe [Int])" + }, + { + "module": "HMath.Graph.Analysis", + "name": "katzCentrality", + "signature": "Int -> Double -> Double -> Double -> Graph -> Either MathError [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "labelPropagation", + "signature": "Int -> Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "laplacianSpectrum", + "signature": "Int -> Double -> Bool -> Graph -> Either MathError [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "louvain", + "signature": "Int -> Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "modularity", + "signature": "Graph -> [Int] -> Either MathError Double" + }, + { + "module": "HMath.Graph.Analysis", + "name": "nearestNeighborTour", + "signature": "Graph -> Int -> Either MathError (Maybe (Double, [Int]))" + }, + { + "module": "HMath.Graph.Analysis", + "name": "pageRank", + "signature": "Int -> Double -> Double -> Graph -> Either MathError [Double]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "randomWalk", + "signature": "Int -> Word64 -> Graph -> Int -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Analysis", + "name": "twoOptTour", + "signature": "Int -> Graph -> [Int] -> Either MathError (Double, [Int])" + }, + { + "module": "HMath.Graph.Core", + "name": "CSR", + "signature": "Bool -> Int -> [Int] -> [Int] -> [Double] -> [Int] -> [(Int, Int)] -> CSR" + }, + { + "module": "HMath.Graph.Core", + "name": "Edge", + "signature": "Int -> Int -> Int -> Double -> Edge" + }, + { + "module": "HMath.Graph.Core", + "name": "adjacencyList", + "signature": "Graph -> [[(Int, Double, Int)]]" + }, + { + "module": "HMath.Graph.Core", + "name": "adjacencyMatrix", + "signature": "Graph -> [[[(Int, Double)]]]" + }, + { + "module": "HMath.Graph.Core", + "name": "arcs", + "signature": "Graph -> [Edge]" + }, + { + "module": "HMath.Graph.Core", + "name": "articulationPoints", + "signature": "Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "bfs", + "signature": "Graph -> Int -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "bipartiteBase", + "signature": "BipartiteGraph -> Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "bipartiteGraph", + "signature": "Int -> Int -> [(Int, Int, Double)] -> Either MathError BipartiteGraph" + }, + { + "module": "HMath.Graph.Core", + "name": "bipartiteParts", + "signature": "BipartiteGraph -> (Int, Int)" + }, + { + "module": "HMath.Graph.Core", + "name": "boruvka", + "signature": "Graph -> Either MathError [Edge]" + }, + { + "module": "HMath.Graph.Core", + "name": "bridges", + "signature": "Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "checkVertex", + "signature": "Graph -> Int -> Either MathError ()" + }, + { + "module": "HMath.Graph.Core", + "name": "connectedComponents", + "signature": "Graph -> [[Int]]" + }, + { + "module": "HMath.Graph.Core", + "name": "csrDirected", + "signature": "CSR -> Bool" + }, + { + "module": "HMath.Graph.Core", + "name": "csrIds", + "signature": "CSR -> [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "csrOffsets", + "signature": "CSR -> [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "csrOrientations", + "signature": "CSR -> [(Int, Int)]" + }, + { + "module": "HMath.Graph.Core", + "name": "csrTargets", + "signature": "CSR -> [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "csrVertices", + "signature": "CSR -> Int" + }, + { + "module": "HMath.Graph.Core", + "name": "csrWeights", + "signature": "CSR -> [Double]" + }, + { + "module": "HMath.Graph.Core", + "name": "deserializeBipartiteGraph", + "signature": "String -> Either MathError BipartiteGraph" + }, + { + "module": "HMath.Graph.Core", + "name": "deserializeGraph", + "signature": "String -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "deserializeHypergraph", + "signature": "String -> Either MathError Hypergraph" + }, + { + "module": "HMath.Graph.Core", + "name": "dfs", + "signature": "Graph -> Int -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "directed", + "signature": "Graph -> Bool" + }, + { + "module": "HMath.Graph.Core", + "name": "edgeFrom", + "signature": "Edge -> Int" + }, + { + "module": "HMath.Graph.Core", + "name": "edgeId", + "signature": "Edge -> Int" + }, + { + "module": "HMath.Graph.Core", + "name": "edgeTo", + "signature": "Edge -> Int" + }, + { + "module": "HMath.Graph.Core", + "name": "edgeWeight", + "signature": "Edge -> Double" + }, + { + "module": "HMath.Graph.Core", + "name": "edges", + "signature": "Graph -> [Edge]" + }, + { + "module": "HMath.Graph.Core", + "name": "finite", + "signature": "Double -> Bool" + }, + { + "module": "HMath.Graph.Core", + "name": "fromAdjacencyList", + "signature": "Bool -> [[(Int, Double, Int)]] -> [(Int, Int)] -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "fromAdjacencyMatrix", + "signature": "Bool -> [[[Double]]] -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "fromCSR", + "signature": "CSR -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "fromLabeledAdjacencyMatrix", + "signature": "Bool -> [[[(Int, Double)]]] -> [(Int, Int)] -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "graph", + "signature": "Bool -> Int -> [(Int, Int, Double)] -> Either MathError Graph" + }, + { + "module": "HMath.Graph.Core", + "name": "hasCycle", + "signature": "Graph -> Bool" + }, + { + "module": "HMath.Graph.Core", + "name": "hyperVertices", + "signature": "Hypergraph -> Int" + }, + { + "module": "HMath.Graph.Core", + "name": "hyperedges", + "signature": "Hypergraph -> [[Int]]" + }, + { + "module": "HMath.Graph.Core", + "name": "hypergraph", + "signature": "Int -> [[Int]] -> Either MathError Hypergraph" + }, + { + "module": "HMath.Graph.Core", + "name": "iterativeDeepening", + "signature": "Int -> Graph -> Int -> Int -> Either MathError (Maybe [Int])" + }, + { + "module": "HMath.Graph.Core", + "name": "kosarajuSCC", + "signature": "Graph -> [[Int]]" + }, + { + "module": "HMath.Graph.Core", + "name": "kruskal", + "signature": "Graph -> Either MathError [Edge]" + }, + { + "module": "HMath.Graph.Core", + "name": "neighbors", + "signature": "Graph -> Int -> [(Int, Double, Int)]" + }, + { + "module": "HMath.Graph.Core", + "name": "prim", + "signature": "Graph -> Either MathError [Edge]" + }, + { + "module": "HMath.Graph.Core", + "name": "requireUndirected", + "signature": "Graph -> Either MathError ()" + }, + { + "module": "HMath.Graph.Core", + "name": "serializeBipartiteGraph", + "signature": "BipartiteGraph -> String" + }, + { + "module": "HMath.Graph.Core", + "name": "serializeGraph", + "signature": "Graph -> String" + }, + { + "module": "HMath.Graph.Core", + "name": "serializeHypergraph", + "signature": "Hypergraph -> String" + }, + { + "module": "HMath.Graph.Core", + "name": "tarjanSCC", + "signature": "Graph -> [[Int]]" + }, + { + "module": "HMath.Graph.Core", + "name": "toCSR", + "signature": "Graph -> CSR" + }, + { + "module": "HMath.Graph.Core", + "name": "topologicalSort", + "signature": "Graph -> Either MathError [Int]" + }, + { + "module": "HMath.Graph.Core", + "name": "vertexCount", + "signature": "Graph -> Int" + }, + { + "module": "HMath.Graph.Flow", + "name": "FlowResult", + "signature": "Integer -> [Integer] -> Integer -> FlowResult" + }, + { + "module": "HMath.Graph.Flow", + "name": "NetworkEdge", + "signature": "Int -> Int -> Int -> Integer -> Integer -> NetworkEdge" + }, + { + "module": "HMath.Graph.Flow", + "name": "dinic", + "signature": "Int -> Network -> Int -> Int -> Either MathError FlowResult" + }, + { + "module": "HMath.Graph.Flow", + "name": "edgeFlows", + "signature": "FlowResult -> [Integer]" + }, + { + "module": "HMath.Graph.Flow", + "name": "edmondsKarp", + "signature": "Int -> Network -> Int -> Int -> Either MathError FlowResult" + }, + { + "module": "HMath.Graph.Flow", + "name": "flowCost", + "signature": "FlowResult -> Integer" + }, + { + "module": "HMath.Graph.Flow", + "name": "flowValue", + "signature": "FlowResult -> Integer" + }, + { + "module": "HMath.Graph.Flow", + "name": "fordFulkerson", + "signature": "Int -> Network -> Int -> Int -> Either MathError FlowResult" + }, + { + "module": "HMath.Graph.Flow", + "name": "hopcroftKarp", + "signature": "BipartiteGraph -> [(Int, Int)]" + }, + { + "module": "HMath.Graph.Flow", + "name": "hungarian", + "signature": "[[Integer]] -> Either MathError (Integer, [(Int, Int)])" + }, + { + "module": "HMath.Graph.Flow", + "name": "minimumCostMaximumFlow", + "signature": "Int -> Network -> Int -> Int -> Either MathError FlowResult" + }, + { + "module": "HMath.Graph.Flow", + "name": "minimumCut", + "signature": "Int -> Network -> Int -> Int -> Either MathError ([Int], Integer)" + }, + { + "module": "HMath.Graph.Flow", + "name": "network", + "signature": "Int -> [(Int, Int, Integer, Integer)] -> Either MathError Network" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkCapacity", + "signature": "NetworkEdge -> Integer" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkCost", + "signature": "NetworkEdge -> Integer" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkEdgeId", + "signature": "NetworkEdge -> Int" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkEdges", + "signature": "Network -> [NetworkEdge]" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkFrom", + "signature": "NetworkEdge -> Int" + }, + { + "module": "HMath.Graph.Flow", + "name": "networkTo", + "signature": "NetworkEdge -> Int" + }, + { + "module": "HMath.Graph.Flow", + "name": "pushRelabel", + "signature": "Int -> Network -> Int -> Int -> Either MathError FlowResult" + }, + { + "module": "HMath.Graph.Paths", + "name": "aStar", + "signature": "Graph -> (Int -> Double) -> Int -> Int -> Either MathError (Maybe (Double, [Int]))" + }, + { + "module": "HMath.Graph.Paths", + "name": "bellmanFord", + "signature": "Graph -> Int -> Either MathError [Maybe Double]" + }, + { + "module": "HMath.Graph.Paths", + "name": "bidirectionalDijkstra", + "signature": "Graph -> Int -> Int -> Either MathError (Maybe Double)" + }, + { + "module": "HMath.Graph.Paths", + "name": "dijkstra", + "signature": "Graph -> Int -> Either MathError [Maybe Double]" + }, + { + "module": "HMath.Graph.Paths", + "name": "floydWarshall", + "signature": "Graph -> Either MathError [[Maybe Double]]" + }, + { + "module": "HMath.Graph.Paths", + "name": "johnson", + "signature": "Graph -> Either MathError [[Maybe Double]]" + }, + { + "module": "HMath.Graph.Paths", + "name": "kShortestPaths", + "signature": "Int -> Int -> Graph -> Int -> Int -> Either MathError [(Double, [Int], [Int])]" + }, + { + "module": "HMath.Graph.Paths", + "name": "longestDAGPaths", + "signature": "Graph -> Int -> Either MathError [Maybe Double]" + }, + { + "module": "HMath.Graph.Paths", + "name": "multiSourceDijkstra", + "signature": "Graph -> [Int] -> Either MathError [Maybe Double]" + } + ] +} diff --git a/bindings/schema/graph-objects.json b/bindings/schema/graph-objects.json new file mode 100644 index 0000000..6cc1e66 --- /dev/null +++ b/bindings/schema/graph-objects.json @@ -0,0 +1,1105 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Graph.Core.Graph", + "c": [ + "hmath_graph_graph_object" + ], + "python": "hmath.graph.Graph", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Graph.Core.BipartiteGraph", + "c": [ + "hmath_graph_bipartite_graph_object" + ], + "python": "hmath.graph.BipartiteGraph", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Graph.Core.Hypergraph", + "c": [ + "hmath_graph_hypergraph_object" + ], + "python": "hmath.graph.Hypergraph", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Graph.Flow.Network", + "c": [ + "hmath_graph_network_object" + ], + "python": "hmath.graph.Network", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Graph.Analysis.betweennessCentrality", + "c": [ + "hmath_graph_betweenness_centrality" + ], + "python": "hmath.graph.betweenness_centrality", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.bipartiteColors", + "c": [ + "hmath_graph_bipartite_colors" + ], + "python": "hmath.graph.bipartite_colors", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.closenessCentrality", + "c": [ + "hmath_graph_closeness_centrality" + ], + "python": "hmath.graph.closeness_centrality", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.clusteringCoefficients", + "c": [ + "hmath_graph_clustering_coefficients" + ], + "python": "hmath.graph.clustering_coefficients", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.degreeCentrality", + "c": [ + "hmath_graph_degree_centrality" + ], + "python": "hmath.graph.degree_centrality", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.density", + "c": [ + "hmath_graph_density" + ], + "python": "hmath.graph.density", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.diameterRadius", + "c": [ + "hmath_graph_diameter_radius" + ], + "python": "hmath.graph.diameter_radius", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.eigenvectorCentrality", + "c": [ + "hmath_graph_eigenvector_centrality" + ], + "python": "hmath.graph.eigenvector_centrality", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.eulerianPath", + "c": [ + "hmath_graph_eulerian_path" + ], + "python": "hmath.graph.eulerian_path", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.exactColoring", + "c": [ + "hmath_graph_exact_coloring" + ], + "python": "hmath.graph.exact_coloring", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphEditDistance", + "c": [ + "hmath_graph_graph_edit_distance" + ], + "python": "hmath.graph.graph_edit_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphLaplacian", + "c": [ + "hmath_graph_graph_laplacian" + ], + "python": "hmath.graph.graph_laplacian", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphSimilarity", + "c": [ + "hmath_graph_graph_similarity" + ], + "python": "hmath.graph.graph_similarity", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.greedyColoring", + "c": [ + "hmath_graph_greedy_coloring" + ], + "python": "hmath.graph.greedy_coloring", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.hamiltonianPath", + "c": [ + "hmath_graph_hamiltonian_path" + ], + "python": "hmath.graph.hamiltonian_path", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.katzCentrality", + "c": [ + "hmath_graph_katz_centrality" + ], + "python": "hmath.graph.katz_centrality", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.labelPropagation", + "c": [ + "hmath_graph_label_propagation" + ], + "python": "hmath.graph.label_propagation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.laplacianSpectrum", + "c": [ + "hmath_graph_laplacian_spectrum" + ], + "python": "hmath.graph.laplacian_spectrum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.louvain", + "c": [ + "hmath_graph_louvain" + ], + "python": "hmath.graph.louvain", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.modularity", + "c": [ + "hmath_graph_modularity" + ], + "python": "hmath.graph.modularity", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.nearestNeighborTour", + "c": [ + "hmath_graph_nearest_neighbor_tour" + ], + "python": "hmath.graph.nearest_neighbor_tour", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.pageRank", + "c": [ + "hmath_graph_page_rank" + ], + "python": "hmath.graph.page_rank", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.randomWalk", + "c": [ + "hmath_graph_random_walk" + ], + "python": "hmath.graph.random_walk", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Analysis.twoOptTour", + "c": [ + "hmath_graph_two_opt_tour" + ], + "python": "hmath.graph.two_opt_tour", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.CSR", + "c": [ + "hmath_graph_csr" + ], + "python": "hmath.graph.csr", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.Edge", + "c": [ + "hmath_graph_edge" + ], + "python": "hmath.graph.edge", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.adjacencyList", + "c": [ + "hmath_graph_adjacency_list" + ], + "python": "hmath.graph.adjacency_list", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.adjacencyMatrix", + "c": [ + "hmath_graph_adjacency_matrix" + ], + "python": "hmath.graph.adjacency_matrix", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.arcs", + "c": [ + "hmath_graph_arcs" + ], + "python": "hmath.graph.arcs", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.articulationPoints", + "c": [ + "hmath_graph_articulation_points" + ], + "python": "hmath.graph.articulation_points", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.bfs", + "c": [ + "hmath_graph_bfs" + ], + "python": "hmath.graph.bfs", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteBase", + "c": [ + "hmath_graph_bipartite_base" + ], + "python": "hmath.graph.bipartite_base", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteGraph", + "c": [ + "hmath_graph_bipartite_graph" + ], + "python": "hmath.graph.bipartite_graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteParts", + "c": [ + "hmath_graph_bipartite_parts" + ], + "python": "hmath.graph.bipartite_parts", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.boruvka", + "c": [ + "hmath_graph_boruvka" + ], + "python": "hmath.graph.boruvka", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.bridges", + "c": [ + "hmath_graph_bridges" + ], + "python": "hmath.graph.bridges", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.checkVertex", + "c": [ + "hmath_graph_check_vertex" + ], + "python": "hmath.graph.check_vertex", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.connectedComponents", + "c": [ + "hmath_graph_connected_components" + ], + "python": "hmath.graph.connected_components", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrDirected", + "c": [ + "hmath_graph_csr_directed" + ], + "python": "hmath.graph.csr_directed", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrIds", + "c": [ + "hmath_graph_csr_ids" + ], + "python": "hmath.graph.csr_ids", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrOffsets", + "c": [ + "hmath_graph_csr_offsets" + ], + "python": "hmath.graph.csr_offsets", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrOrientations", + "c": [ + "hmath_graph_csr_orientations" + ], + "python": "hmath.graph.csr_orientations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrTargets", + "c": [ + "hmath_graph_csr_targets" + ], + "python": "hmath.graph.csr_targets", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrVertices", + "c": [ + "hmath_graph_csr_vertices" + ], + "python": "hmath.graph.csr_vertices", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.csrWeights", + "c": [ + "hmath_graph_csr_weights" + ], + "python": "hmath.graph.csr_weights", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeBipartiteGraph", + "c": [ + "hmath_graph_deserialize_bipartite_graph" + ], + "python": "hmath.graph.deserialize_bipartite_graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeGraph", + "c": [ + "hmath_graph_deserialize_graph" + ], + "python": "hmath.graph.deserialize_graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeHypergraph", + "c": [ + "hmath_graph_deserialize_hypergraph" + ], + "python": "hmath.graph.deserialize_hypergraph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.dfs", + "c": [ + "hmath_graph_dfs" + ], + "python": "hmath.graph.dfs", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.directed", + "c": [ + "hmath_graph_directed" + ], + "python": "hmath.graph.directed", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeFrom", + "c": [ + "hmath_graph_edge_from" + ], + "python": "hmath.graph.edge_from", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeId", + "c": [ + "hmath_graph_edge_id" + ], + "python": "hmath.graph.edge_id", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeTo", + "c": [ + "hmath_graph_edge_to" + ], + "python": "hmath.graph.edge_to", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeWeight", + "c": [ + "hmath_graph_edge_weight" + ], + "python": "hmath.graph.edge_weight", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.edges", + "c": [ + "hmath_graph_edges" + ], + "python": "hmath.graph.edges", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.fromAdjacencyList", + "c": [ + "hmath_graph_from_adjacency_list" + ], + "python": "hmath.graph.from_adjacency_list", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.fromAdjacencyMatrix", + "c": [ + "hmath_graph_from_adjacency_matrix" + ], + "python": "hmath.graph.from_adjacency_matrix", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.fromCSR", + "c": [ + "hmath_graph_from_csr" + ], + "python": "hmath.graph.from_csr", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.fromLabeledAdjacencyMatrix", + "c": [ + "hmath_graph_from_labeled_adjacency_matrix" + ], + "python": "hmath.graph.from_labeled_adjacency_matrix", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.graph", + "c": [ + "hmath_graph_graph" + ], + "python": "hmath.graph.graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.hasCycle", + "c": [ + "hmath_graph_has_cycle" + ], + "python": "hmath.graph.has_cycle", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.hyperVertices", + "c": [ + "hmath_graph_hyper_vertices" + ], + "python": "hmath.graph.hyper_vertices", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.hyperedges", + "c": [ + "hmath_graph_hyperedges" + ], + "python": "hmath.graph.hyperedges", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.hypergraph", + "c": [ + "hmath_graph_hypergraph" + ], + "python": "hmath.graph.hypergraph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.iterativeDeepening", + "c": [ + "hmath_graph_iterative_deepening" + ], + "python": "hmath.graph.iterative_deepening", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.kosarajuSCC", + "c": [ + "hmath_graph_kosaraju_scc" + ], + "python": "hmath.graph.kosaraju_scc", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.kruskal", + "c": [ + "hmath_graph_kruskal" + ], + "python": "hmath.graph.kruskal", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.neighbors", + "c": [ + "hmath_graph_neighbors" + ], + "python": "hmath.graph.neighbors", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.prim", + "c": [ + "hmath_graph_prim" + ], + "python": "hmath.graph.prim", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.requireUndirected", + "c": [ + "hmath_graph_require_undirected" + ], + "python": "hmath.graph.require_undirected", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeBipartiteGraph", + "c": [ + "hmath_graph_serialize_bipartite_graph" + ], + "python": "hmath.graph.serialize_bipartite_graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeGraph", + "c": [ + "hmath_graph_serialize_graph" + ], + "python": "hmath.graph.serialize_graph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeHypergraph", + "c": [ + "hmath_graph_serialize_hypergraph" + ], + "python": "hmath.graph.serialize_hypergraph", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.tarjanSCC", + "c": [ + "hmath_graph_tarjan_scc" + ], + "python": "hmath.graph.tarjan_scc", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.toCSR", + "c": [ + "hmath_graph_to_csr" + ], + "python": "hmath.graph.to_csr", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.topologicalSort", + "c": [ + "hmath_graph_topological_sort" + ], + "python": "hmath.graph.topological_sort", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Core.vertexCount", + "c": [ + "hmath_graph_vertex_count" + ], + "python": "hmath.graph.vertex_count", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.FlowResult", + "c": [ + "hmath_graph_flow_result" + ], + "python": "hmath.graph.flow_result", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.NetworkEdge", + "c": [ + "hmath_graph_network_edge" + ], + "python": "hmath.graph.network_edge", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.dinic", + "c": [ + "hmath_graph_dinic" + ], + "python": "hmath.graph.dinic", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.edgeFlows", + "c": [ + "hmath_graph_edge_flows" + ], + "python": "hmath.graph.edge_flows", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.edmondsKarp", + "c": [ + "hmath_graph_edmonds_karp" + ], + "python": "hmath.graph.edmonds_karp", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.flowCost", + "c": [ + "hmath_graph_flow_cost" + ], + "python": "hmath.graph.flow_cost", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.flowValue", + "c": [ + "hmath_graph_flow_value" + ], + "python": "hmath.graph.flow_value", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.fordFulkerson", + "c": [ + "hmath_graph_ford_fulkerson" + ], + "python": "hmath.graph.ford_fulkerson", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.hopcroftKarp", + "c": [ + "hmath_graph_hopcroft_karp" + ], + "python": "hmath.graph.hopcroft_karp", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.hungarian", + "c": [ + "hmath_graph_hungarian" + ], + "python": "hmath.graph.hungarian", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.minimumCostMaximumFlow", + "c": [ + "hmath_graph_minimum_cost_maximum_flow" + ], + "python": "hmath.graph.minimum_cost_maximum_flow", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.minimumCut", + "c": [ + "hmath_graph_minimum_cut" + ], + "python": "hmath.graph.minimum_cut", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.network", + "c": [ + "hmath_graph_network" + ], + "python": "hmath.graph.network", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkCapacity", + "c": [ + "hmath_graph_network_capacity" + ], + "python": "hmath.graph.network_capacity", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkCost", + "c": [ + "hmath_graph_network_cost" + ], + "python": "hmath.graph.network_cost", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkEdgeId", + "c": [ + "hmath_graph_network_edge_id" + ], + "python": "hmath.graph.network_edge_id", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkEdges", + "c": [ + "hmath_graph_network_edges" + ], + "python": "hmath.graph.network_edges", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkFrom", + "c": [ + "hmath_graph_network_from" + ], + "python": "hmath.graph.network_from", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkTo", + "c": [ + "hmath_graph_network_to" + ], + "python": "hmath.graph.network_to", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Flow.pushRelabel", + "c": [ + "hmath_graph_push_relabel" + ], + "python": "hmath.graph.push_relabel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.aStar", + "c": [ + "hmath_graph_a_star" + ], + "python": "hmath.graph.a_star", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.bellmanFord", + "c": [ + "hmath_graph_bellman_ford" + ], + "python": "hmath.graph.bellman_ford", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.bidirectionalDijkstra", + "c": [ + "hmath_graph_bidirectional_dijkstra" + ], + "python": "hmath.graph.bidirectional_dijkstra", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.dijkstra", + "c": [ + "hmath_graph_dijkstra" + ], + "python": "hmath.graph.dijkstra", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.floydWarshall", + "c": [ + "hmath_graph_floyd_warshall" + ], + "python": "hmath.graph.floyd_warshall", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.johnson", + "c": [ + "hmath_graph_johnson" + ], + "python": "hmath.graph.johnson", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.kShortestPaths", + "c": [ + "hmath_graph_k_shortest_paths" + ], + "python": "hmath.graph.k_shortest_paths", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.longestDAGPaths", + "c": [ + "hmath_graph_longest_dag_paths" + ], + "python": "hmath.graph.longest_dag_paths", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Graph.Paths.multiSourceDijkstra", + "c": [ + "hmath_graph_multi_source_dijkstra" + ], + "python": "hmath.graph.multi_source_dijkstra", + "specializations": [ + "original concrete types" + ] + } + ] +} diff --git a/bindings/schema/image-objects.json b/bindings/schema/image-objects.json new file mode 100644 index 0000000..429ba92 --- /dev/null +++ b/bindings/schema/image-objects.json @@ -0,0 +1,915 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Image.Core.Image", + "c": [ + "hmath_image_image_object" + ], + "python": "hmath.image.Image", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Tensor.Tensor", + "c": [ + "hmath_image_tensor_double_object" + ], + "python": "hmath.image.TensorDouble", + "specializations": [ + "Double only" + ] + }, + { + "symbol": "HMath.Image.Core.Boundary", + "c": [ + "hmath_image_boundary_object" + ], + "python": "hmath.image.Boundary", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Filter.GradientOperator", + "c": [ + "hmath_image_gradient_operator_object" + ], + "python": "hmath.image.GradientOperator", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Filter.Morphology", + "c": [ + "hmath_image_morphology_object" + ], + "python": "hmath.image.Morphology", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Measure.TemplateMetric", + "c": [ + "hmath_image_template_metric_object" + ], + "python": "hmath.image.TemplateMetric", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Spatial.Interpolation", + "c": [ + "hmath_image_interpolation_object" + ], + "python": "hmath.image.Interpolation", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Spatial.Connectivity", + "c": [ + "hmath_image_connectivity_object" + ], + "python": "hmath.image.Connectivity", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Color.ColorSpace", + "c": [ + "hmath_image_color_space_object" + ], + "python": "hmath.image.ColorSpace", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Image.Core.image", + "c": [ + "hmath_image_image" + ], + "python": "hmath.image.image", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.fromTensor", + "c": [ + "hmath_image_from_tensor" + ], + "python": "hmath.image.from_tensor", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.toTensor", + "c": [ + "hmath_image_to_tensor" + ], + "python": "hmath.image.to_tensor", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.imageShape", + "c": [ + "hmath_image_image_shape" + ], + "python": "hmath.image.image_shape", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.imageChannels", + "c": [ + "hmath_image_image_channels" + ], + "python": "hmath.image.image_channels", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.imageValues", + "c": [ + "hmath_image_image_values" + ], + "python": "hmath.image.image_values", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.pixel", + "c": [ + "hmath_image_pixel" + ], + "python": "hmath.image.pixel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.channel", + "c": [ + "hmath_image_channel" + ], + "python": "hmath.image.channel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.combineChannels", + "c": [ + "hmath_image_combine_channels" + ], + "python": "hmath.image.combine_channels", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.mapImage", + "c": [ + "hmath_image_map_image" + ], + "python": "hmath.image.map_image", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.zipImage", + "c": [ + "hmath_image_zip_image" + ], + "python": "hmath.image.zip_image", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.normalize", + "c": [ + "hmath_image_normalize" + ], + "python": "hmath.image.normalize", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.brightness", + "c": [ + "hmath_image_brightness" + ], + "python": "hmath.image.brightness", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.contrast", + "c": [ + "hmath_image_contrast" + ], + "python": "hmath.image.contrast", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.gamma", + "c": [ + "hmath_image_gamma" + ], + "python": "hmath.image.gamma", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.Constant", + "c": [ + "hmath_image_constant" + ], + "python": "hmath.image.constant", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.Clamp", + "c": [ + "hmath_image_clamp" + ], + "python": "hmath.image.clamp", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.Reflect", + "c": [ + "hmath_image_reflect" + ], + "python": "hmath.image.reflect", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Core.Wrap", + "c": [ + "hmath_image_wrap" + ], + "python": "hmath.image.wrap", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.convolve", + "c": [ + "hmath_image_convolve" + ], + "python": "hmath.image.convolve", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.correlate", + "c": [ + "hmath_image_correlate" + ], + "python": "hmath.image.correlate", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.gaussianBlur", + "c": [ + "hmath_image_gaussian_blur" + ], + "python": "hmath.image.gaussian_blur", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.boxBlur", + "c": [ + "hmath_image_box_blur" + ], + "python": "hmath.image.box_blur", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.medianBlur", + "c": [ + "hmath_image_median_blur" + ], + "python": "hmath.image.median_blur", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.bilateralBlur", + "c": [ + "hmath_image_bilateral_blur" + ], + "python": "hmath.image.bilateral_blur", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.sharpen", + "c": [ + "hmath_image_sharpen" + ], + "python": "hmath.image.sharpen", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.gradient", + "c": [ + "hmath_image_gradient" + ], + "python": "hmath.image.gradient", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.laplacian", + "c": [ + "hmath_image_laplacian" + ], + "python": "hmath.image.laplacian", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.canny", + "c": [ + "hmath_image_canny" + ], + "python": "hmath.image.canny", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.morphology", + "c": [ + "hmath_image_morphology" + ], + "python": "hmath.image.morphology", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.morphologicalGradient", + "c": [ + "hmath_image_morphological_gradient" + ], + "python": "hmath.image.morphological_gradient", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.validateBoundary", + "c": [ + "hmath_image_validate_boundary" + ], + "python": "hmath.image.validate_boundary", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.scalar2D", + "c": [ + "hmath_image_scalar2_d" + ], + "python": "hmath.image.scalar2_d", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.windowOffsets", + "c": [ + "hmath_image_window_offsets" + ], + "python": "hmath.image.window_offsets", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Sobel", + "c": [ + "hmath_image_sobel" + ], + "python": "hmath.image.sobel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Prewitt", + "c": [ + "hmath_image_prewitt" + ], + "python": "hmath.image.prewitt", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Scharr", + "c": [ + "hmath_image_scharr" + ], + "python": "hmath.image.scharr", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Erosion", + "c": [ + "hmath_image_erosion" + ], + "python": "hmath.image.erosion", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Dilation", + "c": [ + "hmath_image_dilation" + ], + "python": "hmath.image.dilation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Opening", + "c": [ + "hmath_image_opening" + ], + "python": "hmath.image.opening", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Filter.Closing", + "c": [ + "hmath_image_closing" + ], + "python": "hmath.image.closing", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.histogram", + "c": [ + "hmath_image_histogram" + ], + "python": "hmath.image.histogram", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.equalizeHistogram", + "c": [ + "hmath_image_equalize_histogram" + ], + "python": "hmath.image.equalize_histogram", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.clahe", + "c": [ + "hmath_image_clahe" + ], + "python": "hmath.image.clahe", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.threshold", + "c": [ + "hmath_image_threshold" + ], + "python": "hmath.image.threshold", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.otsu", + "c": [ + "hmath_image_otsu" + ], + "python": "hmath.image.otsu", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Histogram.adaptiveThreshold", + "c": [ + "hmath_image_adaptive_threshold" + ], + "python": "hmath.image.adaptive_threshold", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.templateMatch", + "c": [ + "hmath_image_template_match" + ], + "python": "hmath.image.template_match", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.rawMoment", + "c": [ + "hmath_image_raw_moment" + ], + "python": "hmath.image.raw_moment", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.centralMoment", + "c": [ + "hmath_image_central_moment" + ], + "python": "hmath.image.central_moment", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.imageCentroid", + "c": [ + "hmath_image_image_centroid" + ], + "python": "hmath.image.image_centroid", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.integralImage", + "c": [ + "hmath_image_integral_image" + ], + "python": "hmath.image.integral_image", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.rectangleSum", + "c": [ + "hmath_image_rectangle_sum" + ], + "python": "hmath.image.rectangle_sum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.meanSquaredError", + "c": [ + "hmath_image_mean_squared_error" + ], + "python": "hmath.image.mean_squared_error", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.peakSignalToNoise", + "c": [ + "hmath_image_peak_signal_to_noise" + ], + "python": "hmath.image.peak_signal_to_noise", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.structuralSimilarity", + "c": [ + "hmath_image_structural_similarity" + ], + "python": "hmath.image.structural_similarity", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.SquaredDifference", + "c": [ + "hmath_image_squared_difference" + ], + "python": "hmath.image.squared_difference", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Measure.NormalizedCorrelation", + "c": [ + "hmath_image_normalized_correlation" + ], + "python": "hmath.image.normalized_correlation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.resize", + "c": [ + "hmath_image_resize" + ], + "python": "hmath.image.resize", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.warp", + "c": [ + "hmath_image_warp" + ], + "python": "hmath.image.warp", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.translate", + "c": [ + "hmath_image_translate" + ], + "python": "hmath.image.translate", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.rotate", + "c": [ + "hmath_image_rotate" + ], + "python": "hmath.image.rotate", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.connectedComponents", + "c": [ + "hmath_image_connected_components" + ], + "python": "hmath.image.connected_components", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.distanceTransform", + "c": [ + "hmath_image_distance_transform" + ], + "python": "hmath.image.distance_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.Nearest", + "c": [ + "hmath_image_nearest" + ], + "python": "hmath.image.nearest", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.Bilinear", + "c": [ + "hmath_image_bilinear" + ], + "python": "hmath.image.bilinear", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.Bicubic", + "c": [ + "hmath_image_bicubic" + ], + "python": "hmath.image.bicubic", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.Lanczos", + "c": [ + "hmath_image_lanczos" + ], + "python": "hmath.image.lanczos", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.AxisConnected", + "c": [ + "hmath_image_axis_connected" + ], + "python": "hmath.image.axis_connected", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Spatial.FullyConnected", + "c": [ + "hmath_image_fully_connected" + ], + "python": "hmath.image.fully_connected", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.convertColor", + "c": [ + "hmath_image_convert_color" + ], + "python": "hmath.image.convert_color", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.grayscale", + "c": [ + "hmath_image_grayscale" + ], + "python": "hmath.image.grayscale", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.SRGB", + "c": [ + "hmath_image_srgb" + ], + "python": "hmath.image.srgb", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.LinearRGB", + "c": [ + "hmath_image_linear_rgb" + ], + "python": "hmath.image.linear_rgb", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.HSV", + "c": [ + "hmath_image_hsv" + ], + "python": "hmath.image.hsv", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.HSL", + "c": [ + "hmath_image_hsl" + ], + "python": "hmath.image.hsl", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.XYZ", + "c": [ + "hmath_image_xyz" + ], + "python": "hmath.image.xyz", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.Lab", + "c": [ + "hmath_image_lab" + ], + "python": "hmath.image.lab", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Image.Color.YCbCr", + "c": [ + "hmath_image_y_cb_cr" + ], + "python": "hmath.image.y_cb_cr", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Tensor.tensor", + "c": [ + "hmath_image_tensor" + ], + "python": "hmath.image.tensor", + "specializations": [ + "Double only" + ] + }, + { + "symbol": "HMath.Tensor.tensorShape", + "c": [ + "hmath_image_tensor_shape" + ], + "python": "hmath.image.tensor_shape", + "specializations": [ + "Double only" + ] + }, + { + "symbol": "HMath.Tensor.tensorValues", + "c": [ + "hmath_image_tensor_values" + ], + "python": "hmath.image.tensor_values", + "specializations": [ + "Double only" + ] + } + ] +} diff --git a/bindings/schema/image-symbols.txt b/bindings/schema/image-symbols.txt new file mode 100644 index 0000000..95660f3 --- /dev/null +++ b/bindings/schema/image-symbols.txt @@ -0,0 +1,82 @@ +hmath_image_image +hmath_image_from_tensor +hmath_image_to_tensor +hmath_image_image_shape +hmath_image_image_channels +hmath_image_image_values +hmath_image_pixel +hmath_image_channel +hmath_image_combine_channels +hmath_image_map_image +hmath_image_zip_image +hmath_image_normalize +hmath_image_brightness +hmath_image_contrast +hmath_image_gamma +hmath_image_constant +hmath_image_clamp +hmath_image_reflect +hmath_image_wrap +hmath_image_convolve +hmath_image_correlate +hmath_image_gaussian_blur +hmath_image_box_blur +hmath_image_median_blur +hmath_image_bilateral_blur +hmath_image_sharpen +hmath_image_gradient +hmath_image_laplacian +hmath_image_canny +hmath_image_morphology +hmath_image_morphological_gradient +hmath_image_validate_boundary +hmath_image_scalar2_d +hmath_image_window_offsets +hmath_image_sobel +hmath_image_prewitt +hmath_image_scharr +hmath_image_erosion +hmath_image_dilation +hmath_image_opening +hmath_image_closing +hmath_image_histogram +hmath_image_equalize_histogram +hmath_image_clahe +hmath_image_threshold +hmath_image_otsu +hmath_image_adaptive_threshold +hmath_image_template_match +hmath_image_raw_moment +hmath_image_central_moment +hmath_image_image_centroid +hmath_image_integral_image +hmath_image_rectangle_sum +hmath_image_mean_squared_error +hmath_image_peak_signal_to_noise +hmath_image_structural_similarity +hmath_image_squared_difference +hmath_image_normalized_correlation +hmath_image_resize +hmath_image_warp +hmath_image_translate +hmath_image_rotate +hmath_image_connected_components +hmath_image_distance_transform +hmath_image_nearest +hmath_image_bilinear +hmath_image_bicubic +hmath_image_lanczos +hmath_image_axis_connected +hmath_image_fully_connected +hmath_image_convert_color +hmath_image_grayscale +hmath_image_srgb +hmath_image_linear_rgb +hmath_image_hsv +hmath_image_hsl +hmath_image_xyz +hmath_image_lab +hmath_image_y_cb_cr +hmath_image_tensor +hmath_image_tensor_shape +hmath_image_tensor_values diff --git a/bindings/schema/interchange-functions.json b/bindings/schema/interchange-functions.json new file mode 100644 index 0000000..0cc7ec1 --- /dev/null +++ b/bindings/schema/interchange-functions.json @@ -0,0 +1,440 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Interchange.Array", + "name": "BigEndian", + "signature": "Endian" + }, + { + "module": "HMath.Interchange.Array", + "name": "Bool8", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "C128", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "C64", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "COrder", + "signature": "Order" + }, + { + "module": "HMath.Interchange.Array", + "name": "F32", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "F64", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "FOrder", + "signature": "Order" + }, + { + "module": "HMath.Interchange.Array", + "name": "I16", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "I32", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "I64", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "I8", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "InterchangeIOError", + "signature": "String -> InterchangeError" + }, + { + "module": "HMath.Interchange.Array", + "name": "InvalidData", + "signature": "String -> InterchangeError" + }, + { + "module": "HMath.Interchange.Array", + "name": "LimitExceeded", + "signature": "String -> InterchangeError" + }, + { + "module": "HMath.Interchange.Array", + "name": "Limits", + "signature": "Int -> Int -> Int -> Int -> Int -> Limits" + }, + { + "module": "HMath.Interchange.Array", + "name": "LittleEndian", + "signature": "Endian" + }, + { + "module": "HMath.Interchange.Array", + "name": "U16", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "U32", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "U64", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "U8", + "signature": "DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "Unsupported", + "signature": "String -> InterchangeError" + }, + { + "module": "HMath.Interchange.Array", + "name": "array", + "signature": "Limits -> DType -> Endian -> [Int] -> [Int] -> Int -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayBytes", + "signature": "Array -> ByteString" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayDType", + "signature": "Array -> DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayEndian", + "signature": "Array -> Endian" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayMetadata", + "signature": "Array -> [(String, String)]" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayOffset", + "signature": "Array -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayShape", + "signature": "Array -> [Int]" + }, + { + "module": "HMath.Interchange.Array", + "name": "arrayStrides", + "signature": "Array -> [Int]" + }, + { + "module": "HMath.Interchange.Array", + "name": "contiguousArray", + "signature": "Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "defaultLimits", + "signature": "Limits" + }, + { + "module": "HMath.Interchange.Array", + "name": "denseStrides", + "signature": "Order -> Int -> [Int] -> [Int]" + }, + { + "module": "HMath.Interchange.Array", + "name": "elementBytes", + "signature": "DType -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "elementCount", + "signature": "Array -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "elementType", + "signature": "Element a => proxy a -> DType" + }, + { + "module": "HMath.Interchange.Array", + "name": "fromMatrix", + "signature": "Element a => Limits -> Endian -> HMath.Matrix.Matrix a -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "fromTensor", + "signature": "Element a => Limits -> Endian -> HMath.Tensor.Tensor a -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "fromValues", + "signature": "Element a => Limits -> Endian -> [Int] -> [a] -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "getElement", + "signature": "Element a => Endian -> Data.Binary.Get.Internal.Get a" + }, + { + "module": "HMath.Interchange.Array", + "name": "maxArchiveEntries", + "signature": "Limits -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "maxBytes", + "signature": "Limits -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "maxElements", + "signature": "Limits -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "maxMetadata", + "signature": "Limits -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "maxRank", + "signature": "Limits -> Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "putElement", + "signature": "Element a => Endian -> a -> Data.Binary.Put.Put" + }, + { + "module": "HMath.Interchange.Array", + "name": "rawDecode", + "signature": "Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "rawEncode", + "signature": "Limits -> Endian -> Order -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Array", + "name": "repack", + "signature": "Limits -> Endian -> Order -> Array -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Array", + "name": "toMatrix", + "signature": "Element a => Array -> Either InterchangeError (HMath.Matrix.Matrix a)" + }, + { + "module": "HMath.Interchange.Array", + "name": "toTensor", + "signature": "Element a => Array -> Either InterchangeError (HMath.Tensor.Tensor a)" + }, + { + "module": "HMath.Interchange.Array", + "name": "toValues", + "signature": "Element a => Array -> Either InterchangeError [a]" + }, + { + "module": "HMath.Interchange.Array", + "name": "validateShape", + "signature": "Limits -> [Int] -> Either InterchangeError Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "withMetadata", + "signature": "Limits -> [(String, String)] -> Array -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Binary", + "name": "crc32", + "signature": "ByteString -> Word32" + }, + { + "module": "HMath.Interchange.Binary", + "name": "decodeBinary", + "signature": "Limits -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Binary", + "name": "encodeBinary", + "signature": "Limits -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Compression", + "name": "Gzip", + "signature": "Compression" + }, + { + "module": "HMath.Interchange.Compression", + "name": "RawDeflate", + "signature": "Compression" + }, + { + "module": "HMath.Interchange.Compression", + "name": "Zlib", + "signature": "Compression" + }, + { + "module": "HMath.Interchange.Compression", + "name": "compress", + "signature": "Limits -> Compression -> ByteString -> IO (Either InterchangeError ByteString)" + }, + { + "module": "HMath.Interchange.Compression", + "name": "compressionAvailable", + "signature": "IO Bool" + }, + { + "module": "HMath.Interchange.Compression", + "name": "decompress", + "signature": "Limits -> Compression -> Int -> ByteString -> IO (Either InterchangeError ByteString)" + }, + { + "module": "HMath.Interchange.IO", + "name": "RawSpec", + "signature": "DType -> Endian -> Order -> [Int] -> RawSpec" + }, + { + "module": "HMath.Interchange.IO", + "name": "mappedReadBytes", + "signature": "forall {k} (s :: k). MappedArray s -> Int -> Int -> IO (Either InterchangeError ByteString)" + }, + { + "module": "HMath.Interchange.IO", + "name": "mappedShape", + "signature": "forall {k} (s :: k). MappedArray s -> [Int]" + }, + { + "module": "HMath.Interchange.IO", + "name": "mappedValue", + "signature": "forall {k} a (s :: k). Element a => MappedArray s -> [Int] -> IO (Either InterchangeError a)" + }, + { + "module": "HMath.Interchange.IO", + "name": "readArrayFile", + "signature": "Limits -> (ByteString -> Either InterchangeError Array) -> FilePath -> IO (Either InterchangeError Array)" + }, + { + "module": "HMath.Interchange.IO", + "name": "readRawChunks", + "signature": "Limits -> RawSpec -> Int -> Handle -> (Array -> IO (Either InterchangeError Bool)) -> IO (Either InterchangeError ())" + }, + { + "module": "HMath.Interchange.IO", + "name": "withMappedArray", + "signature": "Limits -> RawSpec -> FilePath -> (forall (s :: k). MappedArray s -> IO a) -> IO (Either InterchangeError a)" + }, + { + "module": "HMath.Interchange.IO", + "name": "writeArrayFile", + "signature": "Limits -> (Limits -> Array -> Either InterchangeError ByteString) -> FilePath -> Array -> IO (Either InterchangeError ())" + }, + { + "module": "HMath.Interchange.IO", + "name": "writeRawChunks", + "signature": "Limits -> RawSpec -> Int -> Handle -> (Int -> IO (Either InterchangeError (Maybe ByteString))) -> IO (Either InterchangeError ())" + }, + { + "module": "HMath.Interchange.Numpy", + "name": "decodeNpy", + "signature": "Limits -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Numpy", + "name": "decodeNpz", + "signature": "Limits -> ByteString -> IO (Either InterchangeError [(String, Array)])" + }, + { + "module": "HMath.Interchange.Numpy", + "name": "encodeNpy", + "signature": "Limits -> Order -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Numpy", + "name": "encodeNpz", + "signature": "Limits -> Bool -> [(String, Array)] -> IO (Either InterchangeError ByteString)" + }, + { + "module": "HMath.Interchange.Text", + "name": "decodeDelimited", + "signature": "Limits -> Char -> DType -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Text", + "name": "decodeMatrixMarket", + "signature": "Limits -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Text", + "name": "decodeText", + "signature": "Limits -> ByteString -> Either InterchangeError Array" + }, + { + "module": "HMath.Interchange.Text", + "name": "encodeDelimited", + "signature": "Limits -> Char -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Text", + "name": "encodeMatrixMarket", + "signature": "Limits -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Text", + "name": "encodeText", + "signature": "Limits -> Array -> Either InterchangeError ByteString" + }, + { + "module": "HMath.Interchange.Array", + "name": "boundedInt", + "signature": "String -> Integer -> Integer -> Either InterchangeError Int" + }, + { + "module": "HMath.Interchange.Array", + "name": "byteOffsets", + "signature": "Array -> [Int]" + }, + { + "module": "HMath.Interchange.Array", + "name": "checkLimits", + "signature": "Limits -> Either InterchangeError ()" + }, + { + "module": "HMath.Interchange.Array", + "name": "guardI", + "signature": "Bool -> InterchangeError -> Either InterchangeError ()" + }, + { + "module": "HMath.Interchange.Binary", + "name": "runDecoder", + "signature": "Get a -> ByteString -> Either InterchangeError a" + } + ] +} diff --git a/bindings/schema/interchange-objects.json b/bindings/schema/interchange-objects.json new file mode 100644 index 0000000..4248a95 --- /dev/null +++ b/bindings/schema/interchange-objects.json @@ -0,0 +1,957 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Interchange.Array.Array", + "c": [ + "hmath_interchange_array_object" + ], + "python": "hmath.interchange.Array", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Array.InterchangeError", + "c": [ + "hmath_interchange_interchange_error_object" + ], + "python": "hmath.interchange.InterchangeError", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Array.DType", + "c": [ + "hmath_interchange_d_type_object" + ], + "python": "hmath.interchange.DType", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Array.Endian", + "c": [ + "hmath_interchange_endian_object" + ], + "python": "hmath.interchange.Endian", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Array.Order", + "c": [ + "hmath_interchange_order_object" + ], + "python": "hmath.interchange.Order", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Compression", + "c": [ + "hmath_interchange_compression_object" + ], + "python": "hmath.interchange.Compression", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.IO.MappedArray", + "c": [ + "hmath_interchange_mapped_array_object" + ], + "python": "hmath.interchange.MappedArray", + "specializations": [ + "original structured type and scoped lifetime" + ] + }, + { + "symbol": "HMath.Interchange.Array.Element", + "c": [ + "hmath_interchange_value_element_type", + "hmath_interchange_value_get_element", + "hmath_interchange_value_put_element" + ], + "python": "hmath.interchange.Element", + "specializations": [ + "all13 original fixed-width Element dictionaries" + ] + }, + { + "symbol": "HMath.Interchange.Array.BigEndian", + "c": [ + "hmath_interchange_value_big_endian" + ], + "python": "hmath.interchange.big_endian", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.Bool8", + "c": [ + "hmath_interchange_value_bool8" + ], + "python": "hmath.interchange.bool8", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.C128", + "c": [ + "hmath_interchange_value_c128" + ], + "python": "hmath.interchange.c128", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.C64", + "c": [ + "hmath_interchange_value_c64" + ], + "python": "hmath.interchange.c64", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.COrder", + "c": [ + "hmath_interchange_value_c_order" + ], + "python": "hmath.interchange.c_order", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.F32", + "c": [ + "hmath_interchange_value_f32" + ], + "python": "hmath.interchange.f32", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.F64", + "c": [ + "hmath_interchange_value_f64" + ], + "python": "hmath.interchange.f64", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.FOrder", + "c": [ + "hmath_interchange_value_f_order" + ], + "python": "hmath.interchange.f_order", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.I16", + "c": [ + "hmath_interchange_value_i16" + ], + "python": "hmath.interchange.i16", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.I32", + "c": [ + "hmath_interchange_value_i32" + ], + "python": "hmath.interchange.i32", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.I64", + "c": [ + "hmath_interchange_value_i64" + ], + "python": "hmath.interchange.i64", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.I8", + "c": [ + "hmath_interchange_value_i8" + ], + "python": "hmath.interchange.i8", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.InterchangeIOError", + "c": [ + "hmath_interchange_value_interchange_io_error" + ], + "python": "hmath.interchange.interchange_io_error", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.InvalidData", + "c": [ + "hmath_interchange_value_invalid_data" + ], + "python": "hmath.interchange.invalid_data", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.LimitExceeded", + "c": [ + "hmath_interchange_value_limit_exceeded" + ], + "python": "hmath.interchange.limit_exceeded", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.Limits", + "c": [ + "hmath_interchange_value_limits" + ], + "python": "hmath.interchange.limits", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.LittleEndian", + "c": [ + "hmath_interchange_value_little_endian" + ], + "python": "hmath.interchange.little_endian", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.U16", + "c": [ + "hmath_interchange_value_u16" + ], + "python": "hmath.interchange.u16", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.U32", + "c": [ + "hmath_interchange_value_u32" + ], + "python": "hmath.interchange.u32", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.U64", + "c": [ + "hmath_interchange_value_u64" + ], + "python": "hmath.interchange.u64", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.U8", + "c": [ + "hmath_interchange_value_u8" + ], + "python": "hmath.interchange.u8", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.Unsupported", + "c": [ + "hmath_interchange_value_unsupported" + ], + "python": "hmath.interchange.unsupported", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.array", + "c": [ + "hmath_interchange_value_array" + ], + "python": "hmath.interchange.array", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayBytes", + "c": [ + "hmath_interchange_value_array_bytes" + ], + "python": "hmath.interchange.array_bytes", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayDType", + "c": [ + "hmath_interchange_value_array_d_type" + ], + "python": "hmath.interchange.array_d_type", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayEndian", + "c": [ + "hmath_interchange_value_array_endian" + ], + "python": "hmath.interchange.array_endian", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayMetadata", + "c": [ + "hmath_interchange_value_array_metadata" + ], + "python": "hmath.interchange.array_metadata", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayOffset", + "c": [ + "hmath_interchange_value_array_offset" + ], + "python": "hmath.interchange.array_offset", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayShape", + "c": [ + "hmath_interchange_value_array_shape" + ], + "python": "hmath.interchange.array_shape", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayStrides", + "c": [ + "hmath_interchange_value_array_strides" + ], + "python": "hmath.interchange.array_strides", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.contiguousArray", + "c": [ + "hmath_interchange_value_contiguous_array" + ], + "python": "hmath.interchange.contiguous_array", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.defaultLimits", + "c": [ + "hmath_interchange_value_default_limits" + ], + "python": "hmath.interchange.default_limits", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.denseStrides", + "c": [ + "hmath_interchange_value_dense_strides" + ], + "python": "hmath.interchange.dense_strides", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementBytes", + "c": [ + "hmath_interchange_value_element_bytes" + ], + "python": "hmath.interchange.element_bytes", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementCount", + "c": [ + "hmath_interchange_value_element_count" + ], + "python": "hmath.interchange.element_count", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementType", + "c": [ + "hmath_interchange_value_element_type" + ], + "python": "hmath.interchange.element_type", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromMatrix", + "c": [ + "hmath_interchange_value_from_matrix" + ], + "python": "hmath.interchange.from_matrix", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromTensor", + "c": [ + "hmath_interchange_value_from_tensor" + ], + "python": "hmath.interchange.from_tensor", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromValues", + "c": [ + "hmath_interchange_value_from_values" + ], + "python": "hmath.interchange.from_values", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.getElement", + "c": [ + "hmath_interchange_value_get_element" + ], + "python": "hmath.interchange.get_element", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxArchiveEntries", + "c": [ + "hmath_interchange_value_max_archive_entries" + ], + "python": "hmath.interchange.max_archive_entries", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxBytes", + "c": [ + "hmath_interchange_value_max_bytes" + ], + "python": "hmath.interchange.max_bytes", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxElements", + "c": [ + "hmath_interchange_value_max_elements" + ], + "python": "hmath.interchange.max_elements", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxMetadata", + "c": [ + "hmath_interchange_value_max_metadata" + ], + "python": "hmath.interchange.max_metadata", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxRank", + "c": [ + "hmath_interchange_value_max_rank" + ], + "python": "hmath.interchange.max_rank", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.putElement", + "c": [ + "hmath_interchange_value_put_element" + ], + "python": "hmath.interchange.put_element", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.rawDecode", + "c": [ + "hmath_interchange_value_raw_decode" + ], + "python": "hmath.interchange.raw_decode", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.rawEncode", + "c": [ + "hmath_interchange_value_raw_encode" + ], + "python": "hmath.interchange.raw_encode", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.repack", + "c": [ + "hmath_interchange_value_repack" + ], + "python": "hmath.interchange.repack", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.toMatrix", + "c": [ + "hmath_interchange_value_to_matrix" + ], + "python": "hmath.interchange.to_matrix", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.toTensor", + "c": [ + "hmath_interchange_value_to_tensor" + ], + "python": "hmath.interchange.to_tensor", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.toValues", + "c": [ + "hmath_interchange_value_to_values" + ], + "python": "hmath.interchange.to_values", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.validateShape", + "c": [ + "hmath_interchange_value_validate_shape" + ], + "python": "hmath.interchange.validate_shape", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.withMetadata", + "c": [ + "hmath_interchange_value_with_metadata" + ], + "python": "hmath.interchange.with_metadata", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Binary.crc32", + "c": [ + "hmath_interchange_value_crc32" + ], + "python": "hmath.interchange.crc32", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Binary.decodeBinary", + "c": [ + "hmath_interchange_value_decode_binary" + ], + "python": "hmath.interchange.decode_binary", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Binary.encodeBinary", + "c": [ + "hmath_interchange_value_encode_binary" + ], + "python": "hmath.interchange.encode_binary", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Gzip", + "c": [ + "hmath_interchange_value_gzip" + ], + "python": "hmath.interchange.gzip", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.RawDeflate", + "c": [ + "hmath_interchange_value_raw_deflate" + ], + "python": "hmath.interchange.raw_deflate", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Zlib", + "c": [ + "hmath_interchange_value_zlib" + ], + "python": "hmath.interchange.zlib", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.compress", + "c": [ + "hmath_interchange_value_compress" + ], + "python": "hmath.interchange.compress", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.compressionAvailable", + "c": [ + "hmath_interchange_value_compression_available" + ], + "python": "hmath.interchange.compression_available", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Compression.decompress", + "c": [ + "hmath_interchange_value_decompress" + ], + "python": "hmath.interchange.decompress", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.RawSpec", + "c": [ + "hmath_interchange_value_raw_spec" + ], + "python": "hmath.interchange.raw_spec", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedReadBytes", + "c": [ + "hmath_interchange_value_mapped_read_bytes" + ], + "python": "hmath.interchange.mapped_read_bytes", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedShape", + "c": [ + "hmath_interchange_value_mapped_shape" + ], + "python": "hmath.interchange.mapped_shape", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedValue", + "c": [ + "hmath_interchange_value_mapped_value" + ], + "python": "hmath.interchange.mapped_value", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.readArrayFile", + "c": [ + "hmath_interchange_value_read_array_file" + ], + "python": "hmath.interchange.read_array_file", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.readRawChunks", + "c": [ + "hmath_interchange_value_read_raw_chunks" + ], + "python": "hmath.interchange.read_raw_chunks", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.withMappedArray", + "c": [ + "hmath_interchange_value_with_mapped_array" + ], + "python": "hmath.interchange.with_mapped_array", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.writeArrayFile", + "c": [ + "hmath_interchange_value_write_array_file" + ], + "python": "hmath.interchange.write_array_file", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.IO.writeRawChunks", + "c": [ + "hmath_interchange_value_write_raw_chunks" + ], + "python": "hmath.interchange.write_raw_chunks", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.decodeNpy", + "c": [ + "hmath_interchange_value_decode_npy" + ], + "python": "hmath.interchange.decode_npy", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.decodeNpz", + "c": [ + "hmath_interchange_value_decode_npz" + ], + "python": "hmath.interchange.decode_npz", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.encodeNpy", + "c": [ + "hmath_interchange_value_encode_npy" + ], + "python": "hmath.interchange.encode_npy", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.encodeNpz", + "c": [ + "hmath_interchange_value_encode_npz" + ], + "python": "hmath.interchange.encode_npz", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeDelimited", + "c": [ + "hmath_interchange_value_decode_delimited" + ], + "python": "hmath.interchange.decode_delimited", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeMatrixMarket", + "c": [ + "hmath_interchange_value_decode_matrix_market" + ], + "python": "hmath.interchange.decode_matrix_market", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeText", + "c": [ + "hmath_interchange_value_decode_text" + ], + "python": "hmath.interchange.decode_text", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeDelimited", + "c": [ + "hmath_interchange_value_encode_delimited" + ], + "python": "hmath.interchange.encode_delimited", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeMatrixMarket", + "c": [ + "hmath_interchange_value_encode_matrix_market" + ], + "python": "hmath.interchange.encode_matrix_market", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeText", + "c": [ + "hmath_interchange_value_encode_text" + ], + "python": "hmath.interchange.encode_text", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.boundedInt", + "c": [ + "hmath_interchange_value_bounded_int" + ], + "python": "hmath.interchange.bounded_int", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.byteOffsets", + "c": [ + "hmath_interchange_value_byte_offsets" + ], + "python": "hmath.interchange.byte_offsets", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.checkLimits", + "c": [ + "hmath_interchange_value_check_limits" + ], + "python": "hmath.interchange.check_limits", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Array.guardI", + "c": [ + "hmath_interchange_value_guard_i" + ], + "python": "hmath.interchange.guard_i", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + }, + { + "symbol": "HMath.Interchange.Binary.runDecoder", + "c": [ + "hmath_interchange_value_run_decoder" + ], + "python": "hmath.interchange.run_decoder", + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ] + } + ] +} diff --git a/bindings/schema/linear-functions.json b/bindings/schema/linear-functions.json new file mode 100644 index 0000000..dee2b35 --- /dev/null +++ b/bindings/schema/linear-functions.json @@ -0,0 +1,8468 @@ +{ + "functions": [ + { + "module": "HMath.Vector", + "name": "vector", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Vector", + [ + "a" + ] + ], + "constraints": "", + "signature": "[a] -> Vector a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorValues", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "Vector a -> [a]", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorDimension", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "Vector a -> Int", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "fixedVector", + "args": [ + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "FixedVector", + [ + "n" + ], + [ + "a" + ] + ] + ], + "constraints": "(KnownNat n)", + "signature": "[a] -> Either MathError (FixedVector n a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "fixedValues", + "args": [ + [ + "FixedVector", + [ + "n" + ], + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "FixedVector n a -> [a]", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "sparseVector", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseVector", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Int -> [(Int, a)] -> Either MathError (SparseVector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "sparseVectorValues", + "args": [ + [ + "SparseVector", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "SparseVector a -> [a]", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorSlice", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorConcat", + "args": [ + [ + "list", + [ + "Vector", + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "[Vector a] -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorAdd", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorSubtract", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorScale", + "args": [ + [ + "a" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Vector", + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "a -> Vector a -> Vector a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "vectorDot", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "cross", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "outer", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "triple", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "Vector a -> Vector a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "norm0", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "(Eq a, Num a)", + "signature": "Vector a -> Int", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "norm1", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(Num a)", + "signature": "Vector a -> a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "norm2", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "normInfinity", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(Ord a, Num a)", + "signature": "Vector a -> a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "normP", + "args": [ + [ + "a" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "normalizeVector", + "args": [ + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "project", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "reflect", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "refract", + "args": [ + [ + "a" + ], + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Vector a -> Vector a -> Either MathError (Vector a)", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "distance", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "cosineSimilarity", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "angle", + "args": [ + [ + "Vector", + [ + "a" + ] + ], + [ + "Vector", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(RealFloat a)", + "signature": "Vector a -> Vector a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Vector", + "name": "gramSchmidt", + "args": [ + [ + "a" + ], + [ + "list", + [ + "Vector", + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Vector", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> [Vector a] -> Either MathError [Vector a]", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "generateMatrix", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "function", + [ + "Int" + ], + [ + "Int" + ], + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> (Int -> Int -> a) -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "triangularMatrix", + "args": [ + [ + "Bool" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Bool -> Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "symmetricMatrix", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Fractional a)", + "signature": "Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "hermitianMatrix", + "args": [ + [ + "Matrix", + [ + "Complex", + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Complex", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix (Complex a) -> Either MathError (Matrix (Complex a))", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "permutationMatrix", + "args": [ + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "[Int] -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "blockMatrix", + "args": [ + [ + "list", + [ + "list", + [ + "Matrix", + [ + "a" + ] + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "[[Matrix a]] -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "bandedMatrix", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Int -> Int -> [(Int, [a])] -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "conjugateTranspose", + "args": [ + [ + "Matrix", + [ + "Complex", + [ + "a" + ] + ] + ] + ], + "result": [ + "Matrix", + [ + "Complex", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix (Complex a) -> Matrix (Complex a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "zipMatrixWith", + "args": [ + [ + "function", + [ + "a" + ], + [ + "b" + ], + [ + "c" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "b" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "c" + ] + ] + ], + "constraints": "", + "signature": "(a -> b -> c) -> Matrix a -> Matrix b -> Either MathError (Matrix c)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "batchedMultiply", + "args": [ + [ + "list", + [ + "Matrix", + [ + "a" + ] + ] + ], + [ + "list", + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "constraints": "(Num a)", + "signature": "[Matrix a] -> [Matrix a] -> Either MathError [Matrix a]", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "kronecker", + "args": [ + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Matrix a -> Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "khatriRao", + "args": [ + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Matrix a -> Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixPower", + "args": [ + [ + "Integer" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Integer -> Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "trace", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "Matrix a -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixNorm1", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(Ord a, Num a)", + "signature": "Matrix a -> a", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixNormInfinity", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(Ord a, Num a)", + "signature": "Matrix a -> a", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "frobeniusNorm", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> a", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "spectralNorm", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixRank", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Int" + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Either MathError Int", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "pseudoinverse", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "conditionNumber", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "columnSpace", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "rowSpace", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "nullSpace", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "changeCoordinates", + "args": [ + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Matrix a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixExp", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixLog", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixSqrt", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "polar", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError (Matrix Double, Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "complexPseudoinverse", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Double -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double))", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixSqrtGeneral", + "args": [ + [ + "Double" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Int -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Advanced", + "name": "matrixLogGeneral", + "args": [ + [ + "Double" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Int -> Matrix Double -> Either MathError (Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "gaussianElimination", + "args": [ + [ + "a" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "Int" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Matrix a -> Either MathError (Matrix a, [Int])", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "gaussJordan", + "args": [ + [ + "a" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "Int" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Matrix a -> Either MathError (Matrix a, [Int])", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "cholesky", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "ldlt", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Matrix a, [a])", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "givensQR", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Matrix a, Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "bidiagonalize", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Bidiagonal", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Bidiagonal a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "tridiagonalize", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError (Matrix Double, Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "powerIteration", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Iteration", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "inverseIteration", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "a" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Iteration", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> a -> Matrix a -> [a] -> Either MathError (Iteration a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "rayleighIteration", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Iteration", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "arnoldi", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Arnoldi", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "lanczos", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Arnoldi", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "qrIteration", + "args": [ + [ + "a" + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Int -> Matrix a -> Either MathError (Matrix a, Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "jordanChains", + "args": [ + [ + "a" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Matrix a -> [(a, [[a]])] -> Either MathError (Matrix a, Matrix a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "jordanForm", + "args": [ + [ + "Matrix", + [ + "Rational" + ] + ], + [ + "list", + [ + "Rational" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "Rational" + ] + ], + [ + "Matrix", + [ + "Rational" + ] + ] + ] + ], + "constraints": "", + "signature": "Matrix Rational -> [Rational] -> Either MathError (Matrix Rational, Matrix Rational)", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "bidiagonalU", + "args": [ + [ + "Bidiagonal", + [ + "a" + ] + ] + ], + "result": [ + "Matrix", + [ + "a" + ] + ], + "constraints": "", + "signature": "Bidiagonal -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "bidiagonalB", + "args": [ + [ + "Bidiagonal", + [ + "a" + ] + ] + ], + "result": [ + "Matrix", + [ + "a" + ] + ], + "constraints": "", + "signature": "Bidiagonal -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "bidiagonalV", + "args": [ + [ + "Bidiagonal", + [ + "a" + ] + ] + ], + "result": [ + "Matrix", + [ + "a" + ] + ], + "constraints": "", + "signature": "Bidiagonal -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "Bidiagonal", + "args": [ + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Bidiagonal", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "iterationValue", + "args": [ + [ + "Iteration", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "Iteration -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "iterationVector", + "args": [ + [ + "Iteration", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "Iteration -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "iterationResidual", + "args": [ + [ + "Iteration", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "Iteration -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "iterationCount", + "args": [ + [ + "Iteration", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "Iteration -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "Iteration", + "args": [ + [ + "a" + ], + [ + "list", + [ + "a" + ] + ], + [ + "a" + ], + [ + "Int" + ] + ], + "result": [ + "Iteration", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "arnoldiBasis", + "args": [ + [ + "Arnoldi", + [ + "a" + ] + ] + ], + "result": [ + "Matrix", + [ + "a" + ] + ], + "constraints": "", + "signature": "Arnoldi -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "arnoldiHessenberg", + "args": [ + [ + "Arnoldi", + [ + "a" + ] + ] + ], + "result": [ + "Matrix", + [ + "a" + ] + ], + "constraints": "", + "signature": "Arnoldi -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Decomposition", + "name": "Arnoldi", + "args": [ + [ + "Matrix", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Arnoldi", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.Iterative", + "name": "defaultIterativeOptions", + "args": [], + "result": [ + "IterativeOptions", + [ + "a" + ] + ], + "constraints": "(Fractional a)", + "signature": "IterativeOptions a", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "applyPreconditioner", + "args": [ + [ + "Preconditioner", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Preconditioner a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "identityPreconditioner", + "args": [ + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Preconditioner", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Int -> Either MathError (Preconditioner a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "jacobiPreconditioner", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Preconditioner", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Preconditioner a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "blockJacobiPreconditioner", + "args": [ + [ + "list", + [ + "Int" + ] + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Preconditioner", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "[Int] -> Matrix a -> Either MathError (Preconditioner a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "ilu0Preconditioner", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Preconditioner", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Preconditioner a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "ic0Preconditioner", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Preconditioner", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Matrix a -> Either MathError (Preconditioner a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "conjugateGradient", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "preconditionedCG", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Preconditioner", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Preconditioner a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "gmres", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Int" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Int -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "minres", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "bicg", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "bicgstab", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "lsqr", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "lsmr", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "jacobiSolve", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "gaussSeidelSolve", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "sorSolve", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "a" + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "iterativeRefinement", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ], + [ + "Matrix", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "absoluteTolerance", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "IterativeOptions -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "relativeTolerance", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "IterativeOptions -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "maximumIterations", + "args": [ + [ + "IterativeOptions", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "IterativeOptions -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "IterativeOptions", + "args": [ + [ + "a" + ], + [ + "a" + ], + [ + "Int" + ] + ], + "result": [ + "IterativeOptions", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.Iterative", + "name": "iterativeSolution", + "args": [ + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "IterativeResult -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "iterativeIterations", + "args": [ + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "IterativeResult -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "iterativeResidualNorm", + "args": [ + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "IterativeResult -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "iterativeNormalResidualNorm", + "args": [ + [ + "IterativeResult", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "IterativeResult -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.Iterative", + "name": "IterativeResult", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "Int" + ], + [ + "a" + ], + [ + "a" + ] + ], + "result": [ + "IterativeResult", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "svd", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError SVD", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "fullSVD", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError SVD", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "truncatedSVD", + "args": [ + [ + "Int" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Int -> Matrix Double -> Either MathError SVD", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "randomizedSVD", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Integer" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Int -> Int -> Int -> Integer -> Matrix Double -> Either MathError SVD", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "eigen", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Eigen", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "symmetricEigen", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Eigen", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "generalizedEigen", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "GeneralizedEigen" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Matrix Double -> Either MathError GeneralizedEigen", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "schur", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Schur" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Schur", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qz", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "QZ" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Matrix Double -> Either MathError QZ", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "hessenberg", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Hessenberg" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Hessenberg", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "balance", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Balance" + ] + ], + "constraints": "", + "signature": "Matrix Double -> Either MathError Balance", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "complexSVD", + "args": [ + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "ComplexSVD" + ] + ], + "constraints": "", + "signature": "Matrix (Complex Double) -> Either MathError ComplexSVD", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "complexEigen", + "args": [ + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "Matrix (Complex Double) -> Either MathError Eigen", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "svdU", + "args": [ + [ + "SVD" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "SVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "singularValues", + "args": [ + [ + "SVD" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "SVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "svdVT", + "args": [ + [ + "SVD" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "SVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "SVD", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "SVD" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "eigenvalues", + "args": [ + [ + "Eigen" + ] + ], + "result": [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Eigen -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "eigenvectors", + "args": [ + [ + "Eigen" + ] + ], + "result": [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Eigen -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "Eigen", + "args": [ + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Eigen" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "eigenAlpha", + "args": [ + [ + "GeneralizedEigen" + ] + ], + "result": [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "GeneralizedEigen -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "eigenBeta", + "args": [ + [ + "GeneralizedEigen" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "GeneralizedEigen -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "generalizedEigenvectors", + "args": [ + [ + "GeneralizedEigen" + ] + ], + "result": [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "GeneralizedEigen -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "GeneralizedEigen", + "args": [ + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "GeneralizedEigen" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "schurQ", + "args": [ + [ + "Schur" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Schur -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "schurT", + "args": [ + [ + "Schur" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Schur -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "schurEigenvalues", + "args": [ + [ + "Schur" + ] + ], + "result": [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Schur -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "Schur", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Schur" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzQ", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzZ", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzS", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzT", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzAlpha", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "qzBeta", + "args": [ + [ + "QZ" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "QZ -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "QZ", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "QZ" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "hessenbergQ", + "args": [ + [ + "Hessenberg" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Hessenberg -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "hessenbergH", + "args": [ + [ + "Hessenberg" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Hessenberg -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "Hessenberg", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Hessenberg" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "balancedMatrix", + "args": [ + [ + "Balance" + ] + ], + "result": [ + "Matrix", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Balance -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "balanceScales", + "args": [ + [ + "Balance" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "Balance -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "Balance", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Balance" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "complexU", + "args": [ + [ + "ComplexSVD" + ] + ], + "result": [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "ComplexSVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "complexSingularValues", + "args": [ + [ + "ComplexSVD" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "ComplexSVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "complexVT", + "args": [ + [ + "ComplexSVD" + ] + ], + "result": [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "ComplexSVD -> field", + "constructor": false + }, + { + "module": "HMath.Matrix.LAPACK", + "name": "ComplexSVD", + "args": [ + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "ComplexSVD" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "sparse", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "Int" + ], + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Int -> Int -> [(Int, Int, a)] -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseShape", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "tuple", + [ + "Int" + ], + [ + "Int" + ] + ], + "constraints": "", + "signature": "Sparse a -> (Int, Int)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseEntries", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "Int" + ], + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "Sparse a -> [(Int, Int, a)]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "nonzeros", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "Sparse a -> Int", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "fromFormat", + "args": [ + [ + "SparseFormat", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "SparseFormat a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toCOO", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "Sparse a -> SparseFormat a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toCSR", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "Sparse a -> SparseFormat a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toCSC", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "Sparse a -> SparseFormat a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toDIA", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "Sparse a -> SparseFormat a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toBSR", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseFormat", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Int -> Int -> Sparse a -> Either MathError (SparseFormat a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "toELLPACK", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseFormat", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Sparse a -> Either MathError (SparseFormat a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseToDense", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Sparse a -> Either MathError (Matrix a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "denseToSparse", + "args": [ + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "Sparse", + [ + "a" + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Matrix a -> Sparse a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTranspose", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Sparse", + [ + "a" + ] + ], + "constraints": "", + "signature": "Sparse a -> Sparse a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseAdd", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Sparse a -> Sparse a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseSubtract", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Sparse a -> Sparse a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "spmv", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(Num a)", + "signature": "Sparse a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "spmm", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Sparse a -> Sparse a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseKronecker", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "Sparse a -> Sparse a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTriangularSolve", + "args": [ + [ + "Bool" + ], + [ + "Sparse", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Bool -> Sparse a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseDiagonalSolve", + "args": [ + [ + "Sparse", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Sparse a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseLULower", + "args": [ + [ + "SparseLU", + [ + "a" + ] + ] + ], + "result": [ + "Sparse", + [ + "a" + ] + ], + "constraints": "", + "signature": "SparseLU a -> Sparse a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseLUUpper", + "args": [ + [ + "SparseLU", + [ + "a" + ] + ] + ], + "result": [ + "Sparse", + [ + "a" + ] + ], + "constraints": "", + "signature": "SparseLU a -> Sparse a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseLUPermutation", + "args": [ + [ + "SparseLU", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "Int" + ] + ], + "constraints": "", + "signature": "SparseLU a -> [Int]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseLU", + "args": [ + [ + "a" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseLU", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "a -> Sparse a -> Either MathError (SparseLU a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseSolveLU", + "args": [ + [ + "SparseLU", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "SparseLU a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseCholesky", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Sparse a -> Either MathError (Sparse a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseQRUpper", + "args": [ + [ + "SparseQR", + [ + "a" + ] + ] + ], + "result": [ + "Sparse", + [ + "a" + ] + ], + "constraints": "", + "signature": "SparseQR a -> Sparse a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseQR", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseQR", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "Sparse a -> Either MathError (SparseQR a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseQRApplyQT", + "args": [ + [ + "SparseQR", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "SparseQR a -> [a] -> Either MathError [a]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseGraph", + "args": [ + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "a" + ] + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Sparse a -> Either MathError [(Int, [(Int, a)])]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseStorageBytes", + "args": [ + [ + "Int" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Integer" + ] + ], + "constraints": "", + "signature": "Int -> Sparse a -> Either MathError Integer", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTensor", + "args": [ + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "tuple", + [ + "list", + [ + "Int" + ] + ], + [ + "a" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseTensor", + [ + "a" + ] + ] + ], + "constraints": "(Eq a, Num a)", + "signature": "[Int] -> [([Int], a)] -> Either MathError (SparseTensor a)", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTensorShape", + "args": [ + [ + "SparseTensor", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "Int" + ] + ], + "constraints": "", + "signature": "SparseTensor a -> [Int]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTensorEntries", + "args": [ + [ + "SparseTensor", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "list", + [ + "Int" + ] + ], + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "SparseTensor a -> [([Int], a)]", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseTensorLookup", + "args": [ + [ + "SparseTensor", + [ + "a" + ] + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "a" + ] + ], + "constraints": "(Num a)", + "signature": "SparseTensor a -> [Int] -> Either MathError a", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseEigenReference", + "args": [ + [ + "Integer" + ], + [ + "Sparse", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "Integer -> Sparse Double -> Either MathError Eigen", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "sparseSVDReference", + "args": [ + [ + "Integer" + ], + [ + "Sparse", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Integer -> Sparse Double -> Either MathError SVD", + "constructor": false + }, + { + "module": "HMath.Sparse", + "name": "COO", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "Int" + ], + [ + "a" + ] + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "CSR", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "CSC", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "DIA", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "tuple", + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "BSR", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse", + "name": "ELLPACK", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Int" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "SparseFormat", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse.Spectral", + "name": "defaultSparseSpectralOptions", + "args": [], + "result": [ + "SparseSpectralOptions", + [ + "a" + ] + ], + "constraints": "(Fractional a)", + "signature": "SparseSpectralOptions a", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseDominantEigen", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ], + [ + "Sparse", + [ + "a" + ] + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseEigenResult", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "SparseSpectralOptions a -> Sparse a -> [a] -> Either MathError (SparseEigenResult a)", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseTruncatedSVD", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ], + [ + "Int" + ], + [ + "Integer" + ], + [ + "Sparse", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "constraints": "(RealFloat a)", + "signature": "SparseSpectralOptions a -> Int -> Integer -> Sparse a -> Either MathError (SparseSVD a)", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseAbsoluteTolerance", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "SparseSpectralOptions -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseRelativeTolerance", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "SparseSpectralOptions -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseIterationLimit", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "SparseSpectralOptions -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseWorkspaceLimit", + "args": [ + [ + "SparseSpectralOptions", + [ + "a" + ] + ] + ], + "result": [ + "Integer" + ], + "constraints": "", + "signature": "SparseSpectralOptions -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "SparseSpectralOptions", + "args": [ + [ + "a" + ], + [ + "a" + ], + [ + "Int" + ], + [ + "Integer" + ] + ], + "result": [ + "SparseSpectralOptions", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseEigenvalue", + "args": [ + [ + "SparseEigenResult", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "SparseEigenResult -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseEigenvector", + "args": [ + [ + "SparseEigenResult", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "SparseEigenResult -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseEigenResidual", + "args": [ + [ + "SparseEigenResult", + [ + "a" + ] + ] + ], + "result": [ + "a" + ], + "constraints": "", + "signature": "SparseEigenResult -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseEigenIterations", + "args": [ + [ + "SparseEigenResult", + [ + "a" + ] + ] + ], + "result": [ + "Int" + ], + "constraints": "", + "signature": "SparseEigenResult -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "SparseEigenResult", + "args": [ + [ + "a" + ], + [ + "list", + [ + "a" + ] + ], + [ + "a" + ], + [ + "Int" + ] + ], + "result": [ + "SparseEigenResult", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseSingularValues", + "args": [ + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "SparseSVD -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseLeftVectors", + "args": [ + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "SparseSVD -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseRightVectors", + "args": [ + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "list", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "SparseSVD -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseSingularResiduals", + "args": [ + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "SparseSVD -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "sparseSingularIterations", + "args": [ + [ + "SparseSVD", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "Int" + ] + ], + "constraints": "", + "signature": "SparseSVD -> field", + "constructor": false + }, + { + "module": "HMath.Sparse.Spectral", + "name": "SparseSVD", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ], + [ + "list", + [ + "list", + [ + "a" + ] + ] + ], + [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "a" + ] + ] + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "SparseSVD", + [ + "a" + ] + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "backendInfo", + "args": [ + [ + "Backend" + ] + ], + "result": [ + "BackendInfo" + ], + "constraints": "", + "signature": "Backend -> BackendInfo", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "pureBackend", + "args": [], + "result": [ + "Backend" + ], + "constraints": "", + "signature": "Backend", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "lapackAvailable", + "args": [], + "result": [ + "IO", + [ + "Bool" + ] + ], + "constraints": "", + "signature": "IO Bool", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "selectBackend", + "args": [ + [ + "BackendRequest" + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Backend" + ] + ] + ], + "constraints": "", + "signature": "BackendRequest -> IO (Either MathError Backend)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "setBackendThreads", + "args": [ + [ + "Backend" + ], + [ + "Int" + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "unit" + ] + ] + ], + "constraints": "", + "signature": "Backend -> Int -> IO (Either MathError ())", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "lapackStatus", + "args": [ + [ + "String" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "unit" + ] + ], + "constraints": "", + "signature": "String -> Int -> Either MathError ()", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "matrixFromLayout", + "args": [ + [ + "BackendLayout" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "constraints": "", + "signature": "BackendLayout -> Int -> Int -> [a] -> Either MathError (M.Matrix a)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "matrixToLayout", + "args": [ + [ + "BackendLayout" + ], + [ + "Matrix", + [ + "a" + ] + ] + ], + "result": [ + "list", + [ + "a" + ] + ], + "constraints": "", + "signature": "BackendLayout -> M.Matrix a -> [a]", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "axpy", + "args": [ + [ + "Backend" + ], + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Double -> [Double] -> [Double] -> IO (Either MathError [Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "dot", + "args": [ + [ + "Backend" + ], + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> [Double] -> [Double] -> IO (Either MathError Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "nrm2", + "args": [ + [ + "Backend" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> [Double] -> IO (Either MathError Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "gemv", + "args": [ + [ + "Backend" + ], + [ + "Transpose" + ], + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Transpose -> Double -> M.Matrix Double -> [Double] -> Double -> [Double] -> IO (Either MathError [Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "gemm", + "args": [ + [ + "Backend" + ], + [ + "Transpose" + ], + [ + "Transpose" + ], + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Transpose -> Transpose -> Double -> M.Matrix Double -> M.Matrix Double -> Double -> M.Matrix Double -> IO (Either MathError (M.Matrix Double))", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "complexGemm", + "args": [ + [ + "Backend" + ], + [ + "Transpose" + ], + [ + "Transpose" + ], + [ + "Complex", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "Complex", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Transpose -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> M.Matrix (Complex Double) -> Complex Double -> M.Matrix (Complex Double) -> IO (Either MathError (M.Matrix (Complex Double)))", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "complexAxpy", + "args": [ + [ + "Backend" + ], + [ + "Complex", + [ + "Double" + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Complex Double -> [Complex Double] -> [Complex Double] -> IO (Either MathError [Complex Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "complexDot", + "args": [ + [ + "Backend" + ], + [ + "Bool" + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Bool -> [Complex Double] -> [Complex Double] -> IO (Either MathError (Complex Double))", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "complexNrm2", + "args": [ + [ + "Backend" + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> [Complex Double] -> IO (Either MathError Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "complexGemv", + "args": [ + [ + "Backend" + ], + [ + "Transpose" + ], + [ + "Complex", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ], + [ + "Complex", + [ + "Double" + ] + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> [Complex Double] -> Complex Double -> [Complex Double] -> IO (Either MathError [Complex Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "batchedGemm", + "args": [ + [ + "Backend" + ], + [ + "Transpose" + ], + [ + "Transpose" + ], + [ + "Double" + ], + [ + "Double" + ], + [ + "list", + [ + "tuple", + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Matrix", + [ + "Double" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Transpose -> Transpose -> Double -> Double -> [(M.Matrix Double, M.Matrix Double, M.Matrix Double)] -> IO (Either MathError [M.Matrix Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "stridedBatchedGemm", + "args": [ + [ + "Backend" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Int" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "IO", + [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Matrix", + [ + "Double" + ] + ] + ] + ] + ], + "constraints": "", + "signature": "Backend -> Int -> Int -> Int -> Int -> Int -> [Double] -> Int -> [Double] -> IO (Either MathError [M.Matrix Double])", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendLU", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "LU", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> Either MathError (LU.LU Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendQR", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "QR", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> Either MathError (QR.QR Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendSolve", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendCholesky", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> Either MathError (M.Matrix Double)", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendLeastSquares", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendSVD", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> Either MathError L.SVD", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "backendSymmetricEigen", + "args": [ + [ + "Backend" + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "Backend -> M.Matrix Double -> Either MathError L.Eigen", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "pureSymmetricEigen", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Eigen" + ] + ], + "constraints": "", + "signature": "M.Matrix Double -> Either MathError L.Eigen", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "pureSVD", + "args": [ + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "SVD" + ] + ], + "constraints": "", + "signature": "M.Matrix Double -> Either MathError L.SVD", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "Pure", + "args": [], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "OpenBLAS", + "args": [], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "BLIS", + "args": [], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "OneMKL", + "args": [], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "Accelerate", + "args": [], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "LP64", + "args": [], + "result": [ + "IntegerABI" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "ILP64", + "args": [], + "result": [ + "IntegerABI" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "AutoBackend", + "args": [], + "result": [ + "BackendRequest" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "RequireBackend", + "args": [ + [ + "Provider" + ], + [ + "IntegerABI" + ], + [ + "Maybe", + [ + "String" + ] + ] + ], + "result": [ + "BackendRequest" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "selectedProvider", + "args": [ + [ + "BackendInfo" + ] + ], + "result": [ + "Provider" + ], + "constraints": "", + "signature": "BackendInfo -> field", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "selectedIntegerABI", + "args": [ + [ + "BackendInfo" + ] + ], + "result": [ + "IntegerABI" + ], + "constraints": "", + "signature": "BackendInfo -> field", + "constructor": false + }, + { + "module": "HMath.Backend", + "name": "BackendInfo", + "args": [ + [ + "Provider" + ], + [ + "IntegerABI" + ] + ], + "result": [ + "BackendInfo" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "RowMajor", + "args": [], + "result": [ + "BackendLayout" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "ColumnMajor", + "args": [], + "result": [ + "BackendLayout" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "NoTranspose", + "args": [], + "result": [ + "Transpose" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "Transpose", + "args": [], + "result": [ + "Transpose" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Backend", + "name": "ConjugateTranspose", + "args": [], + "result": [ + "Transpose" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + } + ], + "types": { + "Vector": { + "module": "HMath.Vector", + "alias": "V", + "namespace": "vector", + "name": "Vector", + "params": [ + "a" + ] + }, + "FixedVector": { + "module": "HMath.Vector", + "alias": "V", + "namespace": "vector", + "name": "FixedVector", + "params": [ + "n", + "a" + ] + }, + "SparseVector": { + "module": "HMath.Vector", + "alias": "V", + "namespace": "vector", + "name": "SparseVector", + "params": [ + "a" + ] + }, + "Bidiagonal": { + "module": "HMath.Matrix.Decomposition", + "alias": "D", + "namespace": "decomposition", + "name": "Bidiagonal", + "params": [ + "a" + ] + }, + "Iteration": { + "module": "HMath.Matrix.Decomposition", + "alias": "D", + "namespace": "decomposition", + "name": "Iteration", + "params": [ + "a" + ] + }, + "Arnoldi": { + "module": "HMath.Matrix.Decomposition", + "alias": "D", + "namespace": "decomposition", + "name": "Arnoldi", + "params": [ + "a" + ] + }, + "IterativeOptions": { + "module": "HMath.Matrix.Iterative", + "alias": "I", + "namespace": "iterative", + "name": "IterativeOptions", + "params": [ + "a" + ] + }, + "IterativeResult": { + "module": "HMath.Matrix.Iterative", + "alias": "I", + "namespace": "iterative", + "name": "IterativeResult", + "params": [ + "a" + ] + }, + "Preconditioner": { + "module": "HMath.Matrix.Iterative", + "alias": "I", + "namespace": "iterative", + "name": "Preconditioner", + "params": [ + "a" + ] + }, + "SVD": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "SVD", + "params": [] + }, + "Eigen": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "Eigen", + "params": [] + }, + "GeneralizedEigen": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "GeneralizedEigen", + "params": [] + }, + "Schur": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "Schur", + "params": [] + }, + "QZ": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "QZ", + "params": [] + }, + "Hessenberg": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "Hessenberg", + "params": [] + }, + "Balance": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "Balance", + "params": [] + }, + "ComplexSVD": { + "module": "HMath.Matrix.LAPACK", + "alias": "L", + "namespace": "lapack", + "name": "ComplexSVD", + "params": [] + }, + "Sparse": { + "module": "HMath.Sparse", + "alias": "S", + "namespace": "sparse", + "name": "Sparse", + "params": [ + "a" + ] + }, + "SparseFormat": { + "module": "HMath.Sparse", + "alias": "S", + "namespace": "sparse", + "name": "SparseFormat", + "params": [ + "a" + ] + }, + "SparseLU": { + "module": "HMath.Sparse", + "alias": "S", + "namespace": "sparse", + "name": "SparseLU", + "params": [ + "a" + ] + }, + "SparseQR": { + "module": "HMath.Sparse", + "alias": "S", + "namespace": "sparse", + "name": "SparseQR", + "params": [ + "a" + ] + }, + "SparseTensor": { + "module": "HMath.Sparse", + "alias": "S", + "namespace": "sparse", + "name": "SparseTensor", + "params": [ + "a" + ] + }, + "SparseSpectralOptions": { + "module": "HMath.Sparse.Spectral", + "alias": "P", + "namespace": "sparse_spectral", + "name": "SparseSpectralOptions", + "params": [ + "a" + ] + }, + "SparseEigenResult": { + "module": "HMath.Sparse.Spectral", + "alias": "P", + "namespace": "sparse_spectral", + "name": "SparseEigenResult", + "params": [ + "a" + ] + }, + "SparseSVD": { + "module": "HMath.Sparse.Spectral", + "alias": "P", + "namespace": "sparse_spectral", + "name": "SparseSVD", + "params": [ + "a" + ] + }, + "Provider": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "Provider", + "params": [] + }, + "IntegerABI": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "IntegerABI", + "params": [] + }, + "BackendRequest": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "BackendRequest", + "params": [] + }, + "BackendInfo": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "BackendInfo", + "params": [] + }, + "Backend": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "Backend", + "params": [] + }, + "BackendLayout": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "BackendLayout", + "params": [] + }, + "Transpose": { + "module": "HMath.Backend", + "alias": "B", + "namespace": "backend", + "name": "Transpose", + "params": [] + } + }, + "fields": { + "Vector": [], + "FixedVector": [], + "SparseVector": [], + "Bidiagonal": [ + [ + "bidiagonalU", + [ + "Matrix", + [ + "a" + ] + ] + ], + [ + "bidiagonalB", + [ + "Matrix", + [ + "a" + ] + ] + ], + [ + "bidiagonalV", + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "Iteration": [ + [ + "iterationValue", + [ + "a" + ] + ], + [ + "iterationVector", + [ + "list", + [ + "a" + ] + ] + ], + [ + "iterationResidual", + [ + "a" + ] + ], + [ + "iterationCount", + [ + "Int" + ] + ] + ], + "Arnoldi": [ + [ + "arnoldiBasis", + [ + "Matrix", + [ + "a" + ] + ] + ], + [ + "arnoldiHessenberg", + [ + "Matrix", + [ + "a" + ] + ] + ] + ], + "IterativeOptions": [ + [ + "absoluteTolerance", + [ + "a" + ] + ], + [ + "relativeTolerance", + [ + "a" + ] + ], + [ + "maximumIterations", + [ + "Int" + ] + ] + ], + "IterativeResult": [ + [ + "iterativeSolution", + [ + "list", + [ + "a" + ] + ] + ], + [ + "iterativeIterations", + [ + "Int" + ] + ], + [ + "iterativeResidualNorm", + [ + "a" + ] + ], + [ + "iterativeNormalResidualNorm", + [ + "a" + ] + ] + ], + "Preconditioner": [], + "SVD": [ + [ + "svdU", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "singularValues", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "svdVT", + [ + "Matrix", + [ + "Double" + ] + ] + ] + ], + "Eigen": [ + [ + "eigenvalues", + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + [ + "eigenvectors", + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "GeneralizedEigen": [ + [ + "eigenAlpha", + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + [ + "eigenBeta", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "generalizedEigenvectors", + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "Schur": [ + [ + "schurQ", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "schurT", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "schurEigenvalues", + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "QZ": [ + [ + "qzQ", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "qzZ", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "qzS", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "qzT", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "qzAlpha", + [ + "list", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + [ + "qzBeta", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "Hessenberg": [ + [ + "hessenbergQ", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "hessenbergH", + [ + "Matrix", + [ + "Double" + ] + ] + ] + ], + "Balance": [ + [ + "balancedMatrix", + [ + "Matrix", + [ + "Double" + ] + ] + ], + [ + "balanceScales", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "ComplexSVD": [ + [ + "complexU", + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ], + [ + "complexSingularValues", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "complexVT", + [ + "Matrix", + [ + "Complex", + [ + "Double" + ] + ] + ] + ] + ], + "Sparse": [], + "SparseFormat": [], + "SparseLU": [], + "SparseQR": [], + "SparseTensor": [], + "SparseSpectralOptions": [ + [ + "sparseAbsoluteTolerance", + [ + "a" + ] + ], + [ + "sparseRelativeTolerance", + [ + "a" + ] + ], + [ + "sparseIterationLimit", + [ + "Int" + ] + ], + [ + "sparseWorkspaceLimit", + [ + "Integer" + ] + ] + ], + "SparseEigenResult": [ + [ + "sparseEigenvalue", + [ + "a" + ] + ], + [ + "sparseEigenvector", + [ + "list", + [ + "a" + ] + ] + ], + [ + "sparseEigenResidual", + [ + "a" + ] + ], + [ + "sparseEigenIterations", + [ + "Int" + ] + ] + ], + "SparseSVD": [ + [ + "sparseSingularValues", + [ + "list", + [ + "a" + ] + ] + ], + [ + "sparseLeftVectors", + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + [ + "sparseRightVectors", + [ + "list", + [ + "list", + [ + "a" + ] + ] + ] + ], + [ + "sparseSingularResiduals", + [ + "list", + [ + "tuple", + [ + "a" + ], + [ + "a" + ] + ] + ] + ], + [ + "sparseSingularIterations", + [ + "list", + [ + "Int" + ] + ] + ] + ], + "Provider": [], + "IntegerABI": [], + "BackendRequest": [], + "BackendInfo": [ + [ + "selectedProvider", + [ + "Provider" + ] + ], + [ + "selectedIntegerABI", + [ + "IntegerABI" + ] + ] + ], + "Backend": [], + "BackendLayout": [], + "Transpose": [] + } +} diff --git a/bindings/schema/linear-objects.json b/bindings/schema/linear-objects.json new file mode 100644 index 0000000..14a0382 --- /dev/null +++ b/bindings/schema/linear-objects.json @@ -0,0 +1,2845 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Backend.Accelerate", + "c": [ + "hmath_linear_backend_new_accelerate" + ], + "python": "hmath.backend.accelerate", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.AutoBackend", + "c": [ + "hmath_linear_backend_new_auto_backend" + ], + "python": "hmath.backend.auto_backend", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.BLIS", + "c": [ + "hmath_linear_backend_new_blis" + ], + "python": "hmath.backend.blis", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.Backend", + "c": [ + "hmath_linear_backend_backend_object" + ], + "python": "hmath.backend.Backend", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Backend.BackendInfo", + "c": [ + "hmath_linear_backend_new_backend_info" + ], + "python": "hmath.backend.BackendInfo", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.BackendLayout", + "c": [ + "hmath_linear_backend_backend_layout_object" + ], + "python": "hmath.backend.BackendLayout", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Backend.BackendRequest", + "c": [ + "hmath_linear_backend_backend_request_object" + ], + "python": "hmath.backend.BackendRequest", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Backend.ColumnMajor", + "c": [ + "hmath_linear_backend_new_column_major" + ], + "python": "hmath.backend.column_major", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.ConjugateTranspose", + "c": [ + "hmath_linear_backend_new_conjugate_transpose" + ], + "python": "hmath.backend.conjugate_transpose", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.ILP64", + "c": [ + "hmath_linear_backend_new_ilp64" + ], + "python": "hmath.backend.ilp64", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.IntegerABI", + "c": [ + "hmath_linear_backend_integer_abi_object" + ], + "python": "hmath.backend.IntegerABI", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Backend.LP64", + "c": [ + "hmath_linear_backend_new_lp64" + ], + "python": "hmath.backend.lp64", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.NoTranspose", + "c": [ + "hmath_linear_backend_new_no_transpose" + ], + "python": "hmath.backend.no_transpose", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.OneMKL", + "c": [ + "hmath_linear_backend_new_one_mkl" + ], + "python": "hmath.backend.one_mkl", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.OpenBLAS", + "c": [ + "hmath_linear_backend_new_open_blas" + ], + "python": "hmath.backend.open_blas", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.Provider", + "c": [ + "hmath_linear_backend_provider_object" + ], + "python": "hmath.backend.Provider", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Backend.Pure", + "c": [ + "hmath_linear_backend_new_pure" + ], + "python": "hmath.backend.pure", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.RequireBackend", + "c": [ + "hmath_linear_backend_new_require_backend" + ], + "python": "hmath.backend.require_backend", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.RowMajor", + "c": [ + "hmath_linear_backend_new_row_major" + ], + "python": "hmath.backend.row_major", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.Transpose", + "c": [ + "hmath_linear_backend_new_transpose" + ], + "python": "hmath.backend.Transpose", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.axpy", + "c": [ + "hmath_linear_backend_axpy" + ], + "python": "hmath.backend.axpy", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendCholesky", + "c": [ + "hmath_linear_backend_backend_cholesky" + ], + "python": "hmath.backend.backend_cholesky", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendInfo", + "c": [ + "hmath_linear_backend_backend_info" + ], + "python": "hmath.backend.backend_info", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendLU", + "c": [ + "hmath_linear_backend_backend_lu" + ], + "python": "hmath.backend.backend_lu", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendLeastSquares", + "c": [ + "hmath_linear_backend_backend_least_squares" + ], + "python": "hmath.backend.backend_least_squares", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendQR", + "c": [ + "hmath_linear_backend_backend_qr" + ], + "python": "hmath.backend.backend_qr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendSVD", + "c": [ + "hmath_linear_backend_backend_svd" + ], + "python": "hmath.backend.backend_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendSolve", + "c": [ + "hmath_linear_backend_backend_solve" + ], + "python": "hmath.backend.backend_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.backendSymmetricEigen", + "c": [ + "hmath_linear_backend_backend_symmetric_eigen" + ], + "python": "hmath.backend.backend_symmetric_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.batchedGemm", + "c": [ + "hmath_linear_backend_batched_gemm" + ], + "python": "hmath.backend.batched_gemm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.complexAxpy", + "c": [ + "hmath_linear_backend_complex_axpy" + ], + "python": "hmath.backend.complex_axpy", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.complexDot", + "c": [ + "hmath_linear_backend_complex_dot" + ], + "python": "hmath.backend.complex_dot", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.complexGemm", + "c": [ + "hmath_linear_backend_complex_gemm" + ], + "python": "hmath.backend.complex_gemm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.complexGemv", + "c": [ + "hmath_linear_backend_complex_gemv" + ], + "python": "hmath.backend.complex_gemv", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.complexNrm2", + "c": [ + "hmath_linear_backend_complex_nrm2" + ], + "python": "hmath.backend.complex_nrm2", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.dot", + "c": [ + "hmath_linear_backend_dot" + ], + "python": "hmath.backend.dot", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.gemm", + "c": [ + "hmath_linear_backend_gemm" + ], + "python": "hmath.backend.gemm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.gemv", + "c": [ + "hmath_linear_backend_gemv" + ], + "python": "hmath.backend.gemv", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.lapackAvailable", + "c": [ + "hmath_linear_backend_lapack_available" + ], + "python": "hmath.backend.lapack_available", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.lapackStatus", + "c": [ + "hmath_linear_backend_lapack_status" + ], + "python": "hmath.backend.lapack_status", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.matrixFromLayout", + "c": [ + "hmath_linear_backend_matrix_from_layout" + ], + "python": "hmath.backend.matrix_from_layout", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.matrixToLayout", + "c": [ + "hmath_linear_backend_matrix_to_layout" + ], + "python": "hmath.backend.matrix_to_layout", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.nrm2", + "c": [ + "hmath_linear_backend_nrm2" + ], + "python": "hmath.backend.nrm2", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.pureBackend", + "c": [ + "hmath_linear_backend_pure_backend" + ], + "python": "hmath.backend.pure_backend", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.pureSVD", + "c": [ + "hmath_linear_backend_pure_svd" + ], + "python": "hmath.backend.pure_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.pureSymmetricEigen", + "c": [ + "hmath_linear_backend_pure_symmetric_eigen" + ], + "python": "hmath.backend.pure_symmetric_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.selectBackend", + "c": [ + "hmath_linear_backend_select_backend" + ], + "python": "hmath.backend.select_backend", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.selectedIntegerABI", + "c": [ + "hmath_linear_backend_selected_integer_abi" + ], + "python": "hmath.backend.selected_integer_abi", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.selectedProvider", + "c": [ + "hmath_linear_backend_selected_provider" + ], + "python": "hmath.backend.selected_provider", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.setBackendThreads", + "c": [ + "hmath_linear_backend_set_backend_threads" + ], + "python": "hmath.backend.set_backend_threads", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Backend.stridedBatchedGemm", + "c": [ + "hmath_linear_backend_strided_batched_gemm" + ], + "python": "hmath.backend.strided_batched_gemm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.bandedMatrix", + "c": [ + "hmath_linear_matrix_advanced_banded_matrix" + ], + "python": "hmath.matrix_advanced.banded_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.batchedMultiply", + "c": [ + "hmath_linear_matrix_advanced_batched_multiply" + ], + "python": "hmath.matrix_advanced.batched_multiply", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.blockMatrix", + "c": [ + "hmath_linear_matrix_advanced_block_matrix" + ], + "python": "hmath.matrix_advanced.block_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.changeCoordinates", + "c": [ + "hmath_linear_matrix_advanced_change_coordinates" + ], + "python": "hmath.matrix_advanced.change_coordinates", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.columnSpace", + "c": [ + "hmath_linear_matrix_advanced_column_space" + ], + "python": "hmath.matrix_advanced.column_space", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.complexPseudoinverse", + "c": [ + "hmath_linear_matrix_advanced_complex_pseudoinverse" + ], + "python": "hmath.matrix_advanced.complex_pseudoinverse", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.conditionNumber", + "c": [ + "hmath_linear_matrix_advanced_condition_number" + ], + "python": "hmath.matrix_advanced.condition_number", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.conjugateTranspose", + "c": [ + "hmath_linear_matrix_advanced_conjugate_transpose" + ], + "python": "hmath.matrix_advanced.conjugate_transpose", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.frobeniusNorm", + "c": [ + "hmath_linear_matrix_advanced_frobenius_norm" + ], + "python": "hmath.matrix_advanced.frobenius_norm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.generateMatrix", + "c": [ + "hmath_linear_matrix_advanced_generate_matrix" + ], + "python": "hmath.matrix_advanced.generate_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.hermitianMatrix", + "c": [ + "hmath_linear_matrix_advanced_hermitian_matrix" + ], + "python": "hmath.matrix_advanced.hermitian_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.khatriRao", + "c": [ + "hmath_linear_matrix_advanced_khatri_rao" + ], + "python": "hmath.matrix_advanced.khatri_rao", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.kronecker", + "c": [ + "hmath_linear_matrix_advanced_kronecker" + ], + "python": "hmath.matrix_advanced.kronecker", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixExp", + "c": [ + "hmath_linear_matrix_advanced_matrix_exp" + ], + "python": "hmath.matrix_advanced.matrix_exp", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixLog", + "c": [ + "hmath_linear_matrix_advanced_matrix_log" + ], + "python": "hmath.matrix_advanced.matrix_log", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixLogGeneral", + "c": [ + "hmath_linear_matrix_advanced_matrix_log_general" + ], + "python": "hmath.matrix_advanced.matrix_log_general", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixNorm1", + "c": [ + "hmath_linear_matrix_advanced_matrix_norm1" + ], + "python": "hmath.matrix_advanced.matrix_norm1", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixNormInfinity", + "c": [ + "hmath_linear_matrix_advanced_matrix_norm_infinity" + ], + "python": "hmath.matrix_advanced.matrix_norm_infinity", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixPower", + "c": [ + "hmath_linear_matrix_advanced_matrix_power" + ], + "python": "hmath.matrix_advanced.matrix_power", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixRank", + "c": [ + "hmath_linear_matrix_advanced_matrix_rank" + ], + "python": "hmath.matrix_advanced.matrix_rank", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixSqrt", + "c": [ + "hmath_linear_matrix_advanced_matrix_sqrt" + ], + "python": "hmath.matrix_advanced.matrix_sqrt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixSqrtGeneral", + "c": [ + "hmath_linear_matrix_advanced_matrix_sqrt_general" + ], + "python": "hmath.matrix_advanced.matrix_sqrt_general", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.nullSpace", + "c": [ + "hmath_linear_matrix_advanced_null_space" + ], + "python": "hmath.matrix_advanced.null_space", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.permutationMatrix", + "c": [ + "hmath_linear_matrix_advanced_permutation_matrix" + ], + "python": "hmath.matrix_advanced.permutation_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.polar", + "c": [ + "hmath_linear_matrix_advanced_polar" + ], + "python": "hmath.matrix_advanced.polar", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.pseudoinverse", + "c": [ + "hmath_linear_matrix_advanced_pseudoinverse" + ], + "python": "hmath.matrix_advanced.pseudoinverse", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.rowSpace", + "c": [ + "hmath_linear_matrix_advanced_row_space" + ], + "python": "hmath.matrix_advanced.row_space", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.spectralNorm", + "c": [ + "hmath_linear_matrix_advanced_spectral_norm" + ], + "python": "hmath.matrix_advanced.spectral_norm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.symmetricMatrix", + "c": [ + "hmath_linear_matrix_advanced_symmetric_matrix" + ], + "python": "hmath.matrix_advanced.symmetric_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.trace", + "c": [ + "hmath_linear_matrix_advanced_trace" + ], + "python": "hmath.matrix_advanced.trace", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.triangularMatrix", + "c": [ + "hmath_linear_matrix_advanced_triangular_matrix" + ], + "python": "hmath.matrix_advanced.triangular_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.zipMatrixWith", + "c": [ + "hmath_linear_matrix_advanced_zip_matrix_with" + ], + "python": "hmath.matrix_advanced.zip_matrix_with", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Arnoldi", + "c": [ + "hmath_linear_decomposition_new_arnoldi" + ], + "python": "hmath.decomposition.Arnoldi", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Bidiagonal", + "c": [ + "hmath_linear_decomposition_new_bidiagonal" + ], + "python": "hmath.decomposition.Bidiagonal", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Iteration", + "c": [ + "hmath_linear_decomposition_new_iteration" + ], + "python": "hmath.decomposition.Iteration", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldi", + "c": [ + "hmath_linear_decomposition_arnoldi" + ], + "python": "hmath.decomposition.arnoldi", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldiBasis", + "c": [ + "hmath_linear_decomposition_arnoldi_basis" + ], + "python": "hmath.decomposition.arnoldi_basis", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldiHessenberg", + "c": [ + "hmath_linear_decomposition_arnoldi_hessenberg" + ], + "python": "hmath.decomposition.arnoldi_hessenberg", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalB", + "c": [ + "hmath_linear_decomposition_bidiagonal_b" + ], + "python": "hmath.decomposition.bidiagonal_b", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalU", + "c": [ + "hmath_linear_decomposition_bidiagonal_u" + ], + "python": "hmath.decomposition.bidiagonal_u", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalV", + "c": [ + "hmath_linear_decomposition_bidiagonal_v" + ], + "python": "hmath.decomposition.bidiagonal_v", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalize", + "c": [ + "hmath_linear_decomposition_bidiagonalize" + ], + "python": "hmath.decomposition.bidiagonalize", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.cholesky", + "c": [ + "hmath_linear_decomposition_cholesky" + ], + "python": "hmath.decomposition.cholesky", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.gaussJordan", + "c": [ + "hmath_linear_decomposition_gauss_jordan" + ], + "python": "hmath.decomposition.gauss_jordan", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.gaussianElimination", + "c": [ + "hmath_linear_decomposition_gaussian_elimination" + ], + "python": "hmath.decomposition.gaussian_elimination", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.givensQR", + "c": [ + "hmath_linear_decomposition_givens_qr" + ], + "python": "hmath.decomposition.givens_qr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.inverseIteration", + "c": [ + "hmath_linear_decomposition_inverse_iteration" + ], + "python": "hmath.decomposition.inverse_iteration", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationCount", + "c": [ + "hmath_linear_decomposition_iteration_count" + ], + "python": "hmath.decomposition.iteration_count", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationResidual", + "c": [ + "hmath_linear_decomposition_iteration_residual" + ], + "python": "hmath.decomposition.iteration_residual", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationValue", + "c": [ + "hmath_linear_decomposition_iteration_value" + ], + "python": "hmath.decomposition.iteration_value", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationVector", + "c": [ + "hmath_linear_decomposition_iteration_vector" + ], + "python": "hmath.decomposition.iteration_vector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.jordanChains", + "c": [ + "hmath_linear_decomposition_jordan_chains" + ], + "python": "hmath.decomposition.jordan_chains", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.jordanForm", + "c": [ + "hmath_linear_decomposition_jordan_form" + ], + "python": "hmath.decomposition.jordan_form", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.lanczos", + "c": [ + "hmath_linear_decomposition_lanczos" + ], + "python": "hmath.decomposition.lanczos", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.ldlt", + "c": [ + "hmath_linear_decomposition_ldlt" + ], + "python": "hmath.decomposition.ldlt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.powerIteration", + "c": [ + "hmath_linear_decomposition_power_iteration" + ], + "python": "hmath.decomposition.power_iteration", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.qrIteration", + "c": [ + "hmath_linear_decomposition_qr_iteration" + ], + "python": "hmath.decomposition.qr_iteration", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.rayleighIteration", + "c": [ + "hmath_linear_decomposition_rayleigh_iteration" + ], + "python": "hmath.decomposition.rayleigh_iteration", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.tridiagonalize", + "c": [ + "hmath_linear_decomposition_tridiagonalize" + ], + "python": "hmath.decomposition.tridiagonalize", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.IterativeOptions", + "c": [ + "hmath_linear_iterative_new_iterative_options" + ], + "python": "hmath.iterative.IterativeOptions", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.IterativeResult", + "c": [ + "hmath_linear_iterative_new_iterative_result" + ], + "python": "hmath.iterative.IterativeResult", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.Preconditioner", + "c": [ + "hmath_linear_iterative_preconditioner_object" + ], + "python": "hmath.iterative.Preconditioner", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.absoluteTolerance", + "c": [ + "hmath_linear_iterative_absolute_tolerance" + ], + "python": "hmath.iterative.absolute_tolerance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.applyPreconditioner", + "c": [ + "hmath_linear_iterative_apply_preconditioner" + ], + "python": "hmath.iterative.apply_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.bicg", + "c": [ + "hmath_linear_iterative_bicg" + ], + "python": "hmath.iterative.bicg", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.bicgstab", + "c": [ + "hmath_linear_iterative_bicgstab" + ], + "python": "hmath.iterative.bicgstab", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.blockJacobiPreconditioner", + "c": [ + "hmath_linear_iterative_block_jacobi_preconditioner" + ], + "python": "hmath.iterative.block_jacobi_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.conjugateGradient", + "c": [ + "hmath_linear_iterative_conjugate_gradient" + ], + "python": "hmath.iterative.conjugate_gradient", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.defaultIterativeOptions", + "c": [ + "hmath_linear_iterative_default_iterative_options" + ], + "python": "hmath.iterative.default_iterative_options", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.gaussSeidelSolve", + "c": [ + "hmath_linear_iterative_gauss_seidel_solve" + ], + "python": "hmath.iterative.gauss_seidel_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.gmres", + "c": [ + "hmath_linear_iterative_gmres" + ], + "python": "hmath.iterative.gmres", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.ic0Preconditioner", + "c": [ + "hmath_linear_iterative_ic0_preconditioner" + ], + "python": "hmath.iterative.ic0_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.identityPreconditioner", + "c": [ + "hmath_linear_iterative_identity_preconditioner" + ], + "python": "hmath.iterative.identity_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.ilu0Preconditioner", + "c": [ + "hmath_linear_iterative_ilu0_preconditioner" + ], + "python": "hmath.iterative.ilu0_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeIterations", + "c": [ + "hmath_linear_iterative_iterative_iterations" + ], + "python": "hmath.iterative.iterative_iterations", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeNormalResidualNorm", + "c": [ + "hmath_linear_iterative_iterative_normal_residual_norm" + ], + "python": "hmath.iterative.iterative_normal_residual_norm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeRefinement", + "c": [ + "hmath_linear_iterative_iterative_refinement" + ], + "python": "hmath.iterative.iterative_refinement", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeResidualNorm", + "c": [ + "hmath_linear_iterative_iterative_residual_norm" + ], + "python": "hmath.iterative.iterative_residual_norm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeSolution", + "c": [ + "hmath_linear_iterative_iterative_solution" + ], + "python": "hmath.iterative.iterative_solution", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.jacobiPreconditioner", + "c": [ + "hmath_linear_iterative_jacobi_preconditioner" + ], + "python": "hmath.iterative.jacobi_preconditioner", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.jacobiSolve", + "c": [ + "hmath_linear_iterative_jacobi_solve" + ], + "python": "hmath.iterative.jacobi_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.lsmr", + "c": [ + "hmath_linear_iterative_lsmr" + ], + "python": "hmath.iterative.lsmr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.lsqr", + "c": [ + "hmath_linear_iterative_lsqr" + ], + "python": "hmath.iterative.lsqr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.maximumIterations", + "c": [ + "hmath_linear_iterative_maximum_iterations" + ], + "python": "hmath.iterative.maximum_iterations", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.minres", + "c": [ + "hmath_linear_iterative_minres" + ], + "python": "hmath.iterative.minres", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.preconditionedCG", + "c": [ + "hmath_linear_iterative_preconditioned_cg" + ], + "python": "hmath.iterative.preconditioned_cg", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.relativeTolerance", + "c": [ + "hmath_linear_iterative_relative_tolerance" + ], + "python": "hmath.iterative.relative_tolerance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.sorSolve", + "c": [ + "hmath_linear_iterative_sor_solve" + ], + "python": "hmath.iterative.sor_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Balance", + "c": [ + "hmath_linear_lapack_new_balance" + ], + "python": "hmath.lapack.Balance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.ComplexSVD", + "c": [ + "hmath_linear_lapack_new_complex_svd" + ], + "python": "hmath.lapack.ComplexSVD", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Eigen", + "c": [ + "hmath_linear_lapack_new_eigen" + ], + "python": "hmath.lapack.Eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.GeneralizedEigen", + "c": [ + "hmath_linear_lapack_new_generalized_eigen" + ], + "python": "hmath.lapack.GeneralizedEigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Hessenberg", + "c": [ + "hmath_linear_lapack_new_hessenberg" + ], + "python": "hmath.lapack.Hessenberg", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.QZ", + "c": [ + "hmath_linear_lapack_new_qz" + ], + "python": "hmath.lapack.QZ", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.SVD", + "c": [ + "hmath_linear_lapack_new_svd" + ], + "python": "hmath.lapack.SVD", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Schur", + "c": [ + "hmath_linear_lapack_new_schur" + ], + "python": "hmath.lapack.Schur", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balance", + "c": [ + "hmath_linear_lapack_balance" + ], + "python": "hmath.lapack.balance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balanceScales", + "c": [ + "hmath_linear_lapack_balance_scales" + ], + "python": "hmath.lapack.balance_scales", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balancedMatrix", + "c": [ + "hmath_linear_lapack_balanced_matrix" + ], + "python": "hmath.lapack.balanced_matrix", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexEigen", + "c": [ + "hmath_linear_lapack_complex_eigen" + ], + "python": "hmath.lapack.complex_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexSVD", + "c": [ + "hmath_linear_lapack_complex_svd" + ], + "python": "hmath.lapack.complex_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexSingularValues", + "c": [ + "hmath_linear_lapack_complex_singular_values" + ], + "python": "hmath.lapack.complex_singular_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexU", + "c": [ + "hmath_linear_lapack_complex_u" + ], + "python": "hmath.lapack.complex_u", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexVT", + "c": [ + "hmath_linear_lapack_complex_vt" + ], + "python": "hmath.lapack.complex_vt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigen", + "c": [ + "hmath_linear_lapack_eigen" + ], + "python": "hmath.lapack.eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenAlpha", + "c": [ + "hmath_linear_lapack_eigen_alpha" + ], + "python": "hmath.lapack.eigen_alpha", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenBeta", + "c": [ + "hmath_linear_lapack_eigen_beta" + ], + "python": "hmath.lapack.eigen_beta", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenvalues", + "c": [ + "hmath_linear_lapack_eigenvalues" + ], + "python": "hmath.lapack.eigenvalues", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenvectors", + "c": [ + "hmath_linear_lapack_eigenvectors" + ], + "python": "hmath.lapack.eigenvectors", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.fullSVD", + "c": [ + "hmath_linear_lapack_full_svd" + ], + "python": "hmath.lapack.full_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.generalizedEigen", + "c": [ + "hmath_linear_lapack_generalized_eigen" + ], + "python": "hmath.lapack.generalized_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.generalizedEigenvectors", + "c": [ + "hmath_linear_lapack_generalized_eigenvectors" + ], + "python": "hmath.lapack.generalized_eigenvectors", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenberg", + "c": [ + "hmath_linear_lapack_hessenberg" + ], + "python": "hmath.lapack.hessenberg", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenbergH", + "c": [ + "hmath_linear_lapack_hessenberg_h" + ], + "python": "hmath.lapack.hessenberg_h", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenbergQ", + "c": [ + "hmath_linear_lapack_hessenberg_q" + ], + "python": "hmath.lapack.hessenberg_q", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qz", + "c": [ + "hmath_linear_lapack_qz" + ], + "python": "hmath.lapack.qz", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzAlpha", + "c": [ + "hmath_linear_lapack_qz_alpha" + ], + "python": "hmath.lapack.qz_alpha", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzBeta", + "c": [ + "hmath_linear_lapack_qz_beta" + ], + "python": "hmath.lapack.qz_beta", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzQ", + "c": [ + "hmath_linear_lapack_qz_q" + ], + "python": "hmath.lapack.qz_q", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzS", + "c": [ + "hmath_linear_lapack_qz_s" + ], + "python": "hmath.lapack.qz_s", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzT", + "c": [ + "hmath_linear_lapack_qz_t" + ], + "python": "hmath.lapack.qz_t", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzZ", + "c": [ + "hmath_linear_lapack_qz_z" + ], + "python": "hmath.lapack.qz_z", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.randomizedSVD", + "c": [ + "hmath_linear_lapack_randomized_svd" + ], + "python": "hmath.lapack.randomized_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schur", + "c": [ + "hmath_linear_lapack_schur" + ], + "python": "hmath.lapack.schur", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurEigenvalues", + "c": [ + "hmath_linear_lapack_schur_eigenvalues" + ], + "python": "hmath.lapack.schur_eigenvalues", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurQ", + "c": [ + "hmath_linear_lapack_schur_q" + ], + "python": "hmath.lapack.schur_q", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurT", + "c": [ + "hmath_linear_lapack_schur_t" + ], + "python": "hmath.lapack.schur_t", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.singularValues", + "c": [ + "hmath_linear_lapack_singular_values" + ], + "python": "hmath.lapack.singular_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svd", + "c": [ + "hmath_linear_lapack_svd" + ], + "python": "hmath.lapack.svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svdU", + "c": [ + "hmath_linear_lapack_svd_u" + ], + "python": "hmath.lapack.svd_u", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svdVT", + "c": [ + "hmath_linear_lapack_svd_vt" + ], + "python": "hmath.lapack.svd_vt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.symmetricEigen", + "c": [ + "hmath_linear_lapack_symmetric_eigen" + ], + "python": "hmath.lapack.symmetric_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.truncatedSVD", + "c": [ + "hmath_linear_lapack_truncated_svd" + ], + "python": "hmath.lapack.truncated_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.BSR", + "c": [ + "hmath_linear_sparse_new_bsr" + ], + "python": "hmath.sparse.bsr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.COO", + "c": [ + "hmath_linear_sparse_new_coo" + ], + "python": "hmath.sparse.coo", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.CSC", + "c": [ + "hmath_linear_sparse_new_csc" + ], + "python": "hmath.sparse.csc", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.CSR", + "c": [ + "hmath_linear_sparse_new_csr" + ], + "python": "hmath.sparse.csr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.DIA", + "c": [ + "hmath_linear_sparse_new_dia" + ], + "python": "hmath.sparse.dia", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.ELLPACK", + "c": [ + "hmath_linear_sparse_new_ellpack" + ], + "python": "hmath.sparse.ellpack", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Sparse", + "c": [ + "hmath_linear_sparse_sparse_object" + ], + "python": "hmath.sparse.Sparse", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Sparse.SparseFormat", + "c": [ + "hmath_linear_sparse_sparse_format_object" + ], + "python": "hmath.sparse.SparseFormat", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Sparse.SparseLU", + "c": [ + "hmath_linear_sparse_sparse_lu_object" + ], + "python": "hmath.sparse.SparseLU", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Sparse.SparseQR", + "c": [ + "hmath_linear_sparse_sparse_qr_object" + ], + "python": "hmath.sparse.SparseQR", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Sparse.SparseTensor", + "c": [ + "hmath_linear_sparse_sparse_tensor_object" + ], + "python": "hmath.sparse.SparseTensor", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseEigenResult", + "c": [ + "hmath_linear_sparse_spectral_new_sparse_eigen_result" + ], + "python": "hmath.sparse_spectral.SparseEigenResult", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseSVD", + "c": [ + "hmath_linear_sparse_spectral_new_sparse_svd" + ], + "python": "hmath.sparse_spectral.SparseSVD", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseSpectralOptions", + "c": [ + "hmath_linear_sparse_spectral_new_sparse_spectral_options" + ], + "python": "hmath.sparse_spectral.SparseSpectralOptions", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.defaultSparseSpectralOptions", + "c": [ + "hmath_linear_sparse_spectral_default_sparse_spectral_options" + ], + "python": "hmath.sparse_spectral.default_sparse_spectral_options", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseAbsoluteTolerance", + "c": [ + "hmath_linear_sparse_spectral_sparse_absolute_tolerance" + ], + "python": "hmath.sparse_spectral.sparse_absolute_tolerance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseDominantEigen", + "c": [ + "hmath_linear_sparse_spectral_sparse_dominant_eigen" + ], + "python": "hmath.sparse_spectral.sparse_dominant_eigen", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenIterations", + "c": [ + "hmath_linear_sparse_spectral_sparse_eigen_iterations" + ], + "python": "hmath.sparse_spectral.sparse_eigen_iterations", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenResidual", + "c": [ + "hmath_linear_sparse_spectral_sparse_eigen_residual" + ], + "python": "hmath.sparse_spectral.sparse_eigen_residual", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenvalue", + "c": [ + "hmath_linear_sparse_spectral_sparse_eigenvalue" + ], + "python": "hmath.sparse_spectral.sparse_eigenvalue", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenvector", + "c": [ + "hmath_linear_sparse_spectral_sparse_eigenvector" + ], + "python": "hmath.sparse_spectral.sparse_eigenvector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseIterationLimit", + "c": [ + "hmath_linear_sparse_spectral_sparse_iteration_limit" + ], + "python": "hmath.sparse_spectral.sparse_iteration_limit", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseLeftVectors", + "c": [ + "hmath_linear_sparse_spectral_sparse_left_vectors" + ], + "python": "hmath.sparse_spectral.sparse_left_vectors", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseRelativeTolerance", + "c": [ + "hmath_linear_sparse_spectral_sparse_relative_tolerance" + ], + "python": "hmath.sparse_spectral.sparse_relative_tolerance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseRightVectors", + "c": [ + "hmath_linear_sparse_spectral_sparse_right_vectors" + ], + "python": "hmath.sparse_spectral.sparse_right_vectors", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularIterations", + "c": [ + "hmath_linear_sparse_spectral_sparse_singular_iterations" + ], + "python": "hmath.sparse_spectral.sparse_singular_iterations", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularResiduals", + "c": [ + "hmath_linear_sparse_spectral_sparse_singular_residuals" + ], + "python": "hmath.sparse_spectral.sparse_singular_residuals", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularValues", + "c": [ + "hmath_linear_sparse_spectral_sparse_singular_values" + ], + "python": "hmath.sparse_spectral.sparse_singular_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseTruncatedSVD", + "c": [ + "hmath_linear_sparse_spectral_sparse_truncated_svd" + ], + "python": "hmath.sparse_spectral.sparse_truncated_svd", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseWorkspaceLimit", + "c": [ + "hmath_linear_sparse_spectral_sparse_workspace_limit" + ], + "python": "hmath.sparse_spectral.sparse_workspace_limit", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.denseToSparse", + "c": [ + "hmath_linear_sparse_dense_to_sparse" + ], + "python": "hmath.sparse.dense_to_sparse", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.fromFormat", + "c": [ + "hmath_linear_sparse_from_format" + ], + "python": "hmath.sparse.from_format", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.nonzeros", + "c": [ + "hmath_linear_sparse_nonzeros" + ], + "python": "hmath.sparse.nonzeros", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparse", + "c": [ + "hmath_linear_sparse_sparse" + ], + "python": "hmath.sparse.sparse", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseAdd", + "c": [ + "hmath_linear_sparse_sparse_add" + ], + "python": "hmath.sparse.sparse_add", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseCholesky", + "c": [ + "hmath_linear_sparse_sparse_cholesky" + ], + "python": "hmath.sparse.sparse_cholesky", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseDiagonalSolve", + "c": [ + "hmath_linear_sparse_sparse_diagonal_solve" + ], + "python": "hmath.sparse.sparse_diagonal_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseEigenReference", + "c": [ + "hmath_linear_sparse_sparse_eigen_reference" + ], + "python": "hmath.sparse.sparse_eigen_reference", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseEntries", + "c": [ + "hmath_linear_sparse_sparse_entries" + ], + "python": "hmath.sparse.sparse_entries", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseGraph", + "c": [ + "hmath_linear_sparse_sparse_graph" + ], + "python": "hmath.sparse.sparse_graph", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseKronecker", + "c": [ + "hmath_linear_sparse_sparse_kronecker" + ], + "python": "hmath.sparse.sparse_kronecker", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseLU", + "c": [ + "hmath_linear_sparse_sparse_lu" + ], + "python": "hmath.sparse.sparse_lu", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseLULower", + "c": [ + "hmath_linear_sparse_sparse_lu_lower" + ], + "python": "hmath.sparse.sparse_lu_lower", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseLUPermutation", + "c": [ + "hmath_linear_sparse_sparse_lu_permutation" + ], + "python": "hmath.sparse.sparse_lu_permutation", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseLUUpper", + "c": [ + "hmath_linear_sparse_sparse_lu_upper" + ], + "python": "hmath.sparse.sparse_lu_upper", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseQR", + "c": [ + "hmath_linear_sparse_sparse_qr" + ], + "python": "hmath.sparse.sparse_qr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseQRApplyQT", + "c": [ + "hmath_linear_sparse_sparse_qr_apply_qt" + ], + "python": "hmath.sparse.sparse_qr_apply_qt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseQRUpper", + "c": [ + "hmath_linear_sparse_sparse_qr_upper" + ], + "python": "hmath.sparse.sparse_qr_upper", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseSVDReference", + "c": [ + "hmath_linear_sparse_sparse_svd_reference" + ], + "python": "hmath.sparse.sparse_svd_reference", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseShape", + "c": [ + "hmath_linear_sparse_sparse_shape" + ], + "python": "hmath.sparse.sparse_shape", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseSolveLU", + "c": [ + "hmath_linear_sparse_sparse_solve_lu" + ], + "python": "hmath.sparse.sparse_solve_lu", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseStorageBytes", + "c": [ + "hmath_linear_sparse_sparse_storage_bytes" + ], + "python": "hmath.sparse.sparse_storage_bytes", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseSubtract", + "c": [ + "hmath_linear_sparse_sparse_subtract" + ], + "python": "hmath.sparse.sparse_subtract", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensor", + "c": [ + "hmath_linear_sparse_sparse_tensor" + ], + "python": "hmath.sparse.sparse_tensor", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorEntries", + "c": [ + "hmath_linear_sparse_sparse_tensor_entries" + ], + "python": "hmath.sparse.sparse_tensor_entries", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorLookup", + "c": [ + "hmath_linear_sparse_sparse_tensor_lookup" + ], + "python": "hmath.sparse.sparse_tensor_lookup", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorShape", + "c": [ + "hmath_linear_sparse_sparse_tensor_shape" + ], + "python": "hmath.sparse.sparse_tensor_shape", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseToDense", + "c": [ + "hmath_linear_sparse_sparse_to_dense" + ], + "python": "hmath.sparse.sparse_to_dense", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTranspose", + "c": [ + "hmath_linear_sparse_sparse_transpose" + ], + "python": "hmath.sparse.sparse_transpose", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.sparseTriangularSolve", + "c": [ + "hmath_linear_sparse_sparse_triangular_solve" + ], + "python": "hmath.sparse.sparse_triangular_solve", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.spmm", + "c": [ + "hmath_linear_sparse_spmm" + ], + "python": "hmath.sparse.spmm", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.spmv", + "c": [ + "hmath_linear_sparse_spmv" + ], + "python": "hmath.sparse.spmv", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toBSR", + "c": [ + "hmath_linear_sparse_to_bsr" + ], + "python": "hmath.sparse.to_bsr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toCOO", + "c": [ + "hmath_linear_sparse_to_coo" + ], + "python": "hmath.sparse.to_coo", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toCSC", + "c": [ + "hmath_linear_sparse_to_csc" + ], + "python": "hmath.sparse.to_csc", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toCSR", + "c": [ + "hmath_linear_sparse_to_csr" + ], + "python": "hmath.sparse.to_csr", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toDIA", + "c": [ + "hmath_linear_sparse_to_dia" + ], + "python": "hmath.sparse.to_dia", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Sparse.toELLPACK", + "c": [ + "hmath_linear_sparse_to_ellpack" + ], + "python": "hmath.sparse.to_ellpack", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.FixedVector", + "c": [ + "hmath_linear_vector_fixed_vector_object" + ], + "python": "hmath.vector.FixedVector", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Vector.SparseVector", + "c": [ + "hmath_linear_vector_sparse_vector_object" + ], + "python": "hmath.vector.SparseVector", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Vector.Vector", + "c": [ + "hmath_linear_vector_vector_object" + ], + "python": "hmath.vector.Vector", + "specializations": [ + "original owned opaque type with source coefficient type" + ] + }, + { + "symbol": "HMath.Vector.angle", + "c": [ + "hmath_linear_vector_angle" + ], + "python": "hmath.vector.angle", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.cosineSimilarity", + "c": [ + "hmath_linear_vector_cosine_similarity" + ], + "python": "hmath.vector.cosine_similarity", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.cross", + "c": [ + "hmath_linear_vector_cross" + ], + "python": "hmath.vector.cross", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.distance", + "c": [ + "hmath_linear_vector_distance" + ], + "python": "hmath.vector.distance", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.fixedValues", + "c": [ + "hmath_linear_vector_fixed_values" + ], + "python": "hmath.vector.fixed_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.fixedVector", + "c": [ + "hmath_linear_vector_fixed_vector" + ], + "python": "hmath.vector.fixed_vector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.gramSchmidt", + "c": [ + "hmath_linear_vector_gram_schmidt" + ], + "python": "hmath.vector.gram_schmidt", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.norm0", + "c": [ + "hmath_linear_vector_norm0" + ], + "python": "hmath.vector.norm0", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.norm1", + "c": [ + "hmath_linear_vector_norm1" + ], + "python": "hmath.vector.norm1", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.norm2", + "c": [ + "hmath_linear_vector_norm2" + ], + "python": "hmath.vector.norm2", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.normInfinity", + "c": [ + "hmath_linear_vector_norm_infinity" + ], + "python": "hmath.vector.norm_infinity", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.normP", + "c": [ + "hmath_linear_vector_norm_p" + ], + "python": "hmath.vector.norm_p", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.normalizeVector", + "c": [ + "hmath_linear_vector_normalize_vector" + ], + "python": "hmath.vector.normalize_vector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.outer", + "c": [ + "hmath_linear_vector_outer" + ], + "python": "hmath.vector.outer", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.project", + "c": [ + "hmath_linear_vector_project" + ], + "python": "hmath.vector.project", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.reflect", + "c": [ + "hmath_linear_vector_reflect" + ], + "python": "hmath.vector.reflect", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.refract", + "c": [ + "hmath_linear_vector_refract" + ], + "python": "hmath.vector.refract", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.sparseVector", + "c": [ + "hmath_linear_vector_sparse_vector" + ], + "python": "hmath.vector.sparse_vector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.sparseVectorValues", + "c": [ + "hmath_linear_vector_sparse_vector_values" + ], + "python": "hmath.vector.sparse_vector_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.triple", + "c": [ + "hmath_linear_vector_triple" + ], + "python": "hmath.vector.triple", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vector", + "c": [ + "hmath_linear_vector_vector" + ], + "python": "hmath.vector.vector", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorAdd", + "c": [ + "hmath_linear_vector_vector_add" + ], + "python": "hmath.vector.vector_add", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorConcat", + "c": [ + "hmath_linear_vector_vector_concat" + ], + "python": "hmath.vector.vector_concat", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorDimension", + "c": [ + "hmath_linear_vector_vector_dimension" + ], + "python": "hmath.vector.vector_dimension", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorDot", + "c": [ + "hmath_linear_vector_vector_dot" + ], + "python": "hmath.vector.vector_dot", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorScale", + "c": [ + "hmath_linear_vector_vector_scale" + ], + "python": "hmath.vector.vector_scale", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorSlice", + "c": [ + "hmath_linear_vector_vector_slice" + ], + "python": "hmath.vector.vector_slice", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorSubtract", + "c": [ + "hmath_linear_vector_vector_subtract" + ], + "python": "hmath.vector.vector_subtract", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + }, + { + "symbol": "HMath.Vector.vectorValues", + "c": [ + "hmath_linear_vector_vector_values" + ], + "python": "hmath.vector.vector_values", + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ] + } + ] +} diff --git a/bindings/schema/machinelearning-functions.json b/bindings/schema/machinelearning-functions.json new file mode 100644 index 0000000..467660a --- /dev/null +++ b/bindings/schema/machinelearning-functions.json @@ -0,0 +1,959 @@ +{ + "schema": 1, + "types": [ + { + "module": "HMath.MachineLearning.Clustering", + "name": "ClusterModel" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "GaussianMixture" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Linkage" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Merge" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "CCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "FactorAnalysis" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "ICA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "IncrementalPCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "KernelPCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "PCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "PLS" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "Dataset" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "Fit" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "MLConfig" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "IndexKind" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "IsolationForest" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "LSH" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "NeighborResult" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "OneClassSVM" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "SpatialIndex" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Encoder" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Fold" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Imputation" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Imputer" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "PowerTransform" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "QuantileTransformer" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Scaler" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Scaling" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "UnknownCategory" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "BayesFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "BayesianLinear" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Discriminant" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "GLM" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "GLMFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "GPClassifier" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "GaussianProcess" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Kernel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "LinearModel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "MultinomialModel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "NaiveBayes" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Penalty" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "RecursiveLS" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "SVM" + } + ], + "functions": [ + { + "module": "HMath.MachineLearning.Clustering", + "name": "Average", + "signature": "Linkage" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Complete", + "signature": "Linkage" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Merge", + "signature": "Int -> Int -> Double -> Int -> Merge" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Single", + "signature": "Linkage" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "Ward", + "signature": "Linkage" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "affinityPropagation", + "signature": "MLConfig -> Double -> Double -> Dataset -> Either MathError (Fit [Int])" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "clusterCenters", + "signature": "ClusterModel -> Dataset" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "cutHierarchy", + "signature": "Int -> Int -> [Merge] -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "dbscan", + "signature": "Double -> Int -> Dataset -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "extractOPTICS", + "signature": "Double -> [(Int, Maybe Double, Maybe Double)] -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "fitGaussianMixture", + "signature": "MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit GaussianMixture)" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "hierarchical", + "signature": "Linkage -> Dataset -> Either MathError [Merge]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "kMeans", + "signature": "MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel)" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "kMeansPlusPlus", + "signature": "MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel)" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "kMedoids", + "signature": "MLConfig -> Int -> Dataset -> Either MathError (Fit [Int])" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "leftCluster", + "signature": "Merge -> Int" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "meanShift", + "signature": "MLConfig -> Double -> Dataset -> Either MathError (Fit ClusterModel)" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mergeDistance", + "signature": "Merge -> Double" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mergedSize", + "signature": "Merge -> Int" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "miniBatchKMeans", + "signature": "MLConfig -> Int -> Int -> Dataset -> Either MathError (Fit ClusterModel)" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mixtureCovariances", + "signature": "GaussianMixture -> [Dataset]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mixtureMeans", + "signature": "GaussianMixture -> Dataset" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mixtureResponsibilities", + "signature": "GaussianMixture -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "mixtureWeights", + "signature": "GaussianMixture -> [Double]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "optics", + "signature": "Double -> Int -> Dataset -> Either MathError [(Int, Maybe Double, Maybe Double)]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "predictClusters", + "signature": "ClusterModel -> Dataset -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "rightCluster", + "signature": "Merge -> Int" + }, + { + "module": "HMath.MachineLearning.Clustering", + "name": "spectralClustering", + "signature": "MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit [Int])" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "canonicalCorrelations", + "signature": "CCA -> [Double]" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "classicalMDS", + "signature": "Int -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "factorLoadings", + "signature": "FactorAnalysis -> Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "factorNoise", + "signature": "FactorAnalysis -> [Double]" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "finishPCA", + "signature": "Int -> IncrementalPCA -> Either MathError PCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitCCA", + "signature": "Int -> Double -> Dataset -> Dataset -> Either MathError CCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitFactorAnalysis", + "signature": "MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit FactorAnalysis)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitICA", + "signature": "MLConfig -> Int -> Dataset -> Either MathError (Fit ICA)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitKernelPCA", + "signature": "Int -> Kernel -> Dataset -> Either MathError KernelPCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitPCA", + "signature": "Int -> Dataset -> Either MathError PCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "fitPLS", + "signature": "MLConfig -> Int -> Dataset -> Dataset -> Either MathError (Fit PLS)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "incrementalPCA", + "signature": "Int -> Either MathError IncrementalPCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "inversePCA", + "signature": "PCA -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "isomap", + "signature": "Int -> Int -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "mergePCA", + "signature": "IncrementalPCA -> IncrementalPCA -> Either MathError IncrementalPCA" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "pcaComponents", + "signature": "PCA -> Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "pcaMean", + "signature": "PCA -> [Double]" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "pcaVariances", + "signature": "PCA -> [Double]" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "predictPLS", + "signature": "PLS -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "randomProjection", + "signature": "MLConfig -> Int -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "transformCCA", + "signature": "CCA -> Dataset -> Dataset -> Either MathError (Dataset, Dataset)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "transformICA", + "signature": "ICA -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "transformKernelPCA", + "signature": "KernelPCA -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "transformPCA", + "signature": "PCA -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "truncatedSVD", + "signature": "Int -> Dataset -> Either MathError (Dataset, [Double], Dataset)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "tsne", + "signature": "MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit Dataset)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "umap", + "signature": "MLConfig -> Int -> Int -> Double -> Double -> Dataset -> Either MathError (Fit Dataset)" + }, + { + "module": "HMath.MachineLearning.Decomposition", + "name": "updatePCA", + "signature": "IncrementalPCA -> Dataset -> Either MathError IncrementalPCA" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "Fit", + "signature": "a -> Int -> Double -> Bool -> Fit a" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "MLConfig", + "signature": "Int -> Double -> Double -> Word64 -> MLConfig" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "defaultMLConfig", + "signature": "MLConfig" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "fitConverged", + "signature": "Fit a -> Bool" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "fitIterations", + "signature": "Fit a -> Int" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "fitResidual", + "signature": "Fit a -> Double" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "fitted", + "signature": "Fit a -> a" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "mlIterations", + "signature": "MLConfig -> Int" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "mlRate", + "signature": "MLConfig -> Double" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "mlSeed", + "signature": "MLConfig -> Word64" + }, + { + "module": "HMath.MachineLearning.Internal", + "name": "mlTolerance", + "signature": "MLConfig -> Double" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "BallTree", + "signature": "IndexKind" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "KDTree", + "signature": "IndexKind" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "NeighborResult", + "signature": "[(Int, Double)] -> Int -> Bool -> NeighborResult" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "buildIndex", + "signature": "IndexKind -> Int -> Dataset -> Either MathError SpatialIndex" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "buildLSH", + "signature": "Word64 -> Int -> Int -> Double -> Dataset -> Either MathError LSH" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "decisionOneClassSVM", + "signature": "OneClassSVM -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "exhaustive", + "signature": "NeighborResult -> Bool" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "fitIsolationForest", + "signature": "Word64 -> Int -> Int -> Dataset -> Either MathError IsolationForest" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "fitOneClassSVM", + "signature": "MLConfig -> Kernel -> Double -> Dataset -> Either MathError (Fit OneClassSVM)" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "knnClassify", + "signature": "Int -> SpatialIndex -> [Int] -> Dataset -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "knnRegress", + "signature": "Int -> SpatialIndex -> [Double] -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "localOutlierFactor", + "signature": "Int -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "nearestNeighbors", + "signature": "Int -> Int -> SpatialIndex -> [Double] -> Either MathError NeighborResult" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "neighbors", + "signature": "NeighborResult -> [(Int, Double)]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "queryLSH", + "signature": "Int -> LSH -> [Double] -> Either MathError [(Int, Double)]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "scoreIsolationForest", + "signature": "IsolationForest -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Neighbors", + "name": "visitedLeaves", + "signature": "NeighborResult -> Int" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "BoxCox", + "signature": "Double -> PowerTransform" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "ConstantImpute", + "signature": "Double -> Imputation" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Fold", + "signature": "[Int] -> [Int] -> Fold" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "MeanImpute", + "signature": "Imputation" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "MedianImpute", + "signature": "Imputation" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "MinMax", + "signature": "Scaling" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "RejectUnknown", + "signature": "UnknownCategory" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "RobustScale", + "signature": "Scaling" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "Standardize", + "signature": "Scaling" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "YeoJohnson", + "signature": "Double -> PowerTransform" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "ZeroUnknown", + "signature": "UnknownCategory" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "fitEncoder", + "signature": "Ord a => [a] -> Either MathError (Encoder a)" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "fitImputer", + "signature": "Imputation -> Dataset -> Either MathError Imputer" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "fitQuantileTransformer", + "signature": "Dataset -> Either MathError QuantileTransformer" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "fitScaler", + "signature": "Scaling -> Dataset -> Either MathError Scaler" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "gridSearch", + "signature": "[p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double)" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "impute", + "signature": "Imputer -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "inversePowerTransform", + "signature": "PowerTransform -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "inverseQuantileTransform", + "signature": "QuantileTransformer -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "inverseTransform", + "signature": "Scaler -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "kFold", + "signature": "Word64 -> Int -> Int -> Either MathError [Fold]" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "labelDecode", + "signature": "Encoder a -> [Int] -> Either MathError [a]" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "labelEncode", + "signature": "Eq a => Encoder a -> [a] -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "oneHotEncode", + "signature": "Eq a => UnknownCategory -> Encoder a -> [a] -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "powerTransform", + "signature": "PowerTransform -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "quantileTransform", + "signature": "QuantileTransformer -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "randomSearch", + "signature": "Word64 -> Int -> [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double)" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "stratifiedKFold", + "signature": "Ord a => Word64 -> Int -> [a] -> Either MathError [Fold]" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "trainTestSplit", + "signature": "Word64 -> Double -> Int -> Either MathError Fold" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "trainingIndices", + "signature": "Fold -> [Int]" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "transform", + "signature": "Scaler -> Dataset -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Preprocessing", + "name": "validationIndices", + "signature": "Fold -> [Int]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "BernoulliBayes", + "signature": "BayesFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "BinomialLogit", + "signature": "GLMFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "ElasticNet", + "signature": "Double -> Double -> Penalty" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "GaussianBayes", + "signature": "BayesFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Lasso", + "signature": "Double -> Penalty" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "LinearKernel", + "signature": "Kernel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "MultinomialBayes", + "signature": "BayesFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Ordinary", + "signature": "Penalty" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "PoissonLog", + "signature": "GLMFamily" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "PolynomialKernel", + "signature": "Int -> Double -> Double -> Kernel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "RBFKernel", + "signature": "Double -> Kernel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "Ridge", + "signature": "Double -> Penalty" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "bayesianCovariance", + "signature": "BayesianLinear -> Dataset" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "bayesianMean", + "signature": "BayesianLinear -> LinearModel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "coefficients", + "signature": "LinearModel -> [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "decisionSVM", + "signature": "SVM -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitBayesian", + "signature": "Double -> Double -> Dataset -> [Double] -> Either MathError BayesianLinear" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitDiscriminant", + "signature": "Bool -> Double -> Dataset -> [Int] -> Either MathError Discriminant" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitGLM", + "signature": "MLConfig -> GLMFamily -> Double -> Dataset -> [Double] -> Either MathError (Fit GLM)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitGPClassifier", + "signature": "MLConfig -> Kernel -> Dataset -> [Double] -> Either MathError (Fit GPClassifier)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitGaussianProcess", + "signature": "Kernel -> Double -> Dataset -> [Double] -> Either MathError GaussianProcess" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitLinear", + "signature": "MLConfig -> Penalty -> Dataset -> [Double] -> Either MathError (Fit LinearModel)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitMultinomial", + "signature": "MLConfig -> Double -> Dataset -> [Int] -> Either MathError (Fit MultinomialModel)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitNaiveBayes", + "signature": "BayesFamily -> Double -> Dataset -> [Int] -> Either MathError NaiveBayes" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitRobust", + "signature": "MLConfig -> Double -> Dataset -> [Double] -> Either MathError (Fit LinearModel)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitSVM", + "signature": "MLConfig -> Kernel -> Double -> Dataset -> [Double] -> Either MathError (Fit SVM)" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "fitWeighted", + "signature": "Dataset -> [Double] -> [Double] -> Either MathError LinearModel" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "kernel", + "signature": "Kernel -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "polynomialFeatures", + "signature": "Int -> [Double] -> Either MathError Dataset" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictDiscriminant", + "signature": "Discriminant -> Dataset -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictGLM", + "signature": "GLM -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictGPClassifier", + "signature": "GPClassifier -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictGaussianProcess", + "signature": "GaussianProcess -> Dataset -> Either MathError [(Double, Double)]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictLinear", + "signature": "LinearModel -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictMultinomial", + "signature": "MultinomialModel -> Dataset -> Either MathError [[(Int, Double)]]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictNaiveBayes", + "signature": "NaiveBayes -> Dataset -> Either MathError [Int]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "predictSVM", + "signature": "SVM -> Dataset -> Either MathError [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "recursiveCoefficients", + "signature": "RecursiveLS -> [Double]" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "recursiveLS", + "signature": "Int -> Double -> Double -> Either MathError RecursiveLS" + }, + { + "module": "HMath.MachineLearning.Regression", + "name": "updateRecursiveLS", + "signature": "RecursiveLS -> [Double] -> Double -> Either MathError RecursiveLS" + } + ] +} diff --git a/bindings/schema/machinelearning-objects.json b/bindings/schema/machinelearning-objects.json new file mode 100644 index 0000000..41f0f1c --- /dev/null +++ b/bindings/schema/machinelearning-objects.json @@ -0,0 +1,1945 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.MachineLearning.Clustering.ClusterModel", + "c": [ + "hmath_ml_cluster_model_object" + ], + "python": "hmath.machinelearning.ClusterModel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.GaussianMixture", + "c": [ + "hmath_ml_gaussian_mixture_object" + ], + "python": "hmath.machinelearning.GaussianMixture", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Linkage", + "c": [ + "hmath_ml_linkage_object" + ], + "python": "hmath.machinelearning.Linkage", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.CCA", + "c": [ + "hmath_ml_cca_object" + ], + "python": "hmath.machinelearning.CCA", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.FactorAnalysis", + "c": [ + "hmath_ml_factor_analysis_object" + ], + "python": "hmath.machinelearning.FactorAnalysis", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.ICA", + "c": [ + "hmath_ml_ica_object" + ], + "python": "hmath.machinelearning.ICA", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.IncrementalPCA", + "c": [ + "hmath_ml_incremental_pca_object" + ], + "python": "hmath.machinelearning.IncrementalPCA", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.KernelPCA", + "c": [ + "hmath_ml_kernel_pca_object" + ], + "python": "hmath.machinelearning.KernelPCA", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.PCA", + "c": [ + "hmath_ml_pca_object" + ], + "python": "hmath.machinelearning.PCA", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.PLS", + "c": [ + "hmath_ml_pls_object" + ], + "python": "hmath.machinelearning.PLS", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.IndexKind", + "c": [ + "hmath_ml_index_kind_object" + ], + "python": "hmath.machinelearning.IndexKind", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.IsolationForest", + "c": [ + "hmath_ml_isolation_forest_object" + ], + "python": "hmath.machinelearning.IsolationForest", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.LSH", + "c": [ + "hmath_ml_lsh_object" + ], + "python": "hmath.machinelearning.LSH", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.OneClassSVM", + "c": [ + "hmath_ml_one_class_svm_object" + ], + "python": "hmath.machinelearning.OneClassSVM", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.SpatialIndex", + "c": [ + "hmath_ml_spatial_index_object" + ], + "python": "hmath.machinelearning.SpatialIndex", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Encoder", + "c": [ + "hmath_ml_encoder_object" + ], + "python": "hmath.machinelearning.Encoder", + "specializations": [ + "actual native supported category dictionaries" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Imputation", + "c": [ + "hmath_ml_imputation_object" + ], + "python": "hmath.machinelearning.Imputation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Imputer", + "c": [ + "hmath_ml_imputer_object" + ], + "python": "hmath.machinelearning.Imputer", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.PowerTransform", + "c": [ + "hmath_ml_power_transform_object" + ], + "python": "hmath.machinelearning.PowerTransform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.QuantileTransformer", + "c": [ + "hmath_ml_quantile_transformer_object" + ], + "python": "hmath.machinelearning.QuantileTransformer", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Scaler", + "c": [ + "hmath_ml_scaler_object" + ], + "python": "hmath.machinelearning.Scaler", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Scaling", + "c": [ + "hmath_ml_scaling_object" + ], + "python": "hmath.machinelearning.Scaling", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.UnknownCategory", + "c": [ + "hmath_ml_unknown_category_object" + ], + "python": "hmath.machinelearning.UnknownCategory", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BayesFamily", + "c": [ + "hmath_ml_bayes_family_object" + ], + "python": "hmath.machinelearning.BayesFamily", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BayesianLinear", + "c": [ + "hmath_ml_bayesian_linear_object" + ], + "python": "hmath.machinelearning.BayesianLinear", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Discriminant", + "c": [ + "hmath_ml_discriminant_object" + ], + "python": "hmath.machinelearning.Discriminant", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GLM", + "c": [ + "hmath_ml_glm_object" + ], + "python": "hmath.machinelearning.GLM", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GLMFamily", + "c": [ + "hmath_ml_glm_family_object" + ], + "python": "hmath.machinelearning.GLMFamily", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GPClassifier", + "c": [ + "hmath_ml_gp_classifier_object" + ], + "python": "hmath.machinelearning.GPClassifier", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GaussianProcess", + "c": [ + "hmath_ml_gaussian_process_object" + ], + "python": "hmath.machinelearning.GaussianProcess", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Kernel", + "c": [ + "hmath_ml_kernel_object" + ], + "python": "hmath.machinelearning.Kernel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.LinearModel", + "c": [ + "hmath_ml_linear_model_object" + ], + "python": "hmath.machinelearning.LinearModel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.MultinomialModel", + "c": [ + "hmath_ml_multinomial_model_object" + ], + "python": "hmath.machinelearning.MultinomialModel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.NaiveBayes", + "c": [ + "hmath_ml_naive_bayes_object" + ], + "python": "hmath.machinelearning.NaiveBayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Penalty", + "c": [ + "hmath_ml_penalty_object" + ], + "python": "hmath.machinelearning.Penalty", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.RecursiveLS", + "c": [ + "hmath_ml_recursive_ls_object" + ], + "python": "hmath.machinelearning.RecursiveLS", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.SVM", + "c": [ + "hmath_ml_svm_object" + ], + "python": "hmath.machinelearning.SVM", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.Dataset", + "c": [ + "hmath_ml_dataset_value" + ], + "python": "hmath.machinelearning.Dataset", + "specializations": [ + "original Double rows" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Average", + "c": [ + "hmath_ml_average" + ], + "python": "hmath.machinelearning.average", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Complete", + "c": [ + "hmath_ml_complete" + ], + "python": "hmath.machinelearning.complete", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Merge", + "c": [ + "hmath_ml_merge" + ], + "python": "hmath.machinelearning.merge", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Single", + "c": [ + "hmath_ml_single" + ], + "python": "hmath.machinelearning.single", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Ward", + "c": [ + "hmath_ml_ward" + ], + "python": "hmath.machinelearning.ward", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.affinityPropagation", + "c": [ + "hmath_ml_affinity_propagation" + ], + "python": "hmath.machinelearning.affinity_propagation", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.clusterCenters", + "c": [ + "hmath_ml_cluster_centers" + ], + "python": "hmath.machinelearning.cluster_centers", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.cutHierarchy", + "c": [ + "hmath_ml_cut_hierarchy" + ], + "python": "hmath.machinelearning.cut_hierarchy", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.dbscan", + "c": [ + "hmath_ml_dbscan" + ], + "python": "hmath.machinelearning.dbscan", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.extractOPTICS", + "c": [ + "hmath_ml_extract_optics" + ], + "python": "hmath.machinelearning.extract_optics", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.fitGaussianMixture", + "c": [ + "hmath_ml_fit_gaussian_mixture" + ], + "python": "hmath.machinelearning.fit_gaussian_mixture", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.hierarchical", + "c": [ + "hmath_ml_hierarchical" + ], + "python": "hmath.machinelearning.hierarchical", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMeans", + "c": [ + "hmath_ml_k_means" + ], + "python": "hmath.machinelearning.k_means", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMeansPlusPlus", + "c": [ + "hmath_ml_k_means_plus_plus" + ], + "python": "hmath.machinelearning.k_means_plus_plus", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMedoids", + "c": [ + "hmath_ml_k_medoids" + ], + "python": "hmath.machinelearning.k_medoids", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.leftCluster", + "c": [ + "hmath_ml_left_cluster" + ], + "python": "hmath.machinelearning.left_cluster", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.meanShift", + "c": [ + "hmath_ml_mean_shift" + ], + "python": "hmath.machinelearning.mean_shift", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mergeDistance", + "c": [ + "hmath_ml_merge_distance" + ], + "python": "hmath.machinelearning.merge_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mergedSize", + "c": [ + "hmath_ml_merged_size" + ], + "python": "hmath.machinelearning.merged_size", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.miniBatchKMeans", + "c": [ + "hmath_ml_mini_batch_k_means" + ], + "python": "hmath.machinelearning.mini_batch_k_means", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureCovariances", + "c": [ + "hmath_ml_mixture_covariances" + ], + "python": "hmath.machinelearning.mixture_covariances", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureMeans", + "c": [ + "hmath_ml_mixture_means" + ], + "python": "hmath.machinelearning.mixture_means", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureResponsibilities", + "c": [ + "hmath_ml_mixture_responsibilities" + ], + "python": "hmath.machinelearning.mixture_responsibilities", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureWeights", + "c": [ + "hmath_ml_mixture_weights" + ], + "python": "hmath.machinelearning.mixture_weights", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.optics", + "c": [ + "hmath_ml_optics" + ], + "python": "hmath.machinelearning.optics", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.predictClusters", + "c": [ + "hmath_ml_predict_clusters" + ], + "python": "hmath.machinelearning.predict_clusters", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.rightCluster", + "c": [ + "hmath_ml_right_cluster" + ], + "python": "hmath.machinelearning.right_cluster", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.spectralClustering", + "c": [ + "hmath_ml_spectral_clustering" + ], + "python": "hmath.machinelearning.spectral_clustering", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.canonicalCorrelations", + "c": [ + "hmath_ml_canonical_correlations" + ], + "python": "hmath.machinelearning.canonical_correlations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.classicalMDS", + "c": [ + "hmath_ml_classical_mds" + ], + "python": "hmath.machinelearning.classical_mds", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.factorLoadings", + "c": [ + "hmath_ml_factor_loadings" + ], + "python": "hmath.machinelearning.factor_loadings", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.factorNoise", + "c": [ + "hmath_ml_factor_noise" + ], + "python": "hmath.machinelearning.factor_noise", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.finishPCA", + "c": [ + "hmath_ml_finish_pca" + ], + "python": "hmath.machinelearning.finish_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitCCA", + "c": [ + "hmath_ml_fit_cca" + ], + "python": "hmath.machinelearning.fit_cca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitFactorAnalysis", + "c": [ + "hmath_ml_fit_factor_analysis" + ], + "python": "hmath.machinelearning.fit_factor_analysis", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitICA", + "c": [ + "hmath_ml_fit_ica" + ], + "python": "hmath.machinelearning.fit_ica", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitKernelPCA", + "c": [ + "hmath_ml_fit_kernel_pca" + ], + "python": "hmath.machinelearning.fit_kernel_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitPCA", + "c": [ + "hmath_ml_fit_pca" + ], + "python": "hmath.machinelearning.fit_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitPLS", + "c": [ + "hmath_ml_fit_pls" + ], + "python": "hmath.machinelearning.fit_pls", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.incrementalPCA", + "c": [ + "hmath_ml_incremental_pca" + ], + "python": "hmath.machinelearning.incremental_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.inversePCA", + "c": [ + "hmath_ml_inverse_pca" + ], + "python": "hmath.machinelearning.inverse_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.isomap", + "c": [ + "hmath_ml_isomap" + ], + "python": "hmath.machinelearning.isomap", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.mergePCA", + "c": [ + "hmath_ml_merge_pca" + ], + "python": "hmath.machinelearning.merge_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaComponents", + "c": [ + "hmath_ml_pca_components" + ], + "python": "hmath.machinelearning.pca_components", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaMean", + "c": [ + "hmath_ml_pca_mean" + ], + "python": "hmath.machinelearning.pca_mean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaVariances", + "c": [ + "hmath_ml_pca_variances" + ], + "python": "hmath.machinelearning.pca_variances", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.predictPLS", + "c": [ + "hmath_ml_predict_pls" + ], + "python": "hmath.machinelearning.predict_pls", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.randomProjection", + "c": [ + "hmath_ml_random_projection" + ], + "python": "hmath.machinelearning.random_projection", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformCCA", + "c": [ + "hmath_ml_transform_cca" + ], + "python": "hmath.machinelearning.transform_cca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformICA", + "c": [ + "hmath_ml_transform_ica" + ], + "python": "hmath.machinelearning.transform_ica", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformKernelPCA", + "c": [ + "hmath_ml_transform_kernel_pca" + ], + "python": "hmath.machinelearning.transform_kernel_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformPCA", + "c": [ + "hmath_ml_transform_pca" + ], + "python": "hmath.machinelearning.transform_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.truncatedSVD", + "c": [ + "hmath_ml_truncated_svd" + ], + "python": "hmath.machinelearning.truncated_svd", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.tsne", + "c": [ + "hmath_ml_tsne" + ], + "python": "hmath.machinelearning.tsne", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.umap", + "c": [ + "hmath_ml_umap" + ], + "python": "hmath.machinelearning.umap", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.updatePCA", + "c": [ + "hmath_ml_update_pca" + ], + "python": "hmath.machinelearning.update_pca", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.Fit", + "c": [ + "hmath_ml_fit" + ], + "python": "hmath.machinelearning.fit", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.MLConfig", + "c": [ + "hmath_ml_ml_config" + ], + "python": "hmath.machinelearning.ml_config", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.defaultMLConfig", + "c": [ + "hmath_ml_default_ml_config" + ], + "python": "hmath.machinelearning.default_ml_config", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitConverged", + "c": [ + "hmath_ml_fit_converged" + ], + "python": "hmath.machinelearning.fit_converged", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitIterations", + "c": [ + "hmath_ml_fit_iterations" + ], + "python": "hmath.machinelearning.fit_iterations", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitResidual", + "c": [ + "hmath_ml_fit_residual" + ], + "python": "hmath.machinelearning.fit_residual", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitted", + "c": [ + "hmath_ml_fitted" + ], + "python": "hmath.machinelearning.fitted", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlIterations", + "c": [ + "hmath_ml_ml_iterations" + ], + "python": "hmath.machinelearning.ml_iterations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlRate", + "c": [ + "hmath_ml_ml_rate" + ], + "python": "hmath.machinelearning.ml_rate", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlSeed", + "c": [ + "hmath_ml_ml_seed" + ], + "python": "hmath.machinelearning.ml_seed", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlTolerance", + "c": [ + "hmath_ml_ml_tolerance" + ], + "python": "hmath.machinelearning.ml_tolerance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.BallTree", + "c": [ + "hmath_ml_ball_tree" + ], + "python": "hmath.machinelearning.ball_tree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.KDTree", + "c": [ + "hmath_ml_kd_tree" + ], + "python": "hmath.machinelearning.kd_tree", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.NeighborResult", + "c": [ + "hmath_ml_neighbor_result" + ], + "python": "hmath.machinelearning.neighbor_result", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.buildIndex", + "c": [ + "hmath_ml_build_index" + ], + "python": "hmath.machinelearning.build_index", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.buildLSH", + "c": [ + "hmath_ml_build_lsh" + ], + "python": "hmath.machinelearning.build_lsh", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.decisionOneClassSVM", + "c": [ + "hmath_ml_decision_one_class_svm" + ], + "python": "hmath.machinelearning.decision_one_class_svm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.exhaustive", + "c": [ + "hmath_ml_exhaustive" + ], + "python": "hmath.machinelearning.exhaustive", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.fitIsolationForest", + "c": [ + "hmath_ml_fit_isolation_forest" + ], + "python": "hmath.machinelearning.fit_isolation_forest", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.fitOneClassSVM", + "c": [ + "hmath_ml_fit_one_class_svm" + ], + "python": "hmath.machinelearning.fit_one_class_svm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.knnClassify", + "c": [ + "hmath_ml_knn_classify" + ], + "python": "hmath.machinelearning.knn_classify", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.knnRegress", + "c": [ + "hmath_ml_knn_regress" + ], + "python": "hmath.machinelearning.knn_regress", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.localOutlierFactor", + "c": [ + "hmath_ml_local_outlier_factor" + ], + "python": "hmath.machinelearning.local_outlier_factor", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.nearestNeighbors", + "c": [ + "hmath_ml_nearest_neighbors" + ], + "python": "hmath.machinelearning.nearest_neighbors", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.neighbors", + "c": [ + "hmath_ml_neighbors" + ], + "python": "hmath.machinelearning.neighbors", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.queryLSH", + "c": [ + "hmath_ml_query_lsh" + ], + "python": "hmath.machinelearning.query_lsh", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.scoreIsolationForest", + "c": [ + "hmath_ml_score_isolation_forest" + ], + "python": "hmath.machinelearning.score_isolation_forest", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.visitedLeaves", + "c": [ + "hmath_ml_visited_leaves" + ], + "python": "hmath.machinelearning.visited_leaves", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.BoxCox", + "c": [ + "hmath_ml_box_cox" + ], + "python": "hmath.machinelearning.box_cox", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.ConstantImpute", + "c": [ + "hmath_ml_constant_impute" + ], + "python": "hmath.machinelearning.constant_impute", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Fold", + "c": [ + "hmath_ml_fold" + ], + "python": "hmath.machinelearning.fold", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MeanImpute", + "c": [ + "hmath_ml_mean_impute" + ], + "python": "hmath.machinelearning.mean_impute", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MedianImpute", + "c": [ + "hmath_ml_median_impute" + ], + "python": "hmath.machinelearning.median_impute", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MinMax", + "c": [ + "hmath_ml_min_max" + ], + "python": "hmath.machinelearning.min_max", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.RejectUnknown", + "c": [ + "hmath_ml_reject_unknown" + ], + "python": "hmath.machinelearning.reject_unknown", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.RobustScale", + "c": [ + "hmath_ml_robust_scale" + ], + "python": "hmath.machinelearning.robust_scale", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Standardize", + "c": [ + "hmath_ml_standardize" + ], + "python": "hmath.machinelearning.standardize", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.YeoJohnson", + "c": [ + "hmath_ml_yeo_johnson" + ], + "python": "hmath.machinelearning.yeo_johnson", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.ZeroUnknown", + "c": [ + "hmath_ml_zero_unknown" + ], + "python": "hmath.machinelearning.zero_unknown", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitEncoder", + "c": [ + "hmath_ml_fit_encoder" + ], + "python": "hmath.machinelearning.fit_encoder", + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitImputer", + "c": [ + "hmath_ml_fit_imputer" + ], + "python": "hmath.machinelearning.fit_imputer", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitQuantileTransformer", + "c": [ + "hmath_ml_fit_quantile_transformer" + ], + "python": "hmath.machinelearning.fit_quantile_transformer", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitScaler", + "c": [ + "hmath_ml_fit_scaler" + ], + "python": "hmath.machinelearning.fit_scaler", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.gridSearch", + "c": [ + "hmath_ml_grid_search" + ], + "python": "hmath.machinelearning.grid_search", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.impute", + "c": [ + "hmath_ml_impute" + ], + "python": "hmath.machinelearning.impute", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inversePowerTransform", + "c": [ + "hmath_ml_inverse_power_transform" + ], + "python": "hmath.machinelearning.inverse_power_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inverseQuantileTransform", + "c": [ + "hmath_ml_inverse_quantile_transform" + ], + "python": "hmath.machinelearning.inverse_quantile_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inverseTransform", + "c": [ + "hmath_ml_inverse_transform" + ], + "python": "hmath.machinelearning.inverse_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.kFold", + "c": [ + "hmath_ml_k_fold" + ], + "python": "hmath.machinelearning.k_fold", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.labelDecode", + "c": [ + "hmath_ml_label_decode" + ], + "python": "hmath.machinelearning.label_decode", + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.labelEncode", + "c": [ + "hmath_ml_label_encode" + ], + "python": "hmath.machinelearning.label_encode", + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.oneHotEncode", + "c": [ + "hmath_ml_one_hot_encode" + ], + "python": "hmath.machinelearning.one_hot_encode", + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.powerTransform", + "c": [ + "hmath_ml_power_transform" + ], + "python": "hmath.machinelearning.power_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.quantileTransform", + "c": [ + "hmath_ml_quantile_transform" + ], + "python": "hmath.machinelearning.quantile_transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.randomSearch", + "c": [ + "hmath_ml_random_search" + ], + "python": "hmath.machinelearning.random_search", + "specializations": [ + "generic record/configuration payload preserved" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.stratifiedKFold", + "c": [ + "hmath_ml_stratified_k_fold" + ], + "python": "hmath.machinelearning.stratified_k_fold", + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.trainTestSplit", + "c": [ + "hmath_ml_train_test_split" + ], + "python": "hmath.machinelearning.train_test_split", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.trainingIndices", + "c": [ + "hmath_ml_training_indices" + ], + "python": "hmath.machinelearning.training_indices", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.transform", + "c": [ + "hmath_ml_transform" + ], + "python": "hmath.machinelearning.transform", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.validationIndices", + "c": [ + "hmath_ml_validation_indices" + ], + "python": "hmath.machinelearning.validation_indices", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BernoulliBayes", + "c": [ + "hmath_ml_bernoulli_bayes" + ], + "python": "hmath.machinelearning.bernoulli_bayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BinomialLogit", + "c": [ + "hmath_ml_binomial_logit" + ], + "python": "hmath.machinelearning.binomial_logit", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.ElasticNet", + "c": [ + "hmath_ml_elastic_net" + ], + "python": "hmath.machinelearning.elastic_net", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GaussianBayes", + "c": [ + "hmath_ml_gaussian_bayes" + ], + "python": "hmath.machinelearning.gaussian_bayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Lasso", + "c": [ + "hmath_ml_lasso" + ], + "python": "hmath.machinelearning.lasso", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.LinearKernel", + "c": [ + "hmath_ml_linear_kernel" + ], + "python": "hmath.machinelearning.linear_kernel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.MultinomialBayes", + "c": [ + "hmath_ml_multinomial_bayes" + ], + "python": "hmath.machinelearning.multinomial_bayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Ordinary", + "c": [ + "hmath_ml_ordinary" + ], + "python": "hmath.machinelearning.ordinary", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.PoissonLog", + "c": [ + "hmath_ml_poisson_log" + ], + "python": "hmath.machinelearning.poisson_log", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.PolynomialKernel", + "c": [ + "hmath_ml_polynomial_kernel" + ], + "python": "hmath.machinelearning.polynomial_kernel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.RBFKernel", + "c": [ + "hmath_ml_rbf_kernel" + ], + "python": "hmath.machinelearning.rbf_kernel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Ridge", + "c": [ + "hmath_ml_ridge" + ], + "python": "hmath.machinelearning.ridge", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.bayesianCovariance", + "c": [ + "hmath_ml_bayesian_covariance" + ], + "python": "hmath.machinelearning.bayesian_covariance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.bayesianMean", + "c": [ + "hmath_ml_bayesian_mean" + ], + "python": "hmath.machinelearning.bayesian_mean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.coefficients", + "c": [ + "hmath_ml_coefficients" + ], + "python": "hmath.machinelearning.coefficients", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.decisionSVM", + "c": [ + "hmath_ml_decision_svm" + ], + "python": "hmath.machinelearning.decision_svm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitBayesian", + "c": [ + "hmath_ml_fit_bayesian" + ], + "python": "hmath.machinelearning.fit_bayesian", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitDiscriminant", + "c": [ + "hmath_ml_fit_discriminant" + ], + "python": "hmath.machinelearning.fit_discriminant", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGLM", + "c": [ + "hmath_ml_fit_glm" + ], + "python": "hmath.machinelearning.fit_glm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGPClassifier", + "c": [ + "hmath_ml_fit_gp_classifier" + ], + "python": "hmath.machinelearning.fit_gp_classifier", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGaussianProcess", + "c": [ + "hmath_ml_fit_gaussian_process" + ], + "python": "hmath.machinelearning.fit_gaussian_process", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitLinear", + "c": [ + "hmath_ml_fit_linear" + ], + "python": "hmath.machinelearning.fit_linear", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitMultinomial", + "c": [ + "hmath_ml_fit_multinomial" + ], + "python": "hmath.machinelearning.fit_multinomial", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitNaiveBayes", + "c": [ + "hmath_ml_fit_naive_bayes" + ], + "python": "hmath.machinelearning.fit_naive_bayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitRobust", + "c": [ + "hmath_ml_fit_robust" + ], + "python": "hmath.machinelearning.fit_robust", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitSVM", + "c": [ + "hmath_ml_fit_svm" + ], + "python": "hmath.machinelearning.fit_svm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitWeighted", + "c": [ + "hmath_ml_fit_weighted" + ], + "python": "hmath.machinelearning.fit_weighted", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.kernel", + "c": [ + "hmath_ml_kernel" + ], + "python": "hmath.machinelearning.kernel", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.polynomialFeatures", + "c": [ + "hmath_ml_polynomial_features" + ], + "python": "hmath.machinelearning.polynomial_features", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictDiscriminant", + "c": [ + "hmath_ml_predict_discriminant" + ], + "python": "hmath.machinelearning.predict_discriminant", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGLM", + "c": [ + "hmath_ml_predict_glm" + ], + "python": "hmath.machinelearning.predict_glm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGPClassifier", + "c": [ + "hmath_ml_predict_gp_classifier" + ], + "python": "hmath.machinelearning.predict_gp_classifier", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGaussianProcess", + "c": [ + "hmath_ml_predict_gaussian_process" + ], + "python": "hmath.machinelearning.predict_gaussian_process", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictLinear", + "c": [ + "hmath_ml_predict_linear" + ], + "python": "hmath.machinelearning.predict_linear", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictMultinomial", + "c": [ + "hmath_ml_predict_multinomial" + ], + "python": "hmath.machinelearning.predict_multinomial", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictNaiveBayes", + "c": [ + "hmath_ml_predict_naive_bayes" + ], + "python": "hmath.machinelearning.predict_naive_bayes", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictSVM", + "c": [ + "hmath_ml_predict_svm" + ], + "python": "hmath.machinelearning.predict_svm", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.recursiveCoefficients", + "c": [ + "hmath_ml_recursive_coefficients" + ], + "python": "hmath.machinelearning.recursive_coefficients", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.recursiveLS", + "c": [ + "hmath_ml_recursive_ls" + ], + "python": "hmath.machinelearning.recursive_ls", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.updateRecursiveLS", + "c": [ + "hmath_ml_update_recursive_ls" + ], + "python": "hmath.machinelearning.update_recursive_ls", + "specializations": [ + "original concrete types" + ] + } + ] +} diff --git a/bindings/schema/machinelearning-symbols.txt b/bindings/schema/machinelearning-symbols.txt new file mode 100644 index 0000000..013426e --- /dev/null +++ b/bindings/schema/machinelearning-symbols.txt @@ -0,0 +1,158 @@ +hmath_ml_describe +hmath_ml_parts +hmath_ml_average +hmath_ml_complete +hmath_ml_merge +hmath_ml_single +hmath_ml_ward +hmath_ml_affinity_propagation +hmath_ml_cluster_centers +hmath_ml_cut_hierarchy +hmath_ml_dbscan +hmath_ml_extract_optics +hmath_ml_fit_gaussian_mixture +hmath_ml_hierarchical +hmath_ml_k_means +hmath_ml_k_means_plus_plus +hmath_ml_k_medoids +hmath_ml_left_cluster +hmath_ml_mean_shift +hmath_ml_merge_distance +hmath_ml_merged_size +hmath_ml_mini_batch_k_means +hmath_ml_mixture_covariances +hmath_ml_mixture_means +hmath_ml_mixture_responsibilities +hmath_ml_mixture_weights +hmath_ml_optics +hmath_ml_predict_clusters +hmath_ml_right_cluster +hmath_ml_spectral_clustering +hmath_ml_canonical_correlations +hmath_ml_classical_mds +hmath_ml_factor_loadings +hmath_ml_factor_noise +hmath_ml_finish_pca +hmath_ml_fit_cca +hmath_ml_fit_factor_analysis +hmath_ml_fit_ica +hmath_ml_fit_kernel_pca +hmath_ml_fit_pca +hmath_ml_fit_pls +hmath_ml_incremental_pca +hmath_ml_inverse_pca +hmath_ml_isomap +hmath_ml_merge_pca +hmath_ml_pca_components +hmath_ml_pca_mean +hmath_ml_pca_variances +hmath_ml_predict_pls +hmath_ml_random_projection +hmath_ml_transform_cca +hmath_ml_transform_ica +hmath_ml_transform_kernel_pca +hmath_ml_transform_pca +hmath_ml_truncated_svd +hmath_ml_tsne +hmath_ml_umap +hmath_ml_update_pca +hmath_ml_fit +hmath_ml_ml_config +hmath_ml_default_ml_config +hmath_ml_fit_converged +hmath_ml_fit_iterations +hmath_ml_fit_residual +hmath_ml_fitted +hmath_ml_ml_iterations +hmath_ml_ml_rate +hmath_ml_ml_seed +hmath_ml_ml_tolerance +hmath_ml_ball_tree +hmath_ml_kd_tree +hmath_ml_neighbor_result +hmath_ml_build_index +hmath_ml_build_lsh +hmath_ml_decision_one_class_svm +hmath_ml_exhaustive +hmath_ml_fit_isolation_forest +hmath_ml_fit_one_class_svm +hmath_ml_knn_classify +hmath_ml_knn_regress +hmath_ml_local_outlier_factor +hmath_ml_nearest_neighbors +hmath_ml_neighbors +hmath_ml_query_lsh +hmath_ml_score_isolation_forest +hmath_ml_visited_leaves +hmath_ml_box_cox +hmath_ml_constant_impute +hmath_ml_fold +hmath_ml_mean_impute +hmath_ml_median_impute +hmath_ml_min_max +hmath_ml_reject_unknown +hmath_ml_robust_scale +hmath_ml_standardize +hmath_ml_yeo_johnson +hmath_ml_zero_unknown +hmath_ml_fit_encoder +hmath_ml_fit_imputer +hmath_ml_fit_quantile_transformer +hmath_ml_fit_scaler +hmath_ml_grid_search +hmath_ml_impute +hmath_ml_inverse_power_transform +hmath_ml_inverse_quantile_transform +hmath_ml_inverse_transform +hmath_ml_k_fold +hmath_ml_label_decode +hmath_ml_label_encode +hmath_ml_one_hot_encode +hmath_ml_power_transform +hmath_ml_quantile_transform +hmath_ml_random_search +hmath_ml_stratified_k_fold +hmath_ml_train_test_split +hmath_ml_training_indices +hmath_ml_transform +hmath_ml_validation_indices +hmath_ml_bernoulli_bayes +hmath_ml_binomial_logit +hmath_ml_elastic_net +hmath_ml_gaussian_bayes +hmath_ml_lasso +hmath_ml_linear_kernel +hmath_ml_multinomial_bayes +hmath_ml_ordinary +hmath_ml_poisson_log +hmath_ml_polynomial_kernel +hmath_ml_rbf_kernel +hmath_ml_ridge +hmath_ml_bayesian_covariance +hmath_ml_bayesian_mean +hmath_ml_coefficients +hmath_ml_decision_svm +hmath_ml_fit_bayesian +hmath_ml_fit_discriminant +hmath_ml_fit_glm +hmath_ml_fit_gp_classifier +hmath_ml_fit_gaussian_process +hmath_ml_fit_linear +hmath_ml_fit_multinomial +hmath_ml_fit_naive_bayes +hmath_ml_fit_robust +hmath_ml_fit_svm +hmath_ml_fit_weighted +hmath_ml_kernel +hmath_ml_polynomial_features +hmath_ml_predict_discriminant +hmath_ml_predict_glm +hmath_ml_predict_gp_classifier +hmath_ml_predict_gaussian_process +hmath_ml_predict_linear +hmath_ml_predict_multinomial +hmath_ml_predict_naive_bayes +hmath_ml_predict_svm +hmath_ml_recursive_coefficients +hmath_ml_recursive_ls +hmath_ml_update_recursive_ls diff --git a/bindings/schema/matrix-functions.json b/bindings/schema/matrix-functions.json new file mode 100644 index 0000000..ea5ea3c --- /dev/null +++ b/bindings/schema/matrix-functions.json @@ -0,0 +1,1002 @@ +[ + { + "source": "HMath.Matrix.fromList", + "c": "hmath_dense_from_list_f32", + "precision": 32, + "name": "fromList", + "mode": "maybe", + "args": "iiv", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.zeroMatrix", + "c": "hmath_dense_zero_matrix_f32", + "precision": 32, + "name": "zeroMatrix", + "mode": "maybe", + "args": "ii", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.diagonal", + "c": "hmath_dense_diagonal_f32", + "precision": 32, + "name": "diagonal", + "mode": "maybe", + "args": "v", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.at", + "c": "hmath_dense_at_f32", + "precision": 32, + "name": "at", + "mode": "maybe", + "args": "mii", + "result": "f", + "module": "M" + }, + { + "source": "HMath.Matrix.sliceMatrix", + "c": "hmath_dense_slice_matrix_f32", + "precision": 32, + "name": "sliceMatrix", + "mode": "maybe", + "args": "iiiim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.reshape", + "c": "hmath_dense_reshape_f32", + "precision": 32, + "name": "reshape", + "mode": "maybe", + "args": "iim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.addMatrix", + "c": "hmath_dense_add_matrix_f32", + "precision": 32, + "name": "addMatrix", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.subtractMatrix", + "c": "hmath_dense_subtract_matrix_f32", + "precision": 32, + "name": "subtractMatrix", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.hadamard", + "c": "hmath_dense_hadamard_f32", + "precision": 32, + "name": "hadamard", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.multiply", + "c": "hmath_dense_multiply_f32", + "precision": 32, + "name": "multiply", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.identity", + "c": "hmath_dense_identity_f32", + "precision": 32, + "name": "identity", + "mode": "maybe", + "args": "i", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.fromListChecked", + "c": "hmath_dense_from_list_checked_f32", + "precision": 32, + "name": "fromListChecked", + "mode": "either", + "args": "iiv", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.zeroMatrixChecked", + "c": "hmath_dense_zero_matrix_checked_f32", + "precision": 32, + "name": "zeroMatrixChecked", + "mode": "either", + "args": "ii", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.diagonalChecked", + "c": "hmath_dense_diagonal_checked_f32", + "precision": 32, + "name": "diagonalChecked", + "mode": "either", + "args": "v", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.atChecked", + "c": "hmath_dense_at_checked_f32", + "precision": 32, + "name": "atChecked", + "mode": "either", + "args": "mii", + "result": "f", + "module": "M" + }, + { + "source": "HMath.Matrix.sliceMatrixChecked", + "c": "hmath_dense_slice_matrix_checked_f32", + "precision": 32, + "name": "sliceMatrixChecked", + "mode": "either", + "args": "iiiim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.reshapeChecked", + "c": "hmath_dense_reshape_checked_f32", + "precision": 32, + "name": "reshapeChecked", + "mode": "either", + "args": "iim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.addMatrixChecked", + "c": "hmath_dense_add_matrix_checked_f32", + "precision": 32, + "name": "addMatrixChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.subtractMatrixChecked", + "c": "hmath_dense_subtract_matrix_checked_f32", + "precision": 32, + "name": "subtractMatrixChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.hadamardChecked", + "c": "hmath_dense_hadamard_checked_f32", + "precision": 32, + "name": "hadamardChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.multiplyChecked", + "c": "hmath_dense_multiply_checked_f32", + "precision": 32, + "name": "multiplyChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.identityChecked", + "c": "hmath_dense_identity_checked_f32", + "precision": 32, + "name": "identityChecked", + "mode": "either", + "args": "i", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.scaleMatrix", + "c": "hmath_dense_scale_matrix_f32", + "precision": 32, + "name": "scaleMatrix", + "mode": "pure", + "args": "fm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.transposeMatrix", + "c": "hmath_dense_transpose_matrix_f32", + "precision": 32, + "name": "transposeMatrix", + "mode": "pure", + "args": "m", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.LU.luDecompose", + "c": "hmath_dense_lu_lu_decompose_f32", + "precision": 32, + "name": "luDecompose", + "mode": "either", + "args": "m", + "result": "l", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luDecomposeWithTolerance", + "c": "hmath_dense_lu_lu_decompose_with_tolerance_f32", + "precision": 32, + "name": "luDecomposeWithTolerance", + "mode": "either", + "args": "fm", + "result": "l", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luLower", + "c": "hmath_dense_lu_lu_lower_f32", + "precision": 32, + "name": "luLower", + "mode": "pure", + "args": "l", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luUpper", + "c": "hmath_dense_lu_lu_upper_f32", + "precision": 32, + "name": "luUpper", + "mode": "pure", + "args": "l", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luPermutation", + "c": "hmath_dense_lu_lu_permutation_f32", + "precision": 32, + "name": "luPermutation", + "mode": "pure", + "args": "l", + "result": "p", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveLU", + "c": "hmath_dense_lu_solve_lu_f32", + "precision": 32, + "name": "solveLU", + "mode": "either", + "args": "lv", + "result": "v", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveMatrixLU", + "c": "hmath_dense_lu_solve_matrix_lu_f32", + "precision": 32, + "name": "solveMatrixLU", + "mode": "either", + "args": "lm", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solve", + "c": "hmath_dense_lu_solve_f32", + "precision": 32, + "name": "solve", + "mode": "either", + "args": "mv", + "result": "v", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveMatrix", + "c": "hmath_dense_lu_solve_matrix_f32", + "precision": 32, + "name": "solveMatrix", + "mode": "either", + "args": "mm", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.determinantLU", + "c": "hmath_dense_lu_determinant_lu_f32", + "precision": 32, + "name": "determinantLU", + "mode": "either", + "args": "l", + "result": "f", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.determinant", + "c": "hmath_dense_lu_determinant_f32", + "precision": 32, + "name": "determinant", + "mode": "either", + "args": "m", + "result": "f", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.inverse", + "c": "hmath_dense_lu_inverse_f32", + "precision": 32, + "name": "inverse", + "mode": "either", + "args": "m", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.QR.qrDecompose", + "c": "hmath_dense_qr_qr_decompose_f32", + "precision": 32, + "name": "qrDecompose", + "mode": "either", + "args": "m", + "result": "q", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrDecomposeWithTolerance", + "c": "hmath_dense_qr_qr_decompose_with_tolerance_f32", + "precision": 32, + "name": "qrDecomposeWithTolerance", + "mode": "either", + "args": "fm", + "result": "q", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrQ", + "c": "hmath_dense_qr_qr_q_f32", + "precision": 32, + "name": "qrQ", + "mode": "pure", + "args": "q", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrR", + "c": "hmath_dense_qr_qr_r_f32", + "precision": 32, + "name": "qrR", + "mode": "pure", + "args": "q", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrPermutation", + "c": "hmath_dense_qr_qr_permutation_f32", + "precision": 32, + "name": "qrPermutation", + "mode": "pure", + "args": "q", + "result": "p", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrRank", + "c": "hmath_dense_qr_qr_rank_f32", + "precision": 32, + "name": "qrRank", + "mode": "pure", + "args": "q", + "result": "i", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.applyQ", + "c": "hmath_dense_qr_apply_q_f32", + "precision": 32, + "name": "applyQ", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.applyQT", + "c": "hmath_dense_qr_apply_qt_f32", + "precision": 32, + "name": "applyQT", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.solveMatrixQR", + "c": "hmath_dense_qr_solve_matrix_qr_f32", + "precision": 32, + "name": "solveMatrixQR", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.solveQR", + "c": "hmath_dense_qr_solve_qr_f32", + "precision": 32, + "name": "solveQR", + "mode": "either", + "args": "qv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.leastSquares", + "c": "hmath_dense_qr_least_squares_f32", + "precision": 32, + "name": "leastSquares", + "mode": "either", + "args": "mv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.leastSquaresMatrix", + "c": "hmath_dense_qr_least_squares_matrix_f32", + "precision": 32, + "name": "leastSquaresMatrix", + "mode": "either", + "args": "mm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.ridgeSolve", + "c": "hmath_dense_qr_ridge_solve_f32", + "precision": 32, + "name": "ridgeSolve", + "mode": "either", + "args": "fmv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.ridgeSolveMatrix", + "c": "hmath_dense_qr_ridge_solve_matrix_f32", + "precision": 32, + "name": "ridgeSolveMatrix", + "mode": "either", + "args": "fmm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.fromList", + "c": "hmath_dense_from_list_f64", + "precision": 64, + "name": "fromList", + "mode": "maybe", + "args": "iiv", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.zeroMatrix", + "c": "hmath_dense_zero_matrix_f64", + "precision": 64, + "name": "zeroMatrix", + "mode": "maybe", + "args": "ii", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.diagonal", + "c": "hmath_dense_diagonal_f64", + "precision": 64, + "name": "diagonal", + "mode": "maybe", + "args": "v", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.at", + "c": "hmath_dense_at_f64", + "precision": 64, + "name": "at", + "mode": "maybe", + "args": "mii", + "result": "f", + "module": "M" + }, + { + "source": "HMath.Matrix.sliceMatrix", + "c": "hmath_dense_slice_matrix_f64", + "precision": 64, + "name": "sliceMatrix", + "mode": "maybe", + "args": "iiiim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.reshape", + "c": "hmath_dense_reshape_f64", + "precision": 64, + "name": "reshape", + "mode": "maybe", + "args": "iim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.addMatrix", + "c": "hmath_dense_add_matrix_f64", + "precision": 64, + "name": "addMatrix", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.subtractMatrix", + "c": "hmath_dense_subtract_matrix_f64", + "precision": 64, + "name": "subtractMatrix", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.hadamard", + "c": "hmath_dense_hadamard_f64", + "precision": 64, + "name": "hadamard", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.multiply", + "c": "hmath_dense_multiply_f64", + "precision": 64, + "name": "multiply", + "mode": "maybe", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.identity", + "c": "hmath_dense_identity_f64", + "precision": 64, + "name": "identity", + "mode": "maybe", + "args": "i", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.fromListChecked", + "c": "hmath_dense_from_list_checked_f64", + "precision": 64, + "name": "fromListChecked", + "mode": "either", + "args": "iiv", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.zeroMatrixChecked", + "c": "hmath_dense_zero_matrix_checked_f64", + "precision": 64, + "name": "zeroMatrixChecked", + "mode": "either", + "args": "ii", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.diagonalChecked", + "c": "hmath_dense_diagonal_checked_f64", + "precision": 64, + "name": "diagonalChecked", + "mode": "either", + "args": "v", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.atChecked", + "c": "hmath_dense_at_checked_f64", + "precision": 64, + "name": "atChecked", + "mode": "either", + "args": "mii", + "result": "f", + "module": "M" + }, + { + "source": "HMath.Matrix.sliceMatrixChecked", + "c": "hmath_dense_slice_matrix_checked_f64", + "precision": 64, + "name": "sliceMatrixChecked", + "mode": "either", + "args": "iiiim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.reshapeChecked", + "c": "hmath_dense_reshape_checked_f64", + "precision": 64, + "name": "reshapeChecked", + "mode": "either", + "args": "iim", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.addMatrixChecked", + "c": "hmath_dense_add_matrix_checked_f64", + "precision": 64, + "name": "addMatrixChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.subtractMatrixChecked", + "c": "hmath_dense_subtract_matrix_checked_f64", + "precision": 64, + "name": "subtractMatrixChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.hadamardChecked", + "c": "hmath_dense_hadamard_checked_f64", + "precision": 64, + "name": "hadamardChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.multiplyChecked", + "c": "hmath_dense_multiply_checked_f64", + "precision": 64, + "name": "multiplyChecked", + "mode": "either", + "args": "mm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.identityChecked", + "c": "hmath_dense_identity_checked_f64", + "precision": 64, + "name": "identityChecked", + "mode": "either", + "args": "i", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.scaleMatrix", + "c": "hmath_dense_scale_matrix_f64", + "precision": 64, + "name": "scaleMatrix", + "mode": "pure", + "args": "fm", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.transposeMatrix", + "c": "hmath_dense_transpose_matrix_f64", + "precision": 64, + "name": "transposeMatrix", + "mode": "pure", + "args": "m", + "result": "m", + "module": "M" + }, + { + "source": "HMath.Matrix.LU.luDecompose", + "c": "hmath_dense_lu_lu_decompose_f64", + "precision": 64, + "name": "luDecompose", + "mode": "either", + "args": "m", + "result": "l", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luDecomposeWithTolerance", + "c": "hmath_dense_lu_lu_decompose_with_tolerance_f64", + "precision": 64, + "name": "luDecomposeWithTolerance", + "mode": "either", + "args": "fm", + "result": "l", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luLower", + "c": "hmath_dense_lu_lu_lower_f64", + "precision": 64, + "name": "luLower", + "mode": "pure", + "args": "l", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luUpper", + "c": "hmath_dense_lu_lu_upper_f64", + "precision": 64, + "name": "luUpper", + "mode": "pure", + "args": "l", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.luPermutation", + "c": "hmath_dense_lu_lu_permutation_f64", + "precision": 64, + "name": "luPermutation", + "mode": "pure", + "args": "l", + "result": "p", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveLU", + "c": "hmath_dense_lu_solve_lu_f64", + "precision": 64, + "name": "solveLU", + "mode": "either", + "args": "lv", + "result": "v", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveMatrixLU", + "c": "hmath_dense_lu_solve_matrix_lu_f64", + "precision": 64, + "name": "solveMatrixLU", + "mode": "either", + "args": "lm", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solve", + "c": "hmath_dense_lu_solve_f64", + "precision": 64, + "name": "solve", + "mode": "either", + "args": "mv", + "result": "v", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.solveMatrix", + "c": "hmath_dense_lu_solve_matrix_f64", + "precision": 64, + "name": "solveMatrix", + "mode": "either", + "args": "mm", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.determinantLU", + "c": "hmath_dense_lu_determinant_lu_f64", + "precision": 64, + "name": "determinantLU", + "mode": "either", + "args": "l", + "result": "f", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.determinant", + "c": "hmath_dense_lu_determinant_f64", + "precision": 64, + "name": "determinant", + "mode": "either", + "args": "m", + "result": "f", + "module": "L" + }, + { + "source": "HMath.Matrix.LU.inverse", + "c": "hmath_dense_lu_inverse_f64", + "precision": 64, + "name": "inverse", + "mode": "either", + "args": "m", + "result": "m", + "module": "L" + }, + { + "source": "HMath.Matrix.QR.qrDecompose", + "c": "hmath_dense_qr_qr_decompose_f64", + "precision": 64, + "name": "qrDecompose", + "mode": "either", + "args": "m", + "result": "q", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrDecomposeWithTolerance", + "c": "hmath_dense_qr_qr_decompose_with_tolerance_f64", + "precision": 64, + "name": "qrDecomposeWithTolerance", + "mode": "either", + "args": "fm", + "result": "q", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrQ", + "c": "hmath_dense_qr_qr_q_f64", + "precision": 64, + "name": "qrQ", + "mode": "pure", + "args": "q", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrR", + "c": "hmath_dense_qr_qr_r_f64", + "precision": 64, + "name": "qrR", + "mode": "pure", + "args": "q", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrPermutation", + "c": "hmath_dense_qr_qr_permutation_f64", + "precision": 64, + "name": "qrPermutation", + "mode": "pure", + "args": "q", + "result": "p", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.qrRank", + "c": "hmath_dense_qr_qr_rank_f64", + "precision": 64, + "name": "qrRank", + "mode": "pure", + "args": "q", + "result": "i", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.applyQ", + "c": "hmath_dense_qr_apply_q_f64", + "precision": 64, + "name": "applyQ", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.applyQT", + "c": "hmath_dense_qr_apply_qt_f64", + "precision": 64, + "name": "applyQT", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.solveMatrixQR", + "c": "hmath_dense_qr_solve_matrix_qr_f64", + "precision": 64, + "name": "solveMatrixQR", + "mode": "either", + "args": "qm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.solveQR", + "c": "hmath_dense_qr_solve_qr_f64", + "precision": 64, + "name": "solveQR", + "mode": "either", + "args": "qv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.leastSquares", + "c": "hmath_dense_qr_least_squares_f64", + "precision": 64, + "name": "leastSquares", + "mode": "either", + "args": "mv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.leastSquaresMatrix", + "c": "hmath_dense_qr_least_squares_matrix_f64", + "precision": 64, + "name": "leastSquaresMatrix", + "mode": "either", + "args": "mm", + "result": "m", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.ridgeSolve", + "c": "hmath_dense_qr_ridge_solve_f64", + "precision": 64, + "name": "ridgeSolve", + "mode": "either", + "args": "fmv", + "result": "v", + "module": "Q" + }, + { + "source": "HMath.Matrix.QR.ridgeSolveMatrix", + "c": "hmath_dense_qr_ridge_solve_matrix_f64", + "precision": 64, + "name": "ridgeSolveMatrix", + "mode": "either", + "args": "fmm", + "result": "m", + "module": "Q" + } +] diff --git a/bindings/schema/matrix-objects.json b/bindings/schema/matrix-objects.json new file mode 100644 index 0000000..266ceb0 --- /dev/null +++ b/bindings/schema/matrix-objects.json @@ -0,0 +1,662 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Matrix.LU.determinant", + "c": [ + "hmath_dense_lu_determinant_f32", + "hmath_dense_lu_determinant_f64" + ], + "python": "hmath.matrix.determinant", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.determinantLU", + "c": [ + "hmath_dense_lu_determinant_lu_f32", + "hmath_dense_lu_determinant_lu_f64" + ], + "python": "hmath.matrix.determinant_lu", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.inverse", + "c": [ + "hmath_dense_lu_inverse_f32", + "hmath_dense_lu_inverse_f64" + ], + "python": "hmath.matrix.inverse", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.luDecompose", + "c": [ + "hmath_dense_lu_lu_decompose_f32", + "hmath_dense_lu_lu_decompose_f64" + ], + "python": "hmath.matrix.lu_decompose", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.luDecomposeWithTolerance", + "c": [ + "hmath_dense_lu_lu_decompose_with_tolerance_f32", + "hmath_dense_lu_lu_decompose_with_tolerance_f64" + ], + "python": "hmath.matrix.lu_decompose_with_tolerance", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.luLower", + "c": [ + "hmath_dense_lu_lu_lower_f32", + "hmath_dense_lu_lu_lower_f64" + ], + "python": "hmath.matrix.lu_lower", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.luPermutation", + "c": [ + "hmath_dense_lu_lu_permutation_f32", + "hmath_dense_lu_lu_permutation_f64" + ], + "python": "hmath.matrix.lu_permutation", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.luUpper", + "c": [ + "hmath_dense_lu_lu_upper_f32", + "hmath_dense_lu_lu_upper_f64" + ], + "python": "hmath.matrix.lu_upper", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.solve", + "c": [ + "hmath_dense_lu_solve_f32", + "hmath_dense_lu_solve_f64" + ], + "python": "hmath.matrix.solve", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveLU", + "c": [ + "hmath_dense_lu_solve_lu_f32", + "hmath_dense_lu_solve_lu_f64" + ], + "python": "hmath.matrix.solve_lu", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveMatrix", + "c": [ + "hmath_dense_lu_solve_matrix_f32", + "hmath_dense_lu_solve_matrix_f64" + ], + "python": "hmath.matrix.solve_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveMatrixLU", + "c": [ + "hmath_dense_lu_solve_matrix_lu_f32", + "hmath_dense_lu_solve_matrix_lu_f64" + ], + "python": "hmath.matrix.solve_matrix_lu", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.applyQ", + "c": [ + "hmath_dense_qr_apply_q_f32", + "hmath_dense_qr_apply_q_f64" + ], + "python": "hmath.matrix.apply_q", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.applyQT", + "c": [ + "hmath_dense_qr_apply_qt_f32", + "hmath_dense_qr_apply_qt_f64" + ], + "python": "hmath.matrix.apply_qt", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.leastSquares", + "c": [ + "hmath_dense_qr_least_squares_f32", + "hmath_dense_qr_least_squares_f64" + ], + "python": "hmath.matrix.least_squares", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.leastSquaresMatrix", + "c": [ + "hmath_dense_qr_least_squares_matrix_f32", + "hmath_dense_qr_least_squares_matrix_f64" + ], + "python": "hmath.matrix.least_squares_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrDecompose", + "c": [ + "hmath_dense_qr_qr_decompose_f32", + "hmath_dense_qr_qr_decompose_f64" + ], + "python": "hmath.matrix.qr_decompose", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrDecomposeWithTolerance", + "c": [ + "hmath_dense_qr_qr_decompose_with_tolerance_f32", + "hmath_dense_qr_qr_decompose_with_tolerance_f64" + ], + "python": "hmath.matrix.qr_decompose_with_tolerance", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrPermutation", + "c": [ + "hmath_dense_qr_qr_permutation_f32", + "hmath_dense_qr_qr_permutation_f64" + ], + "python": "hmath.matrix.qr_permutation", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrQ", + "c": [ + "hmath_dense_qr_qr_q_f32", + "hmath_dense_qr_qr_q_f64" + ], + "python": "hmath.matrix.qr_q", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrR", + "c": [ + "hmath_dense_qr_qr_r_f32", + "hmath_dense_qr_qr_r_f64" + ], + "python": "hmath.matrix.qr_r", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrRank", + "c": [ + "hmath_dense_qr_qr_rank_f32", + "hmath_dense_qr_qr_rank_f64" + ], + "python": "hmath.matrix.qr_rank", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.ridgeSolve", + "c": [ + "hmath_dense_qr_ridge_solve_f32", + "hmath_dense_qr_ridge_solve_f64" + ], + "python": "hmath.matrix.ridge_solve", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.ridgeSolveMatrix", + "c": [ + "hmath_dense_qr_ridge_solve_matrix_f32", + "hmath_dense_qr_ridge_solve_matrix_f64" + ], + "python": "hmath.matrix.ridge_solve_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.solveMatrixQR", + "c": [ + "hmath_dense_qr_solve_matrix_qr_f32", + "hmath_dense_qr_solve_matrix_qr_f64" + ], + "python": "hmath.matrix.solve_matrix_qr", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.solveQR", + "c": [ + "hmath_dense_qr_solve_qr_f32", + "hmath_dense_qr_solve_qr_f64" + ], + "python": "hmath.matrix.solve_qr", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.addMatrix", + "c": [ + "hmath_dense_add_matrix_f32", + "hmath_dense_add_matrix_f64" + ], + "python": "hmath.matrix.add_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.addMatrixChecked", + "c": [ + "hmath_dense_add_matrix_checked_f32", + "hmath_dense_add_matrix_checked_f64" + ], + "python": "hmath.matrix.add_matrix_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.at", + "c": [ + "hmath_dense_at_f32", + "hmath_dense_at_f64" + ], + "python": "hmath.matrix.at", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.atChecked", + "c": [ + "hmath_dense_at_checked_f32", + "hmath_dense_at_checked_f64" + ], + "python": "hmath.matrix.at_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.diagonal", + "c": [ + "hmath_dense_diagonal_f32", + "hmath_dense_diagonal_f64" + ], + "python": "hmath.matrix.diagonal", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.diagonalChecked", + "c": [ + "hmath_dense_diagonal_checked_f32", + "hmath_dense_diagonal_checked_f64" + ], + "python": "hmath.matrix.diagonal_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.fromList", + "c": [ + "hmath_dense_from_list_f32", + "hmath_dense_from_list_f64" + ], + "python": "hmath.matrix.from_list", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.fromListChecked", + "c": [ + "hmath_dense_from_list_checked_f32", + "hmath_dense_from_list_checked_f64" + ], + "python": "hmath.matrix.from_list_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.hadamard", + "c": [ + "hmath_dense_hadamard_f32", + "hmath_dense_hadamard_f64" + ], + "python": "hmath.matrix.hadamard", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.hadamardChecked", + "c": [ + "hmath_dense_hadamard_checked_f32", + "hmath_dense_hadamard_checked_f64" + ], + "python": "hmath.matrix.hadamard_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.identity", + "c": [ + "hmath_dense_identity_f32", + "hmath_dense_identity_f64" + ], + "python": "hmath.matrix.identity", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.identityChecked", + "c": [ + "hmath_dense_identity_checked_f32", + "hmath_dense_identity_checked_f64" + ], + "python": "hmath.matrix.identity_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.multiply", + "c": [ + "hmath_dense_multiply_f32", + "hmath_dense_multiply_f64" + ], + "python": "hmath.matrix.multiply", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.multiplyChecked", + "c": [ + "hmath_dense_multiply_checked_f32", + "hmath_dense_multiply_checked_f64" + ], + "python": "hmath.matrix.multiply_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.reshape", + "c": [ + "hmath_dense_reshape_f32", + "hmath_dense_reshape_f64" + ], + "python": "hmath.matrix.reshape", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.reshapeChecked", + "c": [ + "hmath_dense_reshape_checked_f32", + "hmath_dense_reshape_checked_f64" + ], + "python": "hmath.matrix.reshape_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.scaleMatrix", + "c": [ + "hmath_dense_scale_matrix_f32", + "hmath_dense_scale_matrix_f64" + ], + "python": "hmath.matrix.scale_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrix", + "c": [ + "hmath_dense_slice_matrix_f32", + "hmath_dense_slice_matrix_f64" + ], + "python": "hmath.matrix.slice_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrixChecked", + "c": [ + "hmath_dense_slice_matrix_checked_f32", + "hmath_dense_slice_matrix_checked_f64" + ], + "python": "hmath.matrix.slice_matrix_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrix", + "c": [ + "hmath_dense_subtract_matrix_f32", + "hmath_dense_subtract_matrix_f64" + ], + "python": "hmath.matrix.subtract_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrixChecked", + "c": [ + "hmath_dense_subtract_matrix_checked_f32", + "hmath_dense_subtract_matrix_checked_f64" + ], + "python": "hmath.matrix.subtract_matrix_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.transposeMatrix", + "c": [ + "hmath_dense_transpose_matrix_f32", + "hmath_dense_transpose_matrix_f64" + ], + "python": "hmath.matrix.transpose_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrix", + "c": [ + "hmath_dense_zero_matrix_f32", + "hmath_dense_zero_matrix_f64" + ], + "python": "hmath.matrix.zero_matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrixChecked", + "c": [ + "hmath_dense_zero_matrix_checked_f32", + "hmath_dense_zero_matrix_checked_f64" + ], + "python": "hmath.matrix.zero_matrix_checked", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.shape", + "c": [ + "hmath_dense_shape" + ], + "python": "hmath.matrix.shape", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.toList", + "c": [ + "hmath_dense_count", + "hmath_dense_values_f32", + "hmath_dense_values_f64" + ], + "python": "hmath.matrix.to_list", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.Matrix", + "c": [ + "hmath_dense_matrix" + ], + "python": "hmath.matrix.Matrix", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.LU.LU", + "c": [ + "hmath_dense_lu" + ], + "python": "hmath.matrix.LU", + "specializations": [ + "Float", + "Double" + ] + }, + { + "symbol": "HMath.Matrix.QR.QR", + "c": [ + "hmath_dense_qr" + ], + "python": "hmath.matrix.QR", + "specializations": [ + "Float", + "Double" + ] + } + ] +} diff --git a/bindings/schema/matrix-value-objects.json b/bindings/schema/matrix-value-objects.json new file mode 100644 index 0000000..020a3e2 --- /dev/null +++ b/bindings/schema/matrix-value-objects.json @@ -0,0 +1,443 @@ +{ + "schema": 1, + "extends": "matrix-objects.json", + "bindings": [ + { + "symbol": "HMath.Matrix.fromList", + "c": [ + "hmath_matrix_value_from_list" + ], + "python": "hmath.matrix.from_list", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrix", + "c": [ + "hmath_matrix_value_zero_matrix" + ], + "python": "hmath.matrix.zero_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.diagonal", + "c": [ + "hmath_matrix_value_diagonal" + ], + "python": "hmath.matrix.diagonal", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.at", + "c": [ + "hmath_matrix_value_at" + ], + "python": "hmath.matrix.at", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrix", + "c": [ + "hmath_matrix_value_slice_matrix" + ], + "python": "hmath.matrix.slice_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.reshape", + "c": [ + "hmath_matrix_value_reshape" + ], + "python": "hmath.matrix.reshape", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.addMatrix", + "c": [ + "hmath_matrix_value_add_matrix" + ], + "python": "hmath.matrix.add_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrix", + "c": [ + "hmath_matrix_value_subtract_matrix" + ], + "python": "hmath.matrix.subtract_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.hadamard", + "c": [ + "hmath_matrix_value_hadamard" + ], + "python": "hmath.matrix.hadamard", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.multiply", + "c": [ + "hmath_matrix_value_multiply" + ], + "python": "hmath.matrix.multiply", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.identity", + "c": [ + "hmath_matrix_value_identity" + ], + "python": "hmath.matrix.identity", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.fromListChecked", + "c": [ + "hmath_matrix_value_from_list_checked" + ], + "python": "hmath.matrix.from_list_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrixChecked", + "c": [ + "hmath_matrix_value_zero_matrix_checked" + ], + "python": "hmath.matrix.zero_matrix_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.diagonalChecked", + "c": [ + "hmath_matrix_value_diagonal_checked" + ], + "python": "hmath.matrix.diagonal_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.atChecked", + "c": [ + "hmath_matrix_value_at_checked" + ], + "python": "hmath.matrix.at_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrixChecked", + "c": [ + "hmath_matrix_value_slice_matrix_checked" + ], + "python": "hmath.matrix.slice_matrix_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.reshapeChecked", + "c": [ + "hmath_matrix_value_reshape_checked" + ], + "python": "hmath.matrix.reshape_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.addMatrixChecked", + "c": [ + "hmath_matrix_value_add_matrix_checked" + ], + "python": "hmath.matrix.add_matrix_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrixChecked", + "c": [ + "hmath_matrix_value_subtract_matrix_checked" + ], + "python": "hmath.matrix.subtract_matrix_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.hadamardChecked", + "c": [ + "hmath_matrix_value_hadamard_checked" + ], + "python": "hmath.matrix.hadamard_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.multiplyChecked", + "c": [ + "hmath_matrix_value_multiply_checked" + ], + "python": "hmath.matrix.multiply_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.identityChecked", + "c": [ + "hmath_matrix_value_identity_checked" + ], + "python": "hmath.matrix.identity_checked", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.scaleMatrix", + "c": [ + "hmath_matrix_value_scale_matrix" + ], + "python": "hmath.matrix.scale_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values" + ] + }, + { + "symbol": "HMath.Matrix.transposeMatrix", + "c": [ + "hmath_matrix_value_transpose_matrix" + ], + "python": "hmath.matrix.transpose_matrix", + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + "Bool/String and other captured structural codecs" + ] + }, + { + "symbol": "HMath.Matrix.toList", + "c": [ + "hmath_matrix_value_to_list" + ], + "python": "hmath.matrix.to_list", + "specializations": [ + "same standard coefficients and Bool/String structural elements as Matrix Value" + ] + }, + { + "symbol": "HMath.Matrix.shape", + "c": [ + "hmath_matrix_value_shape" + ], + "python": "hmath.matrix.shape", + "specializations": [ + "same standard coefficients and Bool/String structural elements as Matrix Value" + ] + } + ] +} diff --git a/bindings/schema/numeric-object-specializations.json b/bindings/schema/numeric-object-specializations.json new file mode 100644 index 0000000..b48bd1c --- /dev/null +++ b/bindings/schema/numeric-object-specializations.json @@ -0,0 +1,203 @@ +{ + "schema": 1, + "additional_specializations": [ + { + "symbol": "HMath.Basic.clamp", + "additional_c": "hmath_basic_clamp_value", + "python": "hmath.basic.clamp", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Basic.lerp", + "additional_c": "hmath_basic_lerp_value", + "python": "hmath.basic.lerp", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.add", + "additional_c": "hmath_scalar_add_value", + "python": "hmath.scalar.add", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.subtractScalar", + "additional_c": "hmath_scalar_subtract_scalar_value", + "python": "hmath.scalar.subtract_scalar", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.multiply", + "additional_c": "hmath_scalar_multiply_value", + "python": "hmath.scalar.multiply", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.minimumScalar", + "additional_c": "hmath_scalar_minimum_scalar_value", + "python": "hmath.scalar.minimum_scalar", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.maximumScalar", + "additional_c": "hmath_scalar_maximum_scalar_value", + "python": "hmath.scalar.maximum_scalar", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.absolute", + "additional_c": "hmath_scalar_absolute_value", + "python": "hmath.scalar.absolute", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.sign", + "additional_c": "hmath_scalar_sign_value", + "python": "hmath.scalar.sign", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.positiveModulo", + "additional_c": "hmath_scalar_positive_modulo_value", + "python": "hmath.scalar.positive_modulo", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.cumulativeSum", + "additional_c": "hmath_scalar_cumulative_sum_value", + "python": "hmath.scalar.cumulative_sum", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.cumulativeProduct", + "additional_c": "hmath_scalar_cumulative_product_value", + "python": "hmath.scalar.cumulative_product", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.prefixSum", + "additional_c": "hmath_scalar_prefix_sum_value", + "python": "hmath.scalar.prefix_sum", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Statistics.mean", + "additional_c": "hmath_statistics_mean_value", + "python": "hmath.statistics.mean", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Statistics.variance", + "additional_c": "hmath_statistics_variance_value", + "python": "hmath.statistics.variance", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Statistics.standardDeviation", + "additional_c": "hmath_statistics_standard_deviation_value", + "python": "hmath.statistics.standard_deviation", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Statistics.median", + "additional_c": "hmath_statistics_median_value", + "python": "hmath.statistics.median", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.dot", + "additional_c": "hmath_linear_dot_value", + "python": "hmath.linear.dot", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.dotChecked", + "additional_c": "hmath_linear_dot_checked_value", + "python": "hmath.linear.dot_checked", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.magnitude", + "additional_c": "hmath_linear_magnitude_value", + "python": "hmath.linear.magnitude", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.normalize", + "additional_c": "hmath_linear_normalize_value", + "python": "hmath.linear.normalize", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.add", + "additional_c": "hmath_linear_add_value", + "python": "hmath.linear.add", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.addChecked", + "additional_c": "hmath_linear_add_checked_value", + "python": "hmath.linear.add_checked", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.subtractChecked", + "additional_c": "hmath_linear_subtract_checked_value", + "python": "hmath.linear.subtract_checked", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Linear.scale", + "additional_c": "hmath_linear_scale_value", + "python": "hmath.linear.scale", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.saturatingAdd", + "additional_c": "hmath_scalar_saturating_add_value", + "python": "hmath.scalar.saturating_add", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.saturatingSubtract", + "additional_c": "hmath_scalar_saturating_subtract_value", + "python": "hmath.scalar.saturating_subtract", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.saturatingMultiply", + "additional_c": "hmath_scalar_saturating_multiply_value", + "python": "hmath.scalar.saturating_multiply", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.checkedAdd", + "additional_c": "hmath_scalar_checked_add_value", + "python": "hmath.scalar.checked_add", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.checkedSubtract", + "additional_c": "hmath_scalar_checked_subtract_value", + "python": "hmath.scalar.checked_subtract", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Scalar.checkedMultiply", + "additional_c": "hmath_scalar_checked_multiply_value", + "python": "hmath.scalar.checked_multiply", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Geometry.Primitives.hammingDistance", + "additional_c": "hmath_geometry_primitives_hamming_distance_value", + "python": "hmath.geometry_primitives.hamming_distance", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + }, + { + "symbol": "HMath.Geometry.Primitives.jaccardDistance", + "additional_c": "hmath_geometry_primitives_jaccard_distance_value", + "python": "hmath.geometry_primitives.jaccard_distance", + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries" + } + ] +} diff --git a/bindings/schema/numeric-object-symbols.txt b/bindings/schema/numeric-object-symbols.txt new file mode 100644 index 0000000..fe29eb1 --- /dev/null +++ b/bindings/schema/numeric-object-symbols.txt @@ -0,0 +1,33 @@ +hmath_basic_clamp_value +hmath_basic_lerp_value +hmath_scalar_add_value +hmath_scalar_subtract_scalar_value +hmath_scalar_multiply_value +hmath_scalar_minimum_scalar_value +hmath_scalar_maximum_scalar_value +hmath_scalar_absolute_value +hmath_scalar_sign_value +hmath_scalar_positive_modulo_value +hmath_scalar_cumulative_sum_value +hmath_scalar_cumulative_product_value +hmath_scalar_prefix_sum_value +hmath_statistics_mean_value +hmath_statistics_variance_value +hmath_statistics_standard_deviation_value +hmath_statistics_median_value +hmath_linear_dot_value +hmath_linear_dot_checked_value +hmath_linear_magnitude_value +hmath_linear_normalize_value +hmath_linear_add_value +hmath_linear_add_checked_value +hmath_linear_subtract_checked_value +hmath_linear_scale_value +hmath_scalar_saturating_add_value +hmath_scalar_saturating_subtract_value +hmath_scalar_saturating_multiply_value +hmath_scalar_checked_add_value +hmath_scalar_checked_subtract_value +hmath_scalar_checked_multiply_value +hmath_geometry_primitives_hamming_distance_value +hmath_geometry_primitives_jaccard_distance_value diff --git a/bindings/schema/numeric-symbols.txt b/bindings/schema/numeric-symbols.txt new file mode 100644 index 0000000..7b4dea3 --- /dev/null +++ b/bindings/schema/numeric-symbols.txt @@ -0,0 +1,921 @@ +hmath_numeric_string_free +hmath_numeric_buffer_free +hmath_basic_factorial +hmath_basic_fibonacci +hmath_basic_is_prime +hmath_basic_clamp_f32 +hmath_basic_clamp_f64 +hmath_basic_clamp_rational +hmath_basic_clamp_integer +hmath_basic_clamp_i8 +hmath_basic_clamp_i16 +hmath_basic_clamp_i32 +hmath_basic_clamp_i64 +hmath_basic_clamp_u8 +hmath_basic_clamp_u16 +hmath_basic_clamp_u32 +hmath_basic_clamp_u64 +hmath_basic_clamp_int +hmath_basic_clamp_word +hmath_basic_lerp_f32 +hmath_basic_lerp_f64 +hmath_basic_lerp_rational +hmath_basic_lerp_c64 +hmath_basic_lerp_c128 +hmath_scalar_add_f32 +hmath_scalar_add_f64 +hmath_scalar_add_rational +hmath_scalar_add_integer +hmath_scalar_add_i8 +hmath_scalar_add_i16 +hmath_scalar_add_i32 +hmath_scalar_add_i64 +hmath_scalar_add_u8 +hmath_scalar_add_u16 +hmath_scalar_add_u32 +hmath_scalar_add_u64 +hmath_scalar_add_int +hmath_scalar_add_word +hmath_scalar_add_c64 +hmath_scalar_add_c128 +hmath_scalar_subtract_scalar_f32 +hmath_scalar_subtract_scalar_f64 +hmath_scalar_subtract_scalar_rational +hmath_scalar_subtract_scalar_integer +hmath_scalar_subtract_scalar_i8 +hmath_scalar_subtract_scalar_i16 +hmath_scalar_subtract_scalar_i32 +hmath_scalar_subtract_scalar_i64 +hmath_scalar_subtract_scalar_u8 +hmath_scalar_subtract_scalar_u16 +hmath_scalar_subtract_scalar_u32 +hmath_scalar_subtract_scalar_u64 +hmath_scalar_subtract_scalar_int +hmath_scalar_subtract_scalar_word +hmath_scalar_subtract_scalar_c64 +hmath_scalar_subtract_scalar_c128 +hmath_scalar_multiply_f32 +hmath_scalar_multiply_f64 +hmath_scalar_multiply_rational +hmath_scalar_multiply_integer +hmath_scalar_multiply_i8 +hmath_scalar_multiply_i16 +hmath_scalar_multiply_i32 +hmath_scalar_multiply_i64 +hmath_scalar_multiply_u8 +hmath_scalar_multiply_u16 +hmath_scalar_multiply_u32 +hmath_scalar_multiply_u64 +hmath_scalar_multiply_int +hmath_scalar_multiply_word +hmath_scalar_multiply_c64 +hmath_scalar_multiply_c128 +hmath_scalar_minimum_scalar_f32 +hmath_scalar_minimum_scalar_f64 +hmath_scalar_minimum_scalar_rational +hmath_scalar_minimum_scalar_integer +hmath_scalar_minimum_scalar_i8 +hmath_scalar_minimum_scalar_i16 +hmath_scalar_minimum_scalar_i32 +hmath_scalar_minimum_scalar_i64 +hmath_scalar_minimum_scalar_u8 +hmath_scalar_minimum_scalar_u16 +hmath_scalar_minimum_scalar_u32 +hmath_scalar_minimum_scalar_u64 +hmath_scalar_minimum_scalar_int +hmath_scalar_minimum_scalar_word +hmath_scalar_maximum_scalar_f32 +hmath_scalar_maximum_scalar_f64 +hmath_scalar_maximum_scalar_rational +hmath_scalar_maximum_scalar_integer +hmath_scalar_maximum_scalar_i8 +hmath_scalar_maximum_scalar_i16 +hmath_scalar_maximum_scalar_i32 +hmath_scalar_maximum_scalar_i64 +hmath_scalar_maximum_scalar_u8 +hmath_scalar_maximum_scalar_u16 +hmath_scalar_maximum_scalar_u32 +hmath_scalar_maximum_scalar_u64 +hmath_scalar_maximum_scalar_int +hmath_scalar_maximum_scalar_word +hmath_scalar_absolute_f32 +hmath_scalar_absolute_f64 +hmath_scalar_absolute_rational +hmath_scalar_absolute_integer +hmath_scalar_absolute_i8 +hmath_scalar_absolute_i16 +hmath_scalar_absolute_i32 +hmath_scalar_absolute_i64 +hmath_scalar_absolute_u8 +hmath_scalar_absolute_u16 +hmath_scalar_absolute_u32 +hmath_scalar_absolute_u64 +hmath_scalar_absolute_int +hmath_scalar_absolute_word +hmath_scalar_absolute_c64 +hmath_scalar_absolute_c128 +hmath_scalar_sign_f32 +hmath_scalar_sign_f64 +hmath_scalar_sign_rational +hmath_scalar_sign_integer +hmath_scalar_sign_i8 +hmath_scalar_sign_i16 +hmath_scalar_sign_i32 +hmath_scalar_sign_i64 +hmath_scalar_sign_u8 +hmath_scalar_sign_u16 +hmath_scalar_sign_u32 +hmath_scalar_sign_u64 +hmath_scalar_sign_int +hmath_scalar_sign_word +hmath_scalar_sign_c64 +hmath_scalar_sign_c128 +hmath_scalar_divide_f32 +hmath_scalar_divide_f64 +hmath_scalar_power_f32 +hmath_scalar_power_f64 +hmath_scalar_hypot_f32 +hmath_scalar_hypot_f64 +hmath_scalar_clamp_checked_f32 +hmath_scalar_clamp_checked_f64 +hmath_scalar_lerp_checked_f32 +hmath_scalar_lerp_checked_f64 +hmath_scalar_inverse_lerp_f32 +hmath_scalar_inverse_lerp_f64 +hmath_scalar_smoothstep_f32 +hmath_scalar_smoothstep_f64 +hmath_scalar_smootherstep_f32 +hmath_scalar_smootherstep_f64 +hmath_scalar_remap_f32 +hmath_scalar_remap_f64 +hmath_scalar_step_f32 +hmath_scalar_step_f64 +hmath_scalar_sqrt_checked_f32 +hmath_scalar_sqrt_checked_f64 +hmath_scalar_cube_root_f32 +hmath_scalar_cube_root_f64 +hmath_scalar_reciprocal_sqrt_f32 +hmath_scalar_reciprocal_sqrt_f64 +hmath_scalar_exp_checked_f32 +hmath_scalar_exp_checked_f64 +hmath_scalar_log_checked_f32 +hmath_scalar_log_checked_f64 +hmath_scalar_expm1_f32 +hmath_scalar_expm1_f64 +hmath_scalar_log1p_f32 +hmath_scalar_log1p_f64 +hmath_scalar_integer_power_f32 +hmath_scalar_integer_power_f64 +hmath_scalar_nth_root_f32 +hmath_scalar_nth_root_f64 +hmath_scalar_round_digits_f32 +hmath_scalar_round_digits_f64 +hmath_scalar_absolute_error_f32 +hmath_scalar_absolute_error_f64 +hmath_scalar_relative_error_f32 +hmath_scalar_relative_error_f64 +hmath_scalar_fused_multiply_add_f32 +hmath_scalar_fused_multiply_add_f64 +hmath_scalar_checked_float_multiply_f32 +hmath_scalar_checked_float_multiply_f64 +hmath_scalar_floor_checked_f32 +hmath_scalar_floor_checked_f64 +hmath_scalar_ceil_checked_f32 +hmath_scalar_ceil_checked_f64 +hmath_scalar_round_checked_f32 +hmath_scalar_round_checked_f64 +hmath_scalar_truncate_checked_f32 +hmath_scalar_truncate_checked_f64 +hmath_scalar_bankers_round_f32 +hmath_scalar_bankers_round_f64 +hmath_scalar_integer_fraction_f32 +hmath_scalar_integer_fraction_f64 +hmath_scalar_quotient_remainder +hmath_scalar_euclidean_division +hmath_scalar_positive_modulo_integer +hmath_scalar_positive_modulo_i8 +hmath_scalar_positive_modulo_i16 +hmath_scalar_positive_modulo_i32 +hmath_scalar_positive_modulo_i64 +hmath_scalar_positive_modulo_u8 +hmath_scalar_positive_modulo_u16 +hmath_scalar_positive_modulo_u32 +hmath_scalar_positive_modulo_u64 +hmath_scalar_positive_modulo_int +hmath_scalar_positive_modulo_word +hmath_scalar_positive_modulo +hmath_scalar_modular_power +hmath_scalar_factorial_checked +hmath_scalar_double_factorial +hmath_scalar_fibonacci_checked +hmath_scalar_lucas +hmath_scalar_catalan +hmath_scalar_rising_factorial +hmath_scalar_falling_factorial +hmath_scalar_permutations +hmath_scalar_combinations +hmath_scalar_bernoulli +hmath_scalar_harmonic +hmath_scalar_cumulative_sum_f32 +hmath_scalar_cumulative_sum_f64 +hmath_scalar_cumulative_sum_rational +hmath_scalar_cumulative_sum_integer +hmath_scalar_cumulative_sum_i8 +hmath_scalar_cumulative_sum_i16 +hmath_scalar_cumulative_sum_i32 +hmath_scalar_cumulative_sum_i64 +hmath_scalar_cumulative_sum_u8 +hmath_scalar_cumulative_sum_u16 +hmath_scalar_cumulative_sum_u32 +hmath_scalar_cumulative_sum_u64 +hmath_scalar_cumulative_sum_int +hmath_scalar_cumulative_sum_word +hmath_scalar_cumulative_sum_c64 +hmath_scalar_cumulative_sum_c128 +hmath_scalar_cumulative_product_f32 +hmath_scalar_cumulative_product_f64 +hmath_scalar_cumulative_product_rational +hmath_scalar_cumulative_product_integer +hmath_scalar_cumulative_product_i8 +hmath_scalar_cumulative_product_i16 +hmath_scalar_cumulative_product_i32 +hmath_scalar_cumulative_product_i64 +hmath_scalar_cumulative_product_u8 +hmath_scalar_cumulative_product_u16 +hmath_scalar_cumulative_product_u32 +hmath_scalar_cumulative_product_u64 +hmath_scalar_cumulative_product_int +hmath_scalar_cumulative_product_word +hmath_scalar_cumulative_product_c64 +hmath_scalar_cumulative_product_c128 +hmath_scalar_prefix_sum_f32 +hmath_scalar_prefix_sum_f64 +hmath_scalar_prefix_sum_rational +hmath_scalar_prefix_sum_integer +hmath_scalar_prefix_sum_i8 +hmath_scalar_prefix_sum_i16 +hmath_scalar_prefix_sum_i32 +hmath_scalar_prefix_sum_i64 +hmath_scalar_prefix_sum_u8 +hmath_scalar_prefix_sum_u16 +hmath_scalar_prefix_sum_u32 +hmath_scalar_prefix_sum_u64 +hmath_scalar_prefix_sum_int +hmath_scalar_prefix_sum_word +hmath_scalar_prefix_sum_c64 +hmath_scalar_prefix_sum_c128 +hmath_trigonometry_sin_checked_f32 +hmath_trigonometry_sin_checked_f64 +hmath_trigonometry_cos_checked_f32 +hmath_trigonometry_cos_checked_f64 +hmath_trigonometry_tan_checked_f32 +hmath_trigonometry_tan_checked_f64 +hmath_trigonometry_asin_checked_f32 +hmath_trigonometry_asin_checked_f64 +hmath_trigonometry_acos_checked_f32 +hmath_trigonometry_acos_checked_f64 +hmath_trigonometry_atan_checked_f32 +hmath_trigonometry_atan_checked_f64 +hmath_trigonometry_sec_f32 +hmath_trigonometry_sec_f64 +hmath_trigonometry_csc_f32 +hmath_trigonometry_csc_f64 +hmath_trigonometry_cot_f32 +hmath_trigonometry_cot_f64 +hmath_trigonometry_asec_f32 +hmath_trigonometry_asec_f64 +hmath_trigonometry_acsc_f32 +hmath_trigonometry_acsc_f64 +hmath_trigonometry_acot_f32 +hmath_trigonometry_acot_f64 +hmath_trigonometry_sinh_checked_f32 +hmath_trigonometry_sinh_checked_f64 +hmath_trigonometry_cosh_checked_f32 +hmath_trigonometry_cosh_checked_f64 +hmath_trigonometry_tanh_checked_f32 +hmath_trigonometry_tanh_checked_f64 +hmath_trigonometry_asinh_checked_f32 +hmath_trigonometry_asinh_checked_f64 +hmath_trigonometry_acosh_checked_f32 +hmath_trigonometry_acosh_checked_f64 +hmath_trigonometry_atanh_checked_f32 +hmath_trigonometry_atanh_checked_f64 +hmath_trigonometry_sech_f32 +hmath_trigonometry_sech_f64 +hmath_trigonometry_csch_f32 +hmath_trigonometry_csch_f64 +hmath_trigonometry_coth_f32 +hmath_trigonometry_coth_f64 +hmath_trigonometry_asech_f32 +hmath_trigonometry_asech_f64 +hmath_trigonometry_acsch_f32 +hmath_trigonometry_acsch_f64 +hmath_trigonometry_acoth_f32 +hmath_trigonometry_acoth_f64 +hmath_trigonometry_normalize_angle_f32 +hmath_trigonometry_normalize_angle_f64 +hmath_trigonometry_normalize_signed_angle_f32 +hmath_trigonometry_normalize_signed_angle_f64 +hmath_trigonometry_versine_f32 +hmath_trigonometry_versine_f64 +hmath_trigonometry_haversine_f32 +hmath_trigonometry_haversine_f64 +hmath_trigonometry_sinc_f32 +hmath_trigonometry_sinc_f64 +hmath_trigonometry_cosc_f32 +hmath_trigonometry_cosc_f64 +hmath_trigonometry_atan2_checked_f32 +hmath_trigonometry_atan2_checked_f64 +hmath_trigonometry_sincos_f32 +hmath_trigonometry_sincos_f64 +hmath_trigonometry_wrap_f32 +hmath_trigonometry_wrap_f64 +hmath_trigonometry_angle_difference_f32 +hmath_trigonometry_angle_difference_f64 +hmath_trigonometry_great_circle_angle_f32 +hmath_trigonometry_great_circle_angle_f64 +hmath_trigonometry_great_circle_distance_f32 +hmath_trigonometry_great_circle_distance_f64 +hmath_trigonometry_spherical_side_f32 +hmath_trigonometry_spherical_side_f64 +hmath_trigonometry_spherical_angles_f32 +hmath_trigonometry_spherical_angles_f64 +hmath_trigonometry_spherical_excess_f32 +hmath_trigonometry_spherical_excess_f64 +hmath_trigonometry_complex_sin_f32 +hmath_trigonometry_complex_sin_f64 +hmath_trigonometry_complex_cos_f32 +hmath_trigonometry_complex_cos_f64 +hmath_trigonometry_complex_tan_f32 +hmath_trigonometry_complex_tan_f64 +hmath_trigonometry_complex_asin_f32 +hmath_trigonometry_complex_asin_f64 +hmath_trigonometry_complex_acos_f32 +hmath_trigonometry_complex_acos_f64 +hmath_trigonometry_complex_atan_f32 +hmath_trigonometry_complex_atan_f64 +hmath_trigonometry_complex_sinh_f32 +hmath_trigonometry_complex_sinh_f64 +hmath_trigonometry_complex_cosh_f32 +hmath_trigonometry_complex_cosh_f64 +hmath_trigonometry_complex_tanh_f32 +hmath_trigonometry_complex_tanh_f64 +hmath_trigonometry_complex_asinh_f32 +hmath_trigonometry_complex_asinh_f64 +hmath_trigonometry_complex_acosh_f32 +hmath_trigonometry_complex_acosh_f64 +hmath_trigonometry_complex_atanh_f32 +hmath_trigonometry_complex_atanh_f64 +hmath_trigonometry_periodic_sawtooth_f32 +hmath_trigonometry_periodic_sawtooth_f64 +hmath_trigonometry_periodic_triangle_f32 +hmath_trigonometry_periodic_triangle_f64 +hmath_trigonometry_periodic_square_f32 +hmath_trigonometry_periodic_square_f64 +hmath_statistics_mean_f32 +hmath_statistics_mean_f64 +hmath_statistics_mean_rational +hmath_statistics_mean_c64 +hmath_statistics_mean_c128 +hmath_statistics_variance_f32 +hmath_statistics_variance_f64 +hmath_statistics_variance_rational +hmath_statistics_variance_c64 +hmath_statistics_variance_c128 +hmath_statistics_standard_deviation_f32 +hmath_statistics_standard_deviation_f64 +hmath_statistics_standard_deviation_c64 +hmath_statistics_standard_deviation_c128 +hmath_statistics_median_f32 +hmath_statistics_median_f64 +hmath_statistics_median_rational +hmath_constants_pi_constant_f32 +hmath_constants_pi_constant_f64 +hmath_constants_e_constant_f32 +hmath_constants_e_constant_f64 +hmath_constants_tau_f32 +hmath_constants_tau_f64 +hmath_constants_golden_ratio_f32 +hmath_constants_golden_ratio_f64 +hmath_constants_euler_mascheroni_f32 +hmath_constants_euler_mascheroni_f64 +hmath_constants_catalan_constant_f32 +hmath_constants_catalan_constant_f64 +hmath_constants_apery_constant_f32 +hmath_constants_apery_constant_f64 +hmath_constants_sqrt2_f32 +hmath_constants_sqrt2_f64 +hmath_constants_sqrt3_f32 +hmath_constants_sqrt3_f64 +hmath_constants_ln2_f32 +hmath_constants_ln2_f64 +hmath_constants_ln10_f32 +hmath_constants_ln10_f64 +hmath_constants_infinity_f32 +hmath_constants_infinity_f64 +hmath_constants_nan_f32 +hmath_constants_nan_f64 +hmath_scalar_multinomial +hmath_numbertheory_gcd_integer +hmath_numbertheory_lcm_integer +hmath_numbertheory_extended_g_c_d +hmath_numbertheory_bezout +hmath_numbertheory_mod_pow +hmath_numbertheory_mod_inverse +hmath_numbertheory_integer_square_root +hmath_numbertheory_is_prime_exact +hmath_numbertheory_next_prime +hmath_numbertheory_miller_rabin +hmath_numbertheory_baillie_p_s_w +hmath_numbertheory_sieve_eratosthenes +hmath_numbertheory_sieve_atkin +hmath_numbertheory_segmented_sieve +hmath_numbertheory_pollard_rho +hmath_numbertheory_pollard_p_minus_one +hmath_numbertheory_fermat_factor +hmath_numbertheory_divisors +hmath_numbertheory_divisor_sum +hmath_numbertheory_divisor_count +hmath_numbertheory_euler_totient +hmath_numbertheory_carmichael +hmath_numbertheory_mobius +hmath_numbertheory_liouville +hmath_numbertheory_multiplicative_order +hmath_numbertheory_primitive_root +hmath_numbertheory_discrete_log +hmath_numbertheory_legendre_symbol +hmath_numbertheory_jacobi_symbol +hmath_numbertheory_kronecker_symbol +hmath_numbertheory_tonelli_shanks +hmath_numbertheory_continued_fraction +hmath_numbertheory_from_continued_fraction +hmath_numbertheory_convergents +hmath_numbertheory_farey +hmath_numbertheory_pell_fundamental +hmath_numbertheory_is_perfect_number +hmath_numbertheory_are_amicable +hmath_numbertheory_partition_count +hmath_numbertheory_fibonacci_fast +hmath_combinatorics_permutations_count +hmath_combinatorics_combinations_count +hmath_combinatorics_multinomial +hmath_combinatorics_rank_permutation +hmath_combinatorics_unrank_permutation +hmath_combinatorics_rank_combination +hmath_combinatorics_unrank_combination +hmath_combinatorics_derangement_count +hmath_combinatorics_stirling_first +hmath_combinatorics_stirling_second +hmath_combinatorics_bell_number +hmath_combinatorics_eulerian_number +hmath_combinatorics_lah_number +hmath_combinatorics_catalan_number +hmath_combinatorics_fibonacci +hmath_combinatorics_lucas +hmath_combinatorics_inclusion_exclusion +hmath_combinatorics_multiset_count_f32 +hmath_combinatorics_multiset_count_f64 +hmath_combinatorics_linear_recurrence +hmath_combinatorics_convolve_series +hmath_combinatorics_finite_sum_f32 +hmath_combinatorics_finite_sum_f64 +hmath_linear_dot_f32 +hmath_linear_dot_f64 +hmath_linear_dot_rational +hmath_linear_dot_integer +hmath_linear_dot_i8 +hmath_linear_dot_i16 +hmath_linear_dot_i32 +hmath_linear_dot_i64 +hmath_linear_dot_u8 +hmath_linear_dot_u16 +hmath_linear_dot_u32 +hmath_linear_dot_u64 +hmath_linear_dot_int +hmath_linear_dot_word +hmath_linear_dot_c64 +hmath_linear_dot_c128 +hmath_linear_dot_checked_f32 +hmath_linear_dot_checked_f64 +hmath_linear_dot_checked_rational +hmath_linear_dot_checked_integer +hmath_linear_dot_checked_i8 +hmath_linear_dot_checked_i16 +hmath_linear_dot_checked_i32 +hmath_linear_dot_checked_i64 +hmath_linear_dot_checked_u8 +hmath_linear_dot_checked_u16 +hmath_linear_dot_checked_u32 +hmath_linear_dot_checked_u64 +hmath_linear_dot_checked_int +hmath_linear_dot_checked_word +hmath_linear_dot_checked_c64 +hmath_linear_dot_checked_c128 +hmath_linear_magnitude_f32 +hmath_linear_magnitude_f64 +hmath_linear_magnitude_c64 +hmath_linear_magnitude_c128 +hmath_linear_normalize_f32 +hmath_linear_normalize_f64 +hmath_linear_normalize_c64 +hmath_linear_normalize_c128 +hmath_linear_add_f32 +hmath_linear_add_f64 +hmath_linear_add_rational +hmath_linear_add_integer +hmath_linear_add_i8 +hmath_linear_add_i16 +hmath_linear_add_i32 +hmath_linear_add_i64 +hmath_linear_add_u8 +hmath_linear_add_u16 +hmath_linear_add_u32 +hmath_linear_add_u64 +hmath_linear_add_int +hmath_linear_add_word +hmath_linear_add_c64 +hmath_linear_add_c128 +hmath_linear_add_checked_f32 +hmath_linear_add_checked_f64 +hmath_linear_add_checked_rational +hmath_linear_add_checked_integer +hmath_linear_add_checked_i8 +hmath_linear_add_checked_i16 +hmath_linear_add_checked_i32 +hmath_linear_add_checked_i64 +hmath_linear_add_checked_u8 +hmath_linear_add_checked_u16 +hmath_linear_add_checked_u32 +hmath_linear_add_checked_u64 +hmath_linear_add_checked_int +hmath_linear_add_checked_word +hmath_linear_add_checked_c64 +hmath_linear_add_checked_c128 +hmath_linear_subtract_checked_f32 +hmath_linear_subtract_checked_f64 +hmath_linear_subtract_checked_rational +hmath_linear_subtract_checked_integer +hmath_linear_subtract_checked_i8 +hmath_linear_subtract_checked_i16 +hmath_linear_subtract_checked_i32 +hmath_linear_subtract_checked_i64 +hmath_linear_subtract_checked_u8 +hmath_linear_subtract_checked_u16 +hmath_linear_subtract_checked_u32 +hmath_linear_subtract_checked_u64 +hmath_linear_subtract_checked_int +hmath_linear_subtract_checked_word +hmath_linear_subtract_checked_c64 +hmath_linear_subtract_checked_c128 +hmath_linear_scale_f32 +hmath_linear_scale_f64 +hmath_linear_scale_rational +hmath_linear_scale_integer +hmath_linear_scale_i8 +hmath_linear_scale_i16 +hmath_linear_scale_i32 +hmath_linear_scale_i64 +hmath_linear_scale_u8 +hmath_linear_scale_u16 +hmath_linear_scale_u32 +hmath_linear_scale_u64 +hmath_linear_scale_int +hmath_linear_scale_word +hmath_linear_scale_c64 +hmath_linear_scale_c128 +hmath_special_gamma_f64 +hmath_special_log_gamma_f64 +hmath_special_log_beta_f64 +hmath_special_beta_f64 +hmath_special_gamma_p_f64 +hmath_special_gamma_q_f64 +hmath_special_incomplete_gamma_f64 +hmath_special_beta_i_f64 +hmath_special_incomplete_beta_f64 +hmath_special_digamma_f64 +hmath_special_trigamma_f64 +hmath_special_polygamma_f64 +hmath_special_erf_f64 +hmath_special_erfc_f64 +hmath_special_erfcx_f64 +hmath_special_normal_c_d_f_f64 +hmath_special_normal_quantile_f64 +hmath_special_inverse_erf_f64 +hmath_special_dawson_f64 +hmath_special_exponential_integral_f64 +hmath_special_logarithmic_integral_f64 +hmath_special_sine_integral_f64 +hmath_special_cosine_integral_f64 +hmath_special_fresnel_f64 +hmath_special_elliptic_f_f64 +hmath_special_elliptic_e_f64 +hmath_special_elliptic_pi_f64 +hmath_special_jacobi_elliptic_f64 +hmath_special_bessel_j_f64 +hmath_special_bessel_y_f64 +hmath_special_bessel_i_f64 +hmath_special_scaled_bessel_i_f64 +hmath_special_bessel_k_f64 +hmath_special_scaled_bessel_k_f64 +hmath_special_spherical_bessel_j_f64 +hmath_special_spherical_bessel_y_f64 +hmath_special_airy_f64 +hmath_special_struve_f64 +hmath_special_hypergeometric_f64 +hmath_special_hypergeometric1_f1_f64 +hmath_special_hypergeometric2_f1_f64 +hmath_special_legendre_f64 +hmath_special_associated_legendre_f64 +hmath_special_hurwitz_zeta_f64 +hmath_special_riemann_zeta_f64 +hmath_special_polylogarithm_f64 +hmath_special_dilogarithm_f64 +hmath_special_lambert_w_f64 +hmath_special_debye_f64 +hmath_special_clausen_f64 +hmath_special_fermi_dirac_f64 +hmath_special_bose_einstein_f64 +hmath_special_coulomb_wave_f64 +hmath_special_gegenbauer_f64 +hmath_special_parabolic_cylinder_f64 +hmath_special_mathieu_f64 +hmath_special_bernoulli_polynomial_f64 +hmath_special_euler_polynomial_f64 +hmath_special_wigner3j_f64 +hmath_special_wigner6j_f64 +hmath_special_wigner9j_f64 +hmath_special_clebsch_gordan_f64 +hmath_complex_to_polar_f64 +hmath_probability_gamma_poisson_update_f64 +hmath_probability_normal_normal_update_f64 +hmath_probability_conditional_probability_f64 +hmath_probability_bayes_f64 +hmath_probability_multinomial_p_m_f_f64 +hmath_probability_dirichlet_density_f64 +hmath_complex_complex_f64 +hmath_complex_reciprocal_f64 +hmath_complex_add_f64 +hmath_complex_subtract_complex_f64 +hmath_complex_multiply_f64 +hmath_complex_divide_f64 +hmath_complex_power_f64 +hmath_complex_from_polar_f64 +hmath_complex_rotate_f64 +hmath_special_hankel_f64 +hmath_special_spherical_harmonic_f64 +hmath_special_complex1_f1_f64 +hmath_api_algebra_inner_product_f32 +hmath_api_algebra_inner_product_f64 +hmath_algorithms_lower_bound_f32 +hmath_algorithms_lower_bound_f64 +hmath_algorithms_upper_bound_f32 +hmath_algorithms_upper_bound_f64 +hmath_algorithms_quickselect_f32 +hmath_algorithms_quickselect_f64 +hmath_algorithms_introselect_f32 +hmath_algorithms_introselect_f64 +hmath_algorithms_partial_sort_f32 +hmath_algorithms_partial_sort_f64 +hmath_algorithms_merge_sort_f32 +hmath_algorithms_merge_sort_f64 +hmath_algorithms_quicksort_f32 +hmath_algorithms_quicksort_f64 +hmath_algorithms_heapsort_f32 +hmath_algorithms_heapsort_f64 +hmath_algorithms_introsort_f32 +hmath_algorithms_introsort_f64 +hmath_algorithms_counting_sort +hmath_algorithms_radix_sort +hmath_algorithms_bucket_sort_f64 +hmath_algorithms_argsort_f32 +hmath_algorithms_argsort_f64 +hmath_algorithms_top_k_f32 +hmath_algorithms_top_k_f64 +hmath_algorithms_quantile_select_f64 +hmath_algorithms_deduplicate_f32 +hmath_algorithms_deduplicate_f64 +hmath_algorithms_prefix_sums_f32 +hmath_algorithms_prefix_sums_f64 +hmath_algorithms_suffix_sums_f32 +hmath_algorithms_suffix_sums_f64 +hmath_algorithms_difference_array_f32 +hmath_algorithms_difference_array_f64 +hmath_algorithms_apply_differences_f32 +hmath_algorithms_apply_differences_f64 +hmath_algorithms_binary_lift +hmath_algorithms_polynomial_hash +hmath_algorithms_rolling_hashes +hmath_datastructure_monotonic_minima_f32 +hmath_datastructure_monotonic_minima_f64 +hmath_deeplearning_core_log_softmax_f64 +hmath_deeplearning_core_softmax_f64 +hmath_deeplearning_core_sparsemax_f64 +hmath_deeplearning_core_gated_linear_unit_f64 +hmath_deeplearning_core_categorical_cross_entropy_logits_f64 +hmath_deeplearning_core_regularization_f64 +hmath_deeplearning_core_contrastive_loss_f64 +hmath_deeplearning_core_triplet_loss_f64 +hmath_deeplearning_core_focal_loss_f64 +hmath_deeplearning_core_dice_loss_f64 +hmath_deeplearning_core_iou_loss_f64 +hmath_deeplearning_metrics_perplexity_f64 +hmath_deeplearning_metrics_margin_ranking_loss_f64 +hmath_deeplearning_precision_gradient_norm_f64 +hmath_deeplearning_precision_clip_gradients_f64 +hmath_discrete_set_union_f32 +hmath_discrete_set_union_f64 +hmath_discrete_set_intersection_f32 +hmath_discrete_set_intersection_f64 +hmath_discrete_set_difference_f32 +hmath_discrete_set_difference_f64 +hmath_discrete_symmetric_difference_f32 +hmath_discrete_symmetric_difference_f64 +hmath_fourier_frequencies_f64 +hmath_fourier_fft_shift_f64 +hmath_fourier_ifft_shift_f64 +hmath_fourier_hartley_f64 +hmath_fourier_periodogram_f64 +hmath_fourier_welch_f64 +hmath_fourier_cepstrum_f64 +hmath_fourier_hilbert_f64 +hmath_geometry_primitives_hamming_distance_f32 +hmath_geometry_primitives_hamming_distance_f64 +hmath_geometry_primitives_jaccard_distance_f64 +hmath_graph_core_finite_f64 +hmath_image_color_srgb_to_linear_f64 +hmath_image_color_linear_to_srgb_f64 +hmath_interpolation_evaluate_chebyshev_f64 +hmath_numeric_next_after_f32 +hmath_numeric_next_after_f64 +hmath_numeric_ldexp_f32 +hmath_numeric_ldexp_f64 +hmath_numeric_ulp_distance_f64 +hmath_numeric_within_u_l_ps_f64 +hmath_numeric_kahan_sum_f32 +hmath_numeric_kahan_sum_f64 +hmath_numeric_neumaier_sum_f32 +hmath_numeric_neumaier_sum_f64 +hmath_numeric_pairwise_sum_f32 +hmath_numeric_pairwise_sum_f64 +hmath_numeric_logsumexp_f32 +hmath_numeric_logsumexp_f64 +hmath_numeric_sum_error_bound_f32 +hmath_numeric_sum_error_bound_f64 +hmath_optimization_common_dot_f64 +hmath_optimization_common_norm_f64 +hmath_optimization_common_add_f64 +hmath_optimization_common_sub_f64 +hmath_optimization_common_scale_f64 +hmath_random_importance_f64 +hmath_random_halton_f64 +hmath_random_sobol_f64 +hmath_random_faure_f64 +hmath_signal_convolution_f64 +hmath_signal_circular_convolution_f64 +hmath_signal_correlation_f64 +hmath_signal_autocorrelation_f64 +hmath_signal_overlap_add_f64 +hmath_signal_overlap_save_f64 +hmath_signal_moving_average_f64 +hmath_signal_median_filter_f64 +hmath_signal_gaussian_filter_f64 +hmath_signal_savitzky_golay_f64 +hmath_signal_downsample_f64 +hmath_signal_upsample_f64 +hmath_signal_resample_polyphase_f64 +hmath_signal_resample_f64 +hmath_signal_anti_alias_f64 +hmath_signal_zero_crossings_f64 +hmath_signal_envelope_f64 +hmath_signal_unwrap_phase_f64 +hmath_signal_detrend_f64 +hmath_signal_normalize_f64 +hmath_signal_smooth_f64 +hmath_signal_noise_estimate_f64 +hmath_signal_signal_to_noise_f64 +hmath_signal_rms_f64 +hmath_statistics_advanced_arithmetic_mean_f64 +hmath_statistics_advanced_weighted_mean_f64 +hmath_statistics_advanced_geometric_mean_f64 +hmath_statistics_advanced_harmonic_mean_f64 +hmath_statistics_advanced_rms_f64 +hmath_statistics_advanced_trimmed_mean_f64 +hmath_statistics_advanced_winsorized_mean_f64 +hmath_statistics_advanced_quantile_f64 +hmath_statistics_advanced_median_f64 +hmath_statistics_advanced_percentile_f64 +hmath_statistics_advanced_modes_f64 +hmath_statistics_advanced_interquartile_range_f64 +hmath_statistics_advanced_median_absolute_deviation_f64 +hmath_statistics_advanced_data_range_f64 +hmath_statistics_advanced_central_moment_f64 +hmath_statistics_advanced_population_variance_f64 +hmath_statistics_advanced_sample_variance_f64 +hmath_statistics_advanced_population_s_d_f64 +hmath_statistics_advanced_sample_s_d_f64 +hmath_statistics_advanced_coefficient_of_variation_f64 +hmath_statistics_advanced_skewness_f64 +hmath_statistics_advanced_kurtosis_f64 +hmath_statistics_advanced_covariance_f64 +hmath_statistics_advanced_correlation_f64 +hmath_statistics_advanced_spearman_f64 +hmath_statistics_advanced_kendall_f64 +hmath_statistics_advanced_autocorrelation_f64 +hmath_statistics_advanced_cross_correlation_f64 +hmath_statistics_advanced_moving_average_f64 +hmath_statistics_advanced_moving_variance_f64 +hmath_statistics_advanced_exponential_moving_average_f64 +hmath_statistics_advanced_entropy_f64 +hmath_statistics_advanced_kl_divergence_f64 +hmath_statistics_advanced_js_divergence_f64 +hmath_statistics_advanced_z_scores_f64 +hmath_statistics_advanced_standard_error_f64 +hmath_statistics_advanced_confidence_interval_f64 +hmath_statistics_advanced_bonferroni_f64 +hmath_statistics_advanced_benjamini_hochberg_f64 +hmath_statistics_advanced_cohens_d_f64 +hmath_statistics_advanced_normal_test_power_f64 +hmath_statistics_advanced_normal_sample_size_f64 +hmath_statistics_advanced_tukey_outliers_f64 +hmath_statistics_advanced_huber_location_f64 +hmath_tensor_shape_size +hmath_tensor_infer_broadcast +hmath_timeseries_core_exponential_average_f64 +hmath_timeseries_core_weighted_average_f64 +hmath_timeseries_core_cumulative_returns_f64 +hmath_timeseries_core_logarithmic_returns_f64 +hmath_timeseries_core_difference_f64 +hmath_timeseries_core_autocorrelation_f64 +hmath_timeseries_core_cross_correlation_f64 +hmath_timeseries_core_partial_autocorrelation_f64 +hmath_timeseries_diagnostics_change_points_f64 +hmath_timeseries_diagnostics_cusum_f64 +hmath_timeseries_diagnostics_anomalies_f64 +hmath_units_radians_to_degrees_f32 +hmath_units_radians_to_degrees_f64 +hmath_units_degrees_to_radians_f32 +hmath_units_degrees_to_radians_f64 +hmath_units_radians_to_gradians_f32 +hmath_units_radians_to_gradians_f64 +hmath_units_gradians_to_radians_f32 +hmath_units_gradians_to_radians_f64 +hmath_scalar_saturating_add_i8 +hmath_scalar_saturating_add_i16 +hmath_scalar_saturating_add_i32 +hmath_scalar_saturating_add_i64 +hmath_scalar_saturating_add_u8 +hmath_scalar_saturating_add_u16 +hmath_scalar_saturating_add_u32 +hmath_scalar_saturating_add_u64 +hmath_scalar_saturating_add_int +hmath_scalar_saturating_add_word +hmath_scalar_saturating_subtract_i8 +hmath_scalar_saturating_subtract_i16 +hmath_scalar_saturating_subtract_i32 +hmath_scalar_saturating_subtract_i64 +hmath_scalar_saturating_subtract_u8 +hmath_scalar_saturating_subtract_u16 +hmath_scalar_saturating_subtract_u32 +hmath_scalar_saturating_subtract_u64 +hmath_scalar_saturating_subtract_int +hmath_scalar_saturating_subtract_word +hmath_scalar_saturating_multiply_i8 +hmath_scalar_saturating_multiply_i16 +hmath_scalar_saturating_multiply_i32 +hmath_scalar_saturating_multiply_i64 +hmath_scalar_saturating_multiply_u8 +hmath_scalar_saturating_multiply_u16 +hmath_scalar_saturating_multiply_u32 +hmath_scalar_saturating_multiply_u64 +hmath_scalar_saturating_multiply_int +hmath_scalar_saturating_multiply_word +hmath_scalar_checked_add_i8 +hmath_scalar_checked_add_i16 +hmath_scalar_checked_add_i32 +hmath_scalar_checked_add_i64 +hmath_scalar_checked_add_u8 +hmath_scalar_checked_add_u16 +hmath_scalar_checked_add_u32 +hmath_scalar_checked_add_u64 +hmath_scalar_checked_add_int +hmath_scalar_checked_add_word +hmath_scalar_checked_subtract_i8 +hmath_scalar_checked_subtract_i16 +hmath_scalar_checked_subtract_i32 +hmath_scalar_checked_subtract_i64 +hmath_scalar_checked_subtract_u8 +hmath_scalar_checked_subtract_u16 +hmath_scalar_checked_subtract_u32 +hmath_scalar_checked_subtract_u64 +hmath_scalar_checked_subtract_int +hmath_scalar_checked_subtract_word +hmath_scalar_checked_multiply_i8 +hmath_scalar_checked_multiply_i16 +hmath_scalar_checked_multiply_i32 +hmath_scalar_checked_multiply_i64 +hmath_scalar_checked_multiply_u8 +hmath_scalar_checked_multiply_u16 +hmath_scalar_checked_multiply_u32 +hmath_scalar_checked_multiply_u64 +hmath_scalar_checked_multiply_int +hmath_scalar_checked_multiply_word diff --git a/bindings/schema/numeric-types-objects.json b/bindings/schema/numeric-types-objects.json new file mode 100644 index 0000000..01c9bcc --- /dev/null +++ b/bindings/schema/numeric-types-objects.json @@ -0,0 +1,1225 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Numeric.roundRational", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.round_rational", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.classify", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.classify", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.frexp", + "c": [ + "hmath_numeric_types_frexp" + ], + "python": "hmath.numeric_types.frexp", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.numericLimits", + "c": [ + "hmath_numeric_types_numeric_limits" + ], + "python": "hmath.numeric_types.numeric_limits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.integerLimits", + "c": [ + "hmath_numeric_types_integer_limits" + ], + "python": "hmath.numeric_types.integer_limits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.float16Limits", + "c": [ + "hmath_numeric_types_float16_limits" + ], + "python": "hmath.numeric_types.float16_limits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16Limits", + "c": [ + "hmath_numeric_types_bfloat16_limits" + ], + "python": "hmath.numeric_types.bfloat16_limits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.NumericLimits", + "c": [ + "hmath_numeric_types_numeric_limits_record" + ], + "python": "hmath.numeric_types.numeric_limits_record", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.minimumNormal", + "c": [ + "hmath_numeric_types_minimum_normal" + ], + "python": "hmath.numeric_types.minimum_normal", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.minimumSubnormal", + "c": [ + "hmath_numeric_types_minimum_subnormal" + ], + "python": "hmath.numeric_types.minimum_subnormal", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.maximumFinite", + "c": [ + "hmath_numeric_types_maximum_finite" + ], + "python": "hmath.numeric_types.maximum_finite", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.machineEpsilon", + "c": [ + "hmath_numeric_types_machine_epsilon" + ], + "python": "hmath.numeric_types.machine_epsilon", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.significandDigits", + "c": [ + "hmath_numeric_types_significand_digits" + ], + "python": "hmath.numeric_types.significand_digits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.minimumExponent", + "c": [ + "hmath_numeric_types_minimum_exponent" + ], + "python": "hmath.numeric_types.minimum_exponent", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.maximumExponent", + "c": [ + "hmath_numeric_types_maximum_exponent" + ], + "python": "hmath.numeric_types.maximum_exponent", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.safeIntegralCast", + "c": [ + "hmath_numeric_types_safe_integral_cast" + ], + "python": "hmath.numeric_types.safe_integral_cast", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.saturatingCast", + "c": [ + "hmath_numeric_types_saturating_cast" + ], + "python": "hmath.numeric_types.saturating_cast", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.realToIntegral", + "c": [ + "hmath_numeric_types_real_to_integral" + ], + "python": "hmath.numeric_types.real_to_integral", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.narrowFloat", + "c": [ + "hmath_numeric_types_narrow_float" + ], + "python": "hmath.numeric_types.narrow_float", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.float16", + "c": [ + "hmath_numeric_types_float16" + ], + "python": "hmath.numeric_types.float16", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16", + "c": [ + "hmath_numeric_types_bfloat16" + ], + "python": "hmath.numeric_types.bfloat16", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.float16FromBits", + "c": [ + "hmath_numeric_types_float16_from_bits" + ], + "python": "hmath.numeric_types.float16_from_bits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16FromBits", + "c": [ + "hmath_numeric_types_bfloat16_from_bits" + ], + "python": "hmath.numeric_types.bfloat16_from_bits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.float16Bits", + "c": [ + "hmath_numeric_types_float16_bits" + ], + "python": "hmath.numeric_types.float16_bits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16Bits", + "c": [ + "hmath_numeric_types_bfloat16_bits" + ], + "python": "hmath.numeric_types.bfloat16_bits", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fromFloat16", + "c": [ + "hmath_numeric_types_from_float16" + ], + "python": "hmath.numeric_types.from_float16", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fromBFloat16", + "c": [ + "hmath_numeric_types_from_bfloat16" + ], + "python": "hmath.numeric_types.from_bfloat16", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.Rounded", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.rounded", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.roundedValue", + "c": [ + "hmath_numeric_types_rounded_value" + ], + "python": "hmath.numeric_types.rounded_value", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.numericalExceptions", + "c": [ + "hmath_numeric_types_numerical_exceptions" + ], + "python": "hmath.numeric_types.numerical_exceptions", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigFloat", + "c": [ + "hmath_numeric_types_big_float" + ], + "python": "hmath.numeric_types.big_float", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.extended", + "c": [ + "hmath_numeric_types_extended" + ], + "python": "hmath.numeric_types.extended", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigPrecision", + "c": [ + "hmath_numeric_types_big_precision" + ], + "python": "hmath.numeric_types.big_precision", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigRational", + "c": [ + "hmath_numeric_types_big_rational" + ], + "python": "hmath.numeric_types.big_rational", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigToDouble", + "c": [ + "hmath_numeric_types_big_to_double" + ], + "python": "hmath.numeric_types.big_to_double", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigAdd", + "c": [ + "hmath_numeric_types_big_add" + ], + "python": "hmath.numeric_types.big_add", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigSubtract", + "c": [ + "hmath_numeric_types_big_subtract" + ], + "python": "hmath.numeric_types.big_subtract", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigMultiply", + "c": [ + "hmath_numeric_types_big_multiply" + ], + "python": "hmath.numeric_types.big_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigDivide", + "c": [ + "hmath_numeric_types_big_divide" + ], + "python": "hmath.numeric_types.big_divide", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigSqrt", + "c": [ + "hmath_numeric_types_big_sqrt" + ], + "python": "hmath.numeric_types.big_sqrt", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigExp", + "c": [ + "hmath_numeric_types_big_exp" + ], + "python": "hmath.numeric_types.big_exp", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.bigLog", + "c": [ + "hmath_numeric_types_big_log" + ], + "python": "hmath.numeric_types.big_log", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.mixedAdd", + "c": [ + "hmath_numeric_types_mixed_add" + ], + "python": "hmath.numeric_types.mixed_add", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.mixedMultiply", + "c": [ + "hmath_numeric_types_mixed_multiply" + ], + "python": "hmath.numeric_types.mixed_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixed", + "c": [ + "hmath_numeric_types_fixed" + ], + "python": "hmath.numeric_types.fixed", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedRational", + "c": [ + "hmath_numeric_types_fixed_rational" + ], + "python": "hmath.numeric_types.fixed_rational", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedAdd", + "c": [ + "hmath_numeric_types_fixed_add" + ], + "python": "hmath.numeric_types.fixed_add", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedMultiply", + "c": [ + "hmath_numeric_types_fixed_multiply" + ], + "python": "hmath.numeric_types.fixed_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedDivide", + "c": [ + "hmath_numeric_types_fixed_divide" + ], + "python": "hmath.numeric_types.fixed_divide", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.decimal", + "c": [ + "hmath_numeric_types_decimal" + ], + "python": "hmath.numeric_types.decimal", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.decimalRational", + "c": [ + "hmath_numeric_types_decimal_rational" + ], + "python": "hmath.numeric_types.decimal_rational", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.decimalAdd", + "c": [ + "hmath_numeric_types_decimal_add" + ], + "python": "hmath.numeric_types.decimal_add", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.decimalMultiply", + "c": [ + "hmath_numeric_types_decimal_multiply" + ], + "python": "hmath.numeric_types.decimal_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.decimalDivide", + "c": [ + "hmath_numeric_types_decimal_divide" + ], + "python": "hmath.numeric_types.decimal_divide", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedScale", + "c": [ + "hmath_numeric_types_fixed_scale" + ], + "python": "hmath.numeric_types.fixed_scale", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.fixedCoefficient", + "c": [ + "hmath_numeric_types_fixed_coefficient" + ], + "python": "hmath.numeric_types.fixed_coefficient", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.interval", + "c": [ + "hmath_numeric_types_interval" + ], + "python": "hmath.numeric_types.interval", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalBounds", + "c": [ + "hmath_numeric_types_interval_bounds" + ], + "python": "hmath.numeric_types.interval_bounds", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalContains", + "c": [ + "hmath_numeric_types_interval_contains" + ], + "python": "hmath.numeric_types.interval_contains", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalAdd", + "c": [ + "hmath_numeric_types_interval_add" + ], + "python": "hmath.numeric_types.interval_add", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalSubtract", + "c": [ + "hmath_numeric_types_interval_subtract" + ], + "python": "hmath.numeric_types.interval_subtract", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalMultiply", + "c": [ + "hmath_numeric_types_interval_multiply" + ], + "python": "hmath.numeric_types.interval_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.intervalDivide", + "c": [ + "hmath_numeric_types_interval_divide" + ], + "python": "hmath.numeric_types.interval_divide", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.Dual", + "c": [ + "hmath_numeric_types_dual" + ], + "python": "hmath.numeric_types.dual", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.primal", + "c": [ + "hmath_numeric_types_primal" + ], + "python": "hmath.numeric_types.primal", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.tangent", + "c": [ + "hmath_numeric_types_tangent" + ], + "python": "hmath.numeric_types.tangent", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.derivative", + "c": [ + "hmath_numeric_types_derivative" + ], + "python": "hmath.numeric_types.derivative", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.Quaternion", + "c": [ + "hmath_numeric_types_quaternion" + ], + "python": "hmath.numeric_types.quaternion", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.quaternionConjugate", + "c": [ + "hmath_numeric_types_quaternion_conjugate" + ], + "python": "hmath.numeric_types.quaternion_conjugate", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.quaternionNorm", + "c": [ + "hmath_numeric_types_quaternion_norm" + ], + "python": "hmath.numeric_types.quaternion_norm", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.quaternionInverse", + "c": [ + "hmath_numeric_types_quaternion_inverse" + ], + "python": "hmath.numeric_types.quaternion_inverse", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.DualQuaternion", + "c": [ + "hmath_numeric_types_dual_quaternion" + ], + "python": "hmath.numeric_types.dual_quaternion", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.dualQuaternionMultiply", + "c": [ + "hmath_numeric_types_dual_quaternion_multiply" + ], + "python": "hmath.numeric_types.dual_quaternion_multiply", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.dualQuaternionInverse", + "c": [ + "hmath_numeric_types_dual_quaternion_inverse" + ], + "python": "hmath.numeric_types.dual_quaternion_inverse", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.rotateVector", + "c": [ + "hmath_numeric_types_rotate_vector" + ], + "python": "hmath.numeric_types.rotate_vector", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.rigidTransform", + "c": [ + "hmath_numeric_types_rigid_transform" + ], + "python": "hmath.numeric_types.rigid_transform", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.transformPoint", + "c": [ + "hmath_numeric_types_transform_point" + ], + "python": "hmath.numeric_types.transform_point", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.Constant", + "c": [ + "hmath_numeric_types_constant" + ], + "python": "hmath.numeric_types.constant", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.constantName", + "c": [ + "hmath_numeric_types_constant_name" + ], + "python": "hmath.numeric_types.constant_name", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.constantValue", + "c": [ + "hmath_numeric_types_constant_value" + ], + "python": "hmath.numeric_types.constant_value", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.standardUncertainty", + "c": [ + "hmath_numeric_types_standard_uncertainty" + ], + "python": "hmath.numeric_types.standard_uncertainty", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.approximationBound", + "c": [ + "hmath_numeric_types_approximation_bound" + ], + "python": "hmath.numeric_types.approximation_bound", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.constantUnit", + "c": [ + "hmath_numeric_types_constant_unit" + ], + "python": "hmath.numeric_types.constant_unit", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.constantSource", + "c": [ + "hmath_numeric_types_constant_source" + ], + "python": "hmath.numeric_types.constant_source", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.constantAs", + "c": [ + "hmath_numeric_types_constant_as" + ], + "python": "hmath.numeric_types.constant_as", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.mathematicalConstants", + "c": [ + "hmath_numeric_types_mathematical_constants" + ], + "python": "hmath.numeric_types.mathematical_constants", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.physicalConstants", + "c": [ + "hmath_numeric_types_physical_constants" + ], + "python": "hmath.numeric_types.physical_constants", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.speedOfLight", + "c": [ + "hmath_numeric_types_speed_of_light" + ], + "python": "hmath.numeric_types.speed_of_light", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.planckConstant", + "c": [ + "hmath_numeric_types_planck_constant" + ], + "python": "hmath.numeric_types.planck_constant", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.elementaryCharge", + "c": [ + "hmath_numeric_types_elementary_charge" + ], + "python": "hmath.numeric_types.elementary_charge", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.boltzmannConstant", + "c": [ + "hmath_numeric_types_boltzmann_constant" + ], + "python": "hmath.numeric_types.boltzmann_constant", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.avogadroConstant", + "c": [ + "hmath_numeric_types_avogadro_constant" + ], + "python": "hmath.numeric_types.avogadro_constant", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.gravitationalConstant", + "c": [ + "hmath_numeric_types_gravitational_constant" + ], + "python": "hmath.numeric_types.gravitational_constant", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.electronMass", + "c": [ + "hmath_numeric_types_electron_mass" + ], + "python": "hmath.numeric_types.electron_mass", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Constants.astronomicalUnit", + "c": [ + "hmath_numeric_types_astronomical_unit" + ], + "python": "hmath.numeric_types.astronomical_unit", + "specializations": [ + "typed opaque representation" + ] + }, + { + "symbol": "HMath.Numeric.Float16", + "c": [ + "hmath_numeric_types_float16_from_bits" + ], + "python": "hmath.numeric_types.float16_from_bits", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.BFloat16", + "c": [ + "hmath_numeric_types_bfloat16_from_bits" + ], + "python": "hmath.numeric_types.bfloat16_from_bits", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.BigFloat", + "c": [ + "hmath_numeric_types_big_float" + ], + "python": "hmath.numeric_types.big_float", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.Fixed", + "c": [ + "hmath_numeric_types_fixed" + ], + "python": "hmath.numeric_types.fixed", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.Decimal", + "c": [ + "hmath_numeric_types_decimal" + ], + "python": "hmath.numeric_types.decimal", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.Interval", + "c": [ + "hmath_numeric_types_interval" + ], + "python": "hmath.numeric_types.interval", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Numeric.RoundingMode", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.RoundingMode", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NearestEven", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.RoundingMode.NEAREST_EVEN", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.TowardZero", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.RoundingMode.TOWARD_ZERO", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.TowardPositive", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.RoundingMode.TOWARD_POSITIVE", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.TowardNegative", + "c": [ + "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types.RoundingMode.TOWARD_NEGATIVE", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NumericException", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.InvalidOperation", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException.INVALID_OPERATION", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.DivisionByZero", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException.DIVISION_BY_ZERO", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NumericOverflow", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException.NUMERIC_OVERFLOW", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NumericUnderflow", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException.NUMERIC_UNDERFLOW", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.Inexact", + "c": [ + "hmath_numeric_types_rounded" + ], + "python": "hmath.numeric_types.NumericException.INEXACT", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.IEEEClass", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NotANumber", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.NOT_A_NUMBER", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.PositiveInfinity", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.POSITIVE_INFINITY", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NegativeInfinity", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.NEGATIVE_INFINITY", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.PositiveZero", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.POSITIVE_ZERO", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.NegativeZero", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.NEGATIVE_ZERO", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.Subnormal", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.SUBNORMAL", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.Normal", + "c": [ + "hmath_numeric_types_classify" + ], + "python": "hmath.numeric_types.IEEEClass.NORMAL", + "specializations": [ + "lossless enum representation" + ] + }, + { + "symbol": "HMath.Numeric.Float32", + "c": [ + "hmath_value_f32" + ], + "python": "hmath.numeric_types.number", + "specializations": [ + "float32" + ] + }, + { + "symbol": "HMath.Numeric.Float64", + "c": [ + "hmath_value_f64" + ], + "python": "hmath.numeric_types.number", + "specializations": [ + "float64" + ] + } + ] +} diff --git a/bindings/schema/numeric-types-symbols.txt b/bindings/schema/numeric-types-symbols.txt new file mode 100644 index 0000000..1ce7ef8 --- /dev/null +++ b/bindings/schema/numeric-types-symbols.txt @@ -0,0 +1,111 @@ +hmath_numeric_types_retain +hmath_numeric_types_release +hmath_numeric_types_buffer_free +hmath_numeric_types_kind +hmath_numeric_types_type_name +hmath_numeric_types_binary +hmath_numeric_types_unary +hmath_numeric_types_literal_integer +hmath_numeric_types_literal_rational +hmath_numeric_types_integer_power +hmath_numeric_types_equal +hmath_numeric_types_sequence_get +hmath_numeric_types_round_rational +hmath_numeric_types_classify +hmath_numeric_types_frexp +hmath_numeric_types_numeric_limits +hmath_numeric_types_integer_limits +hmath_numeric_types_float16_limits +hmath_numeric_types_bfloat16_limits +hmath_numeric_types_numeric_limits_record +hmath_numeric_types_minimum_normal +hmath_numeric_types_minimum_subnormal +hmath_numeric_types_maximum_finite +hmath_numeric_types_machine_epsilon +hmath_numeric_types_significand_digits +hmath_numeric_types_minimum_exponent +hmath_numeric_types_maximum_exponent +hmath_numeric_types_safe_integral_cast +hmath_numeric_types_saturating_cast +hmath_numeric_types_real_to_integral +hmath_numeric_types_narrow_float +hmath_numeric_types_float16 +hmath_numeric_types_bfloat16 +hmath_numeric_types_float16_from_bits +hmath_numeric_types_bfloat16_from_bits +hmath_numeric_types_float16_bits +hmath_numeric_types_bfloat16_bits +hmath_numeric_types_from_float16 +hmath_numeric_types_from_bfloat16 +hmath_numeric_types_rounded +hmath_numeric_types_rounded_value +hmath_numeric_types_numerical_exceptions +hmath_numeric_types_big_float +hmath_numeric_types_extended +hmath_numeric_types_big_precision +hmath_numeric_types_big_rational +hmath_numeric_types_big_to_double +hmath_numeric_types_big_add +hmath_numeric_types_big_subtract +hmath_numeric_types_big_multiply +hmath_numeric_types_big_divide +hmath_numeric_types_big_sqrt +hmath_numeric_types_big_exp +hmath_numeric_types_big_log +hmath_numeric_types_mixed_add +hmath_numeric_types_mixed_multiply +hmath_numeric_types_fixed +hmath_numeric_types_fixed_rational +hmath_numeric_types_fixed_add +hmath_numeric_types_fixed_multiply +hmath_numeric_types_fixed_divide +hmath_numeric_types_decimal +hmath_numeric_types_decimal_rational +hmath_numeric_types_decimal_add +hmath_numeric_types_decimal_multiply +hmath_numeric_types_decimal_divide +hmath_numeric_types_fixed_scale +hmath_numeric_types_fixed_coefficient +hmath_numeric_types_interval +hmath_numeric_types_interval_bounds +hmath_numeric_types_interval_contains +hmath_numeric_types_interval_add +hmath_numeric_types_interval_subtract +hmath_numeric_types_interval_multiply +hmath_numeric_types_interval_divide +hmath_numeric_types_dual +hmath_numeric_types_primal +hmath_numeric_types_tangent +hmath_numeric_types_derivative +hmath_numeric_types_quaternion +hmath_numeric_types_quaternion_conjugate +hmath_numeric_types_quaternion_norm +hmath_numeric_types_quaternion_inverse +hmath_numeric_types_quaternion_component +hmath_numeric_types_dual_quaternion +hmath_numeric_types_dual_quaternion_component +hmath_numeric_types_dual_quaternion_multiply +hmath_numeric_types_dual_quaternion_inverse +hmath_numeric_types_rotate_vector +hmath_numeric_types_rigid_transform +hmath_numeric_types_transform_point +hmath_numeric_types_constant +hmath_numeric_types_constant_name +hmath_numeric_types_constant_value +hmath_numeric_types_standard_uncertainty +hmath_numeric_types_approximation_bound +hmath_numeric_types_constant_unit +hmath_numeric_types_constant_source +hmath_numeric_types_constant_as +hmath_numeric_types_constant_as_like +hmath_numeric_types_mathematical_constants +hmath_numeric_types_physical_constants +hmath_numeric_types_speed_of_light +hmath_numeric_types_planck_constant +hmath_numeric_types_elementary_charge +hmath_numeric_types_boltzmann_constant +hmath_numeric_types_avogadro_constant +hmath_numeric_types_gravitational_constant +hmath_numeric_types_electron_mass +hmath_numeric_types_astronomical_unit +hmath_numeric_types_enum_value diff --git a/bindings/schema/numeric.json b/bindings/schema/numeric.json new file mode 100644 index 0000000..d5b14e0 --- /dev/null +++ b/bindings/schema/numeric.json @@ -0,0 +1,8278 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Basic", + "name": "factorial", + "python": "factorial", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.Basic", + "name": "fibonacci", + "python": "fibonacci", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.Basic", + "name": "isPrime", + "python": "is_prime", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "b", + "checked": false + }, + { + "module": "HMath.Basic", + "name": "clamp", + "python": "clamp", + "args": [ + { + "name": "low", + "type": "f" + }, + { + "name": "high", + "type": "f" + }, + { + "name": "value", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Basic", + "name": "lerp", + "python": "lerp", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "t", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "add", + "python": "add", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "subtractScalar", + "python": "subtract_scalar", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "multiply", + "python": "multiply", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "minimumScalar", + "python": "minimum_scalar", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "maximumScalar", + "python": "maximum_scalar", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "absolute", + "python": "absolute", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "sign", + "python": "sign", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "divide", + "python": "divide", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "power", + "python": "power", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "hypot", + "python": "hypot", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "clampChecked", + "python": "clamp_checked", + "args": [ + { + "name": "low", + "type": "f" + }, + { + "name": "high", + "type": "f" + }, + { + "name": "value", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "lerpChecked", + "python": "lerp_checked", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "t", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "inverseLerp", + "python": "inverse_lerp", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "smoothstep", + "python": "smoothstep", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "smootherstep", + "python": "smootherstep", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "remap", + "python": "remap", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "c", + "type": "f" + }, + { + "name": "d", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "step", + "python": "step", + "args": [ + { + "name": "edge", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "sqrtChecked", + "python": "sqrt_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "cubeRoot", + "python": "cube_root", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "reciprocalSqrt", + "python": "reciprocal_sqrt", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "expChecked", + "python": "exp_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "logChecked", + "python": "log_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "expm1", + "python": "expm1", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "log1p", + "python": "log1p", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "integerPower", + "python": "integer_power", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "nthRoot", + "python": "nth_root", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "roundDigits", + "python": "round_digits", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "absoluteError", + "python": "absolute_error", + "args": [ + { + "name": "actual", + "type": "f" + }, + { + "name": "expected", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "relativeError", + "python": "relative_error", + "args": [ + { + "name": "actual", + "type": "f" + }, + { + "name": "expected", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "fusedMultiplyAdd", + "python": "fused_multiply_add", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "c", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "checkedFloatMultiply", + "python": "checked_float_multiply", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "floorChecked", + "python": "floor_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "ceilChecked", + "python": "ceil_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "roundChecked", + "python": "round_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "truncateChecked", + "python": "truncate_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "bankersRound", + "python": "bankers_round", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "integerFraction", + "python": "integer_fraction", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "zf", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "quotientRemainder", + "python": "quotient_remainder", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + } + ], + "result": "zz", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "euclideanDivision", + "python": "euclidean_division", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + } + ], + "result": "zz", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "positiveModulo", + "python": "positive_modulo", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "modulus", + "type": "z" + } + ], + "result": "z", + "checked": true, + "specializations": [ + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "default_dtype": "integer", + "legacy_variants": [ + { + "dtype": "integer", + "suffix": "" + } + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "modularPower", + "python": "modular_power", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "n", + "type": "z" + }, + { + "name": "modulus", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "factorialChecked", + "python": "factorial_checked", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "doubleFactorial", + "python": "double_factorial", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "fibonacciChecked", + "python": "fibonacci_checked", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "lucas", + "python": "lucas", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "catalan", + "python": "catalan", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "risingFactorial", + "python": "rising_factorial", + "args": [ + { + "name": "x", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "fallingFactorial", + "python": "falling_factorial", + "args": [ + { + "name": "x", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "permutations", + "python": "permutations", + "args": [ + { + "name": "n", + "type": "z" + }, + { + "name": "k", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "combinations", + "python": "combinations", + "args": [ + { + "name": "n", + "type": "z" + }, + { + "name": "k", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "bernoulli", + "python": "bernoulli", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "q", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "harmonic", + "python": "harmonic", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "q", + "checked": true + }, + { + "module": "HMath.Scalar", + "name": "cumulativeSum", + "python": "cumulative_sum", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "fs", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "cumulativeProduct", + "python": "cumulative_product", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "fs", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "prefixSum", + "python": "prefix_sum", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "fs", + "checked": false, + "result_extra": 1, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Trigonometry", + "name": "sinChecked", + "python": "sin_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "cosChecked", + "python": "cos_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "tanChecked", + "python": "tan_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "asinChecked", + "python": "asin_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acosChecked", + "python": "acos_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "atanChecked", + "python": "atan_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sec", + "python": "sec", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "csc", + "python": "csc", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "cot", + "python": "cot", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "asec", + "python": "asec", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acsc", + "python": "acsc", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acot", + "python": "acot", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sinhChecked", + "python": "sinh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "coshChecked", + "python": "cosh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "tanhChecked", + "python": "tanh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "asinhChecked", + "python": "asinh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acoshChecked", + "python": "acosh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "atanhChecked", + "python": "atanh_checked", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sech", + "python": "sech", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "csch", + "python": "csch", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "coth", + "python": "coth", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "asech", + "python": "asech", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acsch", + "python": "acsch", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "acoth", + "python": "acoth", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "normalizeAngle", + "python": "normalize_angle", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "normalizeSignedAngle", + "python": "normalize_signed_angle", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "versine", + "python": "versine", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "haversine", + "python": "haversine", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sinc", + "python": "sinc", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "cosc", + "python": "cosc", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "atan2Checked", + "python": "atan2_checked", + "args": [ + { + "name": "y", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sincos", + "python": "sincos", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "ff", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "wrap", + "python": "wrap", + "args": [ + { + "name": "low", + "type": "f" + }, + { + "name": "high", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "angleDifference", + "python": "angle_difference", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "greatCircleAngle", + "python": "great_circle_angle", + "args": [ + { + "name": "a", + "type": "p" + }, + { + "name": "b", + "type": "p" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "greatCircleDistance", + "python": "great_circle_distance", + "args": [ + { + "name": "radius", + "type": "f" + }, + { + "name": "a", + "type": "p" + }, + { + "name": "b", + "type": "p" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sphericalSide", + "python": "spherical_side", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "included", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sphericalAngles", + "python": "spherical_angles", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "c", + "type": "f" + } + ], + "result": "fff", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "sphericalExcess", + "python": "spherical_excess", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "c", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexSin", + "python": "complex_sin", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexCos", + "python": "complex_cos", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexTan", + "python": "complex_tan", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAsin", + "python": "complex_asin", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAcos", + "python": "complex_acos", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAtan", + "python": "complex_atan", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexSinh", + "python": "complex_sinh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexCosh", + "python": "complex_cosh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexTanh", + "python": "complex_tanh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAsinh", + "python": "complex_asinh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAcosh", + "python": "complex_acosh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "complexAtanh", + "python": "complex_atanh", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "periodicSawtooth", + "python": "periodic_sawtooth", + "args": [ + { + "name": "period", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "periodicTriangle", + "python": "periodic_triangle", + "args": [ + { + "name": "period", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Trigonometry", + "name": "periodicSquare", + "python": "periodic_square", + "args": [ + { + "name": "period", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Statistics", + "name": "mean", + "python": "mean", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Statistics", + "name": "variance", + "python": "variance", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Statistics", + "name": "standardDeviation", + "python": "standard_deviation", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Statistics", + "name": "median", + "python": "median", + "args": [ + { + "name": "values", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Constants", + "name": "piConstant", + "python": "pi_constant", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "eConstant", + "python": "e_constant", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "tau", + "python": "tau", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "goldenRatio", + "python": "golden_ratio", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "eulerMascheroni", + "python": "euler_mascheroni", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "catalanConstant", + "python": "catalan_constant", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "aperyConstant", + "python": "apery_constant", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "sqrt2", + "python": "sqrt2", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "sqrt3", + "python": "sqrt3", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "ln2", + "python": "ln2", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "ln10", + "python": "ln10", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "infinity", + "python": "infinity", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Constants", + "name": "nan", + "python": "nan", + "args": [], + "result": "f", + "checked": false + }, + { + "module": "HMath.Scalar", + "name": "multinomial", + "python": "multinomial", + "args": [ + { + "name": "ks", + "type": "zs" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "gcdInteger", + "python": "gcd_integer", + "args": [ + { + "name": "argument1", + "type": "z" + }, + { + "name": "argument2", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "lcmInteger", + "python": "lcm_integer", + "args": [ + { + "name": "argument1", + "type": "z" + }, + { + "name": "argument2", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "extendedGCD", + "python": "extended_g_c_d", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + } + ], + "result": "zzz", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "bezout", + "python": "bezout", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + } + ], + "result": "zz", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "modPow", + "python": "mod_pow", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "e", + "type": "z" + }, + { + "name": "m", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "modInverse", + "python": "mod_inverse", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "m", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "integerSquareRoot", + "python": "integer_square_root", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "isPrimeExact", + "python": "is_prime_exact", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "b", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "nextPrime", + "python": "next_prime", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "millerRabin", + "python": "miller_rabin", + "args": [ + { + "name": "bases", + "type": "zs" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "b", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "bailliePSW", + "python": "baillie_p_s_w", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "b", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "sieveEratosthenes", + "python": "sieve_eratosthenes", + "args": [ + { + "name": "bound", + "type": "i" + } + ], + "result": "zd", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "sieveAtkin", + "python": "sieve_atkin", + "args": [ + { + "name": "bound", + "type": "i" + } + ], + "result": "zd", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "segmentedSieve", + "python": "segmented_sieve", + "args": [ + { + "name": "lo", + "type": "z" + }, + { + "name": "hi", + "type": "z" + } + ], + "result": "zd", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "pollardRho", + "python": "pollard_rho", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "seed", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "pollardPMinusOne", + "python": "pollard_p_minus_one", + "args": [ + { + "name": "bound", + "type": "i" + }, + { + "name": "base", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "fermatFactor", + "python": "fermat_factor", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "divisors", + "python": "divisors", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "zd", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "divisorSum", + "python": "divisor_sum", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "divisorCount", + "python": "divisor_count", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "eulerTotient", + "python": "euler_totient", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "carmichael", + "python": "carmichael", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "mobius", + "python": "mobius", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "liouville", + "python": "liouville", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "multiplicativeOrder", + "python": "multiplicative_order", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "a", + "type": "z" + }, + { + "name": "m", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "primitiveRoot", + "python": "primitive_root", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "m", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "discreteLog", + "python": "discrete_log", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + }, + { + "name": "m", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "legendreSymbol", + "python": "legendre_symbol", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "a", + "type": "z" + }, + { + "name": "p", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "jacobiSymbol", + "python": "jacobi_symbol", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "kroneckerSymbol", + "python": "kronecker_symbol", + "args": [ + { + "name": "a", + "type": "z" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "tonelliShanks", + "python": "tonelli_shanks", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "a", + "type": "z" + }, + { + "name": "p", + "type": "z" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "continuedFraction", + "python": "continued_fraction", + "args": [ + { + "name": "r", + "type": "q" + } + ], + "result": "zd", + "checked": false + }, + { + "module": "HMath.NumberTheory", + "name": "fromContinuedFraction", + "python": "from_continued_fraction", + "args": [ + { + "name": "argument1", + "type": "zs" + } + ], + "result": "q", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "convergents", + "python": "convergents", + "args": [ + { + "name": "xs", + "type": "zs" + } + ], + "result": "qd", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "farey", + "python": "farey", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "qd", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "pellFundamental", + "python": "pell_fundamental", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "d", + "type": "z" + } + ], + "result": "zz", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "isPerfectNumber", + "python": "is_perfect_number", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "n", + "type": "z" + } + ], + "result": "b", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "areAmicable", + "python": "are_amicable", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "a", + "type": "z" + }, + { + "name": "b", + "type": "z" + } + ], + "result": "b", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "partitionCount", + "python": "partition_count", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.NumberTheory", + "name": "fibonacciFast", + "python": "fibonacci_fast", + "args": [ + { + "name": "n", + "type": "z" + } + ], + "result": "z", + "checked": false + }, + { + "module": "HMath.Combinatorics", + "name": "permutationsCount", + "python": "permutations_count", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "k", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "combinationsCount", + "python": "combinations_count", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "k", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "multinomial", + "python": "multinomial", + "args": [ + { + "name": "argument1", + "type": "is" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "rankPermutation", + "python": "rank_permutation", + "args": [ + { + "name": "p", + "type": "is" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "unrankPermutation", + "python": "unrank_permutation", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "r", + "type": "z" + } + ], + "result": "id", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "rankCombination", + "python": "rank_combination", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "xs", + "type": "is" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "unrankCombination", + "python": "unrank_combination", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "k", + "type": "i" + }, + { + "name": "r", + "type": "z" + } + ], + "result": "id", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "derangementCount", + "python": "derangement_count", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "stirlingFirst", + "python": "stirling_first", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "stirlingSecond", + "python": "stirling_second", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "bellNumber", + "python": "bell_number", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "eulerianNumber", + "python": "eulerian_number", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "lahNumber", + "python": "lah_number", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "k", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "catalanNumber", + "python": "catalan_number", + "args": [ + { + "name": "argument1", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "fibonacci", + "python": "fibonacci", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "lucas", + "python": "lucas", + "args": [ + { + "name": "n", + "type": "i" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "inclusionExclusion", + "python": "inclusion_exclusion", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "sizes", + "type": "zs" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "multisetCount", + "python": "multiset_count", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "linearRecurrence", + "python": "linear_recurrence", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "cs", + "type": "zs" + }, + { + "name": "initial", + "type": "zs" + } + ], + "result": "zd", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "convolveSeries", + "python": "convolve_series", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "a", + "type": "zs" + }, + { + "name": "b", + "type": "zs" + } + ], + "result": "zd", + "checked": true + }, + { + "module": "HMath.Combinatorics", + "name": "finiteSum", + "python": "finite_sum", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Linear", + "name": "dot", + "python": "dot", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "dotChecked", + "python": "dot_checked", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "magnitude", + "python": "magnitude", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "specializations": [ + "float32", + "float64", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "normalize", + "python": "normalize", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "specializations": [ + "float32", + "float64", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "add", + "python": "add", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "addChecked", + "python": "add_checked", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "subtractChecked", + "python": "subtract_checked", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Linear", + "name": "scale", + "python": "scale", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "specializations": [ + "float32", + "float64", + "rational", + "integer", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + "complex64", + "complex128" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Special", + "name": "gamma", + "python": "gamma", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "logGamma", + "python": "log_gamma", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "logBeta", + "python": "log_beta", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "beta", + "python": "beta", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "gammaP", + "python": "gamma_p", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "gammaQ", + "python": "gamma_q", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "incompleteGamma", + "python": "incomplete_gamma", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "betaI", + "python": "beta_i", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "incompleteBeta", + "python": "incomplete_beta", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "digamma", + "python": "digamma", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "trigamma", + "python": "trigamma", + "args": [ + { + "name": "argument1", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "polygamma", + "python": "polygamma", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "erf", + "python": "erf", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "erfc", + "python": "erfc", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "erfcx", + "python": "erfcx", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "normalCDF", + "python": "normal_c_d_f", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "normalQuantile", + "python": "normal_quantile", + "args": [ + { + "name": "p", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "inverseErf", + "python": "inverse_erf", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "dawson", + "python": "dawson", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "exponentialIntegral", + "python": "exponential_integral", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "logarithmicIntegral", + "python": "logarithmic_integral", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "sineIntegral", + "python": "sine_integral", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "cosineIntegral", + "python": "cosine_integral", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "fresnel", + "python": "fresnel", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf2", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "ellipticF", + "python": "elliptic_f", + "args": [ + { + "name": "phi", + "type": "f" + }, + { + "name": "m", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "ellipticE", + "python": "elliptic_e", + "args": [ + { + "name": "phi", + "type": "f" + }, + { + "name": "m", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "ellipticPi", + "python": "elliptic_pi", + "args": [ + { + "name": "n", + "type": "f" + }, + { + "name": "phi", + "type": "f" + }, + { + "name": "m", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "jacobiElliptic", + "python": "jacobi_elliptic", + "args": [ + { + "name": "u", + "type": "f" + }, + { + "name": "m", + "type": "f" + } + ], + "result": "fff", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "besselJ", + "python": "bessel_j", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "besselY", + "python": "bessel_y", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "besselI", + "python": "bessel_i", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "scaledBesselI", + "python": "scaled_bessel_i", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "besselK", + "python": "bessel_k", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "scaledBesselK", + "python": "scaled_bessel_k", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "sphericalBesselJ", + "python": "spherical_bessel_j", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "sphericalBesselY", + "python": "spherical_bessel_y", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "airy", + "python": "airy", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf4", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "struve", + "python": "struve", + "args": [ + { + "name": "nu", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "hypergeometric", + "python": "hypergeometric", + "args": [ + { + "name": "as", + "type": "fs" + }, + { + "name": "bs", + "type": "fs" + }, + { + "name": "z", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "hypergeometric1F1", + "python": "hypergeometric1_f1", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "z", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "hypergeometric2F1", + "python": "hypergeometric2_f1", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "c", + "type": "f" + }, + { + "name": "z", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "legendre", + "python": "legendre", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "associatedLegendre", + "python": "associated_legendre", + "args": [ + { + "name": "l", + "type": "i" + }, + { + "name": "m", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "hurwitzZeta", + "python": "hurwitz_zeta", + "args": [ + { + "name": "s", + "type": "f" + }, + { + "name": "q", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "riemannZeta", + "python": "riemann_zeta", + "args": [ + { + "name": "s", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "polylogarithm", + "python": "polylogarithm", + "args": [ + { + "name": "s", + "type": "f" + }, + { + "name": "z", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "dilogarithm", + "python": "dilogarithm", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "lambertW", + "python": "lambert_w", + "args": [ + { + "name": "branch", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "debye", + "python": "debye", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "clausen", + "python": "clausen", + "args": [ + { + "name": "theta", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "fermiDirac", + "python": "fermi_dirac", + "args": [ + { + "name": "order", + "type": "f" + }, + { + "name": "eta", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "boseEinstein", + "python": "bose_einstein", + "args": [ + { + "name": "order", + "type": "f" + }, + { + "name": "eta", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "coulombWave", + "python": "coulomb_wave", + "args": [ + { + "name": "l", + "type": "i" + }, + { + "name": "eta", + "type": "f" + }, + { + "name": "rho", + "type": "f" + } + ], + "result": "sf2", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "gegenbauer", + "python": "gegenbauer", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "a", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "parabolicCylinder", + "python": "parabolic_cylinder", + "args": [ + { + "name": "nu", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "sf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "mathieu", + "python": "mathieu", + "args": [ + { + "name": "evenMode", + "type": "b" + }, + { + "name": "n", + "type": "i" + }, + { + "name": "q", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "fsf", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "bernoulliPolynomial", + "python": "bernoulli_polynomial", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "eulerPolynomial", + "python": "euler_polynomial", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "wigner3j", + "python": "wigner3j", + "args": [ + { + "name": "j1", + "type": "i" + }, + { + "name": "j2", + "type": "i" + }, + { + "name": "j3", + "type": "i" + }, + { + "name": "m1", + "type": "i" + }, + { + "name": "m2", + "type": "i" + }, + { + "name": "m3", + "type": "i" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "wigner6j", + "python": "wigner6j", + "args": [ + { + "name": "a", + "type": "i" + }, + { + "name": "b", + "type": "i" + }, + { + "name": "c", + "type": "i" + }, + { + "name": "d", + "type": "i" + }, + { + "name": "e", + "type": "i" + }, + { + "name": "f", + "type": "i" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "wigner9j", + "python": "wigner9j", + "args": [ + { + "name": "js", + "type": "is" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "clebschGordan", + "python": "clebsch_gordan", + "args": [ + { + "name": "j1", + "type": "i" + }, + { + "name": "m1", + "type": "i" + }, + { + "name": "j2", + "type": "i" + }, + { + "name": "m2", + "type": "i" + }, + { + "name": "j", + "type": "i" + }, + { + "name": "m", + "type": "i" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "toPolar", + "python": "to_polar", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "ff", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "gammaPoissonUpdate", + "python": "gamma_poisson_update", + "args": [ + { + "name": "shapePrior", + "type": "f" + }, + { + "name": "ratePrior", + "type": "f" + }, + { + "name": "xs", + "type": "is" + } + ], + "result": "ff", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "normalNormalUpdate", + "python": "normal_normal_update", + "args": [ + { + "name": "mu", + "type": "f" + }, + { + "name": "priorVariance", + "type": "f" + }, + { + "name": "observationVariance", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "ff", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "conditionalProbability", + "python": "conditional_probability", + "args": [ + { + "name": "joint", + "type": "f" + }, + { + "name": "given", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "bayes", + "python": "bayes", + "args": [ + { + "name": "priors", + "type": "fs" + }, + { + "name": "likelihoods", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "multinomialPMF", + "python": "multinomial_p_m_f", + "args": [ + { + "name": "ps", + "type": "fs" + }, + { + "name": "counts", + "type": "is" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Probability", + "name": "dirichletDensity", + "python": "dirichlet_density", + "args": [ + { + "name": "as", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "complex", + "python": "complex", + "args": [ + { + "name": "real", + "type": "f" + }, + { + "name": "imaginary", + "type": "f" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "reciprocal", + "python": "reciprocal", + "args": [ + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "add", + "python": "add", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "subtractComplex", + "python": "subtract_complex", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "multiply", + "python": "multiply", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "divide", + "python": "divide", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "power", + "python": "power", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "fromPolar", + "python": "from_polar", + "args": [ + { + "name": "radius", + "type": "f" + }, + { + "name": "angle", + "type": "f" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Complex", + "name": "rotate", + "python": "rotate", + "args": [ + { + "name": "angle", + "type": "f" + }, + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "hankel", + "python": "hankel", + "args": [ + { + "name": "kind", + "type": "i" + }, + { + "name": "order", + "type": "i" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "sphericalHarmonic", + "python": "spherical_harmonic", + "args": [ + { + "name": "degree", + "type": "i" + }, + { + "name": "order", + "type": "i" + }, + { + "name": "theta", + "type": "f" + }, + { + "name": "phi", + "type": "f" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Special", + "name": "complex1F1", + "python": "complex1_f1", + "args": [ + { + "name": "a", + "type": "c" + }, + { + "name": "b", + "type": "c" + }, + { + "name": "z", + "type": "c" + } + ], + "result": "c", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.API.Algebra", + "name": "innerProduct", + "python": "inner_product", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "lowerBound", + "python": "lower_bound", + "args": [ + { + "name": "x", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "i", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "upperBound", + "python": "upper_bound", + "args": [ + { + "name": "x", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "i", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "quickselect", + "python": "quickselect", + "args": [ + { + "name": "k", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "introselect", + "python": "introselect", + "args": [ + { + "name": "k", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "partialSort", + "python": "partial_sort", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "mergeSort", + "python": "merge_sort", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "quicksort", + "python": "quicksort", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "heapsort", + "python": "heapsort", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "introsort", + "python": "introsort", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "countingSort", + "python": "counting_sort", + "args": [ + { + "name": "budget", + "type": "i" + }, + { + "name": "xs", + "type": "is" + } + ], + "result": "id", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "radixSort", + "python": "radix_sort", + "args": [ + { + "name": "argument1", + "type": "zs" + } + ], + "result": "zd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "bucketSort", + "python": "bucket_sort", + "args": [ + { + "name": "buckets", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Algorithms", + "name": "argsort", + "python": "argsort", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "id", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "topK", + "python": "top_k", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "quantileSelect", + "python": "quantile_select", + "args": [ + { + "name": "q", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Algorithms", + "name": "deduplicate", + "python": "deduplicate", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "prefixSums", + "python": "prefix_sums", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "suffixSums", + "python": "suffix_sums", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "differenceArray", + "python": "difference_array", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "applyDifferences", + "python": "apply_differences", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Algorithms", + "name": "binaryLift", + "python": "binary_lift", + "args": [ + { + "name": "next", + "type": "is" + }, + { + "name": "steps", + "type": "z" + }, + { + "name": "start", + "type": "i" + } + ], + "result": "i", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "polynomialHash", + "python": "polynomial_hash", + "args": [ + { + "name": "base", + "type": "z" + }, + { + "name": "modulus", + "type": "z" + }, + { + "name": "xs", + "type": "zs" + } + ], + "result": "z", + "checked": true + }, + { + "module": "HMath.Algorithms", + "name": "rollingHashes", + "python": "rolling_hashes", + "args": [ + { + "name": "base", + "type": "z" + }, + { + "name": "modulus", + "type": "z" + }, + { + "name": "width", + "type": "i" + }, + { + "name": "xs", + "type": "zs" + } + ], + "result": "zd", + "checked": true + }, + { + "module": "HMath.DataStructure", + "name": "monotonicMinima", + "python": "monotonic_minima", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true + }, + { + "module": "HMath.DeepLearning.Core", + "name": "logSoftmax", + "python": "log_softmax", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "softmax", + "python": "softmax", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "sparsemax", + "python": "sparsemax", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "gatedLinearUnit", + "python": "gated_linear_unit", + "args": [ + { + "name": "values", + "type": "fs" + }, + { + "name": "gate", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "categoricalCrossEntropyLogits", + "python": "categorical_cross_entropy_logits", + "args": [ + { + "name": "target", + "type": "fs" + }, + { + "name": "logits", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "regularization", + "python": "regularization", + "args": [ + { + "name": "l1", + "type": "f" + }, + { + "name": "l2", + "type": "f" + }, + { + "name": "weights", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "contrastiveLoss", + "python": "contrastive_loss", + "args": [ + { + "name": "margin", + "type": "f" + }, + { + "name": "similar", + "type": "b" + }, + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "tripletLoss", + "python": "triplet_loss", + "args": [ + { + "name": "margin", + "type": "f" + }, + { + "name": "anchor", + "type": "fs" + }, + { + "name": "positive", + "type": "fs" + }, + { + "name": "negative", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "focalLoss", + "python": "focal_loss", + "args": [ + { + "name": "alpha", + "type": "f" + }, + { + "name": "gamma", + "type": "f" + }, + { + "name": "target", + "type": "fs" + }, + { + "name": "prediction", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "diceLoss", + "python": "dice_loss", + "args": [ + { + "name": "smooth", + "type": "f" + }, + { + "name": "target", + "type": "fs" + }, + { + "name": "prediction", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Core", + "name": "iouLoss", + "python": "iou_loss", + "args": [ + { + "name": "smooth", + "type": "f" + }, + { + "name": "target", + "type": "fs" + }, + { + "name": "prediction", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "perplexity", + "python": "perplexity", + "args": [ + { + "name": "logs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Metrics", + "name": "marginRankingLoss", + "python": "margin_ranking_loss", + "args": [ + { + "name": "margin", + "type": "f" + }, + { + "name": "labels", + "type": "fs" + }, + { + "name": "left", + "type": "fs" + }, + { + "name": "right", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "gradientNorm", + "python": "gradient_norm", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.DeepLearning.Precision", + "name": "clipGradients", + "python": "clip_gradients", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Discrete", + "name": "setUnion", + "python": "set_union", + "args": [ + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Discrete", + "name": "setIntersection", + "python": "set_intersection", + "args": [ + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Discrete", + "name": "setDifference", + "python": "set_difference", + "args": [ + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Discrete", + "name": "symmetricDifference", + "python": "symmetric_difference", + "args": [ + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "fd", + "checked": false + }, + { + "module": "HMath.Fourier", + "name": "frequencies", + "python": "frequencies", + "args": [ + { + "name": "n", + "type": "i" + }, + { + "name": "spacing", + "type": "f" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "fftShift", + "python": "fft_shift", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "ifftShift", + "python": "ifft_shift", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "hartley", + "python": "hartley", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "periodogram", + "python": "periodogram", + "args": [ + { + "name": "rate", + "type": "f" + }, + { + "name": "window", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "welch", + "python": "welch", + "args": [ + { + "name": "rate", + "type": "f" + }, + { + "name": "window", + "type": "fs" + }, + { + "name": "hop", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "cepstrum", + "python": "cepstrum", + "args": [ + { + "name": "floorValue", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Fourier", + "name": "hilbert", + "python": "hilbert", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Geometry.Primitives", + "name": "hammingDistance", + "python": "hamming_distance", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "i", + "checked": true + }, + { + "module": "HMath.Geometry.Primitives", + "name": "jaccardDistance", + "python": "jaccard_distance", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Graph.Core", + "name": "finite", + "python": "finite", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "b", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Image.Color", + "name": "srgbToLinear", + "python": "srgb_to_linear", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Image.Color", + "name": "linearToSrgb", + "python": "linear_to_srgb", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Interpolation", + "name": "evaluateChebyshev", + "python": "evaluate_chebyshev", + "args": [ + { + "name": "cs", + "type": "fs" + }, + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + }, + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Numeric", + "name": "nextAfter", + "python": "next_after", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "f" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Numeric", + "name": "ldexp", + "python": "ldexp", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "i" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Numeric", + "name": "ulpDistance", + "python": "ulp_distance", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "z", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Numeric", + "name": "withinULPs", + "python": "within_u_l_ps", + "args": [ + { + "name": "n", + "type": "z" + }, + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "b", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Numeric", + "name": "kahanSum", + "python": "kahan_sum", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Numeric", + "name": "neumaierSum", + "python": "neumaier_sum", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Numeric", + "name": "pairwiseSum", + "python": "pairwise_sum", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Numeric", + "name": "logsumexp", + "python": "logsumexp", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Numeric", + "name": "sumErrorBound", + "python": "sum_error_bound", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true + }, + { + "module": "HMath.Optimization.Common", + "name": "dot", + "python": "dot", + "args": [ + { + "name": "a", + "type": "fs" + }, + { + "name": "b", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "norm", + "python": "norm", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "add", + "python": "add", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "sub", + "python": "sub", + "args": [ + { + "name": "argument1", + "type": "fs" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "scale", + "python": "scale", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": false, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Random", + "name": "importance", + "python": "importance", + "args": [ + { + "name": "values", + "type": "fs" + }, + { + "name": "weights", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Random", + "name": "halton", + "python": "halton", + "args": [ + { + "name": "dimension", + "type": "i" + }, + { + "name": "index", + "type": "i" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Random", + "name": "sobol", + "python": "sobol", + "args": [ + { + "name": "dimension", + "type": "i" + }, + { + "name": "index", + "type": "i" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Random", + "name": "faure", + "python": "faure", + "args": [ + { + "name": "d", + "type": "i" + }, + { + "name": "ix", + "type": "i" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "convolution", + "python": "convolution", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "circularConvolution", + "python": "circular_convolution", + "args": [ + { + "name": "x", + "type": "fs" + }, + { + "name": "y", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "correlation", + "python": "correlation", + "args": [ + { + "name": "x", + "type": "fs" + }, + { + "name": "y", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "autocorrelation", + "python": "autocorrelation", + "args": [ + { + "name": "x", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "overlapAdd", + "python": "overlap_add", + "args": [ + { + "name": "block", + "type": "i" + }, + { + "name": "kernel", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "overlapSave", + "python": "overlap_save", + "args": [ + { + "name": "fftLength", + "type": "i" + }, + { + "name": "kernel", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "movingAverage", + "python": "moving_average", + "args": [ + { + "name": "count", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "medianFilter", + "python": "median_filter", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "gaussianFilter", + "python": "gaussian_filter", + "args": [ + { + "name": "width", + "type": "i" + }, + { + "name": "sigma", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "savitzkyGolay", + "python": "savitzky_golay", + "args": [ + { + "name": "width", + "type": "i" + }, + { + "name": "degree", + "type": "i" + }, + { + "name": "derivative", + "type": "i" + }, + { + "name": "spacing", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "downsample", + "python": "downsample", + "args": [ + { + "name": "factor", + "type": "i" + }, + { + "name": "offset", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "upsample", + "python": "upsample", + "args": [ + { + "name": "factor", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "resamplePolyphase", + "python": "resample_polyphase", + "args": [ + { + "name": "up", + "type": "i" + }, + { + "name": "down", + "type": "i" + }, + { + "name": "kernel", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "resample", + "python": "resample", + "args": [ + { + "name": "up", + "type": "i" + }, + { + "name": "down", + "type": "i" + }, + { + "name": "taps", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "antiAlias", + "python": "anti_alias", + "args": [ + { + "name": "factor", + "type": "i" + }, + { + "name": "taps", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "zeroCrossings", + "python": "zero_crossings", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "envelope", + "python": "envelope", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "unwrapPhase", + "python": "unwrap_phase", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "detrend", + "python": "detrend", + "args": [ + { + "name": "linear", + "type": "b" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "normalize", + "python": "normalize", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "smooth", + "python": "smooth", + "args": [ + { + "name": "argument1", + "type": "i" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "noiseEstimate", + "python": "noise_estimate", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "signalToNoise", + "python": "signal_to_noise", + "args": [ + { + "name": "signal", + "type": "fs" + }, + { + "name": "noise", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Signal", + "name": "rms", + "python": "rms", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "arithmeticMean", + "python": "arithmetic_mean", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "weightedMean", + "python": "weighted_mean", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ws", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "geometricMean", + "python": "geometric_mean", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "harmonicMean", + "python": "harmonic_mean", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "rms", + "python": "rms", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "trimmedMean", + "python": "trimmed_mean", + "args": [ + { + "name": "fraction", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "winsorizedMean", + "python": "winsorized_mean", + "args": [ + { + "name": "fraction", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "quantile", + "python": "quantile", + "args": [ + { + "name": "p", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "median", + "python": "median", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "percentile", + "python": "percentile", + "args": [ + { + "name": "argument1", + "type": "f" + }, + { + "name": "argument2", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "modes", + "python": "modes", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "interquartileRange", + "python": "interquartile_range", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "medianAbsoluteDeviation", + "python": "median_absolute_deviation", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "dataRange", + "python": "data_range", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "centralMoment", + "python": "central_moment", + "args": [ + { + "name": "k", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "populationVariance", + "python": "population_variance", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "sampleVariance", + "python": "sample_variance", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "populationSD", + "python": "population_s_d", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "sampleSD", + "python": "sample_s_d", + "args": [ + { + "name": "argument1", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "coefficientOfVariation", + "python": "coefficient_of_variation", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "skewness", + "python": "skewness", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "kurtosis", + "python": "kurtosis", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "covariance", + "python": "covariance", + "args": [ + { + "name": "sampleCorrection", + "type": "b" + }, + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "correlation", + "python": "correlation", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "spearman", + "python": "spearman", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "kendall", + "python": "kendall", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "autocorrelation", + "python": "autocorrelation", + "args": [ + { + "name": "lag", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "crossCorrelation", + "python": "cross_correlation", + "args": [ + { + "name": "lag", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "movingAverage", + "python": "moving_average", + "args": [ + { + "name": "window", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "movingVariance", + "python": "moving_variance", + "args": [ + { + "name": "window", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "exponentialMovingAverage", + "python": "exponential_moving_average", + "args": [ + { + "name": "alpha", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "entropy", + "python": "entropy", + "args": [ + { + "name": "ps", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "klDivergence", + "python": "kl_divergence", + "args": [ + { + "name": "p", + "type": "fs" + }, + { + "name": "q", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "jsDivergence", + "python": "js_divergence", + "args": [ + { + "name": "p", + "type": "fs" + }, + { + "name": "q", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "zScores", + "python": "z_scores", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "standardError", + "python": "standard_error", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "confidenceInterval", + "python": "confidence_interval", + "args": [ + { + "name": "level", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "ff", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "bonferroni", + "python": "bonferroni", + "args": [ + { + "name": "ps", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "benjaminiHochberg", + "python": "benjamini_hochberg", + "args": [ + { + "name": "ps", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "cohensD", + "python": "cohens_d", + "args": [ + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "normalTestPower", + "python": "normal_test_power", + "args": [ + { + "name": "alpha", + "type": "f" + }, + { + "name": "standardizedEffect", + "type": "f" + }, + { + "name": "n", + "type": "i" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "normalSampleSize", + "python": "normal_sample_size", + "args": [ + { + "name": "alpha", + "type": "f" + }, + { + "name": "power", + "type": "f" + }, + { + "name": "effect", + "type": "f" + } + ], + "result": "i", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "tukeyOutliers", + "python": "tukey_outliers", + "args": [ + { + "name": "multiplier", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "id", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Statistics.Advanced", + "name": "huberLocation", + "python": "huber_location", + "args": [ + { + "name": "tuning", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Tensor", + "name": "shapeSize", + "python": "shape_size", + "args": [ + { + "name": "dims", + "type": "is" + } + ], + "result": "i", + "checked": true + }, + { + "module": "HMath.Tensor", + "name": "inferBroadcast", + "python": "infer_broadcast", + "args": [ + { + "name": "as", + "type": "is" + }, + { + "name": "bs", + "type": "is" + } + ], + "result": "id", + "checked": true + }, + { + "module": "HMath.TimeSeries.Core", + "name": "exponentialAverage", + "python": "exponential_average", + "args": [ + { + "name": "alpha", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "weightedAverage", + "python": "weighted_average", + "args": [ + { + "name": "ws", + "type": "fs" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "cumulativeReturns", + "python": "cumulative_returns", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "logarithmicReturns", + "python": "logarithmic_returns", + "args": [ + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "difference", + "python": "difference", + "args": [ + { + "name": "order", + "type": "i" + }, + { + "name": "lag", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "autocorrelation", + "python": "autocorrelation", + "args": [ + { + "name": "lags", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "crossCorrelation", + "python": "cross_correlation", + "args": [ + { + "name": "lag", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + }, + { + "name": "ys", + "type": "fs" + } + ], + "result": "f", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Core", + "name": "partialAutocorrelation", + "python": "partial_autocorrelation", + "args": [ + { + "name": "order", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "fd", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "changePoints", + "python": "change_points", + "args": [ + { + "name": "penalty", + "type": "f" + }, + { + "name": "minSegment", + "type": "i" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "id", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "cusum", + "python": "cusum", + "args": [ + { + "name": "mean", + "type": "f" + }, + { + "name": "sd", + "type": "f" + }, + { + "name": "drift", + "type": "f" + }, + { + "name": "threshold", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "id", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "anomalies", + "python": "anomalies", + "args": [ + { + "name": "threshold", + "type": "f" + }, + { + "name": "xs", + "type": "fs" + } + ], + "result": "id", + "checked": true, + "precisions": [ + 64 + ] + }, + { + "module": "HMath.Units", + "name": "radiansToDegrees", + "python": "radians_to_degrees", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Units", + "name": "degreesToRadians", + "python": "degrees_to_radians", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Units", + "name": "radiansToGradians", + "python": "radians_to_gradians", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Units", + "name": "gradiansToRadians", + "python": "gradians_to_radians", + "args": [ + { + "name": "x", + "type": "f" + } + ], + "result": "f", + "checked": false + }, + { + "module": "HMath.Scalar", + "name": "saturatingAdd", + "python": "saturating_add", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "saturatingSubtract", + "python": "saturating_subtract", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "saturatingMultiply", + "python": "saturating_multiply", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": false, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "checkedAdd", + "python": "checked_add", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "checkedSubtract", + "python": "checked_subtract", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + }, + { + "module": "HMath.Scalar", + "name": "checkedMultiply", + "python": "checked_multiply", + "args": [ + { + "name": "a", + "type": "f" + }, + { + "name": "b", + "type": "f" + } + ], + "result": "f", + "checked": true, + "default_dtype": "intp", + "specializations": [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp" + ], + "instance_coverage": "standard_numeric_subset" + } + ] +} diff --git a/bindings/schema/numerical-functions.json b/bindings/schema/numerical-functions.json new file mode 100644 index 0000000..358d513 --- /dev/null +++ b/bindings/schema/numerical-functions.json @@ -0,0 +1,930 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Calculus", + "name": "Estimate", + "signature": "a -> Double -> Int -> Estimate a" + }, + { + "module": "HMath.Calculus", + "name": "estimateValue", + "signature": "Estimate a -> a" + }, + { + "module": "HMath.Calculus", + "name": "estimateError", + "signature": "Estimate a -> Double" + }, + { + "module": "HMath.Calculus", + "name": "evaluations", + "signature": "Estimate a -> Int" + }, + { + "module": "HMath.Calculus", + "name": "Tolerance", + "signature": "Double -> Double -> Int -> Tolerance" + }, + { + "module": "HMath.Calculus", + "name": "absoluteTolerance", + "signature": "Tolerance -> Double" + }, + { + "module": "HMath.Calculus", + "name": "relativeTolerance", + "signature": "Tolerance -> Double" + }, + { + "module": "HMath.Calculus", + "name": "maximumEvaluations", + "signature": "Tolerance -> Int" + }, + { + "module": "HMath.Calculus", + "name": "defaultTolerance", + "signature": "Tolerance" + }, + { + "module": "HMath.Calculus", + "name": "Forward", + "signature": "Difference" + }, + { + "module": "HMath.Calculus", + "name": "Backward", + "signature": "Difference" + }, + { + "module": "HMath.Calculus", + "name": "Central", + "signature": "Difference" + }, + { + "module": "HMath.Calculus", + "name": "Trapezoidal", + "signature": "Quadrature" + }, + { + "module": "HMath.Calculus", + "name": "Simpson", + "signature": "Quadrature" + }, + { + "module": "HMath.Calculus", + "name": "ThreeEighths", + "signature": "Quadrature" + }, + { + "module": "HMath.Calculus", + "name": "derivative", + "signature": "Difference -> Double -> (Double -> Double) -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "derivativeN", + "signature": "Int -> Double -> (Double -> Double) -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "complexDerivative", + "signature": "Double -> (Complex Double -> Complex Double) -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "richardson", + "signature": "Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "ridders", + "signature": "Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "limit", + "signature": "Difference -> Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "partialDerivative", + "signature": "Int -> Double -> ([Double] -> Double) -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "gradient", + "signature": "Double -> ([Double] -> Double) -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "jacobian", + "signature": "Double -> ([Double] -> [Double]) -> [Double] -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Calculus", + "name": "hessian", + "signature": "Double -> ([Double] -> Double) -> [Double] -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.Calculus", + "name": "directionalDerivative", + "signature": "Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "jvp", + "signature": "Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "vjp", + "signature": "Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "hvp", + "signature": "Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "divergence", + "signature": "Double -> ([Double] -> [Double]) -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "curl", + "signature": "Double -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "laplacian", + "signature": "Double -> ([Double] -> Double) -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "integrateComposite", + "signature": "Quadrature -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "romberg", + "signature": "Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "gaussLegendre", + "signature": "Int -> (Double -> Double) -> Double -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "gaussHermite", + "signature": "Int -> (Double -> Double) -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "gaussLaguerre", + "signature": "Int -> (Double -> Double) -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "gaussChebyshev", + "signature": "Int -> (Double -> Double) -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "gaussKronrod", + "signature": "(Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "adaptiveIntegrate", + "signature": "Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "clenshawCurtis", + "signature": "Int -> (Double -> Double) -> Double -> Double -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "tanhSinh", + "signature": "Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "integrateInfinite", + "signature": "Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "integrateOscillatory", + "signature": "Bool -> Double -> Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "integrateND", + "signature": "Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "monteCarlo", + "signature": "Integer -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "quasiMonteCarlo", + "signature": "Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "cumulativeIntegral", + "signature": "[(Double, Double)] -> Either MathError [Double]" + }, + { + "module": "HMath.Calculus", + "name": "pathIntegral", + "signature": "Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> Double) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "lineIntegral", + "signature": "Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> Either MathError (Estimate Double)" + }, + { + "module": "HMath.Calculus", + "name": "surfaceIntegral", + "signature": "Int -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double" + }, + { + "module": "HMath.Calculus", + "name": "volumeIntegral", + "signature": "Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double" + }, + { + "module": "HMath.Root", + "name": "RootOptions", + "signature": "Int -> Int -> Double -> Double -> RootOptions" + }, + { + "module": "HMath.Root", + "name": "rootMaxIterations", + "signature": "RootOptions -> Int" + }, + { + "module": "HMath.Root", + "name": "rootMaxEvaluations", + "signature": "RootOptions -> Int" + }, + { + "module": "HMath.Root", + "name": "rootTolerance", + "signature": "RootOptions -> Double" + }, + { + "module": "HMath.Root", + "name": "rootStepTolerance", + "signature": "RootOptions -> Double" + }, + { + "module": "HMath.Root", + "name": "defaultRootOptions", + "signature": "RootOptions" + }, + { + "module": "HMath.Root", + "name": "RootResult", + "signature": "Double -> Double -> Maybe Double -> Int -> Int -> RootResult" + }, + { + "module": "HMath.Root", + "name": "rootValue", + "signature": "RootResult -> Double" + }, + { + "module": "HMath.Root", + "name": "rootResidual", + "signature": "RootResult -> Double" + }, + { + "module": "HMath.Root", + "name": "rootErrorBound", + "signature": "RootResult -> Maybe Double" + }, + { + "module": "HMath.Root", + "name": "rootIterations", + "signature": "RootResult -> Int" + }, + { + "module": "HMath.Root", + "name": "rootEvaluations", + "signature": "RootResult -> Int" + }, + { + "module": "HMath.Root", + "name": "Bisection", + "signature": "BracketMethod" + }, + { + "module": "HMath.Root", + "name": "RegulaFalsi", + "signature": "BracketMethod" + }, + { + "module": "HMath.Root", + "name": "Illinois", + "signature": "BracketMethod" + }, + { + "module": "HMath.Root", + "name": "Brent", + "signature": "BracketMethod" + }, + { + "module": "HMath.Root", + "name": "Ridder", + "signature": "BracketMethod" + }, + { + "module": "HMath.Root", + "name": "Newton", + "signature": "DerivativeMethod" + }, + { + "module": "HMath.Root", + "name": "Halley", + "signature": "DerivativeMethod" + }, + { + "module": "HMath.Root", + "name": "Householder3", + "signature": "DerivativeMethod" + }, + { + "module": "HMath.Root", + "name": "Picard", + "signature": "FixedPointMethod" + }, + { + "module": "HMath.Root", + "name": "Aitken", + "signature": "FixedPointMethod" + }, + { + "module": "HMath.Root", + "name": "SteffensenFixed", + "signature": "FixedPointMethod" + }, + { + "module": "HMath.Root", + "name": "MultivariateNewton", + "signature": "SystemMethod" + }, + { + "module": "HMath.Root", + "name": "NewtonTrustRegion", + "signature": "Double -> SystemMethod" + }, + { + "module": "HMath.Root", + "name": "Broyden", + "signature": "SystemMethod" + }, + { + "module": "HMath.Root", + "name": "SystemRootResult", + "signature": "[Double] -> Double -> Int -> Int -> SystemRootResult" + }, + { + "module": "HMath.Root", + "name": "systemRoot", + "signature": "SystemRootResult -> [Double]" + }, + { + "module": "HMath.Root", + "name": "systemResidual", + "signature": "SystemRootResult -> Double" + }, + { + "module": "HMath.Root", + "name": "systemIterations", + "signature": "SystemRootResult -> Int" + }, + { + "module": "HMath.Root", + "name": "systemEvaluations", + "signature": "SystemRootResult -> Int" + }, + { + "module": "HMath.Root", + "name": "bracket", + "signature": "(Double -> Double) -> Double -> Double -> Either MathError Bracket" + }, + { + "module": "HMath.Root", + "name": "solveBracket", + "signature": "BracketMethod -> RootOptions -> (Double -> Double) -> Bracket -> Either MathError RootResult" + }, + { + "module": "HMath.Root", + "name": "bracketScan", + "signature": "RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [Bracket]" + }, + { + "module": "HMath.Root", + "name": "isolateIntervals", + "signature": "RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [RootResult]" + }, + { + "module": "HMath.Root", + "name": "solveDerivative", + "signature": "DerivativeMethod -> RootOptions -> (Double -> Double) -> [Double -> Double] -> Double -> Either MathError RootResult" + }, + { + "module": "HMath.Root", + "name": "secant", + "signature": "RootOptions -> (Double -> Double) -> Double -> Double -> Either MathError RootResult" + }, + { + "module": "HMath.Root", + "name": "steffensen", + "signature": "RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult" + }, + { + "module": "HMath.Root", + "name": "fixedPoint", + "signature": "FixedPointMethod -> RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult" + }, + { + "module": "HMath.Root", + "name": "anderson", + "signature": "Int -> Double -> RootOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError SystemRootResult" + }, + { + "module": "HMath.Root", + "name": "solveSystem", + "signature": "SystemMethod -> RootOptions -> ([Double] -> [Double]) -> ([Double] -> [[Double]]) -> [Double] -> Either MathError SystemRootResult" + }, + { + "module": "HMath.Root", + "name": "polynomialRoots", + "signature": "RootOptions -> P.Polynomial (Complex Double) -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Root", + "name": "realPolynomialRoots", + "signature": "Int -> Rational -> P.Polynomial Rational -> Either MathError [(Rational, Rational, Int)]" + }, + { + "module": "HMath.ODE", + "name": "Euler", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "Heun", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "Midpoint", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "RK2", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "RK4", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "RK23", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "RK45", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "DormandPrince", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "DOP853", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "AdamsBashforth", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "AdamsMoulton", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "PredictorCorrector", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "BackwardEuler", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "BDF", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "Radau", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "Rosenbrock", + "signature": "Method" + }, + { + "module": "HMath.ODE", + "name": "ODEOptions", + "signature": "Double -> Double -> Double -> Double -> Double -> Int -> Int -> ODEOptions" + }, + { + "module": "HMath.ODE", + "name": "odeAbsoluteTolerance", + "signature": "ODEOptions -> Double" + }, + { + "module": "HMath.ODE", + "name": "odeRelativeTolerance", + "signature": "ODEOptions -> Double" + }, + { + "module": "HMath.ODE", + "name": "initialStep", + "signature": "ODEOptions -> Double" + }, + { + "module": "HMath.ODE", + "name": "minimumStep", + "signature": "ODEOptions -> Double" + }, + { + "module": "HMath.ODE", + "name": "maximumStep", + "signature": "ODEOptions -> Double" + }, + { + "module": "HMath.ODE", + "name": "maximumSteps", + "signature": "ODEOptions -> Int" + }, + { + "module": "HMath.ODE", + "name": "newtonIterations", + "signature": "ODEOptions -> Int" + }, + { + "module": "HMath.ODE", + "name": "defaultODEOptions", + "signature": "ODEOptions" + }, + { + "module": "HMath.ODE", + "name": "Trajectory", + "signature": "[Double] -> [[Double]] -> [[Double]] -> Trajectory" + }, + { + "module": "HMath.ODE", + "name": "trajectoryTimes", + "signature": "Trajectory -> [Double]" + }, + { + "module": "HMath.ODE", + "name": "trajectoryStates", + "signature": "Trajectory -> [[Double]]" + }, + { + "module": "HMath.ODE", + "name": "trajectoryDerivatives", + "signature": "Trajectory -> [[Double]]" + }, + { + "module": "HMath.ODE", + "name": "solveIVP", + "signature": "Method -> ODEOptions -> Int -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "solveAdaptive", + "signature": "Method -> ODEOptions -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "interpolateTrajectory", + "signature": "Trajectory -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.ODE", + "name": "AnyDirection", + "signature": "EventDirection" + }, + { + "module": "HMath.ODE", + "name": "Rising", + "signature": "EventDirection" + }, + { + "module": "HMath.ODE", + "name": "Falling", + "signature": "EventDirection" + }, + { + "module": "HMath.ODE", + "name": "Event", + "signature": "Double -> [Double] -> Event" + }, + { + "module": "HMath.ODE", + "name": "eventTime", + "signature": "Event -> Double" + }, + { + "module": "HMath.ODE", + "name": "eventState", + "signature": "Event -> [Double]" + }, + { + "module": "HMath.ODE", + "name": "locateEvents", + "signature": "EventDirection -> Double -> (Double -> [Double] -> Double) -> Trajectory -> Either MathError [Event]" + }, + { + "module": "HMath.ODE", + "name": "solveBoundary", + "signature": "Method -> ODEOptions -> Int -> ODE -> ([Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "solveDAE", + "signature": "ODEOptions -> Int -> (Double -> [Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "SymplecticEuler", + "signature": "HamiltonianMethod" + }, + { + "module": "HMath.ODE", + "name": "Verlet", + "signature": "HamiltonianMethod" + }, + { + "module": "HMath.ODE", + "name": "Leapfrog", + "signature": "HamiltonianMethod" + }, + { + "module": "HMath.ODE", + "name": "solveHamiltonian", + "signature": "HamiltonianMethod -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "solveNystrom", + "signature": "Int -> (Double -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory" + }, + { + "module": "HMath.ODE", + "name": "sensitivities", + "signature": "Method -> ODEOptions -> Int -> Double -> ([Double] -> ODE) -> [Double] -> Double -> Double -> [Double] -> Either MathError (Matrix Double)" + }, + { + "module": "HMath.ODE", + "name": "equilibrium", + "signature": "ODEOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.ODE", + "name": "phaseTrajectories", + "signature": "Method -> ODEOptions -> Int -> ([Double] -> [Double]) -> Double -> Double -> [[Double]] -> Either MathError [Trajectory]" + }, + { + "module": "HMath.ODE", + "name": "lyapunovExponents", + "signature": "ODEOptions -> Int -> Double -> ODE -> Double -> Double -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.PDE", + "name": "Dirichlet", + "signature": "Double -> Boundary" + }, + { + "module": "HMath.PDE", + "name": "Neumann", + "signature": "Double -> Boundary" + }, + { + "module": "HMath.PDE", + "name": "Robin", + "signature": "Double -> Double -> Double -> Boundary" + }, + { + "module": "HMath.PDE", + "name": "Periodic", + "signature": "Boundary" + }, + { + "module": "HMath.PDE", + "name": "FiniteDifference", + "signature": "Discretization" + }, + { + "module": "HMath.PDE", + "name": "FiniteVolume", + "signature": "Discretization" + }, + { + "module": "HMath.PDE", + "name": "FiniteElement", + "signature": "Discretization" + }, + { + "module": "HMath.PDE", + "name": "PDEResult", + "signature": "[Double] -> Double -> Double -> PDEResult" + }, + { + "module": "HMath.PDE", + "name": "pdeValues", + "signature": "PDEResult -> [Double]" + }, + { + "module": "HMath.PDE", + "name": "pdeResidual", + "signature": "PDEResult -> Double" + }, + { + "module": "HMath.PDE", + "name": "pdeErrorEstimate", + "signature": "PDEResult -> Double" + }, + { + "module": "HMath.PDE", + "name": "grid", + "signature": "[Int] -> [(Double, Double)] -> [Bool] -> Either MathError Grid" + }, + { + "module": "HMath.PDE", + "name": "gridShape", + "signature": "Grid -> [Int]" + }, + { + "module": "HMath.PDE", + "name": "gridSpacing", + "signature": "Grid -> [Double]" + }, + { + "module": "HMath.PDE", + "name": "flattenIndex", + "signature": "Grid -> [Int] -> Either MathError Int" + }, + { + "module": "HMath.PDE", + "name": "unflattenIndex", + "signature": "Grid -> Int -> Either MathError [Int]" + }, + { + "module": "HMath.PDE", + "name": "gridCoordinates", + "signature": "Grid -> [[Double]]" + }, + { + "module": "HMath.PDE", + "name": "assemblePDE", + "signature": "Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Double -> Either MathError PDEOperator" + }, + { + "module": "HMath.PDE", + "name": "pdeStiffness", + "signature": "PDEOperator -> S.Sparse Double" + }, + { + "module": "HMath.PDE", + "name": "pdeMass", + "signature": "PDEOperator -> S.Sparse Double" + }, + { + "module": "HMath.PDE", + "name": "pdeBoundaryLoad", + "signature": "PDEOperator -> [Double]" + }, + { + "module": "HMath.PDE", + "name": "solveElliptic", + "signature": "PDEOperator -> [Double] -> Either MathError PDEResult" + }, + { + "module": "HMath.PDE", + "name": "poisson", + "signature": "Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError PDEResult" + }, + { + "module": "HMath.PDE", + "name": "laplace", + "signature": "Discretization -> Grid -> [(Boundary, Boundary)] -> Either MathError PDEResult" + }, + { + "module": "HMath.PDE", + "name": "helmholtz", + "signature": "Discretization -> Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> Either MathError PDEResult" + }, + { + "module": "HMath.PDE", + "name": "spatialGradient", + "signature": "Grid -> [Double] -> Either MathError [[Double]]" + }, + { + "module": "HMath.PDE", + "name": "laplacianStencil", + "signature": "Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.PDE", + "name": "spectralDerivative", + "signature": "Grid -> Int -> Int -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.PDE", + "name": "spectralLaplacian", + "signature": "Grid -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.PDE", + "name": "spectralPoisson", + "signature": "Grid -> Double -> [Double] -> Either MathError PDEResult" + }, + { + "module": "HMath.PDE", + "name": "pseudoSpectralDiffusion", + "signature": "Grid -> [Double] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.PDE", + "name": "methodOfLines", + "signature": "O.Method -> PDEOperator -> (Double -> [Double]) -> [Double] -> [Double] -> Either MathError O.Trajectory" + }, + { + "module": "HMath.PDE", + "name": "heat", + "signature": "Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> [Double] -> Either MathError O.Trajectory" + }, + { + "module": "HMath.PDE", + "name": "diffusion", + "signature": "Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> [Double] -> [Double] -> Either MathError O.Trajectory" + }, + { + "module": "HMath.PDE", + "name": "wave", + "signature": "Grid -> Double -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]]" + }, + { + "module": "HMath.PDE", + "name": "advection", + "signature": "Grid -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]]" + }, + { + "module": "HMath.PDE", + "name": "advectionDiffusion", + "signature": "Grid -> [Double] -> Double -> [Double] -> [Double] -> Either MathError [[Double]]" + }, + { + "module": "HMath.PDE", + "name": "stabilityLimit", + "signature": "Grid -> Double -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.PDE", + "name": "cflNumber", + "signature": "Grid -> Double -> [Double] -> Double -> Either MathError Double" + }, + { + "module": "HMath.PDE", + "name": "manufacturedError", + "signature": "Grid -> ([Double] -> Double) -> [Double] -> Either MathError Double" + } + ] +} diff --git a/bindings/schema/numerical-objects.json b/bindings/schema/numerical-objects.json new file mode 100644 index 0000000..44964b4 --- /dev/null +++ b/bindings/schema/numerical-objects.json @@ -0,0 +1,2005 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Calculus.Difference", + "c": [ + "hmath_calculus_difference_object" + ], + "python": "hmath.calculus.Difference", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Calculus.Quadrature", + "c": [ + "hmath_calculus_quadrature_object" + ], + "python": "hmath.calculus.Quadrature", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Root.Bracket", + "c": [ + "hmath_root_bracket_object" + ], + "python": "hmath.root.Bracket", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Root.BracketMethod", + "c": [ + "hmath_root_bracket_method_object" + ], + "python": "hmath.root.BracketMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Root.DerivativeMethod", + "c": [ + "hmath_root_derivative_method_object" + ], + "python": "hmath.root.DerivativeMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Root.FixedPointMethod", + "c": [ + "hmath_root_fixed_point_method_object" + ], + "python": "hmath.root.FixedPointMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Root.SystemMethod", + "c": [ + "hmath_root_system_method_object" + ], + "python": "hmath.root.SystemMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.ODE.Method", + "c": [ + "hmath_ode_method_object" + ], + "python": "hmath.ode.Method", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.ODE.EventDirection", + "c": [ + "hmath_ode_event_direction_object" + ], + "python": "hmath.ode.EventDirection", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.ODE.HamiltonianMethod", + "c": [ + "hmath_ode_hamiltonian_method_object" + ], + "python": "hmath.ode.HamiltonianMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.PDE.Grid", + "c": [ + "hmath_pde_grid_object" + ], + "python": "hmath.pde.Grid", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.PDE.Boundary", + "c": [ + "hmath_pde_boundary_object" + ], + "python": "hmath.pde.Boundary", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.PDE.Discretization", + "c": [ + "hmath_pde_discretization_object" + ], + "python": "hmath.pde.Discretization", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.PDE.PDEOperator", + "c": [ + "hmath_pde_pde_operator_object" + ], + "python": "hmath.pde.PDEOperator", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.ODE.ODE", + "c": [ + "hmath_linear_callback_fn" + ], + "python": "hmath.ode.ODE", + "specializations": [ + "Double -> [Double] -> [Double], flat positional callback" + ] + }, + { + "symbol": "HMath.Calculus.Estimate", + "c": [ + "hmath_calculus_estimate" + ], + "python": "hmath.calculus.estimate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.estimateValue", + "c": [ + "hmath_calculus_estimate_value" + ], + "python": "hmath.calculus.estimate_value", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.estimateError", + "c": [ + "hmath_calculus_estimate_error" + ], + "python": "hmath.calculus.estimate_error", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.evaluations", + "c": [ + "hmath_calculus_evaluations" + ], + "python": "hmath.calculus.evaluations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Tolerance", + "c": [ + "hmath_calculus_tolerance" + ], + "python": "hmath.calculus.tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.absoluteTolerance", + "c": [ + "hmath_calculus_absolute_tolerance" + ], + "python": "hmath.calculus.absolute_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.relativeTolerance", + "c": [ + "hmath_calculus_relative_tolerance" + ], + "python": "hmath.calculus.relative_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.maximumEvaluations", + "c": [ + "hmath_calculus_maximum_evaluations" + ], + "python": "hmath.calculus.maximum_evaluations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.defaultTolerance", + "c": [ + "hmath_calculus_default_tolerance" + ], + "python": "hmath.calculus.default_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Forward", + "c": [ + "hmath_calculus_forward" + ], + "python": "hmath.calculus.forward", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Backward", + "c": [ + "hmath_calculus_backward" + ], + "python": "hmath.calculus.backward", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Central", + "c": [ + "hmath_calculus_central" + ], + "python": "hmath.calculus.central", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Trapezoidal", + "c": [ + "hmath_calculus_trapezoidal" + ], + "python": "hmath.calculus.trapezoidal", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.Simpson", + "c": [ + "hmath_calculus_simpson" + ], + "python": "hmath.calculus.simpson", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.ThreeEighths", + "c": [ + "hmath_calculus_three_eighths" + ], + "python": "hmath.calculus.three_eighths", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.derivative", + "c": [ + "hmath_calculus_derivative" + ], + "python": "hmath.calculus.derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.derivativeN", + "c": [ + "hmath_calculus_derivative_n" + ], + "python": "hmath.calculus.derivative_n", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.complexDerivative", + "c": [ + "hmath_calculus_complex_derivative" + ], + "python": "hmath.calculus.complex_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.richardson", + "c": [ + "hmath_calculus_richardson" + ], + "python": "hmath.calculus.richardson", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.ridders", + "c": [ + "hmath_calculus_ridders" + ], + "python": "hmath.calculus.ridders", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.limit", + "c": [ + "hmath_calculus_limit" + ], + "python": "hmath.calculus.limit", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.partialDerivative", + "c": [ + "hmath_calculus_partial_derivative" + ], + "python": "hmath.calculus.partial_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gradient", + "c": [ + "hmath_calculus_gradient" + ], + "python": "hmath.calculus.gradient", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.jacobian", + "c": [ + "hmath_calculus_jacobian" + ], + "python": "hmath.calculus.jacobian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.hessian", + "c": [ + "hmath_calculus_hessian" + ], + "python": "hmath.calculus.hessian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.directionalDerivative", + "c": [ + "hmath_calculus_directional_derivative" + ], + "python": "hmath.calculus.directional_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.jvp", + "c": [ + "hmath_calculus_jvp" + ], + "python": "hmath.calculus.jvp", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.vjp", + "c": [ + "hmath_calculus_vjp" + ], + "python": "hmath.calculus.vjp", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.hvp", + "c": [ + "hmath_calculus_hvp" + ], + "python": "hmath.calculus.hvp", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.divergence", + "c": [ + "hmath_calculus_divergence" + ], + "python": "hmath.calculus.divergence", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.curl", + "c": [ + "hmath_calculus_curl" + ], + "python": "hmath.calculus.curl", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.laplacian", + "c": [ + "hmath_calculus_laplacian" + ], + "python": "hmath.calculus.laplacian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.integrateComposite", + "c": [ + "hmath_calculus_integrate_composite" + ], + "python": "hmath.calculus.integrate_composite", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.romberg", + "c": [ + "hmath_calculus_romberg" + ], + "python": "hmath.calculus.romberg", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gaussLegendre", + "c": [ + "hmath_calculus_gauss_legendre" + ], + "python": "hmath.calculus.gauss_legendre", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gaussHermite", + "c": [ + "hmath_calculus_gauss_hermite" + ], + "python": "hmath.calculus.gauss_hermite", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gaussLaguerre", + "c": [ + "hmath_calculus_gauss_laguerre" + ], + "python": "hmath.calculus.gauss_laguerre", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gaussChebyshev", + "c": [ + "hmath_calculus_gauss_chebyshev" + ], + "python": "hmath.calculus.gauss_chebyshev", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.gaussKronrod", + "c": [ + "hmath_calculus_gauss_kronrod" + ], + "python": "hmath.calculus.gauss_kronrod", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.adaptiveIntegrate", + "c": [ + "hmath_calculus_adaptive_integrate" + ], + "python": "hmath.calculus.adaptive_integrate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.clenshawCurtis", + "c": [ + "hmath_calculus_clenshaw_curtis" + ], + "python": "hmath.calculus.clenshaw_curtis", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.tanhSinh", + "c": [ + "hmath_calculus_tanh_sinh" + ], + "python": "hmath.calculus.tanh_sinh", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.integrateInfinite", + "c": [ + "hmath_calculus_integrate_infinite" + ], + "python": "hmath.calculus.integrate_infinite", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.integrateOscillatory", + "c": [ + "hmath_calculus_integrate_oscillatory" + ], + "python": "hmath.calculus.integrate_oscillatory", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.integrateND", + "c": [ + "hmath_calculus_integrate_nd" + ], + "python": "hmath.calculus.integrate_nd", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.monteCarlo", + "c": [ + "hmath_calculus_monte_carlo" + ], + "python": "hmath.calculus.monte_carlo", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.quasiMonteCarlo", + "c": [ + "hmath_calculus_quasi_monte_carlo" + ], + "python": "hmath.calculus.quasi_monte_carlo", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.cumulativeIntegral", + "c": [ + "hmath_calculus_cumulative_integral" + ], + "python": "hmath.calculus.cumulative_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.pathIntegral", + "c": [ + "hmath_calculus_path_integral" + ], + "python": "hmath.calculus.path_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.lineIntegral", + "c": [ + "hmath_calculus_line_integral" + ], + "python": "hmath.calculus.line_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.surfaceIntegral", + "c": [ + "hmath_calculus_surface_integral" + ], + "python": "hmath.calculus.surface_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Calculus.volumeIntegral", + "c": [ + "hmath_calculus_volume_integral" + ], + "python": "hmath.calculus.volume_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.RootOptions", + "c": [ + "hmath_root_root_options" + ], + "python": "hmath.root.root_options", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootMaxIterations", + "c": [ + "hmath_root_root_max_iterations" + ], + "python": "hmath.root.root_max_iterations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootMaxEvaluations", + "c": [ + "hmath_root_root_max_evaluations" + ], + "python": "hmath.root.root_max_evaluations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootTolerance", + "c": [ + "hmath_root_root_tolerance" + ], + "python": "hmath.root.root_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootStepTolerance", + "c": [ + "hmath_root_root_step_tolerance" + ], + "python": "hmath.root.root_step_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.defaultRootOptions", + "c": [ + "hmath_root_default_root_options" + ], + "python": "hmath.root.default_root_options", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.RootResult", + "c": [ + "hmath_root_root_result" + ], + "python": "hmath.root.root_result", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootValue", + "c": [ + "hmath_root_root_value" + ], + "python": "hmath.root.root_value", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootResidual", + "c": [ + "hmath_root_root_residual" + ], + "python": "hmath.root.root_residual", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootErrorBound", + "c": [ + "hmath_root_root_error_bound" + ], + "python": "hmath.root.root_error_bound", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootIterations", + "c": [ + "hmath_root_root_iterations" + ], + "python": "hmath.root.root_iterations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.rootEvaluations", + "c": [ + "hmath_root_root_evaluations" + ], + "python": "hmath.root.root_evaluations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Bisection", + "c": [ + "hmath_root_bisection" + ], + "python": "hmath.root.bisection", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.RegulaFalsi", + "c": [ + "hmath_root_regula_falsi" + ], + "python": "hmath.root.regula_falsi", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Illinois", + "c": [ + "hmath_root_illinois" + ], + "python": "hmath.root.illinois", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Brent", + "c": [ + "hmath_root_brent" + ], + "python": "hmath.root.brent", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Ridder", + "c": [ + "hmath_root_ridder" + ], + "python": "hmath.root.ridder", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Newton", + "c": [ + "hmath_root_newton" + ], + "python": "hmath.root.newton", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Halley", + "c": [ + "hmath_root_halley" + ], + "python": "hmath.root.halley", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Householder3", + "c": [ + "hmath_root_householder3" + ], + "python": "hmath.root.householder3", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Picard", + "c": [ + "hmath_root_picard" + ], + "python": "hmath.root.picard", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Aitken", + "c": [ + "hmath_root_aitken" + ], + "python": "hmath.root.aitken", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.SteffensenFixed", + "c": [ + "hmath_root_steffensen_fixed" + ], + "python": "hmath.root.steffensen_fixed", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.MultivariateNewton", + "c": [ + "hmath_root_multivariate_newton" + ], + "python": "hmath.root.multivariate_newton", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.NewtonTrustRegion", + "c": [ + "hmath_root_newton_trust_region" + ], + "python": "hmath.root.newton_trust_region", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.Broyden", + "c": [ + "hmath_root_broyden" + ], + "python": "hmath.root.broyden", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.SystemRootResult", + "c": [ + "hmath_root_system_root_result" + ], + "python": "hmath.root.system_root_result", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.systemRoot", + "c": [ + "hmath_root_system_root" + ], + "python": "hmath.root.system_root", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.systemResidual", + "c": [ + "hmath_root_system_residual" + ], + "python": "hmath.root.system_residual", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.systemIterations", + "c": [ + "hmath_root_system_iterations" + ], + "python": "hmath.root.system_iterations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.systemEvaluations", + "c": [ + "hmath_root_system_evaluations" + ], + "python": "hmath.root.system_evaluations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.bracket", + "c": [ + "hmath_root_bracket" + ], + "python": "hmath.root.bracket", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.solveBracket", + "c": [ + "hmath_root_solve_bracket" + ], + "python": "hmath.root.solve_bracket", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.bracketScan", + "c": [ + "hmath_root_bracket_scan" + ], + "python": "hmath.root.bracket_scan", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.isolateIntervals", + "c": [ + "hmath_root_isolate_intervals" + ], + "python": "hmath.root.isolate_intervals", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.solveDerivative", + "c": [ + "hmath_root_solve_derivative" + ], + "python": "hmath.root.solve_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.secant", + "c": [ + "hmath_root_secant" + ], + "python": "hmath.root.secant", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.steffensen", + "c": [ + "hmath_root_steffensen" + ], + "python": "hmath.root.steffensen", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.fixedPoint", + "c": [ + "hmath_root_fixed_point" + ], + "python": "hmath.root.fixed_point", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.anderson", + "c": [ + "hmath_root_anderson" + ], + "python": "hmath.root.anderson", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.solveSystem", + "c": [ + "hmath_root_solve_system" + ], + "python": "hmath.root.solve_system", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.polynomialRoots", + "c": [ + "hmath_root_polynomial_roots" + ], + "python": "hmath.root.polynomial_roots", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Root.realPolynomialRoots", + "c": [ + "hmath_root_real_polynomial_roots" + ], + "python": "hmath.root.real_polynomial_roots", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Euler", + "c": [ + "hmath_ode_euler" + ], + "python": "hmath.ode.euler", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Heun", + "c": [ + "hmath_ode_heun" + ], + "python": "hmath.ode.heun", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Midpoint", + "c": [ + "hmath_ode_midpoint" + ], + "python": "hmath.ode.midpoint", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.RK2", + "c": [ + "hmath_ode_rk2" + ], + "python": "hmath.ode.rk2", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.RK4", + "c": [ + "hmath_ode_rk4" + ], + "python": "hmath.ode.rk4", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.RK23", + "c": [ + "hmath_ode_rk23" + ], + "python": "hmath.ode.rk23", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.RK45", + "c": [ + "hmath_ode_rk45" + ], + "python": "hmath.ode.rk45", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.DormandPrince", + "c": [ + "hmath_ode_dormand_prince" + ], + "python": "hmath.ode.dormand_prince", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.DOP853", + "c": [ + "hmath_ode_dop853" + ], + "python": "hmath.ode.dop853", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.AdamsBashforth", + "c": [ + "hmath_ode_adams_bashforth" + ], + "python": "hmath.ode.adams_bashforth", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.AdamsMoulton", + "c": [ + "hmath_ode_adams_moulton" + ], + "python": "hmath.ode.adams_moulton", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.PredictorCorrector", + "c": [ + "hmath_ode_predictor_corrector" + ], + "python": "hmath.ode.predictor_corrector", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.BackwardEuler", + "c": [ + "hmath_ode_backward_euler" + ], + "python": "hmath.ode.backward_euler", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.BDF", + "c": [ + "hmath_ode_bdf" + ], + "python": "hmath.ode.bdf", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Radau", + "c": [ + "hmath_ode_radau" + ], + "python": "hmath.ode.radau", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Rosenbrock", + "c": [ + "hmath_ode_rosenbrock" + ], + "python": "hmath.ode.rosenbrock", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.ODEOptions", + "c": [ + "hmath_ode_ode_options" + ], + "python": "hmath.ode.ode_options", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.odeAbsoluteTolerance", + "c": [ + "hmath_ode_ode_absolute_tolerance" + ], + "python": "hmath.ode.ode_absolute_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.odeRelativeTolerance", + "c": [ + "hmath_ode_ode_relative_tolerance" + ], + "python": "hmath.ode.ode_relative_tolerance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.initialStep", + "c": [ + "hmath_ode_initial_step" + ], + "python": "hmath.ode.initial_step", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.minimumStep", + "c": [ + "hmath_ode_minimum_step" + ], + "python": "hmath.ode.minimum_step", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.maximumStep", + "c": [ + "hmath_ode_maximum_step" + ], + "python": "hmath.ode.maximum_step", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.maximumSteps", + "c": [ + "hmath_ode_maximum_steps" + ], + "python": "hmath.ode.maximum_steps", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.newtonIterations", + "c": [ + "hmath_ode_newton_iterations" + ], + "python": "hmath.ode.newton_iterations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.defaultODEOptions", + "c": [ + "hmath_ode_default_ode_options" + ], + "python": "hmath.ode.default_ode_options", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Trajectory", + "c": [ + "hmath_ode_trajectory" + ], + "python": "hmath.ode.trajectory", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.trajectoryTimes", + "c": [ + "hmath_ode_trajectory_times" + ], + "python": "hmath.ode.trajectory_times", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.trajectoryStates", + "c": [ + "hmath_ode_trajectory_states" + ], + "python": "hmath.ode.trajectory_states", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.trajectoryDerivatives", + "c": [ + "hmath_ode_trajectory_derivatives" + ], + "python": "hmath.ode.trajectory_derivatives", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveIVP", + "c": [ + "hmath_ode_solve_ivp" + ], + "python": "hmath.ode.solve_ivp", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveAdaptive", + "c": [ + "hmath_ode_solve_adaptive" + ], + "python": "hmath.ode.solve_adaptive", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.interpolateTrajectory", + "c": [ + "hmath_ode_interpolate_trajectory" + ], + "python": "hmath.ode.interpolate_trajectory", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.AnyDirection", + "c": [ + "hmath_ode_any_direction" + ], + "python": "hmath.ode.any_direction", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Rising", + "c": [ + "hmath_ode_rising" + ], + "python": "hmath.ode.rising", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Falling", + "c": [ + "hmath_ode_falling" + ], + "python": "hmath.ode.falling", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Event", + "c": [ + "hmath_ode_event" + ], + "python": "hmath.ode.event", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.eventTime", + "c": [ + "hmath_ode_event_time" + ], + "python": "hmath.ode.event_time", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.eventState", + "c": [ + "hmath_ode_event_state" + ], + "python": "hmath.ode.event_state", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.locateEvents", + "c": [ + "hmath_ode_locate_events" + ], + "python": "hmath.ode.locate_events", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveBoundary", + "c": [ + "hmath_ode_solve_boundary" + ], + "python": "hmath.ode.solve_boundary", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveDAE", + "c": [ + "hmath_ode_solve_dae" + ], + "python": "hmath.ode.solve_dae", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.SymplecticEuler", + "c": [ + "hmath_ode_symplectic_euler" + ], + "python": "hmath.ode.symplectic_euler", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Verlet", + "c": [ + "hmath_ode_verlet" + ], + "python": "hmath.ode.verlet", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.Leapfrog", + "c": [ + "hmath_ode_leapfrog" + ], + "python": "hmath.ode.leapfrog", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveHamiltonian", + "c": [ + "hmath_ode_solve_hamiltonian" + ], + "python": "hmath.ode.solve_hamiltonian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.solveNystrom", + "c": [ + "hmath_ode_solve_nystrom" + ], + "python": "hmath.ode.solve_nystrom", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.sensitivities", + "c": [ + "hmath_ode_sensitivities" + ], + "python": "hmath.ode.sensitivities", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.equilibrium", + "c": [ + "hmath_ode_equilibrium" + ], + "python": "hmath.ode.equilibrium", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.phaseTrajectories", + "c": [ + "hmath_ode_phase_trajectories" + ], + "python": "hmath.ode.phase_trajectories", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.ODE.lyapunovExponents", + "c": [ + "hmath_ode_lyapunov_exponents" + ], + "python": "hmath.ode.lyapunov_exponents", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.Dirichlet", + "c": [ + "hmath_pde_dirichlet" + ], + "python": "hmath.pde.dirichlet", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.Neumann", + "c": [ + "hmath_pde_neumann" + ], + "python": "hmath.pde.neumann", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.Robin", + "c": [ + "hmath_pde_robin" + ], + "python": "hmath.pde.robin", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.Periodic", + "c": [ + "hmath_pde_periodic" + ], + "python": "hmath.pde.periodic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.FiniteDifference", + "c": [ + "hmath_pde_finite_difference" + ], + "python": "hmath.pde.finite_difference", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.FiniteVolume", + "c": [ + "hmath_pde_finite_volume" + ], + "python": "hmath.pde.finite_volume", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.FiniteElement", + "c": [ + "hmath_pde_finite_element" + ], + "python": "hmath.pde.finite_element", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.PDEResult", + "c": [ + "hmath_pde_pde_result" + ], + "python": "hmath.pde.pde_result", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeValues", + "c": [ + "hmath_pde_pde_values" + ], + "python": "hmath.pde.pde_values", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeResidual", + "c": [ + "hmath_pde_pde_residual" + ], + "python": "hmath.pde.pde_residual", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeErrorEstimate", + "c": [ + "hmath_pde_pde_error_estimate" + ], + "python": "hmath.pde.pde_error_estimate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.grid", + "c": [ + "hmath_pde_grid" + ], + "python": "hmath.pde.grid", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.gridShape", + "c": [ + "hmath_pde_grid_shape" + ], + "python": "hmath.pde.grid_shape", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.gridSpacing", + "c": [ + "hmath_pde_grid_spacing" + ], + "python": "hmath.pde.grid_spacing", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.flattenIndex", + "c": [ + "hmath_pde_flatten_index" + ], + "python": "hmath.pde.flatten_index", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.unflattenIndex", + "c": [ + "hmath_pde_unflatten_index" + ], + "python": "hmath.pde.unflatten_index", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.gridCoordinates", + "c": [ + "hmath_pde_grid_coordinates" + ], + "python": "hmath.pde.grid_coordinates", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.assemblePDE", + "c": [ + "hmath_pde_assemble_pde" + ], + "python": "hmath.pde.assemble_pde", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeStiffness", + "c": [ + "hmath_pde_pde_stiffness" + ], + "python": "hmath.pde.pde_stiffness", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeMass", + "c": [ + "hmath_pde_pde_mass" + ], + "python": "hmath.pde.pde_mass", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pdeBoundaryLoad", + "c": [ + "hmath_pde_pde_boundary_load" + ], + "python": "hmath.pde.pde_boundary_load", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.solveElliptic", + "c": [ + "hmath_pde_solve_elliptic" + ], + "python": "hmath.pde.solve_elliptic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.poisson", + "c": [ + "hmath_pde_poisson" + ], + "python": "hmath.pde.poisson", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.laplace", + "c": [ + "hmath_pde_laplace" + ], + "python": "hmath.pde.laplace", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.helmholtz", + "c": [ + "hmath_pde_helmholtz" + ], + "python": "hmath.pde.helmholtz", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.spatialGradient", + "c": [ + "hmath_pde_spatial_gradient" + ], + "python": "hmath.pde.spatial_gradient", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.laplacianStencil", + "c": [ + "hmath_pde_laplacian_stencil" + ], + "python": "hmath.pde.laplacian_stencil", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.spectralDerivative", + "c": [ + "hmath_pde_spectral_derivative" + ], + "python": "hmath.pde.spectral_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.spectralLaplacian", + "c": [ + "hmath_pde_spectral_laplacian" + ], + "python": "hmath.pde.spectral_laplacian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.spectralPoisson", + "c": [ + "hmath_pde_spectral_poisson" + ], + "python": "hmath.pde.spectral_poisson", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.pseudoSpectralDiffusion", + "c": [ + "hmath_pde_pseudo_spectral_diffusion" + ], + "python": "hmath.pde.pseudo_spectral_diffusion", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.methodOfLines", + "c": [ + "hmath_pde_method_of_lines" + ], + "python": "hmath.pde.method_of_lines", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.heat", + "c": [ + "hmath_pde_heat" + ], + "python": "hmath.pde.heat", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.diffusion", + "c": [ + "hmath_pde_diffusion" + ], + "python": "hmath.pde.diffusion", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.wave", + "c": [ + "hmath_pde_wave" + ], + "python": "hmath.pde.wave", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.advection", + "c": [ + "hmath_pde_advection" + ], + "python": "hmath.pde.advection", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.advectionDiffusion", + "c": [ + "hmath_pde_advection_diffusion" + ], + "python": "hmath.pde.advection_diffusion", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.stabilityLimit", + "c": [ + "hmath_pde_stability_limit" + ], + "python": "hmath.pde.stability_limit", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.cflNumber", + "c": [ + "hmath_pde_cfl_number" + ], + "python": "hmath.pde.cfl_number", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.PDE.manufacturedError", + "c": [ + "hmath_pde_manufactured_error" + ], + "python": "hmath.pde.manufactured_error", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + } + ] +} diff --git a/bindings/schema/objects.json b/bindings/schema/objects.json new file mode 100644 index 0000000..a2d6d76 --- /dev/null +++ b/bindings/schema/objects.json @@ -0,0 +1,167 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Optimization.FirstOrder.initializeOptimizer", + "c": [ + "hmath_initialize_optimizer" + ], + "python": "hmath.optimization.initialize_optimizer", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.optimizerStep", + "c": [ + "hmath_optimizer_step" + ], + "python": "hmath.optimization.optimizer_step", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.OptimizerState", + "c": [ + "hmath_optimizer_state", + "hmath_optimizer_state_retain", + "hmath_optimizer_state_release" + ], + "python": "hmath.optimization.OptimizerState", + "specializations": [ + "Double" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.GradientMethod", + "c": [ + "hmath_gradient_method" + ], + "python": "hmath.optimization.GradientMethod", + "specializations": [ + "enum" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.GradientDescent", + "c": [ + "HMATH_GRADIENT_DESCENT" + ], + "python": "hmath.optimization.GradientMethod.GRADIENT_DESCENT", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Momentum", + "c": [ + "HMATH_MOMENTUM" + ], + "python": "hmath.optimization.GradientMethod.MOMENTUM", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Nesterov", + "c": [ + "HMATH_NESTEROV" + ], + "python": "hmath.optimization.GradientMethod.NESTEROV", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaGrad", + "c": [ + "HMATH_ADAGRAD" + ], + "python": "hmath.optimization.GradientMethod.ADAGRAD", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.RMSProp", + "c": [ + "HMATH_RMSPROP" + ], + "python": "hmath.optimization.GradientMethod.RMSPROP", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaDelta", + "c": [ + "HMATH_ADADELTA" + ], + "python": "hmath.optimization.GradientMethod.ADADELTA", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Adam", + "c": [ + "HMATH_ADAM" + ], + "python": "hmath.optimization.GradientMethod.ADAM", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdamW", + "c": [ + "HMATH_ADAMW" + ], + "python": "hmath.optimization.GradientMethod.ADAMW", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AMSGrad", + "c": [ + "HMATH_AMSGRAD" + ], + "python": "hmath.optimization.GradientMethod.AMSGRAD", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaMax", + "c": [ + "HMATH_ADAMAX" + ], + "python": "hmath.optimization.GradientMethod.ADAMAX", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Nadam", + "c": [ + "HMATH_NADAM" + ], + "python": "hmath.optimization.GradientMethod.NADAM", + "specializations": [ + "enum-constructor" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.RAdam", + "c": [ + "HMATH_RADAM" + ], + "python": "hmath.optimization.GradientMethod.RADAM", + "specializations": [ + "enum-constructor" + ] + } + ] +} diff --git a/bindings/schema/optimization-all-objects.json b/bindings/schema/optimization-all-objects.json new file mode 100644 index 0000000..fbcae02 --- /dev/null +++ b/bindings/schema/optimization-all-objects.json @@ -0,0 +1,1095 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Optimization.Common.OptimizeOptions", + "c": [ + "hmath_optimization_optimize_options_create" + ], + "python": "hmath.optimization.OptimizeOptions", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.defaultOptimizeOptions", + "c": [ + "hmath_optimization_default_optimize_options" + ], + "python": "hmath.optimization.default_optimize_options", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.OptimizeResult", + "c": [ + "hmath_optimization_optimize_result_create" + ], + "python": "hmath.optimization.OptimizeResult", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.EarlyStopping", + "c": [ + "hmath_optimization_early_stopping_create" + ], + "python": "hmath.optimization.EarlyStopping", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.ConstantRate", + "c": [ + "hmath_optimization_constant_rate_create" + ], + "python": "hmath.optimization.ConstantRate", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.StepDecay", + "c": [ + "hmath_optimization_step_decay_create" + ], + "python": "hmath.optimization.StepDecay", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.ExponentialDecay", + "c": [ + "hmath_optimization_exponential_decay_create" + ], + "python": "hmath.optimization.ExponentialDecay", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.CosineAnnealing", + "c": [ + "hmath_optimization_cosine_annealing_create" + ], + "python": "hmath.optimization.CosineAnnealing", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.Warmup", + "c": [ + "hmath_optimization_warmup_create" + ], + "python": "hmath.optimization.Warmup", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.Armijo", + "c": [ + "hmath_optimization_armijo_create" + ], + "python": "hmath.optimization.Armijo", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.StrongWolfe", + "c": [ + "hmath_optimization_strong_wolfe_create" + ], + "python": "hmath.optimization.StrongWolfe", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedOptions", + "c": [ + "hmath_optimization_checked_options" + ], + "python": "hmath.optimization.checked_options", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedPoint", + "c": [ + "hmath_optimization_checked_point" + ], + "python": "hmath.optimization.checked_point", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedValue", + "c": [ + "hmath_optimization_checked_value" + ], + "python": "hmath.optimization.checked_value", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedGradient", + "c": [ + "hmath_optimization_checked_gradient" + ], + "python": "hmath.optimization.checked_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkBudget", + "c": [ + "hmath_optimization_check_budget" + ], + "python": "hmath.optimization.check_budget", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.outer", + "c": [ + "hmath_optimization_outer" + ], + "python": "hmath.optimization.outer", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.identity", + "c": [ + "hmath_optimization_identity" + ], + "python": "hmath.optimization.identity", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.matVec", + "c": [ + "hmath_optimization_mat_vec" + ], + "python": "hmath.optimization.mat_vec", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.matMul", + "c": [ + "hmath_optimization_mat_mul" + ], + "python": "hmath.optimization.mat_mul", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.solveDense", + "c": [ + "hmath_optimization_solve_dense" + ], + "python": "hmath.optimization.solve_dense", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.result", + "c": [ + "hmath_optimization_result" + ], + "python": "hmath.optimization.result", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.learningRate", + "c": [ + "hmath_optimization_learning_rate" + ], + "python": "hmath.optimization.learning_rate", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.earlyStopping", + "c": [ + "hmath_optimization_early_stopping" + ], + "python": "hmath.optimization.early_stopping", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.lineSearch", + "c": [ + "hmath_optimization_line_search" + ], + "python": "hmath.optimization.line_search", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optMaxIterations", + "c": [ + "hmath_optimization_opt_max_iterations" + ], + "python": "hmath.optimization.opt_max_iterations", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optMaxEvaluations", + "c": [ + "hmath_optimization_opt_max_evaluations" + ], + "python": "hmath.optimization.opt_max_evaluations", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optTolerance", + "c": [ + "hmath_optimization_opt_tolerance" + ], + "python": "hmath.optimization.opt_tolerance", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optLearningRate", + "c": [ + "hmath_optimization_opt_learning_rate" + ], + "python": "hmath.optimization.opt_learning_rate", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optPoint", + "c": [ + "hmath_optimization_opt_point" + ], + "python": "hmath.optimization.opt_point", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optValue", + "c": [ + "hmath_optimization_opt_value" + ], + "python": "hmath.optimization.opt_value", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optGradientNorm", + "c": [ + "hmath_optimization_opt_gradient_norm" + ], + "python": "hmath.optimization.opt_gradient_norm", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optIterations", + "c": [ + "hmath_optimization_opt_iterations" + ], + "python": "hmath.optimization.opt_iterations", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optEvaluations", + "c": [ + "hmath_optimization_opt_evaluations" + ], + "python": "hmath.optimization.opt_evaluations", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.optConverged", + "c": [ + "hmath_optimization_opt_converged" + ], + "python": "hmath.optimization.opt_converged", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.bestScore", + "c": [ + "hmath_optimization_best_score" + ], + "python": "hmath.optimization.best_score", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.staleSteps", + "c": [ + "hmath_optimization_stale_steps" + ], + "python": "hmath.optimization.stale_steps", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.stopped", + "c": [ + "hmath_optimization_stopped" + ], + "python": "hmath.optimization.stopped", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.minimizeGradient", + "c": [ + "hmath_optimization_minimize_gradient" + ], + "python": "hmath.optimization.minimize_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.minimizeGradientWithCallback", + "c": [ + "hmath_optimization_minimize_gradient_with_callback" + ], + "python": "hmath.optimization.minimize_gradient_with_callback", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.stochasticGradient", + "c": [ + "hmath_optimization_stochastic_gradient" + ], + "python": "hmath.optimization.stochastic_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.miniBatchGradient", + "c": [ + "hmath_optimization_mini_batch_gradient" + ], + "python": "hmath.optimization.mini_batch_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.projectedGradient", + "c": [ + "hmath_optimization_projected_gradient" + ], + "python": "hmath.optimization.projected_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.proximalGradient", + "c": [ + "hmath_optimization_proximal_gradient" + ], + "python": "hmath.optimization.proximal_gradient", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.fista", + "c": [ + "hmath_optimization_fista" + ], + "python": "hmath.optimization.fista", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.coordinateDescent", + "c": [ + "hmath_optimization_coordinate_descent" + ], + "python": "hmath.optimization.coordinate_descent", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.GoldenSection", + "c": [ + "hmath_optimization_golden_section_create" + ], + "python": "hmath.optimization.GoldenSection", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.TernarySearch", + "c": [ + "hmath_optimization_ternary_search_create" + ], + "python": "hmath.optimization.TernarySearch", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.BrentSearch", + "c": [ + "hmath_optimization_brent_search_create" + ], + "python": "hmath.optimization.BrentSearch", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeScalar", + "c": [ + "hmath_optimization_minimize_scalar" + ], + "python": "hmath.optimization.minimize_scalar", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.BFGS", + "c": [ + "hmath_optimization_bfgs_create" + ], + "python": "hmath.optimization.BFGS", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.DFP", + "c": [ + "hmath_optimization_dfp_create" + ], + "python": "hmath.optimization.DFP", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.SR1", + "c": [ + "hmath_optimization_sr1_create" + ], + "python": "hmath.optimization.SR1", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.LBFGS", + "c": [ + "hmath_optimization_lbfgs_create" + ], + "python": "hmath.optimization.LBFGS", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeQuasiNewton", + "c": [ + "hmath_optimization_minimize_quasi_newton" + ], + "python": "hmath.optimization.minimize_quasi_newton", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.Newton", + "c": [ + "hmath_optimization_newton_create" + ], + "python": "hmath.optimization.Newton", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.NewtonCG", + "c": [ + "hmath_optimization_newton_cg_create" + ], + "python": "hmath.optimization.NewtonCG", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.TrustRegion", + "c": [ + "hmath_optimization_trust_region_create" + ], + "python": "hmath.optimization.TrustRegion", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.Dogleg", + "c": [ + "hmath_optimization_dogleg_create" + ], + "python": "hmath.optimization.Dogleg", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeNewton", + "c": [ + "hmath_optimization_minimize_newton" + ], + "python": "hmath.optimization.minimize_newton", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.nonlinearCG", + "c": [ + "hmath_optimization_nonlinear_cg" + ], + "python": "hmath.optimization.nonlinear_cg", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.SquaredLoss", + "c": [ + "hmath_optimization_squared_loss_create" + ], + "python": "hmath.optimization.SquaredLoss", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.HuberLoss", + "c": [ + "hmath_optimization_huber_loss_create" + ], + "python": "hmath.optimization.HuberLoss", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.CauchyLoss", + "c": [ + "hmath_optimization_cauchy_loss_create" + ], + "python": "hmath.optimization.CauchyLoss", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.SoftL1", + "c": [ + "hmath_optimization_soft_l1_create" + ], + "python": "hmath.optimization.SoftL1", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.leastSquares", + "c": [ + "hmath_optimization_least_squares" + ], + "python": "hmath.optimization.least_squares", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.nelderMead", + "c": [ + "hmath_optimization_nelder_mead" + ], + "python": "hmath.optimization.nelder_mead", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Local.powell", + "c": [ + "hmath_optimization_powell" + ], + "python": "hmath.optimization.powell", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.Equality", + "c": [ + "hmath_optimization_equality_create" + ], + "python": "hmath.optimization.Equality", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LessEqual", + "c": [ + "hmath_optimization_less_equal_create" + ], + "python": "hmath.optimization.LessEqual", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.feasibility", + "c": [ + "hmath_optimization_feasibility" + ], + "python": "hmath.optimization.feasibility", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.QuadraticPenalty", + "c": [ + "hmath_optimization_quadratic_penalty_create" + ], + "python": "hmath.optimization.QuadraticPenalty", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LogBarrier", + "c": [ + "hmath_optimization_log_barrier_create" + ], + "python": "hmath.optimization.LogBarrier", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.InteriorPoint", + "c": [ + "hmath_optimization_interior_point_create" + ], + "python": "hmath.optimization.InteriorPoint", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.AugmentedLagrangian", + "c": [ + "hmath_optimization_augmented_lagrangian_create" + ], + "python": "hmath.optimization.AugmentedLagrangian", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.constrainedMinimize", + "c": [ + "hmath_optimization_constrained_minimize" + ], + "python": "hmath.optimization.constrained_minimize", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LPResult", + "c": [ + "hmath_optimization_lp_result_create" + ], + "python": "hmath.optimization.LPResult", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.linearProgramming", + "c": [ + "hmath_optimization_linear_programming" + ], + "python": "hmath.optimization.linear_programming", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.revisedSimplex", + "c": [ + "hmath_optimization_revised_simplex" + ], + "python": "hmath.optimization.revised_simplex", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.quadraticProgramming", + "c": [ + "hmath_optimization_quadratic_programming" + ], + "python": "hmath.optimization.quadratic_programming", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.slsqp", + "c": [ + "hmath_optimization_slsqp" + ], + "python": "hmath.optimization.slsqp", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.cobyla", + "c": [ + "hmath_optimization_cobyla" + ], + "python": "hmath.optimization.cobyla", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.weightedObjective", + "c": [ + "hmath_optimization_weighted_objective" + ], + "python": "hmath.optimization.weighted_objective", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.paretoFront", + "c": [ + "hmath_optimization_pareto_front" + ], + "python": "hmath.optimization.pareto_front", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpPoint", + "c": [ + "hmath_optimization_lp_point" + ], + "python": "hmath.optimization.lp_point", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpValue", + "c": [ + "hmath_optimization_lp_value" + ], + "python": "hmath.optimization.lp_value", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpBasis", + "c": [ + "hmath_optimization_lp_basis" + ], + "python": "hmath.optimization.lp_basis", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpIterations", + "c": [ + "hmath_optimization_lp_iterations" + ], + "python": "hmath.optimization.lp_iterations", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.SimulatedAnnealing", + "c": [ + "hmath_optimization_simulated_annealing_create" + ], + "python": "hmath.optimization.SimulatedAnnealing", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.DifferentialEvolution", + "c": [ + "hmath_optimization_differential_evolution_create" + ], + "python": "hmath.optimization.DifferentialEvolution", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.GeneticAlgorithm", + "c": [ + "hmath_optimization_genetic_algorithm_create" + ], + "python": "hmath.optimization.GeneticAlgorithm", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.ParticleSwarm", + "c": [ + "hmath_optimization_particle_swarm_create" + ], + "python": "hmath.optimization.ParticleSwarm", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.CMAES", + "c": [ + "hmath_optimization_cmaes_create" + ], + "python": "hmath.optimization.CMAES", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.globalMinimize", + "c": [ + "hmath_optimization_global_minimize" + ], + "python": "hmath.optimization.global_minimize", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Global.basinHopping", + "c": [ + "hmath_optimization_basin_hopping" + ], + "python": "hmath.optimization.basin_hopping", + "specializations": [ + "Double (original fixed type)" + ] + }, + { + "symbol": "HMath.Optimization.Common.Objective", + "c": [ + "hmath_optimization_callback" + ], + "python": "hmath.optimization.Objective", + "specializations": [ + "Double checked callback" + ] + }, + { + "symbol": "HMath.Optimization.Common.Gradient", + "c": [ + "hmath_optimization_callback" + ], + "python": "hmath.optimization.Gradient", + "specializations": [ + "Double checked callback" + ] + }, + { + "symbol": "HMath.Optimization.Common.Hessian", + "c": [ + "hmath_optimization_callback" + ], + "python": "hmath.optimization.Hessian", + "specializations": [ + "Double checked callback" + ] + }, + { + "symbol": "HMath.Optimization.Common.LearningRate", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.LearningRate", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Common.LineSearch", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.LineSearch", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Local.ScalarMethod", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.ScalarMethod", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Local.QuasiNewton", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.QuasiNewton", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Local.NewtonMethod", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.NewtonMethod", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Local.LeastSquaresLoss", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.LeastSquaresLoss", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Local.ResidualFunction", + "c": [ + "hmath_optimization_callback" + ], + "python": "hmath.optimization.ResidualFunction", + "specializations": [ + "Double checked callback" + ] + }, + { + "symbol": "HMath.Optimization.Local.JacobianFunction", + "c": [ + "hmath_optimization_callback" + ], + "python": "hmath.optimization.JacobianFunction", + "specializations": [ + "Double checked callback" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.Constraint", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.Constraint", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.PenaltyMethod", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.PenaltyMethod", + "specializations": [ + "original immutable sum type" + ] + }, + { + "symbol": "HMath.Optimization.Global.GlobalMethod", + "c": [ + "hmath_value" + ], + "python": "hmath.optimization.GlobalMethod", + "specializations": [ + "original immutable sum type" + ] + } + ] +} diff --git a/bindings/schema/optimization.json b/bindings/schema/optimization.json new file mode 100644 index 0000000..31c0f24 --- /dev/null +++ b/bindings/schema/optimization.json @@ -0,0 +1,1777 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Optimization.Common", + "name": "OptimizeOptions", + "python": "optimize_options", + "arguments": [ + "Int", + "Int", + "Double", + "Double" + ], + "result": "Options", + "expression": "C.OptimizeOptions", + "c": "hmath_optimization_optimize_options_create", + "parameters": [ + "max_iterations", + "max_evaluations", + "tolerance", + "learning_rate" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "defaultOptimizeOptions", + "python": "default_optimize_options", + "arguments": [], + "result": "Options", + "expression": "C.defaultOptimizeOptions", + "c": "hmath_optimization_default_optimize_options", + "parameters": [] + }, + { + "module": "HMath.Optimization.Common", + "name": "OptimizeResult", + "python": "optimize_result", + "arguments": [ + "Vector", + "Double", + "Double", + "Int", + "Int", + "Bool" + ], + "result": "Result", + "expression": "C.OptimizeResult", + "c": "hmath_optimization_optimize_result_create", + "parameters": [ + "point", + "value", + "gradient_norm", + "iterations", + "evaluations", + "converged" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "EarlyStopping", + "python": "early_stopping", + "arguments": [ + "MaybeDouble", + "Int", + "Bool" + ], + "result": "EarlyStopping", + "expression": "C.EarlyStopping", + "c": "hmath_optimization_early_stopping_create", + "parameters": [ + "best_score", + "stale_steps", + "stopped" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "ConstantRate", + "python": "constant_rate", + "arguments": [ + "Double" + ], + "result": "LearningRate", + "expression": "C.ConstantRate", + "c": "hmath_optimization_constant_rate_create", + "parameters": [ + "rate" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "StepDecay", + "python": "step_decay", + "arguments": [ + "Double", + "Int", + "Double" + ], + "result": "LearningRate", + "expression": "C.StepDecay", + "c": "hmath_optimization_step_decay_create", + "parameters": [ + "initial_rate", + "period", + "decay" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "ExponentialDecay", + "python": "exponential_decay", + "arguments": [ + "Double", + "Double" + ], + "result": "LearningRate", + "expression": "C.ExponentialDecay", + "c": "hmath_optimization_exponential_decay_create", + "parameters": [ + "initial_rate", + "decay" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "CosineAnnealing", + "python": "cosine_annealing", + "arguments": [ + "Double", + "Double", + "Int" + ], + "result": "LearningRate", + "expression": "C.CosineAnnealing", + "c": "hmath_optimization_cosine_annealing_create", + "parameters": [ + "maximum", + "minimum", + "period" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "Warmup", + "python": "warmup", + "arguments": [ + "Int", + "LearningRate" + ], + "result": "LearningRate", + "expression": "C.Warmup", + "c": "hmath_optimization_warmup_create", + "parameters": [ + "steps", + "base" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "Armijo", + "python": "armijo", + "arguments": [], + "result": "LineSearch", + "expression": "C.Armijo", + "c": "hmath_optimization_armijo_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Common", + "name": "StrongWolfe", + "python": "strong_wolfe", + "arguments": [], + "result": "LineSearch", + "expression": "C.StrongWolfe", + "c": "hmath_optimization_strong_wolfe_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedOptions", + "python": "checked_options", + "arguments": [ + "Options" + ], + "result": "Unit", + "expression": "C.checkedOptions", + "c": "hmath_optimization_checked_options", + "parameters": [ + "options" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedPoint", + "python": "checked_point", + "arguments": [ + "Vector" + ], + "result": "Unit", + "expression": "C.checkedPoint", + "c": "hmath_optimization_checked_point", + "parameters": [ + "point" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedValue", + "python": "checked_value", + "arguments": [ + "Objective", + "Vector" + ], + "result": "Double", + "expression": "C.checkedValue", + "c": "hmath_optimization_checked_value", + "parameters": [ + "objective", + "point" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "checkedGradient", + "python": "checked_gradient", + "arguments": [ + "Gradient", + "Vector" + ], + "result": "Vector", + "expression": "C.checkedGradient", + "c": "hmath_optimization_checked_gradient", + "parameters": [ + "gradient", + "point" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "checkBudget", + "python": "check_budget", + "arguments": [ + "Options", + "Int" + ], + "result": "Unit", + "expression": "C.checkBudget", + "c": "hmath_optimization_check_budget", + "parameters": [ + "options", + "evaluations" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "dot", + "python": "dot", + "arguments": [ + "Vector", + "Vector" + ], + "result": "Value", + "expression": "C.dot", + "c": "hmath_optimization_dot", + "parameters": [ + "left", + "right" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "add", + "python": "add", + "arguments": [ + "Vector", + "Vector" + ], + "result": "Value", + "expression": "C.add", + "c": "hmath_optimization_add", + "parameters": [ + "left", + "right" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "sub", + "python": "sub", + "arguments": [ + "Vector", + "Vector" + ], + "result": "Value", + "expression": "C.sub", + "c": "hmath_optimization_sub", + "parameters": [ + "left", + "right" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "outer", + "python": "outer", + "arguments": [ + "Vector", + "Vector" + ], + "result": "Value", + "expression": "C.outer", + "c": "hmath_optimization_outer", + "parameters": [ + "left", + "right" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "norm", + "python": "norm", + "arguments": [ + "Vector" + ], + "result": "Double", + "expression": "C.norm", + "c": "hmath_optimization_norm", + "parameters": [ + "values" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "scale", + "python": "scale", + "arguments": [ + "Double", + "Vector" + ], + "result": "Vector", + "expression": "C.scale", + "c": "hmath_optimization_scale", + "parameters": [ + "factor", + "values" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "identity", + "python": "identity", + "arguments": [ + "Int" + ], + "result": "Matrix", + "expression": "C.identity", + "c": "hmath_optimization_identity", + "parameters": [ + "dimension" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "matVec", + "python": "mat_vec", + "arguments": [ + "Matrix", + "Vector" + ], + "result": "Vector", + "expression": "C.matVec", + "c": "hmath_optimization_mat_vec", + "parameters": [ + "matrix", + "vector" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "matMul", + "python": "mat_mul", + "arguments": [ + "Matrix", + "Matrix" + ], + "result": "Matrix", + "expression": "C.matMul", + "c": "hmath_optimization_mat_mul", + "parameters": [ + "left", + "right" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "transpose", + "python": "transpose", + "arguments": [ + "GenericMatrix" + ], + "result": "GenericMatrix", + "expression": "(C.transpose :: [[Value]] -> [[Value]])", + "c": "hmath_optimization_transpose", + "parameters": [ + "rows" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "solveDense", + "python": "solve_dense", + "arguments": [ + "Matrix", + "Vector" + ], + "result": "Vector", + "expression": "C.solveDense", + "c": "hmath_optimization_solve_dense", + "parameters": [ + "matrix", + "rhs" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "result", + "python": "result", + "arguments": [ + "Int", + "Int", + "Bool", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "C.result", + "c": "hmath_optimization_result", + "parameters": [ + "iterations", + "evaluations", + "converged", + "objective", + "gradient", + "point" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "learningRate", + "python": "learning_rate", + "arguments": [ + "LearningRate", + "Int" + ], + "result": "Double", + "expression": "C.learningRate", + "c": "hmath_optimization_learning_rate", + "parameters": [ + "schedule", + "step" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "earlyStopping", + "python": "early_stopping", + "arguments": [ + "Int", + "Double", + "Double", + "EarlyStopping" + ], + "result": "EarlyStopping", + "expression": "C.earlyStopping", + "c": "hmath_optimization_early_stopping", + "parameters": [ + "patience", + "min_delta", + "value", + "state" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "lineSearch", + "python": "line_search", + "arguments": [ + "LineSearch", + "Int", + "Objective", + "Gradient", + "Vector", + "Vector", + "Double", + "Vector" + ], + "result": "Tuple", + "expression": "C.lineSearch", + "c": "hmath_optimization_line_search", + "parameters": [ + "method", + "budget", + "objective", + "gradient", + "point", + "direction", + "value", + "point_gradient" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optMaxIterations", + "python": "opt_max_iterations", + "arguments": [ + "Options" + ], + "result": "Value", + "expression": "C.optMaxIterations", + "c": "hmath_optimization_opt_max_iterations", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optMaxEvaluations", + "python": "opt_max_evaluations", + "arguments": [ + "Options" + ], + "result": "Value", + "expression": "C.optMaxEvaluations", + "c": "hmath_optimization_opt_max_evaluations", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optTolerance", + "python": "opt_tolerance", + "arguments": [ + "Options" + ], + "result": "Value", + "expression": "C.optTolerance", + "c": "hmath_optimization_opt_tolerance", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optLearningRate", + "python": "opt_learning_rate", + "arguments": [ + "Options" + ], + "result": "Value", + "expression": "C.optLearningRate", + "c": "hmath_optimization_opt_learning_rate", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optPoint", + "python": "opt_point", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optPoint", + "c": "hmath_optimization_opt_point", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optValue", + "python": "opt_value", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optValue", + "c": "hmath_optimization_opt_value", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optGradientNorm", + "python": "opt_gradient_norm", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optGradientNorm", + "c": "hmath_optimization_opt_gradient_norm", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optIterations", + "python": "opt_iterations", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optIterations", + "c": "hmath_optimization_opt_iterations", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optEvaluations", + "python": "opt_evaluations", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optEvaluations", + "c": "hmath_optimization_opt_evaluations", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "optConverged", + "python": "opt_converged", + "arguments": [ + "Result" + ], + "result": "Value", + "expression": "C.optConverged", + "c": "hmath_optimization_opt_converged", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "bestScore", + "python": "best_score", + "arguments": [ + "EarlyStopping" + ], + "result": "Value", + "expression": "C.bestScore", + "c": "hmath_optimization_best_score", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "staleSteps", + "python": "stale_steps", + "arguments": [ + "EarlyStopping" + ], + "result": "Value", + "expression": "C.staleSteps", + "c": "hmath_optimization_stale_steps", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Common", + "name": "stopped", + "python": "stopped", + "arguments": [ + "EarlyStopping" + ], + "result": "Value", + "expression": "C.stopped", + "c": "hmath_optimization_stopped", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "GradientDescent", + "python": "gradient_descent", + "arguments": [], + "result": "GradientMethod", + "expression": "F.GradientDescent", + "c": "hmath_optimization_gradient_descent_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Momentum", + "python": "momentum", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Momentum", + "c": "hmath_optimization_momentum_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Nesterov", + "python": "nesterov", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Nesterov", + "c": "hmath_optimization_nesterov_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaGrad", + "python": "ada_grad", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaGrad", + "c": "hmath_optimization_ada_grad_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "RMSProp", + "python": "rms_prop", + "arguments": [], + "result": "GradientMethod", + "expression": "F.RMSProp", + "c": "hmath_optimization_rms_prop_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaDelta", + "python": "ada_delta", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaDelta", + "c": "hmath_optimization_ada_delta_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Adam", + "python": "adam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Adam", + "c": "hmath_optimization_adam_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdamW", + "python": "adam_w", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdamW", + "c": "hmath_optimization_adam_w_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AMSGrad", + "python": "ams_grad", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AMSGrad", + "c": "hmath_optimization_ams_grad_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "AdaMax", + "python": "ada_max", + "arguments": [], + "result": "GradientMethod", + "expression": "F.AdaMax", + "c": "hmath_optimization_ada_max_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "Nadam", + "python": "nadam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.Nadam", + "c": "hmath_optimization_nadam_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "RAdam", + "python": "r_adam", + "arguments": [], + "result": "GradientMethod", + "expression": "F.RAdam", + "c": "hmath_optimization_r_adam_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "initializeOptimizer", + "python": "initialize_optimizer", + "arguments": [ + "Int" + ], + "result": "State", + "expression": "F.initializeOptimizer", + "c": "hmath_optimization_initialize_optimizer", + "parameters": [ + "dimension" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "optimizerStep", + "python": "optimizer_step", + "arguments": [ + "GradientMethod", + "Double", + "State", + "Vector", + "Vector" + ], + "result": "Tuple", + "expression": "F.optimizerStep", + "c": "hmath_optimization_optimizer_step", + "parameters": [ + "method", + "rate", + "state", + "parameters", + "gradient" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "minimizeGradient", + "python": "minimize_gradient", + "arguments": [ + "GradientMethod", + "Options", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "F.minimizeGradient", + "c": "hmath_optimization_minimize_gradient", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "minimizeGradientWithCallback", + "python": "minimize_gradient_with_callback", + "arguments": [ + "Monitor", + "GradientMethod", + "Options", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "F.minimizeGradientWithCallback", + "c": "hmath_optimization_minimize_gradient_with_callback", + "parameters": [ + "monitor", + "method", + "options", + "objective", + "gradient", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "stochasticGradient", + "python": "stochastic_gradient", + "arguments": [ + "GradientMethod", + "Double", + "Gradients", + "Vector" + ], + "result": "Tuple", + "expression": "F.stochasticGradient", + "c": "hmath_optimization_stochastic_gradient", + "parameters": [ + "method", + "rate", + "gradients", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "miniBatchGradient", + "python": "mini_batch_gradient", + "arguments": [ + "Gradients" + ], + "result": "Function", + "expression": "(\\values -> functionValue (GradientFn (F.miniBatchGradient values)))", + "c": "hmath_optimization_mini_batch_gradient", + "parameters": [ + "gradients" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "projectedGradient", + "python": "projected_gradient", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "F.projectedGradient", + "c": "hmath_optimization_projected_gradient", + "parameters": [ + "options", + "objective", + "gradient", + "project", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "proximalGradient", + "python": "proximal_gradient", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Prox", + "Vector" + ], + "result": "Result", + "expression": "F.proximalGradient", + "c": "hmath_optimization_proximal_gradient", + "parameters": [ + "options", + "objective", + "gradient", + "prox", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "fista", + "python": "fista", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Prox", + "Vector" + ], + "result": "Result", + "expression": "F.fista", + "c": "hmath_optimization_fista", + "parameters": [ + "options", + "objective", + "gradient", + "prox", + "initial" + ] + }, + { + "module": "HMath.Optimization.FirstOrder", + "name": "coordinateDescent", + "python": "coordinate_descent", + "arguments": [ + "Blocks", + "Options", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "F.coordinateDescent", + "c": "hmath_optimization_coordinate_descent", + "parameters": [ + "blocks", + "options", + "objective", + "gradient", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "GoldenSection", + "python": "golden_section", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.GoldenSection", + "c": "hmath_optimization_golden_section_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "TernarySearch", + "python": "ternary_search", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.TernarySearch", + "c": "hmath_optimization_ternary_search_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "BrentSearch", + "python": "brent_search", + "arguments": [], + "result": "ScalarMethod", + "expression": "L.BrentSearch", + "c": "hmath_optimization_brent_search_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeScalar", + "python": "minimize_scalar", + "arguments": [ + "ScalarMethod", + "Options", + "ScalarObjective", + "Double", + "Double" + ], + "result": "Result", + "expression": "L.minimizeScalar", + "c": "hmath_optimization_minimize_scalar", + "parameters": [ + "method", + "options", + "objective", + "lower", + "upper" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "BFGS", + "python": "bfgs", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.BFGS", + "c": "hmath_optimization_bfgs_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "DFP", + "python": "dfp", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.DFP", + "c": "hmath_optimization_dfp_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "SR1", + "python": "sr1", + "arguments": [], + "result": "QuasiNewton", + "expression": "L.SR1", + "c": "hmath_optimization_sr1_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "LBFGS", + "python": "lbfgs", + "arguments": [ + "Int" + ], + "result": "QuasiNewton", + "expression": "L.LBFGS", + "c": "hmath_optimization_lbfgs_create", + "parameters": [ + "memory" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeQuasiNewton", + "python": "minimize_quasi_newton", + "arguments": [ + "QuasiNewton", + "Options", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "L.minimizeQuasiNewton", + "c": "hmath_optimization_minimize_quasi_newton", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "Newton", + "python": "newton", + "arguments": [], + "result": "NewtonMethod", + "expression": "L.Newton", + "c": "hmath_optimization_newton_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "NewtonCG", + "python": "newton_cg", + "arguments": [], + "result": "NewtonMethod", + "expression": "L.NewtonCG", + "c": "hmath_optimization_newton_cg_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "TrustRegion", + "python": "trust_region", + "arguments": [ + "Double" + ], + "result": "NewtonMethod", + "expression": "L.TrustRegion", + "c": "hmath_optimization_trust_region_create", + "parameters": [ + "radius" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "Dogleg", + "python": "dogleg", + "arguments": [ + "Double" + ], + "result": "NewtonMethod", + "expression": "L.Dogleg", + "c": "hmath_optimization_dogleg_create", + "parameters": [ + "radius" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "minimizeNewton", + "python": "minimize_newton", + "arguments": [ + "NewtonMethod", + "Options", + "Objective", + "Gradient", + "Hessian", + "Vector" + ], + "result": "Result", + "expression": "L.minimizeNewton", + "c": "hmath_optimization_minimize_newton", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "hessian", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "nonlinearCG", + "python": "nonlinear_cg", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Vector" + ], + "result": "Result", + "expression": "L.nonlinearCG", + "c": "hmath_optimization_nonlinear_cg", + "parameters": [ + "options", + "objective", + "gradient", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "SquaredLoss", + "python": "squared_loss", + "arguments": [], + "result": "Loss", + "expression": "L.SquaredLoss", + "c": "hmath_optimization_squared_loss_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Local", + "name": "HuberLoss", + "python": "huber_loss", + "arguments": [ + "Double" + ], + "result": "Loss", + "expression": "L.HuberLoss", + "c": "hmath_optimization_huber_loss_create", + "parameters": [ + "scale" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "CauchyLoss", + "python": "cauchy_loss", + "arguments": [ + "Double" + ], + "result": "Loss", + "expression": "L.CauchyLoss", + "c": "hmath_optimization_cauchy_loss_create", + "parameters": [ + "scale" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "SoftL1", + "python": "soft_l1", + "arguments": [ + "Double" + ], + "result": "Loss", + "expression": "L.SoftL1", + "c": "hmath_optimization_soft_l1_create", + "parameters": [ + "scale" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "leastSquares", + "python": "least_squares", + "arguments": [ + "Loss", + "Double", + "Options", + "Gradient", + "Hessian", + "Vector" + ], + "result": "Result", + "expression": "L.leastSquares", + "c": "hmath_optimization_least_squares", + "parameters": [ + "loss", + "damping", + "options", + "residual", + "jacobian", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "nelderMead", + "python": "nelder_mead", + "arguments": [ + "Options", + "Objective", + "Vector" + ], + "result": "Result", + "expression": "L.nelderMead", + "c": "hmath_optimization_nelder_mead", + "parameters": [ + "options", + "objective", + "initial" + ] + }, + { + "module": "HMath.Optimization.Local", + "name": "powell", + "python": "powell", + "arguments": [ + "Double", + "Options", + "Objective", + "Vector" + ], + "result": "Result", + "expression": "L.powell", + "c": "hmath_optimization_powell", + "parameters": [ + "initial_step", + "options", + "objective", + "initial" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "Equality", + "python": "equality", + "arguments": [ + "Objective", + "Gradient" + ], + "result": "Constraint", + "expression": "K.Equality", + "c": "hmath_optimization_equality_create", + "parameters": [ + "objective", + "gradient" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LessEqual", + "python": "less_equal", + "arguments": [ + "Objective", + "Gradient" + ], + "result": "Constraint", + "expression": "K.LessEqual", + "c": "hmath_optimization_less_equal_create", + "parameters": [ + "objective", + "gradient" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "feasibility", + "python": "feasibility", + "arguments": [ + "Constraints", + "Vector" + ], + "result": "Double", + "expression": "K.feasibility", + "c": "hmath_optimization_feasibility", + "parameters": [ + "constraints", + "point" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "QuadraticPenalty", + "python": "quadratic_penalty", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.QuadraticPenalty", + "c": "hmath_optimization_quadratic_penalty_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LogBarrier", + "python": "log_barrier", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.LogBarrier", + "c": "hmath_optimization_log_barrier_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "InteriorPoint", + "python": "interior_point", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.InteriorPoint", + "c": "hmath_optimization_interior_point_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "AugmentedLagrangian", + "python": "augmented_lagrangian", + "arguments": [], + "result": "PenaltyMethod", + "expression": "K.AugmentedLagrangian", + "c": "hmath_optimization_augmented_lagrangian_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "constrainedMinimize", + "python": "constrained_minimize", + "arguments": [ + "PenaltyMethod", + "Options", + "Objective", + "Gradient", + "Constraints", + "Vector" + ], + "result": "Result", + "expression": "K.constrainedMinimize", + "c": "hmath_optimization_constrained_minimize", + "parameters": [ + "method", + "options", + "objective", + "gradient", + "constraints", + "initial" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "LPResult", + "python": "lp_result", + "arguments": [ + "Vector", + "Double", + "Indices", + "Int" + ], + "result": "LPResult", + "expression": "K.LPResult", + "c": "hmath_optimization_lp_result_create", + "parameters": [ + "point", + "value", + "basis", + "iterations" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "linearProgramming", + "python": "linear_programming", + "arguments": [ + "Int", + "Double", + "Vector", + "Matrix", + "Vector" + ], + "result": "LPResult", + "expression": "K.linearProgramming", + "c": "hmath_optimization_linear_programming", + "parameters": [ + "budget", + "tolerance", + "cost", + "matrix", + "rhs" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "revisedSimplex", + "python": "revised_simplex", + "arguments": [ + "Int", + "Double", + "Vector", + "Matrix", + "Vector", + "Indices" + ], + "result": "LPResult", + "expression": "K.revisedSimplex", + "c": "hmath_optimization_revised_simplex", + "parameters": [ + "budget", + "tolerance", + "cost", + "matrix", + "rhs", + "basis" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "quadraticProgramming", + "python": "quadratic_programming", + "arguments": [ + "Int", + "Double", + "Matrix", + "Vector", + "Matrix", + "Vector" + ], + "result": "Result", + "expression": "K.quadraticProgramming", + "c": "hmath_optimization_quadratic_programming", + "parameters": [ + "budget", + "tolerance", + "hessian", + "cost", + "matrix", + "rhs" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "slsqp", + "python": "slsqp", + "arguments": [ + "Options", + "Objective", + "Gradient", + "Hessian", + "Constraints", + "Vector" + ], + "result": "Result", + "expression": "K.slsqp", + "c": "hmath_optimization_slsqp", + "parameters": [ + "options", + "objective", + "gradient", + "hessian", + "constraints", + "initial" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "cobyla", + "python": "cobyla", + "arguments": [ + "Double", + "Options", + "Objective", + "Objectives", + "Vector" + ], + "result": "Result", + "expression": "K.cobyla", + "c": "hmath_optimization_cobyla", + "parameters": [ + "initial_radius", + "options", + "objective", + "constraints", + "initial" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "weightedObjective", + "python": "weighted_objective", + "arguments": [ + "Vector", + "Objectives" + ], + "result": "Function", + "expression": "(\\weights functions -> functionValue (ObjectiveFn (K.weightedObjective weights functions)))", + "c": "hmath_optimization_weighted_objective", + "parameters": [ + "weights", + "objectives" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "paretoFront", + "python": "pareto_front", + "arguments": [ + "Matrix" + ], + "result": "Indices", + "expression": "K.paretoFront", + "c": "hmath_optimization_pareto_front", + "parameters": [ + "points" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpPoint", + "python": "lp_point", + "arguments": [ + "LPResult" + ], + "result": "Value", + "expression": "K.lpPoint", + "c": "hmath_optimization_lp_point", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpValue", + "python": "lp_value", + "arguments": [ + "LPResult" + ], + "result": "Value", + "expression": "K.lpValue", + "c": "hmath_optimization_lp_value", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpBasis", + "python": "lp_basis", + "arguments": [ + "LPResult" + ], + "result": "Value", + "expression": "K.lpBasis", + "c": "hmath_optimization_lp_basis", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Constrained", + "name": "lpIterations", + "python": "lp_iterations", + "arguments": [ + "LPResult" + ], + "result": "Value", + "expression": "K.lpIterations", + "c": "hmath_optimization_lp_iterations", + "parameters": [ + "value" + ] + }, + { + "module": "HMath.Optimization.Global", + "name": "SimulatedAnnealing", + "python": "simulated_annealing", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.SimulatedAnnealing", + "c": "hmath_optimization_simulated_annealing_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Global", + "name": "DifferentialEvolution", + "python": "differential_evolution", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.DifferentialEvolution", + "c": "hmath_optimization_differential_evolution_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Global", + "name": "GeneticAlgorithm", + "python": "genetic_algorithm", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.GeneticAlgorithm", + "c": "hmath_optimization_genetic_algorithm_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Global", + "name": "ParticleSwarm", + "python": "particle_swarm", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.ParticleSwarm", + "c": "hmath_optimization_particle_swarm_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Global", + "name": "CMAES", + "python": "cmaes", + "arguments": [], + "result": "GlobalMethod", + "expression": "G.CMAES", + "c": "hmath_optimization_cmaes_create", + "parameters": [] + }, + { + "module": "HMath.Optimization.Global", + "name": "globalMinimize", + "python": "global_minimize", + "arguments": [ + "GlobalMethod", + "Int", + "Word64", + "Options", + "Bounds", + "Objective" + ], + "result": "Result", + "expression": "G.globalMinimize", + "c": "hmath_optimization_global_minimize", + "parameters": [ + "method", + "population_size", + "seed", + "options", + "bounds", + "objective" + ] + }, + { + "module": "HMath.Optimization.Global", + "name": "basinHopping", + "python": "basin_hopping", + "arguments": [ + "Word64", + "Double", + "Int", + "Options", + "Bounds", + "Objective", + "Vector" + ], + "result": "Result", + "expression": "G.basinHopping", + "c": "hmath_optimization_basin_hopping", + "parameters": [ + "seed", + "temperature", + "hops", + "options", + "bounds", + "objective", + "initial" + ] + } + ] +} diff --git a/bindings/schema/polynomial-objects.json b/bindings/schema/polynomial-objects.json new file mode 100644 index 0000000..788b841 --- /dev/null +++ b/bindings/schema/polynomial-objects.json @@ -0,0 +1,541 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Polynomial.Polynomial", + "c": [ + "hmath_value", + "hmath_value_release", + "hmath_value_info" + ], + "python": "hmath.polynomial.Polynomial", + "specializations": [ + "owned immutable Value kind6" + ] + }, + { + "symbol": "HMath.Polynomial.PowerSeries", + "c": [ + "hmath_value", + "hmath_value_release", + "hmath_value_info" + ], + "python": "hmath.polynomial.PowerSeries", + "specializations": [ + "owned immutable Value kind7" + ] + }, + { + "symbol": "HMath.Polynomial.RationalFunction", + "c": [ + "hmath_value", + "hmath_value_release", + "hmath_value_info" + ], + "python": "hmath.polynomial.RationalFunction", + "specializations": [ + "owned immutable Value kind8" + ] + }, + { + "symbol": "HMath.Polynomial.aberthEhrlich", + "c": [ + "hmath_polynomial_aberth_ehrlich" + ], + "python": "hmath.polynomial.aberth_ehrlich", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.addPolynomial", + "c": [ + "hmath_polynomial_add_polynomial" + ], + "python": "hmath.polynomial.add_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.addRationalFunction", + "c": [ + "hmath_polynomial_add_rational_function" + ], + "python": "hmath.polynomial.add_rational_function", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.addSeries", + "c": [ + "hmath_polynomial_add_series" + ], + "python": "hmath.polynomial.add_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.bernsteinPolynomial", + "c": [ + "hmath_polynomial_bernstein_polynomial" + ], + "python": "hmath.polynomial.bernstein_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.chebyshevApproximation", + "c": [ + "hmath_polynomial_chebyshev_approximation" + ], + "python": "hmath.polynomial.chebyshev_approximation", + "specializations": [ + "Double callback, synchronous" + ] + }, + { + "symbol": "HMath.Polynomial.chebyshevPolynomial", + "c": [ + "hmath_polynomial_chebyshev_polynomial" + ], + "python": "hmath.polynomial.chebyshev_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.coefficients", + "c": [ + "hmath_polynomial_coefficients" + ], + "python": "hmath.polynomial.coefficients", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.companionMatrix", + "c": [ + "hmath_polynomial_companion_matrix" + ], + "python": "hmath.polynomial.companion_matrix", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.composePolynomial", + "c": [ + "hmath_polynomial_compose_polynomial" + ], + "python": "hmath.polynomial.compose_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.composeSeries", + "c": [ + "hmath_polynomial_compose_series" + ], + "python": "hmath.polynomial.compose_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.countRealRoots", + "c": [ + "hmath_polynomial_count_real_roots" + ], + "python": "hmath.polynomial.count_real_roots", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.differentiatePolynomial", + "c": [ + "hmath_polynomial_differentiate_polynomial" + ], + "python": "hmath.polynomial.differentiate_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.differentiateSeries", + "c": [ + "hmath_polynomial_differentiate_series" + ], + "python": "hmath.polynomial.differentiate_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.dividePolynomial", + "c": [ + "hmath_polynomial_divide_polynomial" + ], + "python": "hmath.polynomial.divide_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.divideSeries", + "c": [ + "hmath_polynomial_divide_series" + ], + "python": "hmath.polynomial.divide_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.durandKerner", + "c": [ + "hmath_polynomial_durand_kerner" + ], + "python": "hmath.polynomial.durand_kerner", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.evaluatePolynomial", + "c": [ + "hmath_polynomial_evaluate_polynomial" + ], + "python": "hmath.polynomial.evaluate_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.evaluateRationalFunction", + "c": [ + "hmath_polynomial_evaluate_rational_function" + ], + "python": "hmath.polynomial.evaluate_rational_function", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.expSeries", + "c": [ + "hmath_polynomial_exp_series" + ], + "python": "hmath.polynomial.exp_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.factorRationalPolynomial", + "c": [ + "hmath_polynomial_factor_rational_polynomial" + ], + "python": "hmath.polynomial.factor_rational_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.gcdPolynomial", + "c": [ + "hmath_polynomial_gcd_polynomial" + ], + "python": "hmath.polynomial.gcd_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.hermitePolynomial", + "c": [ + "hmath_polynomial_hermite_polynomial" + ], + "python": "hmath.polynomial.hermite_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.integratePolynomial", + "c": [ + "hmath_polynomial_integrate_polynomial" + ], + "python": "hmath.polynomial.integrate_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.integrateSeries", + "c": [ + "hmath_polynomial_integrate_series" + ], + "python": "hmath.polynomial.integrate_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.isolateRealRoots", + "c": [ + "hmath_polynomial_isolate_real_roots" + ], + "python": "hmath.polynomial.isolate_real_roots", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.lagrangeInterpolation", + "c": [ + "hmath_polynomial_lagrange_interpolation" + ], + "python": "hmath.polynomial.lagrange_interpolation", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.laguerrePolynomial", + "c": [ + "hmath_polynomial_laguerre_polynomial" + ], + "python": "hmath.polynomial.laguerre_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.legendrePolynomial", + "c": [ + "hmath_polynomial_legendre_polynomial" + ], + "python": "hmath.polynomial.legendre_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.logSeries", + "c": [ + "hmath_polynomial_log_series" + ], + "python": "hmath.polynomial.log_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.monicPolynomial", + "c": [ + "hmath_polynomial_monic_polynomial" + ], + "python": "hmath.polynomial.monic_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.multiplyPolynomial", + "c": [ + "hmath_polynomial_multiply_polynomial" + ], + "python": "hmath.polynomial.multiply_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.multiplyRationalFunction", + "c": [ + "hmath_polynomial_multiply_rational_function" + ], + "python": "hmath.polynomial.multiply_rational_function", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.multiplySeries", + "c": [ + "hmath_polynomial_multiply_series" + ], + "python": "hmath.polynomial.multiply_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.newtonInterpolation", + "c": [ + "hmath_polynomial_newton_interpolation" + ], + "python": "hmath.polynomial.newton_interpolation", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.partialFractions", + "c": [ + "hmath_polynomial_partial_fractions" + ], + "python": "hmath.polynomial.partial_fractions", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.polynomial", + "c": [ + "hmath_polynomial_polynomial" + ], + "python": "hmath.polynomial.polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.polynomialDegree", + "c": [ + "hmath_polynomial_polynomial_degree" + ], + "python": "hmath.polynomial.polynomial_degree", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.polynomialRegression", + "c": [ + "hmath_polynomial_polynomial_regression" + ], + "python": "hmath.polynomial.polynomial_regression", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.powerSeries", + "c": [ + "hmath_polynomial_power_series" + ], + "python": "hmath.polynomial.power_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.rationalDenominator", + "c": [ + "hmath_polynomial_rational_denominator" + ], + "python": "hmath.polynomial.rational_denominator", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.rationalFunction", + "c": [ + "hmath_polynomial_rational_function" + ], + "python": "hmath.polynomial.rational_function", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.rationalNumerator", + "c": [ + "hmath_polynomial_rational_numerator" + ], + "python": "hmath.polynomial.rational_numerator", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.rationalRoots", + "c": [ + "hmath_polynomial_rational_roots" + ], + "python": "hmath.polynomial.rational_roots", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.reciprocalSeries", + "c": [ + "hmath_polynomial_reciprocal_series" + ], + "python": "hmath.polynomial.reciprocal_series", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.scalePolynomial", + "c": [ + "hmath_polynomial_scale_polynomial" + ], + "python": "hmath.polynomial.scale_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.seriesCoefficients", + "c": [ + "hmath_polynomial_series_coefficients" + ], + "python": "hmath.polynomial.series_coefficients", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.squareFreeFactors", + "c": [ + "hmath_polynomial_square_free_factors" + ], + "python": "hmath.polynomial.square_free_factors", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.sturmSequence", + "c": [ + "hmath_polynomial_sturm_sequence" + ], + "python": "hmath.polynomial.sturm_sequence", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + }, + { + "symbol": "HMath.Polynomial.subtractPolynomial", + "c": [ + "hmath_polynomial_subtract_polynomial" + ], + "python": "hmath.polynomial.subtract_polynomial", + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ] + } + ] +} diff --git a/bindings/schema/polynomial-operations.json b/bindings/schema/polynomial-operations.json new file mode 100644 index 0000000..1b883cc --- /dev/null +++ b/bindings/schema/polynomial-operations.json @@ -0,0 +1,410 @@ +[ + { + "name": "polynomial", + "arguments": [ + "prototype", + "coefficients" + ], + "opcode": 0 + }, + { + "name": "coefficients", + "arguments": [ + "polynomial" + ], + "opcode": 1 + }, + { + "name": "polynomialDegree", + "arguments": [ + "polynomial" + ], + "opcode": 2 + }, + { + "name": "evaluatePolynomial", + "arguments": [ + "polynomial", + "x" + ], + "opcode": 3 + }, + { + "name": "addPolynomial", + "arguments": [ + "left", + "right" + ], + "opcode": 4 + }, + { + "name": "subtractPolynomial", + "arguments": [ + "left", + "right" + ], + "opcode": 5 + }, + { + "name": "scalePolynomial", + "arguments": [ + "scalar", + "polynomial" + ], + "opcode": 6 + }, + { + "name": "multiplyPolynomial", + "arguments": [ + "left", + "right" + ], + "opcode": 7 + }, + { + "name": "composePolynomial", + "arguments": [ + "outer", + "inner" + ], + "opcode": 8 + }, + { + "name": "dividePolynomial", + "arguments": [ + "numerator", + "denominator" + ], + "opcode": 9 + }, + { + "name": "monicPolynomial", + "arguments": [ + "polynomial" + ], + "opcode": 10 + }, + { + "name": "gcdPolynomial", + "arguments": [ + "left", + "right" + ], + "opcode": 11 + }, + { + "name": "differentiatePolynomial", + "arguments": [ + "polynomial" + ], + "opcode": 12 + }, + { + "name": "integratePolynomial", + "arguments": [ + "constant", + "polynomial" + ], + "opcode": 13 + }, + { + "name": "squareFreeFactors", + "arguments": [ + "polynomial" + ], + "opcode": 14 + }, + { + "name": "rationalRoots", + "arguments": [ + "budget", + "polynomial" + ], + "opcode": 15 + }, + { + "name": "factorRationalPolynomial", + "arguments": [ + "budget", + "polynomial" + ], + "opcode": 16 + }, + { + "name": "sturmSequence", + "arguments": [ + "polynomial" + ], + "opcode": 17 + }, + { + "name": "countRealRoots", + "arguments": [ + "polynomial", + "left", + "right" + ], + "opcode": 18 + }, + { + "name": "isolateRealRoots", + "arguments": [ + "depth", + "width", + "polynomial" + ], + "opcode": 19 + }, + { + "name": "durandKerner", + "arguments": [ + "iterations", + "tolerance", + "polynomial" + ], + "opcode": 20 + }, + { + "name": "aberthEhrlich", + "arguments": [ + "iterations", + "tolerance", + "polynomial" + ], + "opcode": 21 + }, + { + "name": "companionMatrix", + "arguments": [ + "polynomial" + ], + "opcode": 22 + }, + { + "name": "lagrangeInterpolation", + "arguments": [ + "prototype", + "points" + ], + "opcode": 23 + }, + { + "name": "newtonInterpolation", + "arguments": [ + "prototype", + "points" + ], + "opcode": 24 + }, + { + "name": "chebyshevPolynomial", + "arguments": [ + "prototype", + "degree" + ], + "opcode": 25 + }, + { + "name": "legendrePolynomial", + "arguments": [ + "prototype", + "degree" + ], + "opcode": 26 + }, + { + "name": "hermitePolynomial", + "arguments": [ + "prototype", + "degree" + ], + "opcode": 27 + }, + { + "name": "laguerrePolynomial", + "arguments": [ + "prototype", + "degree" + ], + "opcode": 28 + }, + { + "name": "bernsteinPolynomial", + "arguments": [ + "prototype", + "degree", + "index" + ], + "opcode": 29 + }, + { + "name": "polynomialRegression", + "arguments": [ + "prototype", + "degree", + "points" + ], + "opcode": 30 + }, + { + "name": "powerSeries", + "arguments": [ + "prototype", + "coefficients" + ], + "opcode": 31 + }, + { + "name": "seriesCoefficients", + "arguments": [ + "series" + ], + "opcode": 32 + }, + { + "name": "addSeries", + "arguments": [ + "left", + "right" + ], + "opcode": 33 + }, + { + "name": "multiplySeries", + "arguments": [ + "left", + "right" + ], + "opcode": 34 + }, + { + "name": "reciprocalSeries", + "arguments": [ + "series" + ], + "opcode": 35 + }, + { + "name": "divideSeries", + "arguments": [ + "numerator", + "denominator" + ], + "opcode": 36 + }, + { + "name": "composeSeries", + "arguments": [ + "outer", + "inner" + ], + "opcode": 37 + }, + { + "name": "differentiateSeries", + "arguments": [ + "series" + ], + "opcode": 38 + }, + { + "name": "integrateSeries", + "arguments": [ + "constant", + "series" + ], + "opcode": 39 + }, + { + "name": "expSeries", + "arguments": [ + "series" + ], + "opcode": 40 + }, + { + "name": "logSeries", + "arguments": [ + "series" + ], + "opcode": 41 + }, + { + "name": "rationalFunction", + "arguments": [ + "numerator", + "denominator" + ], + "opcode": 42 + }, + { + "name": "rationalNumerator", + "arguments": [ + "function" + ], + "opcode": 43 + }, + { + "name": "rationalDenominator", + "arguments": [ + "function" + ], + "opcode": 44 + }, + { + "name": "evaluateRationalFunction", + "arguments": [ + "function", + "x" + ], + "opcode": 45 + }, + { + "name": "addRationalFunction", + "arguments": [ + "left", + "right" + ], + "opcode": 46 + }, + { + "name": "multiplyRationalFunction", + "arguments": [ + "left", + "right" + ], + "opcode": 47 + }, + { + "name": "partialFractions", + "arguments": [ + "budget", + "function" + ], + "opcode": 48 + }, + { + "name": "polynomialEqual", + "arguments": [ + "left", + "right" + ], + "opcode": 49 + }, + { + "name": "seriesEqual", + "arguments": [ + "left", + "right" + ], + "opcode": 50 + }, + { + "name": "rationalFunctionEqual", + "arguments": [ + "left", + "right" + ], + "opcode": 51 + } +] diff --git a/bindings/schema/public-api.json b/bindings/schema/public-api.json new file mode 100644 index 0000000..8b7ddef --- /dev/null +++ b/bindings/schema/public-api.json @@ -0,0 +1,23413 @@ +{ + "schema": 1, + "source": "Haddock visible_exports from Cabal exposed modules; canonical defining symbols, deduplicated re-exports", + "symbols": [ + { + "symbol": "HMath.API.Algebra.Differentiable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Differential", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Exact", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra", + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Field", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.FloatingPoint", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.MatrixLike", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Numeric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Ring", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.Scalar", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.TensorLike", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.VectorSpace", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.conjugateScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.differential", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.finiteScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.getExact", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.horner", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.innerProduct", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.integer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.invert", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.machineEpsilon", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixConstruct", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixDimensions", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.matrixElements", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.negative", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.one", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.plus", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.rational", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorConstruct", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorDimensions", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.tensorElements", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.times", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.vectorPlus", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.vectorScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Algebra.zero", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Algebra" + ] + }, + { + "symbol": "HMath.API.Buffer.Boxed", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.IOBuffer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.STBuffer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.UnboxedDouble", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedLength", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedToUnboxed", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.boxedValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.freezeIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.freezeSTBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.ioBufferLength", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.lazyBoxed", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.mapStrict", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.newIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.readIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.readSTBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.runSTBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.strictBoxed", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.thawIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.thawSTBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedDouble", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedToBoxed", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.unboxedValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.withIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.writeIOBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Buffer.writeSTBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Buffer" + ] + }, + { + "symbol": "HMath.API.Convergence.Converged", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.Convergence", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence", + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.IterationLimit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.IterationOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence", + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.ResidualSatisfied", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.Stagnation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.StopReason", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.absoluteTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.defaultIterationOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.estimate", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.finalResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.fromMaybeError", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.iterateUntil", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.iterationCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.maximumIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.relativeTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.requireConvergence", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.resultMaybe", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Convergence.stopReason", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Convergence" + ] + }, + { + "symbol": "HMath.API.Shape.Coordinates", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.KnownShape", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.MatrixShape", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.ScalarShape", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.Shape", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.StaticMatrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.StaticTensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.VectorShape", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.coordinateValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.coordinates", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.coordinatesToVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.dynamicMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.dynamicTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.makeShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.reflectedShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.shapeDimensions", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.shapeElements", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.staticMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.staticMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.staticTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.API.Shape.staticTranspose", + "kind": "function-or-field", + "exported_from": [ + "HMath.API.Shape" + ] + }, + { + "symbol": "HMath.Algebra.Additive", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra", + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Field", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.FieldElement", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.FiniteField", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Group", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Modular", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Module", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Ring", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.Semiring", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.VectorSpace", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.addField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.addModular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldCardinality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldCharacteristic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldDegree", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldElement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldElementCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldElements", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.fieldModulus", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.finiteField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.finiteFieldLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.getAdditive", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.groupCombine", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.groupIdentity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.groupInverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.groupLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.inverseField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.inverseFieldElement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.inverseModular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.linearCombination", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.modular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.modularModulus", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.modularValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.moduleAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.moduleLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.moduleScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.multiplyField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.multiplyModular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.negateField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.negateRing", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.one", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.plus", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.powerField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.powerModular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.primeField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.ringLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.semiringLaws", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.subtractField", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.subtractModular", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.times", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algebra.zero", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algebra" + ] + }, + { + "symbol": "HMath.Algorithms.applyDifferences", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.argsort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.binaryLift", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.binarySearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.bucketSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.coordinateCompression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.countingSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.deduplicate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.differenceArray", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.divideConquerDP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.exponentialSearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.heapsort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.integerMatrixPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.interpolationSearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.intervalSweep", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.introselect", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.introsort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.lowerBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.memoizedDP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.mergeSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.numericGroups", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.partialSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.polynomialHash", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.prefixSums", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.quantileSelect", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.quickselect", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.quicksort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.radixSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.rollingHashes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.runLengthDecode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.runLengthEncode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.suffixSums", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.tabulateDP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.ternarySearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.topK", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Algorithms.upperBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Algorithms" + ] + }, + { + "symbol": "HMath.Autodiff.ADTensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.CompiledGraph", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.Dual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Autodiff", + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.Expr", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.GradientState", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Autodiff", + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.accumulateGradients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.accumulatedGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adBroadcast", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adContract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adMatmul", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.adValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.checkpoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.clipGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.compileGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.complexGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.constant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.customOperation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.customUnary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.detach", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.differentiableStep", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.differentiate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.evaluateGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.forward", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.forwardJVP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.gradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.gradientCheck", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.gradientHook", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.hessian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.hvp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.jacobian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.jvp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.primal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.resetGradients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.stopGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.tangent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.valueAndGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.variable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.vjp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Autodiff.zeroGradients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Autodiff" + ] + }, + { + "symbol": "HMath.Backend.Accelerate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.AutoBackend", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.BLIS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.Backend", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.BackendInfo", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend", + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.BackendLayout", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.BackendRequest", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.ColumnMajor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.ConjugateTranspose", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.ILP64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.IntegerABI", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.LP64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.NoTranspose", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.OneMKL", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.OpenBLAS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.Provider", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.Pure", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.RequireBackend", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.RowMajor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.Transpose", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Backend", + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.axpy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendCholesky", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendInfo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendLeastSquares", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendQR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.backendSymmetricEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.batchedGemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.complexAxpy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.complexDot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.complexGemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.complexGemv", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.complexNrm2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.dot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.gemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.gemv", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.lapackAvailable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.lapackStatus", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.matrixFromLayout", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.matrixToLayout", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.nrm2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.pureBackend", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.pureSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.pureSymmetricEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.selectBackend", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.selectedIntegerABI", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.selectedProvider", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.setBackendThreads", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Backend.stridedBatchedGemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Backend" + ] + }, + { + "symbol": "HMath.Basic.clamp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Basic" + ] + }, + { + "symbol": "HMath.Basic.factorial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Basic" + ] + }, + { + "symbol": "HMath.Basic.fibonacci", + "kind": "function-or-field", + "exported_from": [ + "HMath.Basic" + ] + }, + { + "symbol": "HMath.Basic.isPrime", + "kind": "function-or-field", + "exported_from": [ + "HMath.Basic" + ] + }, + { + "symbol": "HMath.Basic.lerp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Basic" + ] + }, + { + "symbol": "HMath.Calculus.Backward", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Central", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Difference", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Estimate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus", + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Forward", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Quadrature", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Simpson", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.ThreeEighths", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Tolerance", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus", + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.Trapezoidal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.absoluteTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.adaptiveIntegrate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.clenshawCurtis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.complexDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.cumulativeIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.curl", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.defaultTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.derivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.derivativeN", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.directionalDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.divergence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.estimateError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.estimateValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.evaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gaussChebyshev", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gaussHermite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gaussKronrod", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gaussLaguerre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gaussLegendre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.gradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.hessian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.hvp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.integrateComposite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.integrateInfinite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.integrateND", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.integrateOscillatory", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.jacobian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.jvp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.laplacian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.limit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.lineIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.maximumEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.monteCarlo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.partialDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.pathIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.quasiMonteCarlo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.relativeTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.richardson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.ridders", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.romberg", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.surfaceIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.tanhSinh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.vjp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Calculus.volumeIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Calculus" + ] + }, + { + "symbol": "HMath.Combinatorics.bellNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.cartesianProduct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.catalanNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.combinationsCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.combinationsOf", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.convolveSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.derangementCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.derangements", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.eulerianNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.fibonacci", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.finiteDifferences", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.finiteSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.generatingCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.inclusionExclusion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.integerPartitions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.lahNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.linearRecurrence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.lucas", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.multinomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.multisetCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.multisetPermutations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.pascalTriangle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.permutationsCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.permutationsOf", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.rankCombination", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.rankPermutation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.setPartitions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.stirlingFirst", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.stirlingSecond", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.subsets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.unrankCombination", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Combinatorics.unrankPermutation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Combinatorics" + ] + }, + { + "symbol": "HMath.Complex.Acos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Acosh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Asin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Asinh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Atan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Atanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Cos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Cosh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Elementary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Exp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Log", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Sin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Sinh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Sqrt", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Tan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.Tanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.add", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.complex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.complexFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.complexIFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.complexMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.conjugateTranspose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.divide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.elementary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.fromPolar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.multiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.multiplyMatrices", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.power", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.reciprocal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.rotate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.subtractComplex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Complex.toPolar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Complex" + ] + }, + { + "symbol": "HMath.Constants.Constant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Constants", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.aperyConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.approximationBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.astronomicalUnit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.avogadroConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.boltzmannConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.catalanConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.constantAs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.constantName", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.constantSource", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.constantUnit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.constantValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.eConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.electronMass", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.elementaryCharge", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.eulerMascheroni", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.goldenRatio", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.gravitationalConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.infinity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.ln10", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.ln2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.mathematicalConstants", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.nan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.physicalConstants", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.piConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.planckConstant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.speedOfLight", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.sqrt2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.sqrt3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.standardUncertainty", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Constants.tau", + "kind": "function-or-field", + "exported_from": [ + "HMath.Constants" + ] + }, + { + "symbol": "HMath.DataStructure.BinaryHeap", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.Bloom", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.CountMin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.DisjointSparseTable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.Fenwick", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.Heap", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.HyperLogLog", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.IndexedHeap", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.OnlineQuantiles", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.Reservoir", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.SegmentTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.SparseTable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.UnionFind", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.binaryHeap", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.binaryInsert", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.binaryPop", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.bloom", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.bloomFalsePositiveBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.bloomInsert", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.bloomMember", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.components", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.connected", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.countMin", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.countMinAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.countMinErrorBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.countMinEstimate", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.disjointRange", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.disjointSparseTable", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.emptyHeap", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.fenwick", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickPrefix", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.fenwickRange", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.findRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.heapFromList", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.heapInsert", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.heapPop", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.hllAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.hllEstimate", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.hyperLogLog", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.indexedHeap", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.indexedPop", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.indexedSet", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.monotonicMinima", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.nextGreater", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.onlineQuantile", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.onlineQuantiles", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.quantileAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.reservoir", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.reservoirAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.reservoirValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.segmentRange", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.segmentSet", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.segmentTree", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.sparseMinimum", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.sparseTable", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.union", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DataStructure.unionFind", + "kind": "function-or-field", + "exported_from": [ + "HMath.DataStructure" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Activation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.BinaryCrossEntropy", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.CategoricalCrossEntropy", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.CosineLoss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ELU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.GELU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.HardSigmoid", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.HardSwish", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Hinge", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Huber", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.KLDivergence", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.LeakyReLU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Loss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Mean", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.MeanAbsoluteError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.MeanSquaredError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Mish", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.NegativeLogLikelihood", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.PReLU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ReLU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Reduction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SELU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SiLU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Sigmoid", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.SmoothL1", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Softplus", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Softsign", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Sum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.Tanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activation", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activationDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.activationExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.binaryCrossEntropyLogits", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.categoricalCrossEntropyLogits", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.contrastiveLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLossExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.ctcLossGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.diceLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.focalLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.gatedLinearUnit", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.iouLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.logSoftmax", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.logSoftmaxExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.loss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.lossExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.lossGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.regularization", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.softmax", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.softmaxExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.sparsemax", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.sparsemaxExpr", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Core.tripletLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Core" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.AveragePool", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.BatchNormState", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers", + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.ConvOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers", + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Inference", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Initializer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KVCache", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KaimingNormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.KaimingUniform", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.MaxPool", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Orthogonal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.PoolMode", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.Training", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers", + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.TruncatedNormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.XavierNormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.XavierUniform", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.adaptivePooling", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.alibiBias", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.appendCache", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.batchNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.batchesSeen", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.cacheValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.causalMask", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionAD", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionDilation", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionGroups", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionPadding", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.convolutionStride", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.dense", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.denseAD", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.depthwiseConvolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.dropout", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.embedding", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.emptyCache", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.globalPooling", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.groupNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.initializeWeights", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.instanceNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.layerNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.layerNormAD", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.multiheadAttention", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.pooling", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rmsNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rmsNormAD", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.rotaryEmbedding", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.runningMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.runningVariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.scaledDotProductAttention", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.scaledDotProductAttentionAD", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.sinusoidalEncoding", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.spatialDropout", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.transformerFeedForward", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.transposedConvolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Layers.weightNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Layers" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.ClassificationMetrics", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Metrics", + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.accuracy", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.classificationMetrics", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.confusionMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.cosineSimilarityMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.f1ByClass", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.marginRankingLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.perplexity", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.prAUC", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.precisionByClass", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.recallByClass", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.rocAUC", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Metrics.topKAccuracy", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Metrics" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Asymmetric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.BF16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.FP16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.LossScaler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision", + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Precision", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Quantization", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.QuantizedTensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.Symmetric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.clipGradients", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.dequantize", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.finiteSteps", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.gradientNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.initialLossScaler", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.int8Gemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.lossScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizationScales", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizationZeroPoints", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantize", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.quantizedValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.reducedGemm", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.scaleGrowthInterval", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.scaleLoss", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.unscaleGradients", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.DeepLearning.Precision.updateLossScaler", + "kind": "function-or-field", + "exported_from": [ + "HMath.DeepLearning.Precision" + ] + }, + { + "symbol": "HMath.Discrete.And", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.BitSet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Iff", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Implicant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete", + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Implies", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Literal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.MultiSet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Not", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Or", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Prop", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Variable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.Xor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitDelete", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitInsert", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitMember", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitSet", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitUnion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.bitWidth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.booleanMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.equivalenceClosure", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.evaluateProp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.grayDecode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.grayEncode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.hammingDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.implicantCovers", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.implicantMask", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.implicantValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.isEquivalence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.leadingZeros", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multiplicity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multiset", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetDelete", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetEntries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetInsert", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.multisetUnion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.populationCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.quineMcCluskey", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.resizeBitSet", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.reverseBits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.rotateBits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.setDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.setIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.setUnion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.symmetricDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.trailingZeros", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.transitiveClosure", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Discrete.truthTable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Discrete" + ] + }, + { + "symbol": "HMath.Error.DomainError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.ElementCountMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.ElementCountOverflow", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.IndexOutOfBounds", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.InnerDimensionMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.InvalidArgument", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.InvalidTolerance", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.MathError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NearSingularMatrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NegativeDimensions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NonConvergence", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NonFiniteMatrixEntry", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NonFiniteResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NonFiniteVectorEntry", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NonSquareMatrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.NotPositiveDefinite", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.RankDeficient", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.RightHandSideMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.ShapeMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.SingularMatrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.SliceOutOfBounds", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Error.VectorLengthMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Error" + ] + }, + { + "symbol": "HMath.Expression.Abs", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Acos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Add", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Asin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Atan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Binary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.BinaryOp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Bindings", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Builtin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Call", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Ceiling", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Compiled", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Constant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Cos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Cosh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.DepthLimit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Divide", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.DomainFailure", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ErrorKind", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Euler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ExactRational", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ExactValue", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Exp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Expr", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression", + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ExprError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression", + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ExprNode", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.ExpressionCache", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Float64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.FloatValue", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Floor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.InvalidLimits", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Let", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Limits", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression", + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Literal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Log", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Max", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.MemoryLimit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Min", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Multiply", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.NamedConstant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Negate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.NonFinite", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Pi", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Power", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Precision", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Registry", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Signum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Sin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Sinh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.SourcePos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression", + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Sqrt", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.StepLimit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Subtract", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.SyntaxError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Tan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Tanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Tau", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.TypeMismatch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Unary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.UnaryOp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.UnknownName", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Unsupported", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Value", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.Variable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.allowedFunctions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.binary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.cacheSize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.cachedExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.call", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.compileExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.compiledNodeCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.constant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.defaultLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.defaultRegistry", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.deserializeExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.emptyExpressionCache", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.emptyRegistry", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.errorKind", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.errorMessage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.errorPosition", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.evaluateCompiled", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.evaluateExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.evaluateText", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.expressionHash", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.expressionNode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.expressionPosition", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.formatRadix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.formatScientific", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.freeVariables", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.letIn", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.literal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumCacheEntries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumDepth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumInputChars", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumIntegerBits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumNodes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.maximumSteps", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.optimizeExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.parseExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.prettyExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.registerFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.serializeExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.sourceColumn", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.sourceLine", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.sourceOffset", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.typeCheckExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.unary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.unknownPosition", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.validateExpression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.validateLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Expression.variable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Expression" + ] + }, + { + "symbol": "HMath.Fourier.Automatic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Bluestein", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Direct", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Direction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.FFTAlgorithm", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.FFTPlan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Forward", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Inverse", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.MixedRadix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Rader", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Radix2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.Radix4", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.STFT", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.SplitRadix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.TransformType", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.TypeI", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.TypeII", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.TypeIII", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.TypeIV", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.analyticSignal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.cepstrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.chirpZ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.crossSpectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.dct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.dft", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.dst", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.executeFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fft", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftBatch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftConvolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftCorrelate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftInPlace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftND", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.fftShift", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.frequencies", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.goertzel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.hartley", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.hilbert", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.idct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.idst", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.ifft", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.ifftShift", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.inverseRealFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.istft", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.magnitudeSpectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.periodogram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.phaseSpectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.planFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.powerSpectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.realFFT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.spectrogram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.stft", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.stftFrames", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Fourier.welch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Fourier" + ] + }, + { + "symbol": "HMath.Geometry.Collision.Penetration", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Collision", + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.epa", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.gjk", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationDepth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.penetrationNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Collision.separatingAxis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Collision" + ] + }, + { + "symbol": "HMath.Geometry.Internal.AABB", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Boundary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Capsule", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Circle", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Clockwise", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Collinear", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Cone", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Counterclockwise", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Cylinder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Ellipse", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Frustum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Inside", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Line", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Location", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.OBB", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Orientation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Outside", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.P2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.P3", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Plane", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Point2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Point3", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.PointND", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Polygon", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Ray", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Rectangle", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Segment", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Sphere", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.Triangle", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry", + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.point2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.point3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Internal.pointND", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.BooleanOperation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Difference", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.GiftWrapping", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.GrahamScan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.HullAlgorithm", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Intersection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.MonotoneChain", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Quickhull", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.Union", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.clipPolygon", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.convexHull", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minimumBoundingCircle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minimumBoundingRectangle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.minkowskiSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonArea", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonBoolean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.polygonCentroid", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Polygon.shoelace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Polygon" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Chebyshev", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CircleIntersection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CirclePoints", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CoincidentCircles", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.CoincidentLine", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.DisjointCircles", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Euclidean", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Intersection2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.IntersectionPoint", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Manhattan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Metric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.Minkowski", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.NoIntersection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.OverlapSegment", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.boxContains", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.boxSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.capsuleSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.circleIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.circumcenter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.coneSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.cosineDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.cylinderSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.distance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.ellipseContains", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.hammingDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.hausdorffDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.incenter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.incircle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.jaccardDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.lineIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.linePlaneIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.mahalanobisDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.obbSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.orientation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.planeIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointLineDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointPlaneDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.pointSegmentDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.polygonLocation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.rayBox", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.raySphere", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.rayTriangle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.segmentIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.sphereContains", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.sphereSDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleBarycentric", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleIntersection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Primitives.triangleLocation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Primitives" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.BVH", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.BallTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.KDTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.NeighborQuery", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial", + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.Octree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.PointCloud", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.Quadtree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.RTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialHash", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialIndex", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.SpatialKind", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.buildSpatialIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.cloudPoints", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.nearestQuery", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.pointCloud", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryExhaustive", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryLeaves", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.queryNeighbors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.radiusQuery", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Spatial.rangeQuery", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Spatial" + ] + }, + { + "symbol": "HMath.Geometry.Transform.affineTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.applyTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.composeTransforms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.cullBox", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.cullSphere", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.extractFrustum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.inverseTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.lookAt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.orthographic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Transform.perspective", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Transform" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.IndexedTriangle", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Geometry.Triangulation" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.constrainedDelaunay", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Triangulation" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.delaunay", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Triangulation" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.earClip", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Triangulation" + ] + }, + { + "symbol": "HMath.Geometry.Triangulation.voronoi", + "kind": "function-or-field", + "exported_from": [ + "HMath.Geometry.Triangulation" + ] + }, + { + "symbol": "HMath.Graph.Analysis.betweennessCentrality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.bipartiteColors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.closenessCentrality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.clusteringCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.degreeCentrality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.density", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.diameterRadius", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.eigenvectorCentrality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.eulerianPath", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.exactColoring", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphEditDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphLaplacian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.graphSimilarity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.greedyColoring", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.hamiltonianPath", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.katzCentrality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.labelPropagation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.laplacianSpectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.louvain", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.modularity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.nearestNeighborTour", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.pageRank", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.randomWalk", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Analysis.twoOptTour", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Analysis" + ] + }, + { + "symbol": "HMath.Graph.Core.BipartiteGraph", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.CSR", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Core", + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.Edge", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Core", + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.Graph", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.Hypergraph", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.adjacencyList", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.adjacencyMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.arcs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.articulationPoints", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.bfs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteBase", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.bipartiteParts", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.boruvka", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.bridges", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.checkVertex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.connectedComponents", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrDirected", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrIds", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrOffsets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrOrientations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrTargets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrVertices", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.csrWeights", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeBipartiteGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.deserializeHypergraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.dfs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.directed", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeFrom", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeId", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeTo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.edgeWeight", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.edges", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.finite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.fromAdjacencyList", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.fromAdjacencyMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.fromCSR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.fromLabeledAdjacencyMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.graph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.hasCycle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.hyperVertices", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.hyperedges", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.hypergraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.iterativeDeepening", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.kosarajuSCC", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.kruskal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.neighbors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.prim", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.requireUndirected", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeBipartiteGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.serializeHypergraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.tarjanSCC", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.toCSR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.topologicalSort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Core.vertexCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Core" + ] + }, + { + "symbol": "HMath.Graph.Flow.FlowResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Flow", + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.Network", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.NetworkEdge", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Graph.Flow", + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.dinic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.edgeFlows", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.edmondsKarp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.flowCost", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.flowValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.fordFulkerson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.hopcroftKarp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.hungarian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.minimumCostMaximumFlow", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.minimumCut", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.network", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkCapacity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkCost", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkEdgeId", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkEdges", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkFrom", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.networkTo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Flow.pushRelabel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Flow" + ] + }, + { + "symbol": "HMath.Graph.Paths.aStar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.bellmanFord", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.bidirectionalDijkstra", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.dijkstra", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.floydWarshall", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.johnson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.kShortestPaths", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.longestDAGPaths", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Graph.Paths.multiSourceDijkstra", + "kind": "function-or-field", + "exported_from": [ + "HMath.Graph.Paths" + ] + }, + { + "symbol": "HMath.Image.Color.ColorSpace", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.HSL", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.HSV", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.Lab", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.LinearRGB", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.SRGB", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.XYZ", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.YCbCr", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.convertColor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.grayscale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.linearToSrgb", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Color.srgbToLinear", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Color" + ] + }, + { + "symbol": "HMath.Image.Core.Boundary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.Clamp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.Constant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.Image", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.Reflect", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.Wrap", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.brightness", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.channel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.combineChannels", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.contrast", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.fromTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.gamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.image", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.imageChannels", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.imageShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.imageValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.mapImage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.normalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.pixel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.toTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Core.zipImage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Closing", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Dilation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Erosion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.GradientOperator", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Morphology", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Opening", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Prewitt", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Scharr", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.Sobel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.bilateralBlur", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.boxBlur", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.canny", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.convolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.correlate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.gaussianBlur", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.gradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.laplacian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.medianBlur", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.morphologicalGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.morphology", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.scalar2D", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter" + ] + }, + { + "symbol": "HMath.Image.Filter.sharpen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter", + "HMath.Image" + ] + }, + { + "symbol": "HMath.Image.Filter.validateBoundary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter" + ] + }, + { + "symbol": "HMath.Image.Filter.windowOffsets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Filter" + ] + }, + { + "symbol": "HMath.Image.Histogram.adaptiveThreshold", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Histogram.clahe", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Histogram.equalizeHistogram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Histogram.histogram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Histogram.otsu", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Histogram.threshold", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Histogram" + ] + }, + { + "symbol": "HMath.Image.Measure.NormalizedCorrelation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.SquaredDifference", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.TemplateMetric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.centralMoment", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.imageCentroid", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.integralImage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.meanSquaredError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.peakSignalToNoise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.rawMoment", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.rectangleSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.structuralSimilarity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Measure.templateMatch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Measure" + ] + }, + { + "symbol": "HMath.Image.Spatial.AxisConnected", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Bicubic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Bilinear", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Connectivity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.FullyConnected", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Interpolation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Lanczos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.Nearest", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.connectedComponents", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.distanceTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.resize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.rotate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.translate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Image.Spatial.warp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Image.Spatial" + ] + }, + { + "symbol": "HMath.Interchange.Array.Array", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.BigEndian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Bool8", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.C128", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.C64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.COrder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.DType", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Element", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Endian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.F32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.F64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.FOrder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.I16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.I32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.I64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.I8", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.InterchangeError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.InterchangeIOError", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.InvalidData", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.LimitExceeded", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Limits", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange.Array", + "HMath.Interchange", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.LittleEndian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Order", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.U16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.U32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.U64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.U8", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.Unsupported", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.array", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayBytes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayDType", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayEndian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayMetadata", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayOffset", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.arrayStrides", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.boundedInt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array" + ] + }, + { + "symbol": "HMath.Interchange.Array.byteOffsets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array" + ] + }, + { + "symbol": "HMath.Interchange.Array.checkLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array" + ] + }, + { + "symbol": "HMath.Interchange.Array.contiguousArray", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.defaultLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.denseStrides", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementBytes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.elementType", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.fromValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.getElement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.guardI", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxArchiveEntries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxBytes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxElements", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxMetadata", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.maxRank", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.putElement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.rawDecode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.rawEncode", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.repack", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.toMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.toTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.toValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.validateShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Array.withMetadata", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Array", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Binary.crc32", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Binary", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Binary.decodeBinary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Binary", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Binary.encodeBinary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Binary", + "HMath.Interchange" + ] + }, + { + "symbol": "HMath.Interchange.Binary.runDecoder", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Binary" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Compression", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Gzip", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.RawDeflate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.Zlib", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.compress", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.compressionAvailable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.Compression.decompress", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Compression" + ] + }, + { + "symbol": "HMath.Interchange.IO.MappedArray", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.RawSpec", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interchange.IO", + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedReadBytes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.mappedValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.readArrayFile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.readRawChunks", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.withMappedArray", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.writeArrayFile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.IO.writeRawChunks", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.IO" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.decodeNpy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Numpy" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.decodeNpz", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Numpy" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.encodeNpy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Numpy" + ] + }, + { + "symbol": "HMath.Interchange.Numpy.encodeNpz", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Numpy" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeDelimited", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeMatrixMarket", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interchange.Text.decodeText", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeDelimited", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeMatrixMarket", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interchange.Text.encodeText", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interchange.Text" + ] + }, + { + "symbol": "HMath.Interpolation.Approximation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation", + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.BSpline", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Barycentric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Clamp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Clamped", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Cubic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Extrapolate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Extrapolation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Gaussian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.InterpolationMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.InverseMultiquadric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Lagrange", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Linear", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Multiquadric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Natural", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Nearest", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Newton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Periodic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.PiecewisePolynomial", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.RBF", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.RadialKernel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.Reject", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.SplineBoundary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.ThinPlate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.akima", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.approximationCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.approximationError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.approximationIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.arcLength", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.bSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.bezier", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.cardinalSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.catmullRom", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.chebyshevApproximate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.cubicHermite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.cubicSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.curveIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.derivativeBSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.differentiatePiecewise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.evaluateBSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.evaluateChebyshev", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.evaluatePiecewise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.evaluateRBF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.fitRBF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.gridInterpolate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.hermite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.insertKnot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.integratePiecewise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.interpolate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.interpolationError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.inverseDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.kochanekBartels", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.kriging", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.nonlinearFit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.pade", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.pchip", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.piecewiseKnots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.piecewisePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.polynomialFit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.rationalBezier", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.rationalFit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.remez", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.shepard", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Interpolation.smoothingSpline", + "kind": "function-or-field", + "exported_from": [ + "HMath.Interpolation" + ] + }, + { + "symbol": "HMath.Linear.add", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.addChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.dot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.dotChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.magnitude", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.normalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.scale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.Linear.subtractChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Linear" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Average", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.ClusterModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Complete", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.GaussianMixture", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Linkage", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Merge", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering", + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Single", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.Ward", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.affinityPropagation", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.clusterCenters", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.cutHierarchy", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.dbscan", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.extractOPTICS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.fitGaussianMixture", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.hierarchical", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMeans", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMeansPlusPlus", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.kMedoids", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.leftCluster", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.meanShift", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mergeDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mergedSize", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.miniBatchKMeans", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureCovariances", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureMeans", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureResponsibilities", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.mixtureWeights", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.optics", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.predictClusters", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.rightCluster", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Clustering.spectralClustering", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Clustering" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.CCA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.FactorAnalysis", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.ICA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.IncrementalPCA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.KernelPCA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.PCA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.PLS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.canonicalCorrelations", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.classicalMDS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.factorLoadings", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.factorNoise", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.finishPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitCCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitFactorAnalysis", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitICA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitKernelPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.fitPLS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.incrementalPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.inversePCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.isomap", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.mergePCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaComponents", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.pcaVariances", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.predictPLS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.randomProjection", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformCCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformICA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformKernelPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.transformPCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.truncatedSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.tsne", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.umap", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Decomposition.updatePCA", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Decomposition" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.Dataset", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.Fit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning", + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.MLConfig", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning", + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.defaultMLConfig", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitConverged", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.fitted", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlRate", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlSeed", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Internal.mlTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.BallTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.IndexKind", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.IsolationForest", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.KDTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.LSH", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.NeighborResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors", + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.OneClassSVM", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.SpatialIndex", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.buildIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.buildLSH", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.decisionOneClassSVM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.exhaustive", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.fitIsolationForest", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.fitOneClassSVM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.knnClassify", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.knnRegress", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.localOutlierFactor", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.nearestNeighbors", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.neighbors", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.queryLSH", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.scoreIsolationForest", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Neighbors.visitedLeaves", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Neighbors" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.BoxCox", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.ConstantImpute", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Encoder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Fold", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing", + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Imputation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Imputer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MeanImpute", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MedianImpute", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.MinMax", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.PowerTransform", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.QuantileTransformer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.RejectUnknown", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.RobustScale", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Scaler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Scaling", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.Standardize", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.UnknownCategory", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.YeoJohnson", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.ZeroUnknown", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitEncoder", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitImputer", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitQuantileTransformer", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.fitScaler", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.gridSearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.impute", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inversePowerTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inverseQuantileTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.inverseTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.kFold", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.labelDecode", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.labelEncode", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.oneHotEncode", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.powerTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.quantileTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.randomSearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.stratifiedKFold", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.trainTestSplit", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.trainingIndices", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.transform", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Preprocessing.validationIndices", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Preprocessing" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BayesFamily", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BayesianLinear", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BernoulliBayes", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.BinomialLogit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Discriminant", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.ElasticNet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GLM", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GLMFamily", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GPClassifier", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GaussianBayes", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.GaussianProcess", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Kernel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Lasso", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.LinearKernel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.LinearModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.MultinomialBayes", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.MultinomialModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.NaiveBayes", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Ordinary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Penalty", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.PoissonLog", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.PolynomialKernel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.RBFKernel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.RecursiveLS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.Ridge", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.SVM", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.bayesianCovariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.bayesianMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.coefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.decisionSVM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitBayesian", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitDiscriminant", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGLM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGPClassifier", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitGaussianProcess", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitLinear", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitMultinomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitNaiveBayes", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitRobust", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitSVM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.fitWeighted", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.kernel", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.polynomialFeatures", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictDiscriminant", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGLM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGPClassifier", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictGaussianProcess", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictLinear", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictMultinomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictNaiveBayes", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.predictSVM", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.recursiveCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.recursiveLS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.MachineLearning.Regression.updateRecursiveLS", + "kind": "function-or-field", + "exported_from": [ + "HMath.MachineLearning.Regression" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.bandedMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.batchedMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.blockMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.changeCoordinates", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.columnSpace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.complexPseudoinverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.conditionNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.conjugateTranspose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.frobeniusNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.generateMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.hermitianMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.khatriRao", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.kronecker", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixExp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixLog", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixLogGeneral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixNorm1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixNormInfinity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixRank", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixSqrt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.matrixSqrtGeneral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.nullSpace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.permutationMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.polar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.pseudoinverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.rowSpace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.spectralNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.symmetricMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.trace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.triangularMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Advanced.zipMatrixWith", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Advanced" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Arnoldi", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Decomposition", + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Bidiagonal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Decomposition", + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.Iteration", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Decomposition", + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldi", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldiBasis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.arnoldiHessenberg", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalB", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalV", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.bidiagonalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.cholesky", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.gaussJordan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.gaussianElimination", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.givensQR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.inverseIteration", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.iterationVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.jordanChains", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.jordanForm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.lanczos", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.ldlt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.powerIteration", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.qrIteration", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.rayleighIteration", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Decomposition.tridiagonalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Decomposition" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.IterativeOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Iterative", + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.IterativeResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Iterative", + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.Preconditioner", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.absoluteTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.applyPreconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.bicg", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.bicgstab", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.blockJacobiPreconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.conjugateGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.defaultIterativeOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.gaussSeidelSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.gmres", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.ic0Preconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.identityPreconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.ilu0Preconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeNormalResidualNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeRefinement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeResidualNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.iterativeSolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.jacobiPreconditioner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.jacobiSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.lsmr", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.lsqr", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.maximumIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.minres", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.preconditionedCG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.relativeTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.Iterative.sorSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.Iterative" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Balance", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.ComplexSVD", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Eigen", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.GeneralizedEigen", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Hessenberg", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.QZ", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.SVD", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.Schur", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LAPACK", + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balanceScales", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.balancedMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexSingularValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.complexVT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenAlpha", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenBeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenvalues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.eigenvectors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.fullSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.generalizedEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.generalizedEigenvectors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenberg", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenbergH", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.hessenbergQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qz", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzAlpha", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzBeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzS", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.qzZ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.randomizedSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schur", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurEigenvalues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.schurT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.singularValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svdU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.svdVT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.symmetricEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LAPACK.truncatedSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LAPACK" + ] + }, + { + "symbol": "HMath.Matrix.LU.LU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.determinant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.determinantLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.inverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.luDecompose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.luDecomposeWithTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.luLower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.luPermutation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.luUpper", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.solve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.LU.solveMatrixLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.LU" + ] + }, + { + "symbol": "HMath.Matrix.Matrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.QR.QR", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.applyQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.applyQT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.leastSquares", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.leastSquaresMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrDecompose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrDecomposeWithTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrPermutation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.qrRank", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.ridgeSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.ridgeSolveMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.solveMatrixQR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.QR.solveQR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix.QR" + ] + }, + { + "symbol": "HMath.Matrix.addMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.addMatrixChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.at", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.atChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.diagonal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.diagonalChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.fromList", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.fromListChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.hadamard", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.hadamardChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.identity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.identityChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.multiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.multiplyChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.reshape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.reshapeChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.scaleMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.shape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.sliceMatrixChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.subtractMatrixChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.toList", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.transposeMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.Matrix.zeroMatrixChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Matrix" + ] + }, + { + "symbol": "HMath.NumberTheory.areAmicable", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.bailliePSW", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.bezout", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.carmichael", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.chineseRemainder", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.continuedFraction", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.convergents", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.discreteLog", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.divisorCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.divisorSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.divisors", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.eulerTotient", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.extendedGCD", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.farey", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.fermatFactor", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.fibonacciFast", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.fromContinuedFraction", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.gcdInteger", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.integerSquareRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.isPerfectNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.isPrimeExact", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.jacobiSymbol", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.kroneckerSymbol", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.lcmInteger", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.legendreSymbol", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.linearDiophantine", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.liouville", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.millerRabin", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.mobius", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.modInverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.modPow", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.multiplicativeOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.nextPrime", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.partitionCount", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.partitions", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.pellFundamental", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.perfectPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.pollardPMinusOne", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.pollardRho", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.primeFactorization", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.primitiveRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.segmentedSieve", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.sieveAtkin", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.sieveEratosthenes", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.NumberTheory.tonelliShanks", + "kind": "function-or-field", + "exported_from": [ + "HMath.NumberTheory" + ] + }, + { + "symbol": "HMath.Numeric.BFloat16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.BigFloat", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Decimal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.DivisionByZero", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Dual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric", + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.DualQuaternion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric", + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Fixed", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Float16", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Float32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Float64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.IEEEClass", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Inexact", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Interval", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.InvalidOperation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NearestEven", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NegativeInfinity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NegativeZero", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Normal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NotANumber", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NumericException", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NumericLimits", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric", + "HMath.Numeric", + "HMath.Constants", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.NumericOverflow", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.NumericUnderflow", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.PositiveInfinity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.PositiveZero", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Quaternion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric", + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Rounded", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric", + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.RoundingMode", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.Subnormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.TowardNegative", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.TowardPositive", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.TowardZero", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16Bits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16FromBits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bfloat16Limits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigDivide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigExp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigFloat", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigLog", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigPrecision", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigRational", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigSqrt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.bigToDouble", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.classify", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.decimal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.decimalAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.decimalDivide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.decimalMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.decimalRational", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.derivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.dualQuaternionInverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.dualQuaternionMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.extended", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixed", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedCoefficient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedDivide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedRational", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fixedScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.float16", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.float16Bits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.float16FromBits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.float16Limits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.frexp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fromBFloat16", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.fromFloat16", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.integerLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.interval", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalBounds", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalContains", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalDivide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.intervalSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.kahanSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.ldexp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.logsumexp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.machineEpsilon", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.maximumExponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.maximumFinite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.minimumExponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.minimumNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.minimumSubnormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.mixedAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.mixedMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.narrowFloat", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.neumaierSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.nextAfter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.numericLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.numericalExceptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.pairwiseSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.primal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.quaternionConjugate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.quaternionInverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.quaternionNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.realToIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.rigidTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.rotateVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.roundRational", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.roundedValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.safeIntegralCast", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.saturatingCast", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.significandDigits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric", + "HMath.Constants" + ] + }, + { + "symbol": "HMath.Numeric.sumErrorBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.tangent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.transformPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.ulpDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.Numeric.withinULPs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Numeric" + ] + }, + { + "symbol": "HMath.ODE.AdamsBashforth", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.AdamsMoulton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.AnyDirection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.BDF", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.BackwardEuler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.DOP853", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.DormandPrince", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Euler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Event", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE", + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.EventDirection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Falling", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.HamiltonianMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Heun", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Leapfrog", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Method", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Midpoint", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.ODE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.ODEOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE", + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.PredictorCorrector", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.RK2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.RK23", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.RK4", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.RK45", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Radau", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Rising", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Rosenbrock", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.SymplecticEuler", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Trajectory", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE", + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.Verlet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.defaultODEOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.equilibrium", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.eventState", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.eventTime", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.initialStep", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.interpolateTrajectory", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.locateEvents", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.lyapunovExponents", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.maximumStep", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.maximumSteps", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.minimumStep", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.newtonIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.odeAbsoluteTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.odeRelativeTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.phaseTrajectories", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.sensitivities", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveAdaptive", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveBoundary", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveDAE", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveHamiltonian", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveIVP", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.solveNystrom", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.trajectoryDerivatives", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.trajectoryStates", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.ODE.trajectoryTimes", + "kind": "function-or-field", + "exported_from": [ + "HMath.ODE" + ] + }, + { + "symbol": "HMath.Optimization.Common.Armijo", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.ConstantRate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.CosineAnnealing", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.EarlyStopping", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common", + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.ExponentialDecay", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.Gradient", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.Hessian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.LearningRate", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.LineSearch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.Objective", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.OptimizeOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common", + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.OptimizeResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common", + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.StepDecay", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.StrongWolfe", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.Warmup", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.add", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.bestScore", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkBudget", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.checkedValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.defaultOptimizeOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.dot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.earlyStopping", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.identity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.learningRate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.lineSearch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.matMul", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.matVec", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.norm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optConverged", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optGradientNorm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optLearningRate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optMaxEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optMaxIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.optValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.outer", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.result", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.scale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.solveDense", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.staleSteps", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.stopped", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Common.sub", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Common" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.AugmentedLagrangian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.Constraint", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.Equality", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.InteriorPoint", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LPResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained", + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LessEqual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.LogBarrier", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.PenaltyMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.QuadraticPenalty", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.cobyla", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.constrainedMinimize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.feasibility", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.linearProgramming", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpBasis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.lpValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.paretoFront", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.quadraticProgramming", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.revisedSimplex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.slsqp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.Constrained.weightedObjective", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Constrained" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AMSGrad", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaDelta", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaGrad", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdaMax", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Adam", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.AdamW", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.GradientDescent", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.GradientMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Momentum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Nadam", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.Nesterov", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.OptimizerState", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.RAdam", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.RMSProp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.coordinateDescent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.fista", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.initializeOptimizer", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.miniBatchGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.minimizeGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.minimizeGradientWithCallback", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.optimizerStep", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.projectedGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.proximalGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.FirstOrder.stochasticGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.FirstOrder" + ] + }, + { + "symbol": "HMath.Optimization.Global.CMAES", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.DifferentialEvolution", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.GeneticAlgorithm", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.GlobalMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.ParticleSwarm", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.SimulatedAnnealing", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.basinHopping", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Global.globalMinimize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Global" + ] + }, + { + "symbol": "HMath.Optimization.Local.BFGS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.BrentSearch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.CauchyLoss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.DFP", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.Dogleg", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.GoldenSection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.HuberLoss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.JacobianFunction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.LBFGS", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.LeastSquaresLoss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.Newton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.NewtonCG", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.NewtonMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.QuasiNewton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.ResidualFunction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.SR1", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.ScalarMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.SoftL1", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.SquaredLoss", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.TernarySearch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.TrustRegion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.leastSquares", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeNewton", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeQuasiNewton", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.minimizeScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.nelderMead", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.nonlinearCG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.Optimization.Local.powell", + "kind": "function-or-field", + "exported_from": [ + "HMath.Optimization.Local" + ] + }, + { + "symbol": "HMath.PDE.Boundary", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Dirichlet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Discretization", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.FiniteDifference", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.FiniteElement", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.FiniteVolume", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Grid", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Neumann", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.PDEOperator", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.PDEResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE", + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Periodic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.Robin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.advection", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.advectionDiffusion", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.assemblePDE", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.cflNumber", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.diffusion", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.flattenIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.grid", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.gridCoordinates", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.gridShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.gridSpacing", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.heat", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.helmholtz", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.laplace", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.laplacianStencil", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.manufacturedError", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.methodOfLines", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeBoundaryLoad", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeErrorEstimate", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeMass", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeStiffness", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pdeValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.poisson", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.pseudoSpectralDiffusion", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.solveElliptic", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.spatialGradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.spectralDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.spectralLaplacian", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.spectralPoisson", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.stabilityLimit", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.unflattenIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.PDE.wave", + "kind": "function-or-field", + "exported_from": [ + "HMath.PDE" + ] + }, + { + "symbol": "HMath.Polynomial.Polynomial", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.PowerSeries", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.RationalFunction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.aberthEhrlich", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.addPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.addRationalFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.addSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.bernsteinPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.chebyshevApproximation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.chebyshevPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.coefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.companionMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.composePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.composeSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.countRealRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.differentiatePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.differentiateSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.dividePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.divideSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.durandKerner", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.evaluatePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.evaluateRationalFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.expSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.factorRationalPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.gcdPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.hermitePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.integratePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.integrateSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.isolateRealRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.lagrangeInterpolation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.laguerrePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.legendrePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.logSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.monicPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.multiplyPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.multiplyRationalFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.multiplySeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.newtonInterpolation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.partialFractions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.polynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.polynomialDegree", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.polynomialRegression", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.powerSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.rationalDenominator", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.rationalFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.rationalNumerator", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.rationalRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.reciprocalSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.scalePolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.seriesCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.squareFreeFactors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.sturmSequence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Polynomial.subtractPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Polynomial" + ] + }, + { + "symbol": "HMath.Probability.Bernoulli", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Beta", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.BetaBinomial", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Binomial", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Categorical", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Cauchy", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.ChiSquare", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.DiscreteUniform", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Distribution", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Empirical", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Exponential", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.FisherF", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Gamma", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.GaussianKDE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.GeneralizedExtremeValue", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Geometric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Gumbel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.HMM", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Hypergeometric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Laplace", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.LogNormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Logistic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Markov", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Maxwell", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Mixture", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.NegativeBinomial", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Normal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Pareto", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Poisson", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Rayleigh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Skellam", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.StudentT", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Triangular", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.TruncatedNormal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Uniform", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.VonMises", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.Weibull", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.backward", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.baumWelch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.bayes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.betaBernoulliUpdate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.cdf", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.conditionalProbability", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.density", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.dirichletDensity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.entropy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.expectation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.fitBernoulli", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.fitExponential", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.fitMAPGrid", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.fitMLEGrid", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.fitNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.forward", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.gammaPoissonUpdate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.gaussianKDE", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.goodnessOfFit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.hazard", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.hmm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.logDensity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.logLikelihood", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.markov", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.moments", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.multinomialPMF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.multivariateNormalLogDensity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.normalNormalUpdate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.posteriorStates", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.quantile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.sample", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.sampleMultivariateNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.sampleWishart", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.stationary", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.survival", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.transition", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.validateDistribution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.viterbi", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Probability.wishartLogDensity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Probability" + ] + }, + { + "symbol": "HMath.Quaternion.Quaternion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.add", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.axisAngle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.components", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.conjugate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.exponential", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.fromEuler", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.fromMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.inverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.logarithm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.multiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.nlerp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.norm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.normalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.quaternion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.rotateVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.scale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.slerp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.squad", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.swingTwist", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.toAxisAngle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.toEuler", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Quaternion.toMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Quaternion" + ] + }, + { + "symbol": "HMath.Random.AliasTable", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.ChaCha20", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.Generator", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.MT19937", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.PCG32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.Philox4x32", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.RNG", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.Threefry2x64", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.Xoroshiro128Plus", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.Xoshiro256StarStar", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.aliasSample", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.aliasTable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.beta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.binomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.boxMuller", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.cloneRNG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.entropySeed", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.exponential", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.faure", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.gamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.gibbs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.halton", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.hamiltonianMonteCarlo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.importance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.inverseTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.latinHypercube", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.marsagliaNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.metropolisHastings", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.monteCarlo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.nextWord64", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.normal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.poisson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.randomQuality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.rejection", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.reservoir", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.restoreRNG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.sampleN", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.seedRNG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.serializeRNG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.shuffle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.sobol", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.splitRNG", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.stratified", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.uniform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.uniformInt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.uniformOpen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.weighted", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.withReplacement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.withoutReplacement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Random.zigguratNormal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Random" + ] + }, + { + "symbol": "HMath.Root.Aitken", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Bisection", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Bracket", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.BracketMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Brent", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Broyden", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.DerivativeMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.FixedPointMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Halley", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Householder3", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Illinois", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.MultivariateNewton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Newton", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.NewtonTrustRegion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Picard", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.RegulaFalsi", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.Ridder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.RootOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root", + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.RootResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root", + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.SteffensenFixed", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.SystemMethod", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.SystemRootResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Root", + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.anderson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.bracket", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.bracketScan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.defaultRootOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.fixedPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.isolateIntervals", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.polynomialRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.realPolynomialRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootErrorBound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootMaxEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootMaxIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootStepTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.rootValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.secant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.solveBracket", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.solveDerivative", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.solveSystem", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.steffensen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.systemEvaluations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.systemIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.systemResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Root.systemRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Root" + ] + }, + { + "symbol": "HMath.Rotation.DualQuaternion", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.SE3", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.SO3", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.compose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.composeRotation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.dualParts", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.dualQuaternion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.expSE3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.expSO3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.fromDualQuaternion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.fromHomogeneous", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.identityRotation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.identityTransform", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.interpolateDual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.inverse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.inverseDual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.inverseRotation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.logSE3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.logSO3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.multiplyDual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.rotate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.rotationPart", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.rotationQuaternion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.se3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.so3", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.toDualQuaternion", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.toHomogeneous", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.transformPoint", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Rotation.translationPart", + "kind": "function-or-field", + "exported_from": [ + "HMath.Rotation" + ] + }, + { + "symbol": "HMath.Scalar.absolute", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.absoluteError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.add", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.bankersRound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.bernoulli", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.catalan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.ceilChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.checkedAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.checkedFloatMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.checkedMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.checkedSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.clampChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.combinations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.cubeRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.cumulativeProduct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.cumulativeSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.divide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.doubleFactorial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.euclideanDivision", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.expChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.expm1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.factorialChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.fallingFactorial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.fibonacciChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.floorChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.fusedMultiplyAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.harmonic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.hypot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.integerFraction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.integerPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.inverseLerp", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.lerpChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.log1p", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.logChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.lucas", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.maximumScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.minimumScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.modularPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.multinomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.multiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.nthRoot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.permutations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.positiveModulo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.power", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.prefixSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.quotientRemainder", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.reciprocalSqrt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.relativeError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.remap", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.risingFactorial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.roundChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.roundDigits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.saturatingAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.saturatingMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.saturatingSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.sign", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.smootherstep", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.smoothstep", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.sqrtChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.step", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.subtractScalar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Scalar.truncateChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Scalar" + ] + }, + { + "symbol": "HMath.Signal.Bandpass", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Bandstop", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Bartlett", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Bessel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Biorthogonal53", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Blackman", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Butterworth", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.ChebyshevI", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.ChebyshevII", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Daubechies2", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Daubechies4", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.DolphChebyshev", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Elliptic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Filter", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.FilterBand", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.FilterFamily", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.FlatTop", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Gaussian", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.GaussianDerivative", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.GaussianState", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Haar", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Hamming", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Hann", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Highpass", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Kaiser", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Lowpass", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.MexicanHat", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Morlet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.MotherWavelet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Peak", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal", + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Tukey", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Wavelet", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.WaveletPacket", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.WaveletTree", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.Window", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.allPass", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.antiAlias", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.autocorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.circularConvolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.convolution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.correlation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.cwt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.designIIR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.detrend", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.downsample", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.dwt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.envelope", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.extendedKalman", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.filterCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.filterSignal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.filterState", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.fir", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.frequencyResponse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.gaussianFilter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.gaussianState", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.idwt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.iir", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.inverseWaveletPackets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.kalman", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.medianFilter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.movingAverage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.noiseEstimate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.normalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.notch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.overlapAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.overlapSave", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.packetBands", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.peakHeight", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.peakIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.peakProminence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.peakWidth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.peaks", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.resample", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.resamplePolyphase", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.resetFilter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.rms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.savitzkyGolay", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.signalToNoise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.smooth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.stateCovariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.stateMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.unscentedKalman", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.unwrapPhase", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.upsample", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.waveletApproximation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.waveletDenoise", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.waveletDetails", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.waveletPackets", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.wiener", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.window", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.windowedSinc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Signal.zeroCrossings", + "kind": "function-or-field", + "exported_from": [ + "HMath.Signal" + ] + }, + { + "symbol": "HMath.Sparse.BSR", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.COO", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.CSC", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.CSR", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.DIA", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.ELLPACK", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.Sparse", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.SparseFormat", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.SparseLU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.SparseQR", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.SparseTensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseEigenResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse.Spectral", + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseSVD", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse.Spectral", + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.SparseSpectralOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Sparse.Spectral", + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.defaultSparseSpectralOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseAbsoluteTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseDominantEigen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenResidual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenvalue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseEigenvector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseIterationLimit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseLeftVectors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseRelativeTolerance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseRightVectors", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularResiduals", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseSingularValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseTruncatedSVD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.Spectral.sparseWorkspaceLimit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse.Spectral" + ] + }, + { + "symbol": "HMath.Sparse.denseToSparse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.fromFormat", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.nonzeros", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparse", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseCholesky", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseDiagonalSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseEigenReference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseEntries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseKronecker", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseLULower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseLUPermutation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseLUUpper", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseQR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseQRApplyQT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseQRUpper", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseSVDReference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseSolveLU", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseStorageBytes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorEntries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorLookup", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTensorShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseToDense", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTranspose", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.sparseTriangularSolve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.spmm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.spmv", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toBSR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toCOO", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toCSC", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toCSR", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toDIA", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Sparse.toELLPACK", + "kind": "function-or-field", + "exported_from": [ + "HMath.Sparse" + ] + }, + { + "symbol": "HMath.Special.SFResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Special", + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.airy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.associatedLegendre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.bernoulliPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.besselI", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.besselJ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.besselK", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.besselY", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.beta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.betaI", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.boseEinstein", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.clausen", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.clebschGordan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.complex1F1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.cosineIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.coulombWave", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.dawson", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.debye", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.digamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.dilogarithm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.ellipticE", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.ellipticF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.ellipticPi", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.erf", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.erfc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.erfcx", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.eulerPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.exponentialIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.fermiDirac", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.fresnel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.gamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.gammaP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.gammaQ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.gegenbauer", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.hankel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.hurwitzZeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.hypergeometric", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.hypergeometric1F1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.hypergeometric2F1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.incompleteBeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.incompleteGamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.inverseErf", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.jacobiElliptic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.lambertW", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.legendre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.logBeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.logGamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.logarithmicIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.mathieu", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.normalCDF", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.normalQuantile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.parabolicCylinder", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.polygamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.polylogarithm", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.riemannZeta", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.scaledBesselI", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.scaledBesselK", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sfError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sfValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sineIntegral", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sphericalBesselJ", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sphericalBesselY", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.sphericalHarmonic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.struve", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.trigamma", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.wigner3j", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.wigner6j", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Special.wigner9j", + "kind": "function-or-field", + "exported_from": [ + "HMath.Special" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.Streaming", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.TestResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Statistics.Advanced", + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.andersonDarling", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.anova", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.arithmeticMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.autocorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.bartlett", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.benjaminiHochberg", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.bonferroni", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.bootstrap", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.centralMoment", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.chiSquareTest", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.coefficientOfVariation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.cohensD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.combineStreaming", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.confidenceInterval", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.correlation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.covariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.covarianceMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.crossCorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.dataRange", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.degreesOfFreedom", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.emptyStreaming", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.entropy", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.etaSquared", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.exponentialMovingAverage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.fisherExact", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.geometricMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.grubbs", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.harmonicMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.histogramND", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.huberLocation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.interquartileRange", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.jackknife", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.jsDivergence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kendall", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.klDivergence", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kolmogorovSmirnov", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kruskalWallis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kurtosis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.levene", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.mannWhitney", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.masked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.median", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.medianAbsoluteDeviation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.modes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.movingAverage", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.movingVariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.mutualInformation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.normalSampleSize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.normalTestPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.oneSampleT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.pValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.pairedT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.partialCorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.percentile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.permutationTest", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.populationSD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.populationVariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.quantile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.rms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.sampleSD", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.sampleVariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.shapiroWilk", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.skewness", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.spearman", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.standardError", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.streamingResult", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.testStatistic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.trimmedMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.tukeyOutliers", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.twoSampleT", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.updateStreaming", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.varianceFTest", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.weightedMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.welchAnova", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.wilcoxon", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.winsorizedMean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.zScores", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.zTest", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics.Advanced" + ] + }, + { + "symbol": "HMath.Statistics.mean", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics" + ] + }, + { + "symbol": "HMath.Statistics.median", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics" + ] + }, + { + "symbol": "HMath.Statistics.standardDeviation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics" + ] + }, + { + "symbol": "HMath.Statistics.variance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Statistics" + ] + }, + { + "symbol": "HMath.Symbolic.Any", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Assumptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.BinaryPattern", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.CallPattern", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Direction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.DoesNotExist", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Equal", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Exactly", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.FiniteLimit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.FromLeft", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.FromRight", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Greater", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.GreaterEqual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Guarded", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Inconsistent", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Integral", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Less", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.LessEqual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.LimitResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.LinearSolution", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Negative", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.NegativeInfinity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.NonNegative", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.NonPositive", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.NonZero", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.NotEqual", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.ParametricSolution", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Pattern", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.PolynomialFactorization", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Positive", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.PositiveInfinity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Property", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Real", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Relation", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.RelationOp", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.RelationResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.RewriteRule", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Series", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.SymbolicMatrix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.SymbolicOptions", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic", + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Truth", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.TwoSided", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.UnaryPattern", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.Unresolved", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.applyRewrite", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.assumptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.collectTerms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.defaultSymbolicOptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.differentiate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.exactPolynomialRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.expand", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.factorLeading", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.factorPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.factorTerms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.formalPowerSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.fromPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.gradient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.guardedValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.hessian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.integrateBasic", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.integrateByParts", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.integrateRational", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.integrateSubstitution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.jacobian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.laurentSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.logarithmicSimplify", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.maclaurinSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.matchPattern", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.matrixAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.matrixExpressions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.matrixMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.multiplyFormalSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.noAssumptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.normalize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.numericalPolynomialRoots", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.numericalSubstitution", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.proves", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.rationalSimplify", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.reciprocalFormalSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.requiredConditions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.rewritePattern", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.rewriteReplacement", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.rewriteRequirements", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.seriesCenter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.seriesMinimumPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.seriesTerms", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.simplify", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.simplifyRelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.solveLinearEquations", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.solveLinearInequality", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.substitute", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicAssumptions", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicDeterminant", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicEigenvalues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicLimit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicLimits", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.symbolicMatrix", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.taylorSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.toLaTeX", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.toMathML", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.toPolynomial", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Symbolic.trigonometricSimplify", + "kind": "function-or-field", + "exported_from": [ + "HMath.Symbolic" + ] + }, + { + "symbol": "HMath.Tensor.CPU", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.ColumnMajor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.Device", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.Layout", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.MutableTensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.freezeTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.modifyMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.mutableAlignment", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.mutableShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.newMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.readMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.sliceMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.thawTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.transposeMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.withMutableBuffer", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.writeMutable", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor.Mutable" + ] + }, + { + "symbol": "HMath.Tensor.RowMajor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.Strided", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.Tensor", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.TensorGraph", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.argmax", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.argmin", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.argsort", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.batchedMatmul", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.booleanIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.broadcastTo", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.chunkTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.concatenate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.contiguous", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.cumulativeProduct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.cumulativeSum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.deserializeTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.einsum", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.evaluateGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.expand", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.fancyIndex", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.flattenTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.flipTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.gather", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.indexTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.inferBroadcast", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.inputGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.isContiguous", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.mapGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.mapTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.maskedFill", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.maskedSelect", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.maxAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.meanAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.minAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.moveAxis", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.nonzero", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.normAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.numel", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.padTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.permute", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.productAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.promoteTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.repeatTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.reshapeTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.roll", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.rotate", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.scatter", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.scatterAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.serializeTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.shapeSize", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.sliceTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.sortTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.splitTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.squeeze", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.stack", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.sumAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.swapAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorAnd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorArange", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorColumnMajor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorDType", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorDevice", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorDivide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorEqual", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorFull", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorKronecker", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorLayout", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorLess", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorLinspace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorLogspace", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorMultiply", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorNot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorOffset", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorOnes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorOr", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorRandom", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorShape", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorStrides", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensorZeros", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tensordot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.tile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.topk", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.transposeTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.unique", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.unsqueeze", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.varianceAxes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.whereTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.zipGraph", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.Tensor.zipTensor", + "kind": "function-or-field", + "exported_from": [ + "HMath.Tensor" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Alignment", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BackwardFill", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BinLast", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BinMean", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Fill", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.ForwardFill", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Inner", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LeftAligned", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LinearFill", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LinearSamples", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMaximum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMean", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMinimum", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingSD", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingVariance", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Outer", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Resampling", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Rolling", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Series", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.align", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.autocorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.crossCorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.cumulativeReturns", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.difference", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.durbinLevinson", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.exponentialAverage", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.fillMissing", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.isRegular", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.logarithmicReturns", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.observations", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.partialAutocorrelation", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.regularSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.resample", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.rolling", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.series", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.seriesValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.weightedAverage", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.yuleWalker", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.DTWResult", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics", + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Deterministic", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.ForecastMetric", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Level", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.LinearTrend", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MAE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MAPE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MASE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MSE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.RMSE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.SMAPE", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Stationarity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Diagnostics", + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.anomalies", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.augmentedDickeyFuller", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.changePoints", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.cusum", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dtwDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dtwPath", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dynamicTimeWarping", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.forecastError", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.kpss", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.spectrum", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityCriticalValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityNull", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityObservations", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityStatistic", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Diagnostics" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.ARIMAModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.ARModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Decomposition", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models", + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Holt", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.HoltWinters", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.SARIMAOrder", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models", + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.STLConfig", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models", + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Simple", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Smoothing", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.VARModel", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaInnovationVariance", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaParameters", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaResiduals", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.decompose", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.defaultSTLConfig", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.differenceOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitAR", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitARIMA", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitARMA", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitMA", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitSARIMA", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitVAR", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastAR", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastARIMA", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastVAR", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.kalmanSeries", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.maOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.remainderComponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalAROrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalComponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalDifferenceOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalMAOrder", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalPeriod", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.smoothForecast", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stl", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlInnerIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlLowPassWindow", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlPeriod", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlRobustIterations", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlSeasonalWindow", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlTrendWindow", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.trendComponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.varCoefficients", + "kind": "function-or-field", + "exported_from": [ + "HMath.TimeSeries.Models" + ] + }, + { + "symbol": "HMath.Trigonometry.CAcos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CAcosh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CAsin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CAsinh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CAtan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CAtanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCos", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCosh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCot", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCoth", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCsc", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CCsch", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CSec", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CSech", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CSin", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CSinh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CTan", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.CTanh", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.ComplexFunction", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acosChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acoshChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acoth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acsc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.acsch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.angleDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.asec", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.asech", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.asinChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.asinhChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.atan2Checked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.atanChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.atanhChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAcos", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAcosh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAsin", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAsinh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAtan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexAtanh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexCos", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexCosh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexFunction", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexSin", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexSinh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexTan", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.complexTanh", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.cosChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.cosc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.coshChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.cot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.coth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.csc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.csch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.greatCircleAngle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.greatCircleDistance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.haversine", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.normalizeAngle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.normalizeSignedAngle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.periodicSawtooth", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.periodicSquare", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.periodicTriangle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sec", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sech", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sinChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sinc", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sincos", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sinhChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sphericalAngles", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sphericalExcess", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.sphericalSide", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.tanChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.tanhChecked", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.versine", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Trigonometry.wrap", + "kind": "function-or-field", + "exported_from": [ + "HMath.Trigonometry" + ] + }, + { + "symbol": "HMath.Units.Dimension", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.Quantity", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.SIPrefix", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Units", + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.Unit", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.addQuantity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.angleDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.atmosphere", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.bar", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.bit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.byte", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.celsius", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.centimetre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.convert", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.cubicMetre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.dataDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.day", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.degree", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.degreesToRadians", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.dimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.dimensionExponents", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.dimensionless", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.divideQuantity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.fahrenheit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.foot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.gigabyte", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.gradian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.gradiansToRadians", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.gram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.hectare", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.hertz", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.hour", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.inUnit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.inch", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.joule", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.kelvin", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.kibibyte", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.kilogram", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.kilometre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.kilometresPerHour", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.lengthDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.litre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.massDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.mebibyte", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.metre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.metresPerSecond", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.metresPerSecondSquared", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.mile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.milesPerHour", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.millilitre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.millimetre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.minute", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.multiplyQuantity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.nauticalMile", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.newton", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.pascal", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.pound", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.prefixExponent", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.prefixName", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.prefixSymbol", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.prefixed", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.quantity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.quantityDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.radian", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.radiansToDegrees", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.radiansToGradians", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.second", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.siPrefixes", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.siValue", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.squareMetre", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.subtractQuantity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.temperatureDifference", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.temperatureDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.timeDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.tonne", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unit", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitName", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitOffset", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitPower", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitProduct", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitQuotient", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.unitScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.watt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Units.yard", + "kind": "function-or-field", + "exported_from": [ + "HMath.Units" + ] + }, + { + "symbol": "HMath.Vector.FixedVector", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.SparseVector", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.Vector", + "kind": "type-or-constructor", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.angle", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.cosineSimilarity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.cross", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.distance", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.fixedValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.fixedVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.gramSchmidt", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.norm0", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.norm1", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.norm2", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.normInfinity", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.normP", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.normalizeVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.outer", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.project", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.reflect", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.refract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.sparseVector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.sparseVectorValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.triple", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vector", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorAdd", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorConcat", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorDimension", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorDot", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorScale", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorSlice", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorSubtract", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + }, + { + "symbol": "HMath.Vector.vectorValues", + "kind": "function-or-field", + "exported_from": [ + "HMath.Vector" + ] + } + ] +} diff --git a/bindings/schema/rotation-objects.json b/bindings/schema/rotation-objects.json new file mode 100644 index 0000000..81a5aed --- /dev/null +++ b/bindings/schema/rotation-objects.json @@ -0,0 +1,525 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Quaternion.quaternion", + "c": [ + "hmath_quaternion_quaternion" + ], + "python": "hmath.quaternion.quaternion", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.components", + "c": [ + "hmath_quaternion_components" + ], + "python": "hmath.quaternion.components", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.norm", + "c": [ + "hmath_quaternion_norm" + ], + "python": "hmath.quaternion.norm", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.normalize", + "c": [ + "hmath_quaternion_normalize" + ], + "python": "hmath.quaternion.normalize", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.inverse", + "c": [ + "hmath_quaternion_inverse" + ], + "python": "hmath.quaternion.inverse", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.conjugate", + "c": [ + "hmath_quaternion_conjugate" + ], + "python": "hmath.quaternion.conjugate", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.multiply", + "c": [ + "hmath_quaternion_multiply" + ], + "python": "hmath.quaternion.multiply", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.add", + "c": [ + "hmath_quaternion_add" + ], + "python": "hmath.quaternion.add", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.scale", + "c": [ + "hmath_quaternion_scale" + ], + "python": "hmath.quaternion.scale", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.rotateVector", + "c": [ + "hmath_quaternion_rotate_vector" + ], + "python": "hmath.quaternion.rotate_vector", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.axisAngle", + "c": [ + "hmath_quaternion_axis_angle" + ], + "python": "hmath.quaternion.axis_angle", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.toAxisAngle", + "c": [ + "hmath_quaternion_to_axis_angle" + ], + "python": "hmath.quaternion.to_axis_angle", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.fromEuler", + "c": [ + "hmath_quaternion_from_euler" + ], + "python": "hmath.quaternion.from_euler", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.toEuler", + "c": [ + "hmath_quaternion_to_euler" + ], + "python": "hmath.quaternion.to_euler", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.toMatrix", + "c": [ + "hmath_quaternion_to_matrix" + ], + "python": "hmath.quaternion.to_matrix", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.fromMatrix", + "c": [ + "hmath_quaternion_from_matrix" + ], + "python": "hmath.quaternion.from_matrix", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.nlerp", + "c": [ + "hmath_quaternion_nlerp" + ], + "python": "hmath.quaternion.nlerp", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.slerp", + "c": [ + "hmath_quaternion_slerp" + ], + "python": "hmath.quaternion.slerp", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.squad", + "c": [ + "hmath_quaternion_squad" + ], + "python": "hmath.quaternion.squad", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.exponential", + "c": [ + "hmath_quaternion_exponential" + ], + "python": "hmath.quaternion.exponential", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.logarithm", + "c": [ + "hmath_quaternion_logarithm" + ], + "python": "hmath.quaternion.logarithm", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.swingTwist", + "c": [ + "hmath_quaternion_swing_twist" + ], + "python": "hmath.quaternion.swing_twist", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.so3", + "c": [ + "hmath_rotation_so3" + ], + "python": "hmath.rotation.so3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.rotationQuaternion", + "c": [ + "hmath_rotation_rotation_quaternion" + ], + "python": "hmath.rotation.rotation_quaternion", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.identityRotation", + "c": [ + "hmath_rotation_identity_rotation" + ], + "python": "hmath.rotation.identity_rotation", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.composeRotation", + "c": [ + "hmath_rotation_compose_rotation" + ], + "python": "hmath.rotation.compose_rotation", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.inverseRotation", + "c": [ + "hmath_rotation_inverse_rotation" + ], + "python": "hmath.rotation.inverse_rotation", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.rotate", + "c": [ + "hmath_rotation_rotate" + ], + "python": "hmath.rotation.rotate", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.expSO3", + "c": [ + "hmath_rotation_exp_so3" + ], + "python": "hmath.rotation.exp_so3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.logSO3", + "c": [ + "hmath_rotation_log_so3" + ], + "python": "hmath.rotation.log_so3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.se3", + "c": [ + "hmath_rotation_se3" + ], + "python": "hmath.rotation.se3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.rotationPart", + "c": [ + "hmath_rotation_rotation_part" + ], + "python": "hmath.rotation.rotation_part", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.translationPart", + "c": [ + "hmath_rotation_translation_part" + ], + "python": "hmath.rotation.translation_part", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.identityTransform", + "c": [ + "hmath_rotation_identity_transform" + ], + "python": "hmath.rotation.identity_transform", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.compose", + "c": [ + "hmath_rotation_compose" + ], + "python": "hmath.rotation.compose", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.inverse", + "c": [ + "hmath_rotation_inverse" + ], + "python": "hmath.rotation.inverse", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.transformPoint", + "c": [ + "hmath_rotation_transform_point" + ], + "python": "hmath.rotation.transform_point", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.expSE3", + "c": [ + "hmath_rotation_exp_se3" + ], + "python": "hmath.rotation.exp_se3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.logSE3", + "c": [ + "hmath_rotation_log_se3" + ], + "python": "hmath.rotation.log_se3", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.toHomogeneous", + "c": [ + "hmath_rotation_to_homogeneous" + ], + "python": "hmath.rotation.to_homogeneous", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.fromHomogeneous", + "c": [ + "hmath_rotation_from_homogeneous" + ], + "python": "hmath.rotation.from_homogeneous", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.dualQuaternion", + "c": [ + "hmath_rotation_dual_quaternion" + ], + "python": "hmath.rotation.dual_quaternion", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.dualParts", + "c": [ + "hmath_rotation_dual_parts" + ], + "python": "hmath.rotation.dual_parts", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.toDualQuaternion", + "c": [ + "hmath_rotation_to_dual_quaternion" + ], + "python": "hmath.rotation.to_dual_quaternion", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.fromDualQuaternion", + "c": [ + "hmath_rotation_from_dual_quaternion" + ], + "python": "hmath.rotation.from_dual_quaternion", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.multiplyDual", + "c": [ + "hmath_rotation_multiply_dual" + ], + "python": "hmath.rotation.multiply_dual", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.inverseDual", + "c": [ + "hmath_rotation_inverse_dual" + ], + "python": "hmath.rotation.inverse_dual", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Rotation.interpolateDual", + "c": [ + "hmath_rotation_interpolate_dual" + ], + "python": "hmath.rotation.interpolate_dual", + "specializations": [ + "original checked Double representation" + ] + }, + { + "symbol": "HMath.Quaternion.Quaternion", + "c": [ + "hmath_quaternion_quaternion" + ], + "python": "hmath.quaternion.Quaternion", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Rotation.SO3", + "c": [ + "hmath_rotation_so3" + ], + "python": "hmath.rotation.SO3", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Rotation.SE3", + "c": [ + "hmath_rotation_se3" + ], + "python": "hmath.rotation.SE3", + "specializations": [ + "original opaque Haskell type" + ] + }, + { + "symbol": "HMath.Rotation.DualQuaternion", + "c": [ + "hmath_rotation_dual_quaternion" + ], + "python": "hmath.rotation.DualQuaternion", + "specializations": [ + "original opaque Haskell type" + ] + } + ] +} diff --git a/bindings/schema/rotation-symbols.txt b/bindings/schema/rotation-symbols.txt new file mode 100644 index 0000000..73b7f5e --- /dev/null +++ b/bindings/schema/rotation-symbols.txt @@ -0,0 +1,49 @@ +hmath_quaternion_quaternion +hmath_quaternion_components +hmath_quaternion_norm +hmath_quaternion_normalize +hmath_quaternion_inverse +hmath_quaternion_conjugate +hmath_quaternion_multiply +hmath_quaternion_add +hmath_quaternion_scale +hmath_quaternion_rotate_vector +hmath_quaternion_axis_angle +hmath_quaternion_to_axis_angle +hmath_quaternion_from_euler +hmath_quaternion_to_euler +hmath_quaternion_to_matrix +hmath_quaternion_from_matrix +hmath_quaternion_nlerp +hmath_quaternion_slerp +hmath_quaternion_squad +hmath_quaternion_exponential +hmath_quaternion_logarithm +hmath_quaternion_swing_twist +hmath_rotation_so3 +hmath_rotation_rotation_quaternion +hmath_rotation_identity_rotation +hmath_rotation_compose_rotation +hmath_rotation_inverse_rotation +hmath_rotation_rotate +hmath_rotation_exp_so3 +hmath_rotation_log_so3 +hmath_rotation_se3 +hmath_rotation_rotation_part +hmath_rotation_translation_part +hmath_rotation_identity_transform +hmath_rotation_compose +hmath_rotation_inverse +hmath_rotation_transform_point +hmath_rotation_exp_se3 +hmath_rotation_log_se3 +hmath_rotation_to_homogeneous +hmath_rotation_from_homogeneous +hmath_rotation_dual_quaternion +hmath_rotation_dual_parts +hmath_rotation_to_dual_quaternion +hmath_rotation_from_dual_quaternion +hmath_rotation_multiply_dual +hmath_rotation_inverse_dual +hmath_rotation_interpolate_dual +hmath_rotations_equal diff --git a/bindings/schema/scalar-extras-objects.json b/bindings/schema/scalar-extras-objects.json new file mode 100644 index 0000000..5f92f82 --- /dev/null +++ b/bindings/schema/scalar-extras-objects.json @@ -0,0 +1,505 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Complex.Exp", + "c": [ + "hmath_complex_exp" + ], + "python": "hmath.complex.exp", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Log", + "c": [ + "hmath_complex_log" + ], + "python": "hmath.complex.log", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Sqrt", + "c": [ + "hmath_complex_sqrt" + ], + "python": "hmath.complex.sqrt", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Sin", + "c": [ + "hmath_complex_sin" + ], + "python": "hmath.complex.sin", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Cos", + "c": [ + "hmath_complex_cos" + ], + "python": "hmath.complex.cos", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Tan", + "c": [ + "hmath_complex_tan" + ], + "python": "hmath.complex.tan", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Sinh", + "c": [ + "hmath_complex_sinh" + ], + "python": "hmath.complex.sinh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Cosh", + "c": [ + "hmath_complex_cosh" + ], + "python": "hmath.complex.cosh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Tanh", + "c": [ + "hmath_complex_tanh" + ], + "python": "hmath.complex.tanh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Asin", + "c": [ + "hmath_complex_asin" + ], + "python": "hmath.complex.asin", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Acos", + "c": [ + "hmath_complex_acos" + ], + "python": "hmath.complex.acos", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Atan", + "c": [ + "hmath_complex_atan" + ], + "python": "hmath.complex.atan", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Asinh", + "c": [ + "hmath_complex_asinh" + ], + "python": "hmath.complex.asinh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Acosh", + "c": [ + "hmath_complex_acosh" + ], + "python": "hmath.complex.acosh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Atanh", + "c": [ + "hmath_complex_atanh" + ], + "python": "hmath.complex.atanh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CSin", + "c": [ + "hmath_trigonometry_c_sin" + ], + "python": "hmath.trigonometry.c_sin", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCos", + "c": [ + "hmath_trigonometry_c_cos" + ], + "python": "hmath.trigonometry.c_cos", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CTan", + "c": [ + "hmath_trigonometry_c_tan" + ], + "python": "hmath.trigonometry.c_tan", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAsin", + "c": [ + "hmath_trigonometry_c_asin" + ], + "python": "hmath.trigonometry.c_asin", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAcos", + "c": [ + "hmath_trigonometry_c_acos" + ], + "python": "hmath.trigonometry.c_acos", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAtan", + "c": [ + "hmath_trigonometry_c_atan" + ], + "python": "hmath.trigonometry.c_atan", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CSinh", + "c": [ + "hmath_trigonometry_c_sinh" + ], + "python": "hmath.trigonometry.c_sinh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCosh", + "c": [ + "hmath_trigonometry_c_cosh" + ], + "python": "hmath.trigonometry.c_cosh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CTanh", + "c": [ + "hmath_trigonometry_c_tanh" + ], + "python": "hmath.trigonometry.c_tanh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAsinh", + "c": [ + "hmath_trigonometry_c_asinh" + ], + "python": "hmath.trigonometry.c_asinh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAcosh", + "c": [ + "hmath_trigonometry_c_acosh" + ], + "python": "hmath.trigonometry.c_acosh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CAtanh", + "c": [ + "hmath_trigonometry_c_atanh" + ], + "python": "hmath.trigonometry.c_atanh", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CSec", + "c": [ + "hmath_trigonometry_c_sec" + ], + "python": "hmath.trigonometry.c_sec", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCsc", + "c": [ + "hmath_trigonometry_c_csc" + ], + "python": "hmath.trigonometry.c_csc", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCot", + "c": [ + "hmath_trigonometry_c_cot" + ], + "python": "hmath.trigonometry.c_cot", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CSech", + "c": [ + "hmath_trigonometry_c_sech" + ], + "python": "hmath.trigonometry.c_sech", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCsch", + "c": [ + "hmath_trigonometry_c_csch" + ], + "python": "hmath.trigonometry.c_csch", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.CCoth", + "c": [ + "hmath_trigonometry_c_coth" + ], + "python": "hmath.trigonometry.c_coth", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.elementary", + "c": [ + "hmath_complex_elementary" + ], + "python": "hmath.complex.elementary", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.complexMatrix", + "c": [ + "hmath_complex_complex_matrix" + ], + "python": "hmath.complex.complex_matrix", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.multiplyMatrices", + "c": [ + "hmath_complex_multiply_matrices" + ], + "python": "hmath.complex.multiply_matrices", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.conjugateTranspose", + "c": [ + "hmath_complex_conjugate_transpose" + ], + "python": "hmath.complex.conjugate_transpose", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.complexFFT", + "c": [ + "hmath_complex_complex_fft" + ], + "python": "hmath.complex.complex_fft", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.complexIFFT", + "c": [ + "hmath_complex_complex_ifft" + ], + "python": "hmath.complex.complex_ifft", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Trigonometry.complexFunction", + "c": [ + "hmath_trigonometry_complex_function" + ], + "python": "hmath.trigonometry.complex_function", + "specializations": [ + "actual Complex Float/Double RealFloat instances" + ] + }, + { + "symbol": "HMath.NumberTheory.chineseRemainder", + "c": [ + "hmath_numbertheory_chinese_remainder" + ], + "python": "hmath.numbertheory.chinese_remainder", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.NumberTheory.linearDiophantine", + "c": [ + "hmath_numbertheory_linear_diophantine" + ], + "python": "hmath.numbertheory.linear_diophantine", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.NumberTheory.perfectPower", + "c": [ + "hmath_numbertheory_perfect_power" + ], + "python": "hmath.numbertheory.perfect_power", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.NumberTheory.primeFactorization", + "c": [ + "hmath_numbertheory_prime_factorization" + ], + "python": "hmath.numbertheory.prime_factorization", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.NumberTheory.partitions", + "c": [ + "hmath_numbertheory_partitions" + ], + "python": "hmath.numbertheory.partitions", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Special.SFResult", + "c": [ + "hmath_special_sf_result" + ], + "python": "hmath.special.SFResult", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Special.sfValue", + "c": [ + "hmath_special_sf_value" + ], + "python": "hmath.special.sf_value", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Special.sfError", + "c": [ + "hmath_special_sf_error" + ], + "python": "hmath.special.sf_error", + "specializations": [ + "original concrete source type/structure" + ] + }, + { + "symbol": "HMath.Complex.Elementary", + "c": [ + "hmath_complex_elementary_object" + ], + "python": "hmath.complex.Elementary", + "specializations": [ + "actual original selector" + ] + }, + { + "symbol": "HMath.Trigonometry.ComplexFunction", + "c": [ + "hmath_trigonometry_complex_function_object" + ], + "python": "hmath.trigonometry.ComplexFunction", + "specializations": [ + "actual original selector" + ] + } + ] +} diff --git a/bindings/schema/scalar-extras-symbols.txt b/bindings/schema/scalar-extras-symbols.txt new file mode 100644 index 0000000..a869ab4 --- /dev/null +++ b/bindings/schema/scalar-extras-symbols.txt @@ -0,0 +1,50 @@ +hmath_complex_exp +hmath_complex_log +hmath_complex_sqrt +hmath_complex_sin +hmath_complex_cos +hmath_complex_tan +hmath_complex_sinh +hmath_complex_cosh +hmath_complex_tanh +hmath_complex_asin +hmath_complex_acos +hmath_complex_atan +hmath_complex_asinh +hmath_complex_acosh +hmath_complex_atanh +hmath_trigonometry_c_sin +hmath_trigonometry_c_cos +hmath_trigonometry_c_tan +hmath_trigonometry_c_asin +hmath_trigonometry_c_acos +hmath_trigonometry_c_atan +hmath_trigonometry_c_sinh +hmath_trigonometry_c_cosh +hmath_trigonometry_c_tanh +hmath_trigonometry_c_asinh +hmath_trigonometry_c_acosh +hmath_trigonometry_c_atanh +hmath_trigonometry_c_sec +hmath_trigonometry_c_csc +hmath_trigonometry_c_cot +hmath_trigonometry_c_sech +hmath_trigonometry_c_csch +hmath_trigonometry_c_coth +hmath_complex_elementary +hmath_complex_complex_matrix +hmath_complex_multiply_matrices +hmath_complex_conjugate_transpose +hmath_complex_complex_fft +hmath_complex_complex_ifft +hmath_trigonometry_complex_function +hmath_numbertheory_chinese_remainder +hmath_numbertheory_linear_diophantine +hmath_numbertheory_perfect_power +hmath_numbertheory_prime_factorization +hmath_numbertheory_partitions +hmath_special_sf_result +hmath_special_sf_value +hmath_special_sf_error +hmath_scalar_selector_name +hmath_scalar_selector_equal diff --git a/bindings/schema/shape-objects.json b/bindings/schema/shape-objects.json new file mode 100644 index 0000000..f2a8f38 --- /dev/null +++ b/bindings/schema/shape-objects.json @@ -0,0 +1,220 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.API.Shape.Coordinates", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.shape.Coordinates", + "specializations": [ + "actual original type-level witness and source checks" + ] + }, + { + "symbol": "HMath.API.Shape.KnownShape", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.shape.KnownShape", + "specializations": [ + "actual original type-level witness and source checks" + ] + }, + { + "symbol": "HMath.API.Shape.MatrixShape", + "c": [ + "hmath_shape_matrix_shape" + ], + "python": "hmath.shape.matrix_shape", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.ScalarShape", + "c": [ + "hmath_shape_scalar_shape" + ], + "python": "hmath.shape.scalar_shape", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.Shape", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.shape.Shape", + "specializations": [ + "actual original type-level witness and source checks" + ] + }, + { + "symbol": "HMath.API.Shape.StaticMatrix", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.shape.StaticMatrix", + "specializations": [ + "actual original type-level witness and source checks" + ] + }, + { + "symbol": "HMath.API.Shape.StaticTensor", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.shape.StaticTensor", + "specializations": [ + "actual original type-level witness and source checks" + ] + }, + { + "symbol": "HMath.API.Shape.VectorShape", + "c": [ + "hmath_shape_vector_shape" + ], + "python": "hmath.shape.vector_shape", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.coordinateValues", + "c": [ + "hmath_shape_coordinate_values" + ], + "python": "hmath.shape.coordinate_values", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.coordinates", + "c": [ + "hmath_shape_coordinates" + ], + "python": "hmath.shape.coordinates", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.coordinatesToVector", + "c": [ + "hmath_shape_coordinates_to_vector" + ], + "python": "hmath.shape.coordinates_to_vector", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.dynamicMatrix", + "c": [ + "hmath_shape_dynamic_matrix" + ], + "python": "hmath.shape.dynamic_matrix", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.dynamicTensor", + "c": [ + "hmath_shape_dynamic_tensor" + ], + "python": "hmath.shape.dynamic_tensor", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.makeShape", + "c": [ + "hmath_shape_make_shape" + ], + "python": "hmath.shape.make_shape", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.reflectedShape", + "c": [ + "hmath_shape_reflected_shape" + ], + "python": "hmath.shape.reflected_shape", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.shapeDimensions", + "c": [ + "hmath_shape_shape_dimensions" + ], + "python": "hmath.shape.shape_dimensions", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.shapeElements", + "c": [ + "hmath_shape_shape_elements" + ], + "python": "hmath.shape.shape_elements", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.staticMatrix", + "c": [ + "hmath_shape_static_matrix" + ], + "python": "hmath.shape.static_matrix", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.staticMultiply", + "c": [ + "hmath_shape_static_multiply" + ], + "python": "hmath.shape.static_multiply", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.staticTensor", + "c": [ + "hmath_shape_static_tensor" + ], + "python": "hmath.shape.static_tensor", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + }, + { + "symbol": "HMath.API.Shape.staticTranspose", + "c": [ + "hmath_shape_static_transpose" + ], + "python": "hmath.shape.static_transpose", + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ] + } + ] +} diff --git a/bindings/schema/spectral-functions.json b/bindings/schema/spectral-functions.json new file mode 100644 index 0000000..71cf567 --- /dev/null +++ b/bindings/schema/spectral-functions.json @@ -0,0 +1,780 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Signal", + "name": "iir", + "signature": "[Double] -> [Double] -> Either MathError Filter" + }, + { + "module": "HMath.Signal", + "name": "fir", + "signature": "[Double] -> Either MathError Filter" + }, + { + "module": "HMath.Signal", + "name": "filterCoefficients", + "signature": "Filter -> ([Double], [Double])" + }, + { + "module": "HMath.Signal", + "name": "filterState", + "signature": "Filter -> [Double]" + }, + { + "module": "HMath.Signal", + "name": "resetFilter", + "signature": "Filter -> Filter" + }, + { + "module": "HMath.Signal", + "name": "filterSignal", + "signature": "Filter -> [Double] -> Either MathError ([Double], Filter)" + }, + { + "module": "HMath.Signal", + "name": "frequencyResponse", + "signature": "Filter -> Double -> Either MathError (Complex Double)" + }, + { + "module": "HMath.Signal", + "name": "Butterworth", + "signature": "FilterFamily" + }, + { + "module": "HMath.Signal", + "name": "ChebyshevI", + "signature": "Double -> FilterFamily" + }, + { + "module": "HMath.Signal", + "name": "ChebyshevII", + "signature": "Double -> FilterFamily" + }, + { + "module": "HMath.Signal", + "name": "Elliptic", + "signature": "Double -> Double -> FilterFamily" + }, + { + "module": "HMath.Signal", + "name": "Bessel", + "signature": "FilterFamily" + }, + { + "module": "HMath.Signal", + "name": "Lowpass", + "signature": "Double -> FilterBand" + }, + { + "module": "HMath.Signal", + "name": "Highpass", + "signature": "Double -> FilterBand" + }, + { + "module": "HMath.Signal", + "name": "Bandpass", + "signature": "Double -> Double -> FilterBand" + }, + { + "module": "HMath.Signal", + "name": "Bandstop", + "signature": "Double -> Double -> FilterBand" + }, + { + "module": "HMath.Signal", + "name": "designIIR", + "signature": "FilterFamily -> FilterBand -> Int -> Double -> Either MathError Filter" + }, + { + "module": "HMath.Signal", + "name": "notch", + "signature": "Double -> Double -> Either MathError Filter" + }, + { + "module": "HMath.Signal", + "name": "allPass", + "signature": "Double -> Double -> Either MathError Filter" + }, + { + "module": "HMath.Signal", + "name": "wiener", + "signature": "Int -> Maybe Double -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Signal", + "name": "Hann", + "signature": "Window" + }, + { + "module": "HMath.Signal", + "name": "Hamming", + "signature": "Window" + }, + { + "module": "HMath.Signal", + "name": "Blackman", + "signature": "Window" + }, + { + "module": "HMath.Signal", + "name": "Bartlett", + "signature": "Window" + }, + { + "module": "HMath.Signal", + "name": "Kaiser", + "signature": "Double -> Window" + }, + { + "module": "HMath.Signal", + "name": "Gaussian", + "signature": "Double -> Window" + }, + { + "module": "HMath.Signal", + "name": "Tukey", + "signature": "Double -> Window" + }, + { + "module": "HMath.Signal", + "name": "FlatTop", + "signature": "Window" + }, + { + "module": "HMath.Signal", + "name": "DolphChebyshev", + "signature": "Double -> Window" + }, + { + "module": "HMath.Signal", + "name": "window", + "signature": "Window -> Int -> Either MathError [Double]" + }, + { + "module": "HMath.Signal", + "name": "windowedSinc", + "signature": "Window -> Int -> Double -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.Signal", + "name": "Peak", + "signature": "Int -> Double -> Double -> Double -> Peak" + }, + { + "module": "HMath.Signal", + "name": "peakIndex", + "signature": "Peak -> Int" + }, + { + "module": "HMath.Signal", + "name": "peakHeight", + "signature": "Peak -> Double" + }, + { + "module": "HMath.Signal", + "name": "peakProminence", + "signature": "Peak -> Double" + }, + { + "module": "HMath.Signal", + "name": "peakWidth", + "signature": "Peak -> Double" + }, + { + "module": "HMath.Signal", + "name": "peaks", + "signature": "Double -> Int -> [Double] -> Either MathError [Peak]" + }, + { + "module": "HMath.Signal", + "name": "kalman", + "signature": "[[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState" + }, + { + "module": "HMath.Signal", + "name": "extendedKalman", + "signature": "([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState" + }, + { + "module": "HMath.Signal", + "name": "unscentedKalman", + "signature": "Double -> Double -> Double -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState" + }, + { + "module": "HMath.Signal", + "name": "Haar", + "signature": "Wavelet" + }, + { + "module": "HMath.Signal", + "name": "Daubechies2", + "signature": "Wavelet" + }, + { + "module": "HMath.Signal", + "name": "Daubechies4", + "signature": "Wavelet" + }, + { + "module": "HMath.Signal", + "name": "Biorthogonal53", + "signature": "Wavelet" + }, + { + "module": "HMath.Signal", + "name": "waveletApproximation", + "signature": "WaveletTree -> [Double]" + }, + { + "module": "HMath.Signal", + "name": "waveletDetails", + "signature": "WaveletTree -> [[Double]]" + }, + { + "module": "HMath.Signal", + "name": "dwt", + "signature": "Wavelet -> Int -> [Double] -> Either MathError WaveletTree" + }, + { + "module": "HMath.Signal", + "name": "idwt", + "signature": "WaveletTree -> Either MathError [Double]" + }, + { + "module": "HMath.Signal", + "name": "Morlet", + "signature": "Double -> MotherWavelet" + }, + { + "module": "HMath.Signal", + "name": "MexicanHat", + "signature": "MotherWavelet" + }, + { + "module": "HMath.Signal", + "name": "GaussianDerivative", + "signature": "MotherWavelet" + }, + { + "module": "HMath.Signal", + "name": "cwt", + "signature": "MotherWavelet -> Double -> [Double] -> [Double] -> Either MathError [[Complex Double]]" + }, + { + "module": "HMath.Signal", + "name": "waveletPackets", + "signature": "Wavelet -> Int -> [Double] -> Either MathError WaveletPacket" + }, + { + "module": "HMath.Signal", + "name": "inverseWaveletPackets", + "signature": "WaveletPacket -> Either MathError [Double]" + }, + { + "module": "HMath.Signal", + "name": "packetBands", + "signature": "WaveletPacket -> [[Double]]" + }, + { + "module": "HMath.Signal", + "name": "waveletDenoise", + "signature": "Wavelet -> Int -> Maybe Double -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "Reject", + "signature": "Extrapolation" + }, + { + "module": "HMath.Interpolation", + "name": "Clamp", + "signature": "Extrapolation" + }, + { + "module": "HMath.Interpolation", + "name": "Extrapolate", + "signature": "Extrapolation" + }, + { + "module": "HMath.Interpolation", + "name": "Nearest", + "signature": "InterpolationMethod" + }, + { + "module": "HMath.Interpolation", + "name": "Linear", + "signature": "InterpolationMethod" + }, + { + "module": "HMath.Interpolation", + "name": "Lagrange", + "signature": "InterpolationMethod" + }, + { + "module": "HMath.Interpolation", + "name": "Newton", + "signature": "InterpolationMethod" + }, + { + "module": "HMath.Interpolation", + "name": "Barycentric", + "signature": "InterpolationMethod" + }, + { + "module": "HMath.Interpolation", + "name": "Natural", + "signature": "SplineBoundary" + }, + { + "module": "HMath.Interpolation", + "name": "Clamped", + "signature": "Double -> Double -> SplineBoundary" + }, + { + "module": "HMath.Interpolation", + "name": "Periodic", + "signature": "SplineBoundary" + }, + { + "module": "HMath.Interpolation", + "name": "Gaussian", + "signature": "Double -> RadialKernel" + }, + { + "module": "HMath.Interpolation", + "name": "Multiquadric", + "signature": "Double -> RadialKernel" + }, + { + "module": "HMath.Interpolation", + "name": "InverseMultiquadric", + "signature": "Double -> RadialKernel" + }, + { + "module": "HMath.Interpolation", + "name": "ThinPlate", + "signature": "RadialKernel" + }, + { + "module": "HMath.Interpolation", + "name": "Cubic", + "signature": "RadialKernel" + }, + { + "module": "HMath.Interpolation", + "name": "Approximation", + "signature": "[Double] -> Double -> Int -> Approximation" + }, + { + "module": "HMath.Interpolation", + "name": "approximationCoefficients", + "signature": "Approximation -> [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "approximationError", + "signature": "Approximation -> Double" + }, + { + "module": "HMath.Interpolation", + "name": "approximationIterations", + "signature": "Approximation -> Int" + }, + { + "module": "HMath.Interpolation", + "name": "interpolate", + "signature": "InterpolationMethod -> Extrapolation -> [(Double, Double)] -> Double -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "hermite", + "signature": "[(Double, Double, Double)] -> Double -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "piecewisePolynomial", + "signature": "[Double] -> [[Double]] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "piecewiseKnots", + "signature": "PiecewisePolynomial -> [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "evaluatePiecewise", + "signature": "Extrapolation -> PiecewisePolynomial -> Double -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "differentiatePiecewise", + "signature": "PiecewisePolynomial -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "integratePiecewise", + "signature": "PiecewisePolynomial -> Double -> Double -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "cubicHermite", + "signature": "[(Double, Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "cubicSpline", + "signature": "SplineBoundary -> [(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "pchip", + "signature": "[(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "akima", + "signature": "[(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "smoothingSpline", + "signature": "Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "bSpline", + "signature": "Int -> [Double] -> [[Double]] -> [Double] -> Either MathError BSpline" + }, + { + "module": "HMath.Interpolation", + "name": "evaluateBSpline", + "signature": "BSpline -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "derivativeBSpline", + "signature": "BSpline -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "insertKnot", + "signature": "BSpline -> Double -> Either MathError BSpline" + }, + { + "module": "HMath.Interpolation", + "name": "rationalBezier", + "signature": "[[Double]] -> [Double] -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "bezier", + "signature": "[[Double]] -> Double -> Either MathError [Double]" + }, + { + "module": "HMath.Interpolation", + "name": "kochanekBartels", + "signature": "Double -> Double -> Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "cardinalSpline", + "signature": "Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "catmullRom", + "signature": "[(Double, Double)] -> Either MathError PiecewisePolynomial" + }, + { + "module": "HMath.Interpolation", + "name": "curveIntegral", + "signature": "C.Tolerance -> BSpline -> Double -> Double -> Either MathError [C.Estimate Double]" + }, + { + "module": "HMath.Interpolation", + "name": "arcLength", + "signature": "C.Tolerance -> BSpline -> Double -> Double -> Either MathError (C.Estimate Double)" + }, + { + "module": "HMath.Interpolation", + "name": "gridInterpolate", + "signature": "InterpolationMethod -> Extrapolation -> [[Double]] -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "fitRBF", + "signature": "RadialKernel -> Double -> [[Double]] -> [Double] -> Either MathError RBF" + }, + { + "module": "HMath.Interpolation", + "name": "evaluateRBF", + "signature": "RBF -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "inverseDistance", + "signature": "Double -> [[Double]] -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "shepard", + "signature": "[[Double]] -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.Interpolation", + "name": "kriging", + "signature": "Double -> Double -> [[Double]] -> [Double] -> [Double] -> Either MathError (Double, Double)" + }, + { + "module": "HMath.Interpolation", + "name": "polynomialFit", + "signature": "Int -> [(Double, Double)] -> Either MathError Approximation" + }, + { + "module": "HMath.Interpolation", + "name": "chebyshevApproximate", + "signature": "Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation" + }, + { + "module": "HMath.Interpolation", + "name": "pade", + "signature": "Int -> Int -> [Double] -> Either MathError ([Double], [Double])" + }, + { + "module": "HMath.Interpolation", + "name": "rationalFit", + "signature": "Int -> Int -> [(Double, Double)] -> Either MathError ([Double], [Double], Double)" + }, + { + "module": "HMath.Interpolation", + "name": "remez", + "signature": "Int -> Int -> Double -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation" + }, + { + "module": "HMath.Interpolation", + "name": "nonlinearFit", + "signature": "Int -> Double -> (Double -> [Double] -> Double) -> [(Double, Double)] -> [Double] -> Either MathError Approximation" + }, + { + "module": "HMath.Interpolation", + "name": "interpolationError", + "signature": "(Double -> Double) -> [(Double, Double)] -> Either MathError Double" + }, + { + "module": "HMath.Fourier", + "name": "Forward", + "signature": "Direction" + }, + { + "module": "HMath.Fourier", + "name": "Inverse", + "signature": "Direction" + }, + { + "module": "HMath.Fourier", + "name": "Automatic", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "Direct", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "Radix2", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "Radix4", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "MixedRadix", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "SplitRadix", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "Bluestein", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "Rader", + "signature": "FFTAlgorithm" + }, + { + "module": "HMath.Fourier", + "name": "TypeI", + "signature": "TransformType" + }, + { + "module": "HMath.Fourier", + "name": "TypeII", + "signature": "TransformType" + }, + { + "module": "HMath.Fourier", + "name": "TypeIII", + "signature": "TransformType" + }, + { + "module": "HMath.Fourier", + "name": "TypeIV", + "signature": "TransformType" + }, + { + "module": "HMath.Fourier", + "name": "planFFT", + "signature": "Direction -> FFTAlgorithm -> Int -> Either MathError FFTPlan" + }, + { + "module": "HMath.Fourier", + "name": "executeFFT", + "signature": "FFTPlan -> [Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "fft", + "signature": "[Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "ifft", + "signature": "[Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "dft", + "signature": "[Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "realFFT", + "signature": "[Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "inverseRealFFT", + "signature": "Double -> [Complex Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "fftBatch", + "signature": "FFTPlan -> [[Complex Double]] -> Either MathError [[Complex Double]]" + }, + { + "module": "HMath.Fourier", + "name": "fftND", + "signature": "Direction -> [Int] -> [Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "fftInPlace", + "signature": "FFTPlan -> Ptr (Complex Double) -> Int -> IO (Either MathError ())" + }, + { + "module": "HMath.Fourier", + "name": "dct", + "signature": "TransformType -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "idct", + "signature": "TransformType -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "dst", + "signature": "TransformType -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "idst", + "signature": "TransformType -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "stftFrames", + "signature": "STFT -> [[Complex Double]]" + }, + { + "module": "HMath.Fourier", + "name": "stft", + "signature": "[Double] -> Int -> [Double] -> Either MathError STFT" + }, + { + "module": "HMath.Fourier", + "name": "istft", + "signature": "STFT -> Either MathError [Double]" + }, + { + "module": "HMath.Fourier", + "name": "magnitudeSpectrum", + "signature": "[Complex Double] -> [Double]" + }, + { + "module": "HMath.Fourier", + "name": "phaseSpectrum", + "signature": "[Complex Double] -> [Double]" + }, + { + "module": "HMath.Fourier", + "name": "powerSpectrum", + "signature": "[Complex Double] -> [Double]" + }, + { + "module": "HMath.Fourier", + "name": "crossSpectrum", + "signature": "Double -> [Double] -> [Double] -> [Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "spectrogram", + "signature": "[Double] -> Int -> [Double] -> Either MathError [[Double]]" + }, + { + "module": "HMath.Fourier", + "name": "analyticSignal", + "signature": "[Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "chirpZ", + "signature": "Int -> Complex Double -> Complex Double -> [Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "goertzel", + "signature": "Double -> [Double] -> Either MathError (Complex Double)" + }, + { + "module": "HMath.Fourier", + "name": "fftConvolve", + "signature": "[Complex Double] -> [Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "fftCorrelate", + "signature": "[Complex Double] -> [Complex Double] -> Either MathError [Complex Double]" + }, + { + "module": "HMath.Fourier", + "name": "fftShift", + "signature": "[a] -> [a]" + }, + { + "module": "HMath.Fourier", + "name": "ifftShift", + "signature": "[a] -> [a]" + } + ] +} diff --git a/bindings/schema/spectral-generic-objects.json b/bindings/schema/spectral-generic-objects.json new file mode 100644 index 0000000..896e989 --- /dev/null +++ b/bindings/schema/spectral-generic-objects.json @@ -0,0 +1,26 @@ +{ + "schema": 1, + "extends": "numeric.json", + "bindings": [ + { + "symbol": "HMath.Fourier.fftShift", + "c": [ + "hmath_fourier_value_fft_shift" + ], + "python": "hmath.fourier.fft_shift", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.ifftShift", + "c": [ + "hmath_fourier_value_ifft_shift" + ], + "python": "hmath.fourier.ifft_shift", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + } + ] +} diff --git a/bindings/schema/spectral-objects.json b/bindings/schema/spectral-objects.json new file mode 100644 index 0000000..69c94b8 --- /dev/null +++ b/bindings/schema/spectral-objects.json @@ -0,0 +1,1735 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Signal.Filter", + "c": [ + "hmath_signal_value_filter_object" + ], + "python": "hmath.signal.Filter", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.FilterFamily", + "c": [ + "hmath_signal_value_filter_family_object" + ], + "python": "hmath.signal.FilterFamily", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.FilterBand", + "c": [ + "hmath_signal_value_filter_band_object" + ], + "python": "hmath.signal.FilterBand", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.Window", + "c": [ + "hmath_signal_value_window_object" + ], + "python": "hmath.signal.Window", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.Wavelet", + "c": [ + "hmath_signal_value_wavelet_object" + ], + "python": "hmath.signal.Wavelet", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.WaveletTree", + "c": [ + "hmath_signal_value_wavelet_tree_object" + ], + "python": "hmath.signal.WaveletTree", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.MotherWavelet", + "c": [ + "hmath_signal_value_mother_wavelet_object" + ], + "python": "hmath.signal.MotherWavelet", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.WaveletPacket", + "c": [ + "hmath_signal_value_wavelet_packet_object" + ], + "python": "hmath.signal.WaveletPacket", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.Extrapolation", + "c": [ + "hmath_interpolation_value_extrapolation_object" + ], + "python": "hmath.interpolation.Extrapolation", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.InterpolationMethod", + "c": [ + "hmath_interpolation_value_interpolation_method_object" + ], + "python": "hmath.interpolation.InterpolationMethod", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.SplineBoundary", + "c": [ + "hmath_interpolation_value_spline_boundary_object" + ], + "python": "hmath.interpolation.SplineBoundary", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.PiecewisePolynomial", + "c": [ + "hmath_interpolation_value_piecewise_polynomial_object" + ], + "python": "hmath.interpolation.PiecewisePolynomial", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.BSpline", + "c": [ + "hmath_interpolation_value_b_spline_object" + ], + "python": "hmath.interpolation.BSpline", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.RadialKernel", + "c": [ + "hmath_interpolation_value_radial_kernel_object" + ], + "python": "hmath.interpolation.RadialKernel", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Interpolation.RBF", + "c": [ + "hmath_interpolation_value_rbf_object" + ], + "python": "hmath.interpolation.RBF", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Fourier.Direction", + "c": [ + "hmath_fourier_value_direction_object" + ], + "python": "hmath.fourier.Direction", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Fourier.FFTAlgorithm", + "c": [ + "hmath_fourier_value_fft_algorithm_object" + ], + "python": "hmath.fourier.FFTAlgorithm", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Fourier.FFTPlan", + "c": [ + "hmath_fourier_value_fft_plan_object" + ], + "python": "hmath.fourier.FFTPlan", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Fourier.TransformType", + "c": [ + "hmath_fourier_value_transform_type_object" + ], + "python": "hmath.fourier.TransformType", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Fourier.STFT", + "c": [ + "hmath_fourier_value_stft_object" + ], + "python": "hmath.fourier.STFT", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.iir", + "c": [ + "hmath_signal_value_iir" + ], + "python": "hmath.signal.iir", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.fir", + "c": [ + "hmath_signal_value_fir" + ], + "python": "hmath.signal.fir", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.filterCoefficients", + "c": [ + "hmath_signal_value_filter_coefficients" + ], + "python": "hmath.signal.filter_coefficients", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.filterState", + "c": [ + "hmath_signal_value_filter_state" + ], + "python": "hmath.signal.filter_state", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.resetFilter", + "c": [ + "hmath_signal_value_reset_filter" + ], + "python": "hmath.signal.reset_filter", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.filterSignal", + "c": [ + "hmath_signal_value_filter_signal" + ], + "python": "hmath.signal.filter_signal", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.frequencyResponse", + "c": [ + "hmath_signal_value_frequency_response" + ], + "python": "hmath.signal.frequency_response", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Butterworth", + "c": [ + "hmath_signal_value_butterworth" + ], + "python": "hmath.signal.butterworth", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.ChebyshevI", + "c": [ + "hmath_signal_value_chebyshev_i" + ], + "python": "hmath.signal.chebyshev_i", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.ChebyshevII", + "c": [ + "hmath_signal_value_chebyshev_ii" + ], + "python": "hmath.signal.chebyshev_ii", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Elliptic", + "c": [ + "hmath_signal_value_elliptic" + ], + "python": "hmath.signal.elliptic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Bessel", + "c": [ + "hmath_signal_value_bessel" + ], + "python": "hmath.signal.bessel", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Lowpass", + "c": [ + "hmath_signal_value_lowpass" + ], + "python": "hmath.signal.lowpass", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Highpass", + "c": [ + "hmath_signal_value_highpass" + ], + "python": "hmath.signal.highpass", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Bandpass", + "c": [ + "hmath_signal_value_bandpass" + ], + "python": "hmath.signal.bandpass", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Bandstop", + "c": [ + "hmath_signal_value_bandstop" + ], + "python": "hmath.signal.bandstop", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.designIIR", + "c": [ + "hmath_signal_value_design_iir" + ], + "python": "hmath.signal.design_iir", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.notch", + "c": [ + "hmath_signal_value_notch" + ], + "python": "hmath.signal.notch", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.allPass", + "c": [ + "hmath_signal_value_all_pass" + ], + "python": "hmath.signal.all_pass", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.wiener", + "c": [ + "hmath_signal_value_wiener" + ], + "python": "hmath.signal.wiener", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Hann", + "c": [ + "hmath_signal_value_hann" + ], + "python": "hmath.signal.hann", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Hamming", + "c": [ + "hmath_signal_value_hamming" + ], + "python": "hmath.signal.hamming", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Blackman", + "c": [ + "hmath_signal_value_blackman" + ], + "python": "hmath.signal.blackman", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Bartlett", + "c": [ + "hmath_signal_value_bartlett" + ], + "python": "hmath.signal.bartlett", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Kaiser", + "c": [ + "hmath_signal_value_kaiser" + ], + "python": "hmath.signal.kaiser", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Gaussian", + "c": [ + "hmath_signal_value_gaussian" + ], + "python": "hmath.signal.gaussian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Tukey", + "c": [ + "hmath_signal_value_tukey" + ], + "python": "hmath.signal.tukey", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.FlatTop", + "c": [ + "hmath_signal_value_flat_top" + ], + "python": "hmath.signal.flat_top", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.DolphChebyshev", + "c": [ + "hmath_signal_value_dolph_chebyshev" + ], + "python": "hmath.signal.dolph_chebyshev", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.window", + "c": [ + "hmath_signal_value_window" + ], + "python": "hmath.signal.window", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.windowedSinc", + "c": [ + "hmath_signal_value_windowed_sinc" + ], + "python": "hmath.signal.windowed_sinc", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Peak", + "c": [ + "hmath_signal_value_peak" + ], + "python": "hmath.signal.peak", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.peakIndex", + "c": [ + "hmath_signal_value_peak_index" + ], + "python": "hmath.signal.peak_index", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.peakHeight", + "c": [ + "hmath_signal_value_peak_height" + ], + "python": "hmath.signal.peak_height", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.peakProminence", + "c": [ + "hmath_signal_value_peak_prominence" + ], + "python": "hmath.signal.peak_prominence", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.peakWidth", + "c": [ + "hmath_signal_value_peak_width" + ], + "python": "hmath.signal.peak_width", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.peaks", + "c": [ + "hmath_signal_value_peaks" + ], + "python": "hmath.signal.peaks", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.kalman", + "c": [ + "hmath_signal_value_kalman" + ], + "python": "hmath.signal.kalman", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.extendedKalman", + "c": [ + "hmath_signal_value_extended_kalman" + ], + "python": "hmath.signal.extended_kalman", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.unscentedKalman", + "c": [ + "hmath_signal_value_unscented_kalman" + ], + "python": "hmath.signal.unscented_kalman", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Haar", + "c": [ + "hmath_signal_value_haar" + ], + "python": "hmath.signal.haar", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Daubechies2", + "c": [ + "hmath_signal_value_daubechies2" + ], + "python": "hmath.signal.daubechies2", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Daubechies4", + "c": [ + "hmath_signal_value_daubechies4" + ], + "python": "hmath.signal.daubechies4", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Biorthogonal53", + "c": [ + "hmath_signal_value_biorthogonal53" + ], + "python": "hmath.signal.biorthogonal53", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.waveletApproximation", + "c": [ + "hmath_signal_value_wavelet_approximation" + ], + "python": "hmath.signal.wavelet_approximation", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.waveletDetails", + "c": [ + "hmath_signal_value_wavelet_details" + ], + "python": "hmath.signal.wavelet_details", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.dwt", + "c": [ + "hmath_signal_value_dwt" + ], + "python": "hmath.signal.dwt", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.idwt", + "c": [ + "hmath_signal_value_idwt" + ], + "python": "hmath.signal.idwt", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.Morlet", + "c": [ + "hmath_signal_value_morlet" + ], + "python": "hmath.signal.morlet", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.MexicanHat", + "c": [ + "hmath_signal_value_mexican_hat" + ], + "python": "hmath.signal.mexican_hat", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.GaussianDerivative", + "c": [ + "hmath_signal_value_gaussian_derivative" + ], + "python": "hmath.signal.gaussian_derivative", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.cwt", + "c": [ + "hmath_signal_value_cwt" + ], + "python": "hmath.signal.cwt", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.waveletPackets", + "c": [ + "hmath_signal_value_wavelet_packets" + ], + "python": "hmath.signal.wavelet_packets", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.inverseWaveletPackets", + "c": [ + "hmath_signal_value_inverse_wavelet_packets" + ], + "python": "hmath.signal.inverse_wavelet_packets", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.packetBands", + "c": [ + "hmath_signal_value_packet_bands" + ], + "python": "hmath.signal.packet_bands", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Signal.waveletDenoise", + "c": [ + "hmath_signal_value_wavelet_denoise" + ], + "python": "hmath.signal.wavelet_denoise", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Reject", + "c": [ + "hmath_interpolation_value_reject" + ], + "python": "hmath.interpolation.reject", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Clamp", + "c": [ + "hmath_interpolation_value_clamp" + ], + "python": "hmath.interpolation.clamp", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Extrapolate", + "c": [ + "hmath_interpolation_value_extrapolate" + ], + "python": "hmath.interpolation.extrapolate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Nearest", + "c": [ + "hmath_interpolation_value_nearest" + ], + "python": "hmath.interpolation.nearest", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Linear", + "c": [ + "hmath_interpolation_value_linear" + ], + "python": "hmath.interpolation.linear", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Lagrange", + "c": [ + "hmath_interpolation_value_lagrange" + ], + "python": "hmath.interpolation.lagrange", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Newton", + "c": [ + "hmath_interpolation_value_newton" + ], + "python": "hmath.interpolation.newton", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Barycentric", + "c": [ + "hmath_interpolation_value_barycentric" + ], + "python": "hmath.interpolation.barycentric", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Natural", + "c": [ + "hmath_interpolation_value_natural" + ], + "python": "hmath.interpolation.natural", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Clamped", + "c": [ + "hmath_interpolation_value_clamped" + ], + "python": "hmath.interpolation.clamped", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Periodic", + "c": [ + "hmath_interpolation_value_periodic" + ], + "python": "hmath.interpolation.periodic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Gaussian", + "c": [ + "hmath_interpolation_value_gaussian" + ], + "python": "hmath.interpolation.gaussian", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Multiquadric", + "c": [ + "hmath_interpolation_value_multiquadric" + ], + "python": "hmath.interpolation.multiquadric", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.InverseMultiquadric", + "c": [ + "hmath_interpolation_value_inverse_multiquadric" + ], + "python": "hmath.interpolation.inverse_multiquadric", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.ThinPlate", + "c": [ + "hmath_interpolation_value_thin_plate" + ], + "python": "hmath.interpolation.thin_plate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Cubic", + "c": [ + "hmath_interpolation_value_cubic" + ], + "python": "hmath.interpolation.cubic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.Approximation", + "c": [ + "hmath_interpolation_value_approximation" + ], + "python": "hmath.interpolation.approximation", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.approximationCoefficients", + "c": [ + "hmath_interpolation_value_approximation_coefficients" + ], + "python": "hmath.interpolation.approximation_coefficients", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.approximationError", + "c": [ + "hmath_interpolation_value_approximation_error" + ], + "python": "hmath.interpolation.approximation_error", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.approximationIterations", + "c": [ + "hmath_interpolation_value_approximation_iterations" + ], + "python": "hmath.interpolation.approximation_iterations", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.interpolate", + "c": [ + "hmath_interpolation_value_interpolate" + ], + "python": "hmath.interpolation.interpolate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.hermite", + "c": [ + "hmath_interpolation_value_hermite" + ], + "python": "hmath.interpolation.hermite", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.piecewisePolynomial", + "c": [ + "hmath_interpolation_value_piecewise_polynomial" + ], + "python": "hmath.interpolation.piecewise_polynomial", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.piecewiseKnots", + "c": [ + "hmath_interpolation_value_piecewise_knots" + ], + "python": "hmath.interpolation.piecewise_knots", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.evaluatePiecewise", + "c": [ + "hmath_interpolation_value_evaluate_piecewise" + ], + "python": "hmath.interpolation.evaluate_piecewise", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.differentiatePiecewise", + "c": [ + "hmath_interpolation_value_differentiate_piecewise" + ], + "python": "hmath.interpolation.differentiate_piecewise", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.integratePiecewise", + "c": [ + "hmath_interpolation_value_integrate_piecewise" + ], + "python": "hmath.interpolation.integrate_piecewise", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.cubicHermite", + "c": [ + "hmath_interpolation_value_cubic_hermite" + ], + "python": "hmath.interpolation.cubic_hermite", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.cubicSpline", + "c": [ + "hmath_interpolation_value_cubic_spline" + ], + "python": "hmath.interpolation.cubic_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.pchip", + "c": [ + "hmath_interpolation_value_pchip" + ], + "python": "hmath.interpolation.pchip", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.akima", + "c": [ + "hmath_interpolation_value_akima" + ], + "python": "hmath.interpolation.akima", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.smoothingSpline", + "c": [ + "hmath_interpolation_value_smoothing_spline" + ], + "python": "hmath.interpolation.smoothing_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.bSpline", + "c": [ + "hmath_interpolation_value_b_spline" + ], + "python": "hmath.interpolation.b_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.evaluateBSpline", + "c": [ + "hmath_interpolation_value_evaluate_b_spline" + ], + "python": "hmath.interpolation.evaluate_b_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.derivativeBSpline", + "c": [ + "hmath_interpolation_value_derivative_b_spline" + ], + "python": "hmath.interpolation.derivative_b_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.insertKnot", + "c": [ + "hmath_interpolation_value_insert_knot" + ], + "python": "hmath.interpolation.insert_knot", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.rationalBezier", + "c": [ + "hmath_interpolation_value_rational_bezier" + ], + "python": "hmath.interpolation.rational_bezier", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.bezier", + "c": [ + "hmath_interpolation_value_bezier" + ], + "python": "hmath.interpolation.bezier", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.kochanekBartels", + "c": [ + "hmath_interpolation_value_kochanek_bartels" + ], + "python": "hmath.interpolation.kochanek_bartels", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.cardinalSpline", + "c": [ + "hmath_interpolation_value_cardinal_spline" + ], + "python": "hmath.interpolation.cardinal_spline", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.catmullRom", + "c": [ + "hmath_interpolation_value_catmull_rom" + ], + "python": "hmath.interpolation.catmull_rom", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.curveIntegral", + "c": [ + "hmath_interpolation_value_curve_integral" + ], + "python": "hmath.interpolation.curve_integral", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.arcLength", + "c": [ + "hmath_interpolation_value_arc_length" + ], + "python": "hmath.interpolation.arc_length", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.gridInterpolate", + "c": [ + "hmath_interpolation_value_grid_interpolate" + ], + "python": "hmath.interpolation.grid_interpolate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.fitRBF", + "c": [ + "hmath_interpolation_value_fit_rbf" + ], + "python": "hmath.interpolation.fit_rbf", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.evaluateRBF", + "c": [ + "hmath_interpolation_value_evaluate_rbf" + ], + "python": "hmath.interpolation.evaluate_rbf", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.inverseDistance", + "c": [ + "hmath_interpolation_value_inverse_distance" + ], + "python": "hmath.interpolation.inverse_distance", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.shepard", + "c": [ + "hmath_interpolation_value_shepard" + ], + "python": "hmath.interpolation.shepard", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.kriging", + "c": [ + "hmath_interpolation_value_kriging" + ], + "python": "hmath.interpolation.kriging", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.polynomialFit", + "c": [ + "hmath_interpolation_value_polynomial_fit" + ], + "python": "hmath.interpolation.polynomial_fit", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.chebyshevApproximate", + "c": [ + "hmath_interpolation_value_chebyshev_approximate" + ], + "python": "hmath.interpolation.chebyshev_approximate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.pade", + "c": [ + "hmath_interpolation_value_pade" + ], + "python": "hmath.interpolation.pade", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.rationalFit", + "c": [ + "hmath_interpolation_value_rational_fit" + ], + "python": "hmath.interpolation.rational_fit", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.remez", + "c": [ + "hmath_interpolation_value_remez" + ], + "python": "hmath.interpolation.remez", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.nonlinearFit", + "c": [ + "hmath_interpolation_value_nonlinear_fit" + ], + "python": "hmath.interpolation.nonlinear_fit", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Interpolation.interpolationError", + "c": [ + "hmath_interpolation_value_interpolation_error" + ], + "python": "hmath.interpolation.interpolation_error", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Forward", + "c": [ + "hmath_fourier_value_forward" + ], + "python": "hmath.fourier.forward", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Inverse", + "c": [ + "hmath_fourier_value_inverse" + ], + "python": "hmath.fourier.inverse", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Automatic", + "c": [ + "hmath_fourier_value_automatic" + ], + "python": "hmath.fourier.automatic", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Direct", + "c": [ + "hmath_fourier_value_direct" + ], + "python": "hmath.fourier.direct", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Radix2", + "c": [ + "hmath_fourier_value_radix2" + ], + "python": "hmath.fourier.radix2", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Radix4", + "c": [ + "hmath_fourier_value_radix4" + ], + "python": "hmath.fourier.radix4", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.MixedRadix", + "c": [ + "hmath_fourier_value_mixed_radix" + ], + "python": "hmath.fourier.mixed_radix", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.SplitRadix", + "c": [ + "hmath_fourier_value_split_radix" + ], + "python": "hmath.fourier.split_radix", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Bluestein", + "c": [ + "hmath_fourier_value_bluestein" + ], + "python": "hmath.fourier.bluestein", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.Rader", + "c": [ + "hmath_fourier_value_rader" + ], + "python": "hmath.fourier.rader", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.TypeI", + "c": [ + "hmath_fourier_value_type_i" + ], + "python": "hmath.fourier.type_i", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.TypeII", + "c": [ + "hmath_fourier_value_type_ii" + ], + "python": "hmath.fourier.type_ii", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.TypeIII", + "c": [ + "hmath_fourier_value_type_iii" + ], + "python": "hmath.fourier.type_iii", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.TypeIV", + "c": [ + "hmath_fourier_value_type_iv" + ], + "python": "hmath.fourier.type_iv", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.planFFT", + "c": [ + "hmath_fourier_value_plan_fft" + ], + "python": "hmath.fourier.plan_fft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.executeFFT", + "c": [ + "hmath_fourier_value_execute_fft" + ], + "python": "hmath.fourier.execute_fft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fft", + "c": [ + "hmath_fourier_value_fft" + ], + "python": "hmath.fourier.fft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.ifft", + "c": [ + "hmath_fourier_value_ifft" + ], + "python": "hmath.fourier.ifft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.dft", + "c": [ + "hmath_fourier_value_dft" + ], + "python": "hmath.fourier.dft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.realFFT", + "c": [ + "hmath_fourier_value_real_fft" + ], + "python": "hmath.fourier.real_fft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.inverseRealFFT", + "c": [ + "hmath_fourier_value_inverse_real_fft" + ], + "python": "hmath.fourier.inverse_real_fft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fftBatch", + "c": [ + "hmath_fourier_value_fft_batch" + ], + "python": "hmath.fourier.fft_batch", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fftND", + "c": [ + "hmath_fourier_value_fft_nd" + ], + "python": "hmath.fourier.fft_nd", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.dct", + "c": [ + "hmath_fourier_value_dct" + ], + "python": "hmath.fourier.dct", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.idct", + "c": [ + "hmath_fourier_value_idct" + ], + "python": "hmath.fourier.idct", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.dst", + "c": [ + "hmath_fourier_value_dst" + ], + "python": "hmath.fourier.dst", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.idst", + "c": [ + "hmath_fourier_value_idst" + ], + "python": "hmath.fourier.idst", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.stftFrames", + "c": [ + "hmath_fourier_value_stft_frames" + ], + "python": "hmath.fourier.stft_frames", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.stft", + "c": [ + "hmath_fourier_value_stft" + ], + "python": "hmath.fourier.stft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.istft", + "c": [ + "hmath_fourier_value_istft" + ], + "python": "hmath.fourier.istft", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.magnitudeSpectrum", + "c": [ + "hmath_fourier_value_magnitude_spectrum" + ], + "python": "hmath.fourier.magnitude_spectrum", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.phaseSpectrum", + "c": [ + "hmath_fourier_value_phase_spectrum" + ], + "python": "hmath.fourier.phase_spectrum", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.powerSpectrum", + "c": [ + "hmath_fourier_value_power_spectrum" + ], + "python": "hmath.fourier.power_spectrum", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.crossSpectrum", + "c": [ + "hmath_fourier_value_cross_spectrum" + ], + "python": "hmath.fourier.cross_spectrum", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.spectrogram", + "c": [ + "hmath_fourier_value_spectrogram" + ], + "python": "hmath.fourier.spectrogram", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.analyticSignal", + "c": [ + "hmath_fourier_value_analytic_signal" + ], + "python": "hmath.fourier.analytic_signal", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.chirpZ", + "c": [ + "hmath_fourier_value_chirp_z" + ], + "python": "hmath.fourier.chirp_z", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.goertzel", + "c": [ + "hmath_fourier_value_goertzel" + ], + "python": "hmath.fourier.goertzel", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fftConvolve", + "c": [ + "hmath_fourier_value_fft_convolve" + ], + "python": "hmath.fourier.fft_convolve", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fftCorrelate", + "c": [ + "hmath_fourier_value_fft_correlate" + ], + "python": "hmath.fourier.fft_correlate", + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ] + }, + { + "symbol": "HMath.Fourier.fftInPlace", + "c": [ + "hmath_fourier_value_fft_in_place" + ], + "python": "hmath.fourier.fft_in_place", + "specializations": [ + "original in-place binary64 complex buffer with borrowed lifetime" + ] + } + ] +} diff --git a/bindings/schema/stochastic-functions.json b/bindings/schema/stochastic-functions.json new file mode 100644 index 0000000..8d0677f --- /dev/null +++ b/bindings/schema/stochastic-functions.json @@ -0,0 +1,4042 @@ +{ + "functions": [ + { + "module": "HMath.Random", + "name": "cloneRNG", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "RNG" + ], + "constraints": "", + "signature": "RNG -> RNG", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "seedRNG", + "args": [ + [ + "Generator" + ], + [ + "Word64" + ] + ], + "result": [ + "RNG" + ], + "constraints": "", + "signature": "Generator -> Word64 -> RNG", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "nextWord64", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "tuple", + [ + "Word64" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "RNG -> (Word64, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "splitRNG", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "tuple", + [ + "RNG" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "RNG -> (RNG, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "serializeRNG", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "String" + ], + "constraints": "", + "signature": "RNG -> String", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "restoreRNG", + "args": [ + [ + "String" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "String -> Either MathError RNG", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "uniform", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "RNG -> (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "uniformOpen", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "RNG -> (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "uniformInt", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> RNG -> Either MathError (Int, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "sampleN", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "RNG" + ], + [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "a" + ], + [ + "RNG" + ] + ] + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> (RNG -> Either MathError (a, RNG)) -> RNG -> Either MathError ([a], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "boxMuller", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ], + "constraints": "", + "signature": "RNG -> (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "marsagliaNormal", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "zigguratNormal", + "args": [ + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "normal", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Double -> Double -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "exponential", + "args": [ + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Double -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "gamma", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Double -> Double -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "beta", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Double -> Double -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "poisson", + "args": [ + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Double -> RNG -> Either MathError (Int, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "binomial", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Double -> RNG -> Either MathError (Int, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "weighted", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "[Double] -> RNG -> Either MathError (Int, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "aliasTable", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "AliasTable" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError AliasTable", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "aliasSample", + "args": [ + [ + "AliasTable" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "AliasTable -> RNG -> Either MathError (Int, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "shuffle", + "args": [ + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "[a] -> RNG -> Either MathError ([a], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "withReplacement", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> [a] -> RNG -> Either MathError ([a], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "withoutReplacement", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> [a] -> RNG -> Either MathError ([a], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "reservoir", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "a" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> [a] -> RNG -> Either MathError ([a], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "stratified", + "args": [ + [ + "Int" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> RNG -> Either MathError ([Double], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "rejection", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "function", + [ + "RNG" + ], + [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> (Double -> Double) -> (RNG -> Either MathError (Double, RNG)) -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "inverseTransform", + "args": [ + [ + "function", + [ + "Double" + ], + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "(Double -> Either MathError Double) -> RNG -> Either MathError (Double, RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "metropolisHastings", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "function", + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "Double" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Double -> (Double -> Double) -> Double -> RNG -> Either MathError ([Double], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "gibbs", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ], + [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> [([Double] -> RNG -> Either MathError (Double, RNG))] -> [Double] -> RNG -> Either MathError ([[Double]], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "hamiltonianMonteCarlo", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Double" + ], + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "Double" + ] + ], + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> Double -> ([Double] -> Double) -> ([Double] -> [Double]) -> [Double] -> RNG -> Either MathError ([[Double]], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "monteCarlo", + "args": [ + [ + "function", + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "Int" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "(Double -> Double) -> Int -> RNG -> Either MathError ((Double, Double), RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "latinHypercube", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Int -> RNG -> Either MathError ([[Double]], RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "randomQuality", + "args": [ + [ + "Int" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> RNG -> Either MathError ((Double, Double, Double), RNG)", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "entropySeed", + "args": [], + "result": [ + "IO", + [ + "Word64" + ] + ], + "constraints": "", + "signature": "IO Word64", + "constructor": false + }, + { + "module": "HMath.Random", + "name": "PCG32", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "Xoshiro256StarStar", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "Xoroshiro128Plus", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "MT19937", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "Philox4x32", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "Threefry2x64", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Random", + "name": "ChaCha20", + "args": [], + "result": [ + "Generator" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "validateDistribution", + "args": [ + [ + "Distribution" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "unit" + ] + ], + "constraints": "", + "signature": "Distribution -> Either MathError ()", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "logDensity", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "density", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "cdf", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "survival", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "quantile", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "hazard", + "args": [ + [ + "Distribution" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "logLikelihood", + "args": [ + [ + "Distribution" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> [Double] -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "moments", + "args": [ + [ + "Distribution" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Distribution -> Either MathError (Double, Double)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "entropy", + "args": [ + [ + "Distribution" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "expectation", + "args": [ + [ + "Distribution" + ], + [ + "function", + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> (Double -> Double) -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "sample", + "args": [ + [ + "Distribution" + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Distribution -> R.RNG -> Either MathError (Double, R.RNG)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "fitNormal", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "fitExponential", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "fitBernoulli", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "fitMLEGrid", + "args": [ + [ + "list", + [ + "Distribution" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "[Distribution] -> [Double] -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "fitMAPGrid", + "args": [ + [ + "list", + [ + "Distribution" + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "function", + [ + "Distribution" + ], + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "[Distribution] -> [Double] -> (Distribution -> Double) -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "betaBernoulliUpdate", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "list", + [ + "Bool" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Double -> Double -> [Bool] -> Either MathError (Double, Double)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "goodnessOfFit", + "args": [ + [ + "Distribution" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Distribution -> [Double] -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "gaussianKDE", + "args": [ + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Distribution" + ] + ], + "constraints": "", + "signature": "Double -> [Double] -> Either MathError Distribution", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "multivariateNormalLogDensity", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "[Double] -> Matrix Double -> [Double] -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "sampleMultivariateNormal", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "[Double] -> Matrix Double -> R.RNG -> Either MathError ([Double], R.RNG)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "wishartLogDensity", + "args": [ + [ + "Double" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "Matrix", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "Double -> Matrix Double -> Matrix Double -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "sampleWishart", + "args": [ + [ + "Int" + ], + [ + "Matrix", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Matrix", + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> Matrix Double -> R.RNG -> Either MathError (Matrix Double, R.RNG)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "markov", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Markov" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError Markov", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "transition", + "args": [ + [ + "Markov" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Markov -> [Double] -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "stationary", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "Markov" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Int -> Double -> Markov -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "hmm", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "HMM" + ] + ], + "constraints": "", + "signature": "[Double] -> [[Double]] -> [[Double]] -> Either MathError HMM", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "forward", + "args": [ + [ + "HMM" + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "HMM -> [Int] -> Either MathError (Double, [[Double]], [Double])", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "backward", + "args": [ + [ + "HMM" + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "HMM -> [Int] -> Either MathError [[Double]]", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "posteriorStates", + "args": [ + [ + "HMM" + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "HMM -> [Int] -> Either MathError [[Double]]", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "viterbi", + "args": [ + [ + "HMM" + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "Int" + ] + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "HMM -> [Int] -> Either MathError ([Int], Double)", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "baumWelch", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "HMM" + ], + [ + "list", + [ + "Int" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "HMM" + ] + ], + "constraints": "", + "signature": "Int -> Double -> HMM -> [Int] -> Either MathError HMM", + "constructor": false + }, + { + "module": "HMath.Probability", + "name": "Bernoulli", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Binomial", + "args": [ + [ + "Int" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "NegativeBinomial", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Geometric", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Hypergeometric", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Poisson", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Categorical", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "DiscreteUniform", + "args": [ + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Uniform", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Normal", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "LogNormal", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Exponential", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Gamma", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Beta", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "ChiSquare", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "StudentT", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "FisherF", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Cauchy", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Laplace", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Logistic", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Weibull", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Pareto", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Rayleigh", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Maxwell", + "args": [ + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Gumbel", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "GeneralizedExtremeValue", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "BetaBinomial", + "args": [ + [ + "Int" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Skellam", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "VonMises", + "args": [ + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Triangular", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "TruncatedNormal", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "Double" + ], + [ + "Double" + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Mixture", + "args": [ + [ + "list", + [ + "tuple", + [ + "Double" + ], + [ + "Distribution" + ] + ] + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "Empirical", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Probability", + "name": "GaussianKDE", + "args": [ + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Distribution" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + }, + { + "module": "HMath.Statistics.Advanced", + "name": "covarianceMatrix", + "args": [ + [ + "Bool" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "constraints": "", + "signature": "Bool -> [[Double]] -> Either MathError [[Double]]", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "partialCorrelation", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Int -> Int -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "emptyStreaming", + "args": [], + "result": [ + "Streaming" + ], + "constraints": "", + "signature": "Streaming", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "updateStreaming", + "args": [ + [ + "Streaming" + ], + [ + "Double" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Streaming" + ] + ], + "constraints": "", + "signature": "Streaming -> Double -> Either MathError Streaming", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "combineStreaming", + "args": [ + [ + "Streaming" + ], + [ + "Streaming" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Streaming" + ] + ], + "constraints": "", + "signature": "Streaming -> Streaming -> Either MathError Streaming", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "streamingResult", + "args": [ + [ + "Bool" + ], + [ + "Streaming" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Integer" + ], + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "Bool -> Streaming -> Either MathError (Integer, Double, Double)", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "histogramND", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "[[Double]] -> [[Double]] -> [Double] -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "mutualInformation", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "bootstrap", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> ([Double] -> Either MathError Double) -> [Double] -> R.RNG -> Either MathError ([Double], R.RNG)", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "jackknife", + "args": [ + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Double" + ], + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "([Double] -> Either MathError Double) -> [Double] -> Either MathError (Double, Double)", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "oneSampleT", + "args": [ + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Double -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "twoSampleT", + "args": [ + [ + "Bool" + ], + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Bool -> [Double] -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "pairedT", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "zTest", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Double -> Double -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "chiSquareTest", + "args": [ + [ + "Int" + ], + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Int -> [Double] -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "varianceFTest", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "anova", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "welchAnova", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "kruskalWallis", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "mannWhitney", + "args": [ + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "wilcoxon", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "kolmogorovSmirnov", + "args": [ + [ + "Distribution" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "P.Distribution -> [Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "shapiroWilk", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "andersonDarling", + "args": [ + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[Double] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "levene", + "args": [ + [ + "Bool" + ], + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Bool -> [[Double]] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "bartlett", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "fisherExact", + "args": [ + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ], + [ + "Int" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "TestResult" + ] + ], + "constraints": "", + "signature": "Int -> Int -> Int -> Int -> Either MathError TestResult", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "permutationTest", + "args": [ + [ + "Int" + ], + [ + "function", + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "list", + [ + "Double" + ] + ], + [ + "RNG" + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "TestResult" + ], + [ + "RNG" + ] + ] + ], + "constraints": "", + "signature": "Int -> ([Double] -> [Double] -> Either MathError Double) -> [Double] -> [Double] -> R.RNG -> Either MathError (TestResult, R.RNG)", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "etaSquared", + "args": [ + [ + "list", + [ + "list", + [ + "Double" + ] + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "Double" + ] + ], + "constraints": "", + "signature": "[[Double]] -> Either MathError Double", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "grubbs", + "args": [ + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "tuple", + [ + "Int" + ], + [ + "Double" + ], + [ + "Bool" + ] + ] + ], + "constraints": "", + "signature": "Double -> [Double] -> Either MathError (Int, Double, Bool)", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "masked", + "args": [ + [ + "list", + [ + "Bool" + ] + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "Either", + [ + "MathError" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "constraints": "", + "signature": "[Bool] -> [Double] -> Either MathError [Double]", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "testStatistic", + "args": [ + [ + "TestResult" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "TestResult -> field", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "pValue", + "args": [ + [ + "TestResult" + ] + ], + "result": [ + "Double" + ], + "constraints": "", + "signature": "TestResult -> field", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "degreesOfFreedom", + "args": [ + [ + "TestResult" + ] + ], + "result": [ + "list", + [ + "Double" + ] + ], + "constraints": "", + "signature": "TestResult -> field", + "constructor": false + }, + { + "module": "HMath.Statistics.Advanced", + "name": "TestResult", + "args": [ + [ + "Double" + ], + [ + "Double" + ], + [ + "list", + [ + "Double" + ] + ] + ], + "result": [ + "TestResult" + ], + "constraints": "", + "signature": "constructor", + "constructor": true + } + ], + "types": { + "Generator": { + "module": "HMath.Random", + "alias": "R", + "namespace": "random_values", + "name": "Generator", + "params": [] + }, + "RNG": { + "module": "HMath.Random", + "alias": "R", + "namespace": "random_values", + "name": "RNG", + "params": [] + }, + "AliasTable": { + "module": "HMath.Random", + "alias": "R", + "namespace": "random_values", + "name": "AliasTable", + "params": [] + }, + "Distribution": { + "module": "HMath.Probability", + "alias": "P", + "namespace": "probability_values", + "name": "Distribution", + "params": [] + }, + "Markov": { + "module": "HMath.Probability", + "alias": "P", + "namespace": "probability_values", + "name": "Markov", + "params": [] + }, + "HMM": { + "module": "HMath.Probability", + "alias": "P", + "namespace": "probability_values", + "name": "HMM", + "params": [] + }, + "Streaming": { + "module": "HMath.Statistics.Advanced", + "alias": "S", + "namespace": "statistics_values", + "name": "Streaming", + "params": [] + }, + "TestResult": { + "module": "HMath.Statistics.Advanced", + "alias": "S", + "namespace": "statistics_values", + "name": "TestResult", + "params": [] + } + }, + "fields": { + "Generator": [], + "RNG": [], + "AliasTable": [], + "Distribution": [], + "Markov": [], + "HMM": [], + "Streaming": [], + "TestResult": [ + [ + "testStatistic", + [ + "Double" + ] + ], + [ + "pValue", + [ + "Double" + ] + ], + [ + "degreesOfFreedom", + [ + "list", + [ + "Double" + ] + ] + ] + ] + } +} diff --git a/bindings/schema/stochastic-objects.json b/bindings/schema/stochastic-objects.json new file mode 100644 index 0000000..3e204d2 --- /dev/null +++ b/bindings/schema/stochastic-objects.json @@ -0,0 +1,1532 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Probability.Bernoulli", + "c": [ + "hmath_stochastic_probability_new_bernoulli" + ], + "python": "hmath.probability.bernoulli", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Beta", + "c": [ + "hmath_stochastic_probability_new_beta" + ], + "python": "hmath.probability.beta", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.BetaBinomial", + "c": [ + "hmath_stochastic_probability_new_beta_binomial" + ], + "python": "hmath.probability.beta_binomial", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Binomial", + "c": [ + "hmath_stochastic_probability_new_binomial" + ], + "python": "hmath.probability.binomial", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Categorical", + "c": [ + "hmath_stochastic_probability_new_categorical" + ], + "python": "hmath.probability.categorical", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Cauchy", + "c": [ + "hmath_stochastic_probability_new_cauchy" + ], + "python": "hmath.probability.cauchy", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.ChiSquare", + "c": [ + "hmath_stochastic_probability_new_chi_square" + ], + "python": "hmath.probability.chi_square", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.DiscreteUniform", + "c": [ + "hmath_stochastic_probability_new_discrete_uniform" + ], + "python": "hmath.probability.discrete_uniform", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Distribution", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.probability.Distribution", + "specializations": [ + "original raw immutable type, Value kind243" + ] + }, + { + "symbol": "HMath.Probability.Empirical", + "c": [ + "hmath_stochastic_probability_new_empirical" + ], + "python": "hmath.probability.empirical", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Exponential", + "c": [ + "hmath_stochastic_probability_new_exponential" + ], + "python": "hmath.probability.exponential", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.FisherF", + "c": [ + "hmath_stochastic_probability_new_fisher_f" + ], + "python": "hmath.probability.fisher_f", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Gamma", + "c": [ + "hmath_stochastic_probability_new_gamma" + ], + "python": "hmath.probability.gamma", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.GaussianKDE", + "c": [ + "hmath_stochastic_probability_new_gaussian_kde" + ], + "python": "hmath.probability.new_gaussian_kde", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.GeneralizedExtremeValue", + "c": [ + "hmath_stochastic_probability_new_generalized_extreme_value" + ], + "python": "hmath.probability.generalized_extreme_value", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Geometric", + "c": [ + "hmath_stochastic_probability_new_geometric" + ], + "python": "hmath.probability.geometric", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Gumbel", + "c": [ + "hmath_stochastic_probability_new_gumbel" + ], + "python": "hmath.probability.gumbel", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.HMM", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.probability.HMM", + "specializations": [ + "original raw immutable type, Value kind245" + ] + }, + { + "symbol": "HMath.Probability.Hypergeometric", + "c": [ + "hmath_stochastic_probability_new_hypergeometric" + ], + "python": "hmath.probability.hypergeometric", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Laplace", + "c": [ + "hmath_stochastic_probability_new_laplace" + ], + "python": "hmath.probability.laplace", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.LogNormal", + "c": [ + "hmath_stochastic_probability_new_log_normal" + ], + "python": "hmath.probability.log_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Logistic", + "c": [ + "hmath_stochastic_probability_new_logistic" + ], + "python": "hmath.probability.logistic", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Markov", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.probability.Markov", + "specializations": [ + "original raw immutable type, Value kind244" + ] + }, + { + "symbol": "HMath.Probability.Maxwell", + "c": [ + "hmath_stochastic_probability_new_maxwell" + ], + "python": "hmath.probability.maxwell", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Mixture", + "c": [ + "hmath_stochastic_probability_new_mixture" + ], + "python": "hmath.probability.mixture", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.NegativeBinomial", + "c": [ + "hmath_stochastic_probability_new_negative_binomial" + ], + "python": "hmath.probability.negative_binomial", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Normal", + "c": [ + "hmath_stochastic_probability_new_normal" + ], + "python": "hmath.probability.normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Pareto", + "c": [ + "hmath_stochastic_probability_new_pareto" + ], + "python": "hmath.probability.pareto", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Poisson", + "c": [ + "hmath_stochastic_probability_new_poisson" + ], + "python": "hmath.probability.poisson", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Rayleigh", + "c": [ + "hmath_stochastic_probability_new_rayleigh" + ], + "python": "hmath.probability.rayleigh", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Skellam", + "c": [ + "hmath_stochastic_probability_new_skellam" + ], + "python": "hmath.probability.skellam", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.StudentT", + "c": [ + "hmath_stochastic_probability_new_student_t" + ], + "python": "hmath.probability.student_t", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Triangular", + "c": [ + "hmath_stochastic_probability_new_triangular" + ], + "python": "hmath.probability.triangular", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.TruncatedNormal", + "c": [ + "hmath_stochastic_probability_new_truncated_normal" + ], + "python": "hmath.probability.truncated_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Uniform", + "c": [ + "hmath_stochastic_probability_new_uniform" + ], + "python": "hmath.probability.uniform", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.VonMises", + "c": [ + "hmath_stochastic_probability_new_von_mises" + ], + "python": "hmath.probability.von_mises", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.Weibull", + "c": [ + "hmath_stochastic_probability_new_weibull" + ], + "python": "hmath.probability.weibull", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.backward", + "c": [ + "hmath_stochastic_probability_backward" + ], + "python": "hmath.probability.backward", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.baumWelch", + "c": [ + "hmath_stochastic_probability_baum_welch" + ], + "python": "hmath.probability.baum_welch", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.betaBernoulliUpdate", + "c": [ + "hmath_stochastic_probability_beta_bernoulli_update" + ], + "python": "hmath.probability.beta_bernoulli_update", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.cdf", + "c": [ + "hmath_stochastic_probability_cdf" + ], + "python": "hmath.probability.cdf", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.density", + "c": [ + "hmath_stochastic_probability_density" + ], + "python": "hmath.probability.density", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.entropy", + "c": [ + "hmath_stochastic_probability_entropy" + ], + "python": "hmath.probability.entropy", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.expectation", + "c": [ + "hmath_stochastic_probability_expectation" + ], + "python": "hmath.probability.expectation", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.fitBernoulli", + "c": [ + "hmath_stochastic_probability_fit_bernoulli" + ], + "python": "hmath.probability.fit_bernoulli", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.fitExponential", + "c": [ + "hmath_stochastic_probability_fit_exponential" + ], + "python": "hmath.probability.fit_exponential", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.fitMAPGrid", + "c": [ + "hmath_stochastic_probability_fit_map_grid" + ], + "python": "hmath.probability.fit_map_grid", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.fitMLEGrid", + "c": [ + "hmath_stochastic_probability_fit_mle_grid" + ], + "python": "hmath.probability.fit_mle_grid", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.fitNormal", + "c": [ + "hmath_stochastic_probability_fit_normal" + ], + "python": "hmath.probability.fit_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.forward", + "c": [ + "hmath_stochastic_probability_forward" + ], + "python": "hmath.probability.forward", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.gaussianKDE", + "c": [ + "hmath_stochastic_probability_gaussian_kde" + ], + "python": "hmath.probability.gaussian_kde", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.goodnessOfFit", + "c": [ + "hmath_stochastic_probability_goodness_of_fit" + ], + "python": "hmath.probability.goodness_of_fit", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.hazard", + "c": [ + "hmath_stochastic_probability_hazard" + ], + "python": "hmath.probability.hazard", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.hmm", + "c": [ + "hmath_stochastic_probability_hmm" + ], + "python": "hmath.probability.hmm", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.logDensity", + "c": [ + "hmath_stochastic_probability_log_density" + ], + "python": "hmath.probability.log_density", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.logLikelihood", + "c": [ + "hmath_stochastic_probability_log_likelihood" + ], + "python": "hmath.probability.log_likelihood", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.markov", + "c": [ + "hmath_stochastic_probability_markov" + ], + "python": "hmath.probability.markov", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.moments", + "c": [ + "hmath_stochastic_probability_moments" + ], + "python": "hmath.probability.moments", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.multivariateNormalLogDensity", + "c": [ + "hmath_stochastic_probability_multivariate_normal_log_density" + ], + "python": "hmath.probability.multivariate_normal_log_density", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.posteriorStates", + "c": [ + "hmath_stochastic_probability_posterior_states" + ], + "python": "hmath.probability.posterior_states", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.quantile", + "c": [ + "hmath_stochastic_probability_quantile" + ], + "python": "hmath.probability.quantile", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.sample", + "c": [ + "hmath_stochastic_probability_sample" + ], + "python": "hmath.probability.sample", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.sampleMultivariateNormal", + "c": [ + "hmath_stochastic_probability_sample_multivariate_normal" + ], + "python": "hmath.probability.sample_multivariate_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.sampleWishart", + "c": [ + "hmath_stochastic_probability_sample_wishart" + ], + "python": "hmath.probability.sample_wishart", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.stationary", + "c": [ + "hmath_stochastic_probability_stationary" + ], + "python": "hmath.probability.stationary", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.survival", + "c": [ + "hmath_stochastic_probability_survival" + ], + "python": "hmath.probability.survival", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.transition", + "c": [ + "hmath_stochastic_probability_transition" + ], + "python": "hmath.probability.transition", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.validateDistribution", + "c": [ + "hmath_stochastic_probability_validate_distribution" + ], + "python": "hmath.probability.validate_distribution", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.viterbi", + "c": [ + "hmath_stochastic_probability_viterbi" + ], + "python": "hmath.probability.viterbi", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Probability.wishartLogDensity", + "c": [ + "hmath_stochastic_probability_wishart_log_density" + ], + "python": "hmath.probability.wishart_log_density", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.AliasTable", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.random.AliasTable", + "specializations": [ + "original raw immutable type, Value kind242" + ] + }, + { + "symbol": "HMath.Random.ChaCha20", + "c": [ + "hmath_stochastic_random_new_cha_cha20" + ], + "python": "hmath.random.cha_cha20", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.Generator", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.random.Generator", + "specializations": [ + "original raw immutable type, Value kind241" + ] + }, + { + "symbol": "HMath.Random.MT19937", + "c": [ + "hmath_stochastic_random_new_mt19937" + ], + "python": "hmath.random.mt19937", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.PCG32", + "c": [ + "hmath_stochastic_random_new_pcg32" + ], + "python": "hmath.random.pcg32", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.Philox4x32", + "c": [ + "hmath_stochastic_random_new_philox4x32" + ], + "python": "hmath.random.philox4x32", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.RNG", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.random.RNG", + "specializations": [ + "original raw immutable type, Value kind240" + ] + }, + { + "symbol": "HMath.Random.Threefry2x64", + "c": [ + "hmath_stochastic_random_new_threefry2x64" + ], + "python": "hmath.random.threefry2x64", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.Xoroshiro128Plus", + "c": [ + "hmath_stochastic_random_new_xoroshiro128_plus" + ], + "python": "hmath.random.xoroshiro128_plus", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.Xoshiro256StarStar", + "c": [ + "hmath_stochastic_random_new_xoshiro256_star_star" + ], + "python": "hmath.random.xoshiro256_star_star", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.aliasSample", + "c": [ + "hmath_stochastic_random_alias_sample" + ], + "python": "hmath.random.alias_sample", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.aliasTable", + "c": [ + "hmath_stochastic_random_alias_table" + ], + "python": "hmath.random.alias_table", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.beta", + "c": [ + "hmath_stochastic_random_beta" + ], + "python": "hmath.random.beta", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.binomial", + "c": [ + "hmath_stochastic_random_binomial" + ], + "python": "hmath.random.binomial", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.boxMuller", + "c": [ + "hmath_stochastic_random_box_muller" + ], + "python": "hmath.random.box_muller", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.cloneRNG", + "c": [ + "hmath_stochastic_random_clone_rng" + ], + "python": "hmath.random.clone_rng", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.entropySeed", + "c": [ + "hmath_stochastic_random_entropy_seed" + ], + "python": "hmath.random.entropy_seed", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.exponential", + "c": [ + "hmath_stochastic_random_exponential" + ], + "python": "hmath.random.exponential", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.gamma", + "c": [ + "hmath_stochastic_random_gamma" + ], + "python": "hmath.random.gamma", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.gibbs", + "c": [ + "hmath_stochastic_random_gibbs" + ], + "python": "hmath.random.gibbs", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.hamiltonianMonteCarlo", + "c": [ + "hmath_stochastic_random_hamiltonian_monte_carlo" + ], + "python": "hmath.random.hamiltonian_monte_carlo", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.inverseTransform", + "c": [ + "hmath_stochastic_random_inverse_transform" + ], + "python": "hmath.random.inverse_transform", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.latinHypercube", + "c": [ + "hmath_stochastic_random_latin_hypercube" + ], + "python": "hmath.random.latin_hypercube", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.marsagliaNormal", + "c": [ + "hmath_stochastic_random_marsaglia_normal" + ], + "python": "hmath.random.marsaglia_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.metropolisHastings", + "c": [ + "hmath_stochastic_random_metropolis_hastings" + ], + "python": "hmath.random.metropolis_hastings", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.monteCarlo", + "c": [ + "hmath_stochastic_random_monte_carlo" + ], + "python": "hmath.random.monte_carlo", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.nextWord64", + "c": [ + "hmath_stochastic_random_next_word64" + ], + "python": "hmath.random.next_word64", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.normal", + "c": [ + "hmath_stochastic_random_normal" + ], + "python": "hmath.random.normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.poisson", + "c": [ + "hmath_stochastic_random_poisson" + ], + "python": "hmath.random.poisson", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.randomQuality", + "c": [ + "hmath_stochastic_random_random_quality" + ], + "python": "hmath.random.random_quality", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.rejection", + "c": [ + "hmath_stochastic_random_rejection" + ], + "python": "hmath.random.rejection", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.reservoir", + "c": [ + "hmath_stochastic_random_reservoir" + ], + "python": "hmath.random.reservoir", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.restoreRNG", + "c": [ + "hmath_stochastic_random_restore_rng" + ], + "python": "hmath.random.restore_rng", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.sampleN", + "c": [ + "hmath_stochastic_random_sample_n" + ], + "python": "hmath.random.sample_n", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.seedRNG", + "c": [ + "hmath_stochastic_random_seed_rng" + ], + "python": "hmath.random.seed_rng", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.serializeRNG", + "c": [ + "hmath_stochastic_random_serialize_rng" + ], + "python": "hmath.random.serialize_rng", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.shuffle", + "c": [ + "hmath_stochastic_random_shuffle" + ], + "python": "hmath.random.shuffle", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.splitRNG", + "c": [ + "hmath_stochastic_random_split_rng" + ], + "python": "hmath.random.split_rng", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.stratified", + "c": [ + "hmath_stochastic_random_stratified" + ], + "python": "hmath.random.stratified", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.uniform", + "c": [ + "hmath_stochastic_random_uniform" + ], + "python": "hmath.random.uniform", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.uniformInt", + "c": [ + "hmath_stochastic_random_uniform_int" + ], + "python": "hmath.random.uniform_int", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.uniformOpen", + "c": [ + "hmath_stochastic_random_uniform_open" + ], + "python": "hmath.random.uniform_open", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.weighted", + "c": [ + "hmath_stochastic_random_weighted" + ], + "python": "hmath.random.weighted", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.withReplacement", + "c": [ + "hmath_stochastic_random_with_replacement" + ], + "python": "hmath.random.with_replacement", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.withoutReplacement", + "c": [ + "hmath_stochastic_random_without_replacement" + ], + "python": "hmath.random.without_replacement", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Random.zigguratNormal", + "c": [ + "hmath_stochastic_random_ziggurat_normal" + ], + "python": "hmath.random.ziggurat_normal", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.Streaming", + "c": [ + "hmath_value", + "hmath_value_release" + ], + "python": "hmath.statistics_advanced.Streaming", + "specializations": [ + "original raw immutable type, Value kind246" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.TestResult", + "c": [ + "hmath_stochastic_statistics_advanced_new_test_result" + ], + "python": "hmath.statistics_advanced.TestResult", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.andersonDarling", + "c": [ + "hmath_stochastic_statistics_advanced_anderson_darling" + ], + "python": "hmath.statistics_advanced.anderson_darling", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.anova", + "c": [ + "hmath_stochastic_statistics_advanced_anova" + ], + "python": "hmath.statistics_advanced.anova", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.bartlett", + "c": [ + "hmath_stochastic_statistics_advanced_bartlett" + ], + "python": "hmath.statistics_advanced.bartlett", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.bootstrap", + "c": [ + "hmath_stochastic_statistics_advanced_bootstrap" + ], + "python": "hmath.statistics_advanced.bootstrap", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.chiSquareTest", + "c": [ + "hmath_stochastic_statistics_advanced_chi_square_test" + ], + "python": "hmath.statistics_advanced.chi_square_test", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.combineStreaming", + "c": [ + "hmath_stochastic_statistics_advanced_combine_streaming" + ], + "python": "hmath.statistics_advanced.combine_streaming", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.covarianceMatrix", + "c": [ + "hmath_stochastic_statistics_advanced_covariance_matrix" + ], + "python": "hmath.statistics_advanced.covariance_matrix", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.degreesOfFreedom", + "c": [ + "hmath_stochastic_statistics_advanced_degrees_of_freedom" + ], + "python": "hmath.statistics_advanced.degrees_of_freedom", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.emptyStreaming", + "c": [ + "hmath_stochastic_statistics_advanced_empty_streaming" + ], + "python": "hmath.statistics_advanced.empty_streaming", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.etaSquared", + "c": [ + "hmath_stochastic_statistics_advanced_eta_squared" + ], + "python": "hmath.statistics_advanced.eta_squared", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.fisherExact", + "c": [ + "hmath_stochastic_statistics_advanced_fisher_exact" + ], + "python": "hmath.statistics_advanced.fisher_exact", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.grubbs", + "c": [ + "hmath_stochastic_statistics_advanced_grubbs" + ], + "python": "hmath.statistics_advanced.grubbs", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.histogramND", + "c": [ + "hmath_stochastic_statistics_advanced_histogram_nd" + ], + "python": "hmath.statistics_advanced.histogram_nd", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.jackknife", + "c": [ + "hmath_stochastic_statistics_advanced_jackknife" + ], + "python": "hmath.statistics_advanced.jackknife", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kolmogorovSmirnov", + "c": [ + "hmath_stochastic_statistics_advanced_kolmogorov_smirnov" + ], + "python": "hmath.statistics_advanced.kolmogorov_smirnov", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.kruskalWallis", + "c": [ + "hmath_stochastic_statistics_advanced_kruskal_wallis" + ], + "python": "hmath.statistics_advanced.kruskal_wallis", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.levene", + "c": [ + "hmath_stochastic_statistics_advanced_levene" + ], + "python": "hmath.statistics_advanced.levene", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.mannWhitney", + "c": [ + "hmath_stochastic_statistics_advanced_mann_whitney" + ], + "python": "hmath.statistics_advanced.mann_whitney", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.masked", + "c": [ + "hmath_stochastic_statistics_advanced_masked" + ], + "python": "hmath.statistics_advanced.masked", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.mutualInformation", + "c": [ + "hmath_stochastic_statistics_advanced_mutual_information" + ], + "python": "hmath.statistics_advanced.mutual_information", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.oneSampleT", + "c": [ + "hmath_stochastic_statistics_advanced_one_sample_t" + ], + "python": "hmath.statistics_advanced.one_sample_t", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.pValue", + "c": [ + "hmath_stochastic_statistics_advanced_p_value" + ], + "python": "hmath.statistics_advanced.p_value", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.pairedT", + "c": [ + "hmath_stochastic_statistics_advanced_paired_t" + ], + "python": "hmath.statistics_advanced.paired_t", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.partialCorrelation", + "c": [ + "hmath_stochastic_statistics_advanced_partial_correlation" + ], + "python": "hmath.statistics_advanced.partial_correlation", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.permutationTest", + "c": [ + "hmath_stochastic_statistics_advanced_permutation_test" + ], + "python": "hmath.statistics_advanced.permutation_test", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.shapiroWilk", + "c": [ + "hmath_stochastic_statistics_advanced_shapiro_wilk" + ], + "python": "hmath.statistics_advanced.shapiro_wilk", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.streamingResult", + "c": [ + "hmath_stochastic_statistics_advanced_streaming_result" + ], + "python": "hmath.statistics_advanced.streaming_result", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.testStatistic", + "c": [ + "hmath_stochastic_statistics_advanced_test_statistic" + ], + "python": "hmath.statistics_advanced.test_statistic", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.twoSampleT", + "c": [ + "hmath_stochastic_statistics_advanced_two_sample_t" + ], + "python": "hmath.statistics_advanced.two_sample_t", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.updateStreaming", + "c": [ + "hmath_stochastic_statistics_advanced_update_streaming" + ], + "python": "hmath.statistics_advanced.update_streaming", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.varianceFTest", + "c": [ + "hmath_stochastic_statistics_advanced_variance_f_test" + ], + "python": "hmath.statistics_advanced.variance_f_test", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.welchAnova", + "c": [ + "hmath_stochastic_statistics_advanced_welch_anova" + ], + "python": "hmath.statistics_advanced.welch_anova", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.wilcoxon", + "c": [ + "hmath_stochastic_statistics_advanced_wilcoxon" + ], + "python": "hmath.statistics_advanced.wilcoxon", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + }, + { + "symbol": "HMath.Statistics.Advanced.zTest", + "c": [ + "hmath_stochastic_statistics_advanced_z_test" + ], + "python": "hmath.statistics_advanced.z_test", + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ] + } + ] +} diff --git a/bindings/schema/tensor-image-objects.json b/bindings/schema/tensor-image-objects.json new file mode 100644 index 0000000..5324ea8 --- /dev/null +++ b/bindings/schema/tensor-image-objects.json @@ -0,0 +1,46 @@ +{ + "schema": 1, + "extends": "image-objects.json", + "bindings": [ + { + "symbol": "HMath.Tensor.tensor", + "c": [ + "hmath_tensor_object_tensor" + ], + "python": "hmath.tensor.tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorValues", + "c": [ + "hmath_tensor_object_tensor_values" + ], + "python": "hmath.tensor.tensor_values", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorShape", + "c": [ + "hmath_tensor_object_tensor_shape" + ], + "python": "hmath.tensor.tensor_shape", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.Tensor", + "c": [ + "hmath_value" + ], + "python": "hmath.tensor.Tensor", + "specializations": [ + "actual typed original object; no legacy rank/element cap" + ] + } + ] +} diff --git a/bindings/schema/tensor-objects.json b/bindings/schema/tensor-objects.json new file mode 100644 index 0000000..ed04e25 --- /dev/null +++ b/bindings/schema/tensor-objects.json @@ -0,0 +1,1035 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Tensor.RowMajor", + "c": [ + "hmath_tensor_object_row_major_create" + ], + "python": "hmath.tensor.RowMajor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.ColumnMajor", + "c": [ + "hmath_tensor_object_column_major_create" + ], + "python": "hmath.tensor.ColumnMajor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.Strided", + "c": [ + "hmath_tensor_object_strided_create" + ], + "python": "hmath.tensor.Strided", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.CPU", + "c": [ + "hmath_tensor_object_cpu_create" + ], + "python": "hmath.tensor.CPU", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorColumnMajor", + "c": [ + "hmath_tensor_object_tensor_column_major" + ], + "python": "hmath.tensor.tensor_column_major", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorFull", + "c": [ + "hmath_tensor_object_tensor_full" + ], + "python": "hmath.tensor.tensor_full", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorZeros", + "c": [ + "hmath_tensor_object_tensor_zeros" + ], + "python": "hmath.tensor.tensor_zeros", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorOnes", + "c": [ + "hmath_tensor_object_tensor_ones" + ], + "python": "hmath.tensor.tensor_ones", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorArange", + "c": [ + "hmath_tensor_object_tensor_arange" + ], + "python": "hmath.tensor.tensor_arange", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorLinspace", + "c": [ + "hmath_tensor_object_tensor_linspace" + ], + "python": "hmath.tensor.tensor_linspace", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorLogspace", + "c": [ + "hmath_tensor_object_tensor_logspace" + ], + "python": "hmath.tensor.tensor_logspace", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorRandom", + "c": [ + "hmath_tensor_object_tensor_random" + ], + "python": "hmath.tensor.tensor_random", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorStrides", + "c": [ + "hmath_tensor_object_tensor_strides" + ], + "python": "hmath.tensor.tensor_strides", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorOffset", + "c": [ + "hmath_tensor_object_tensor_offset" + ], + "python": "hmath.tensor.tensor_offset", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorDType", + "c": [ + "hmath_tensor_object_tensor_d_type" + ], + "python": "hmath.tensor.tensor_dtype", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorDevice", + "c": [ + "hmath_tensor_object_tensor_device" + ], + "python": "hmath.tensor.tensor_device", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorLayout", + "c": [ + "hmath_tensor_object_tensor_layout" + ], + "python": "hmath.tensor.tensor_layout", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.numel", + "c": [ + "hmath_tensor_object_numel" + ], + "python": "hmath.tensor.numel", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.isContiguous", + "c": [ + "hmath_tensor_object_is_contiguous" + ], + "python": "hmath.tensor.is_contiguous", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.contiguous", + "c": [ + "hmath_tensor_object_contiguous" + ], + "python": "hmath.tensor.contiguous", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.indexTensor", + "c": [ + "hmath_tensor_object_index_tensor" + ], + "python": "hmath.tensor.index_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.sliceTensor", + "c": [ + "hmath_tensor_object_slice_tensor" + ], + "python": "hmath.tensor.slice_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.fancyIndex", + "c": [ + "hmath_tensor_object_fancy_index" + ], + "python": "hmath.tensor.fancy_index", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.gather", + "c": [ + "hmath_tensor_object_gather" + ], + "python": "hmath.tensor.gather", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.booleanIndex", + "c": [ + "hmath_tensor_object_boolean_index" + ], + "python": "hmath.tensor.boolean_index", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.scatter", + "c": [ + "hmath_tensor_object_scatter" + ], + "python": "hmath.tensor.scatter", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.scatterAdd", + "c": [ + "hmath_tensor_object_scatter_add" + ], + "python": "hmath.tensor.scatter_add", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.reshapeTensor", + "c": [ + "hmath_tensor_object_reshape_tensor" + ], + "python": "hmath.tensor.reshape_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.flattenTensor", + "c": [ + "hmath_tensor_object_flatten_tensor" + ], + "python": "hmath.tensor.flatten_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.squeeze", + "c": [ + "hmath_tensor_object_squeeze" + ], + "python": "hmath.tensor.squeeze", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.unsqueeze", + "c": [ + "hmath_tensor_object_unsqueeze" + ], + "python": "hmath.tensor.unsqueeze", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.expand", + "c": [ + "hmath_tensor_object_expand" + ], + "python": "hmath.tensor.expand", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.permute", + "c": [ + "hmath_tensor_object_permute" + ], + "python": "hmath.tensor.permute", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.transposeTensor", + "c": [ + "hmath_tensor_object_transpose_tensor" + ], + "python": "hmath.tensor.transpose_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.moveAxis", + "c": [ + "hmath_tensor_object_move_axis" + ], + "python": "hmath.tensor.move_axis", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.swapAxes", + "c": [ + "hmath_tensor_object_swap_axes" + ], + "python": "hmath.tensor.swap_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.broadcastTo", + "c": [ + "hmath_tensor_object_broadcast_to" + ], + "python": "hmath.tensor.broadcast_to", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.repeatTensor", + "c": [ + "hmath_tensor_object_repeat_tensor" + ], + "python": "hmath.tensor.repeat_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tile", + "c": [ + "hmath_tensor_object_tile" + ], + "python": "hmath.tensor.tile", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.concatenate", + "c": [ + "hmath_tensor_object_concatenate" + ], + "python": "hmath.tensor.concatenate", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.stack", + "c": [ + "hmath_tensor_object_stack" + ], + "python": "hmath.tensor.stack", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.splitTensor", + "c": [ + "hmath_tensor_object_split_tensor" + ], + "python": "hmath.tensor.split_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.chunkTensor", + "c": [ + "hmath_tensor_object_chunk_tensor" + ], + "python": "hmath.tensor.chunk_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.padTensor", + "c": [ + "hmath_tensor_object_pad_tensor" + ], + "python": "hmath.tensor.pad_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.roll", + "c": [ + "hmath_tensor_object_roll" + ], + "python": "hmath.tensor.roll", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.flipTensor", + "c": [ + "hmath_tensor_object_flip_tensor" + ], + "python": "hmath.tensor.flip_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.rotate", + "c": [ + "hmath_tensor_object_rotate" + ], + "python": "hmath.tensor.rotate", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.sortTensor", + "c": [ + "hmath_tensor_object_sort_tensor" + ], + "python": "hmath.tensor.sort_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.unique", + "c": [ + "hmath_tensor_object_unique" + ], + "python": "hmath.tensor.unique", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.argsort", + "c": [ + "hmath_tensor_object_argsort" + ], + "python": "hmath.tensor.argsort", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.topk", + "c": [ + "hmath_tensor_object_topk" + ], + "python": "hmath.tensor.topk", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.nonzero", + "c": [ + "hmath_tensor_object_nonzero" + ], + "python": "hmath.tensor.nonzero", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.whereTensor", + "c": [ + "hmath_tensor_object_where_tensor" + ], + "python": "hmath.tensor.where_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.maskedFill", + "c": [ + "hmath_tensor_object_masked_fill" + ], + "python": "hmath.tensor.masked_fill", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.maskedSelect", + "c": [ + "hmath_tensor_object_masked_select" + ], + "python": "hmath.tensor.masked_select", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.mapTensor", + "c": [ + "hmath_tensor_object_map_tensor" + ], + "python": "hmath.tensor.map_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.zipTensor", + "c": [ + "hmath_tensor_object_zip_tensor" + ], + "python": "hmath.tensor.zip_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorAdd", + "c": [ + "hmath_tensor_object_tensor_add" + ], + "python": "hmath.tensor.tensor_add", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorSubtract", + "c": [ + "hmath_tensor_object_tensor_subtract" + ], + "python": "hmath.tensor.tensor_subtract", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorMultiply", + "c": [ + "hmath_tensor_object_tensor_multiply" + ], + "python": "hmath.tensor.tensor_multiply", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorDivide", + "c": [ + "hmath_tensor_object_tensor_divide" + ], + "python": "hmath.tensor.tensor_divide", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorEqual", + "c": [ + "hmath_tensor_object_tensor_equal" + ], + "python": "hmath.tensor.tensor_equal", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorLess", + "c": [ + "hmath_tensor_object_tensor_less" + ], + "python": "hmath.tensor.tensor_less", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorAnd", + "c": [ + "hmath_tensor_object_tensor_and" + ], + "python": "hmath.tensor.tensor_and", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorOr", + "c": [ + "hmath_tensor_object_tensor_or" + ], + "python": "hmath.tensor.tensor_or", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorNot", + "c": [ + "hmath_tensor_object_tensor_not" + ], + "python": "hmath.tensor.tensor_not", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.promoteTensor", + "c": [ + "hmath_tensor_object_promote_tensor" + ], + "python": "hmath.tensor.promote_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.sumAxes", + "c": [ + "hmath_tensor_object_sum_axes" + ], + "python": "hmath.tensor.sum_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.productAxes", + "c": [ + "hmath_tensor_object_product_axes" + ], + "python": "hmath.tensor.product_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.meanAxes", + "c": [ + "hmath_tensor_object_mean_axes" + ], + "python": "hmath.tensor.mean_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.varianceAxes", + "c": [ + "hmath_tensor_object_variance_axes" + ], + "python": "hmath.tensor.variance_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.normAxes", + "c": [ + "hmath_tensor_object_norm_axes" + ], + "python": "hmath.tensor.norm_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.minAxes", + "c": [ + "hmath_tensor_object_min_axes" + ], + "python": "hmath.tensor.min_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.maxAxes", + "c": [ + "hmath_tensor_object_max_axes" + ], + "python": "hmath.tensor.max_axes", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.argmin", + "c": [ + "hmath_tensor_object_argmin" + ], + "python": "hmath.tensor.argmin", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.argmax", + "c": [ + "hmath_tensor_object_argmax" + ], + "python": "hmath.tensor.argmax", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.cumulativeSum", + "c": [ + "hmath_tensor_object_cumulative_sum" + ], + "python": "hmath.tensor.cumulative_sum", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.cumulativeProduct", + "c": [ + "hmath_tensor_object_cumulative_product" + ], + "python": "hmath.tensor.cumulative_product", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensordot", + "c": [ + "hmath_tensor_object_tensordot" + ], + "python": "hmath.tensor.tensordot", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.einsum", + "c": [ + "hmath_tensor_object_einsum" + ], + "python": "hmath.tensor.einsum", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.batchedMatmul", + "c": [ + "hmath_tensor_object_batched_matmul" + ], + "python": "hmath.tensor.batched_matmul", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.tensorKronecker", + "c": [ + "hmath_tensor_object_tensor_kronecker" + ], + "python": "hmath.tensor.tensor_kronecker", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.serializeTensor", + "c": [ + "hmath_tensor_object_serialize_tensor" + ], + "python": "hmath.tensor.serialize_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.deserializeTensor", + "c": [ + "hmath_tensor_object_deserialize_tensor" + ], + "python": "hmath.tensor.deserialize_tensor", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.inputGraph", + "c": [ + "hmath_tensor_object_input_graph" + ], + "python": "hmath.tensor.input_graph", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.mapGraph", + "c": [ + "hmath_tensor_object_map_graph" + ], + "python": "hmath.tensor.map_graph", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.zipGraph", + "c": [ + "hmath_tensor_object_zip_graph" + ], + "python": "hmath.tensor.zip_graph", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.evaluateGraph", + "c": [ + "hmath_tensor_object_evaluate_graph" + ], + "python": "hmath.tensor.evaluate_graph", + "specializations": [ + "original typed elements: Float/Double/Integer/Rational/complex/fixed integers/Bool/String and available Numeric towers; structural codecs retain actual types and instances" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.newMutable", + "c": [ + "hmath_tensor_object_new_mutable" + ], + "python": "hmath.tensor.new_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.thawTensor", + "c": [ + "hmath_tensor_object_thaw_tensor" + ], + "python": "hmath.tensor.thaw_tensor", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.freezeTensor", + "c": [ + "hmath_tensor_object_freeze_tensor" + ], + "python": "hmath.tensor.freeze_tensor", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.mutableShape", + "c": [ + "hmath_tensor_object_mutable_shape" + ], + "python": "hmath.tensor.mutable_shape", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.readMutable", + "c": [ + "hmath_tensor_object_read_mutable" + ], + "python": "hmath.tensor.read_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.writeMutable", + "c": [ + "hmath_tensor_object_write_mutable" + ], + "python": "hmath.tensor.write_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.modifyMutable", + "c": [ + "hmath_tensor_object_modify_mutable" + ], + "python": "hmath.tensor.modify_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.sliceMutable", + "c": [ + "hmath_tensor_object_slice_mutable" + ], + "python": "hmath.tensor.slice_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.transposeMutable", + "c": [ + "hmath_tensor_object_transpose_mutable" + ], + "python": "hmath.tensor.transpose_mutable", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.mutableAlignment", + "c": [ + "hmath_tensor_object_mutable_alignment" + ], + "python": "hmath.tensor.mutable_alignment", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.withMutableBuffer", + "c": [ + "hmath_tensor_object_with_mutable_buffer" + ], + "python": "hmath.tensor.with_mutable_buffer", + "specializations": [ + "actual original Storable element types; shared pinned views; explicit scoped borrowed buffer" + ] + }, + { + "symbol": "HMath.Tensor.TensorGraph", + "c": [ + "hmath_value" + ], + "python": "hmath.tensor.TensorGraph", + "specializations": [ + "actual typed original object; no legacy rank/element cap" + ] + }, + { + "symbol": "HMath.Tensor.Layout", + "c": [ + "hmath_value" + ], + "python": "hmath.tensor.Layout", + "specializations": [ + "actual typed original object; no legacy rank/element cap" + ] + }, + { + "symbol": "HMath.Tensor.Device", + "c": [ + "hmath_value" + ], + "python": "hmath.tensor.Device", + "specializations": [ + "actual typed original object; no legacy rank/element cap" + ] + }, + { + "symbol": "HMath.Tensor.Mutable.MutableTensor", + "c": [ + "hmath_value" + ], + "python": "hmath.tensor.MutableTensor", + "specializations": [ + "original Storable ForeignPtr with shared views; Scalar Float/Double/complex/fixed integers/Bool and exposed structural Storable instances" + ] + } + ] +} diff --git a/bindings/schema/tensor.json b/bindings/schema/tensor.json new file mode 100644 index 0000000..8830a6c --- /dev/null +++ b/bindings/schema/tensor.json @@ -0,0 +1,1821 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.Tensor", + "name": "RowMajor", + "python": "row_major", + "c": "hmath_tensor_object_row_major_create", + "arguments": [], + "result": "Layout" + }, + { + "module": "HMath.Tensor", + "name": "ColumnMajor", + "python": "column_major", + "c": "hmath_tensor_object_column_major_create", + "arguments": [], + "result": "Layout" + }, + { + "module": "HMath.Tensor", + "name": "Strided", + "python": "strided", + "c": "hmath_tensor_object_strided_create", + "arguments": [], + "result": "Layout" + }, + { + "module": "HMath.Tensor", + "name": "CPU", + "python": "cpu", + "c": "hmath_tensor_object_cpu_create", + "arguments": [], + "result": "Device" + }, + { + "module": "HMath.Tensor", + "name": "tensor", + "python": "tensor", + "c": "hmath_tensor_object_tensor", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "shape", + "[Int]" + ], + [ + "xs", + "Elements" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorColumnMajor", + "python": "tensor_column_major", + "c": "hmath_tensor_object_tensor_column_major", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "shape", + "[Int]" + ], + [ + "xs", + "Elements" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorFull", + "python": "tensor_full", + "c": "hmath_tensor_object_tensor_full", + "arguments": [ + [ + "shape", + "[Int]" + ], + [ + "fill", + "Element" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorZeros", + "python": "tensor_zeros", + "c": "hmath_tensor_object_tensor_zeros", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "shape", + "[Int]" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorOnes", + "python": "tensor_ones", + "c": "hmath_tensor_object_tensor_ones", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "shape", + "[Int]" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorArange", + "python": "tensor_arange", + "c": "hmath_tensor_object_tensor_arange", + "arguments": [ + [ + "start", + "Element" + ], + [ + "end", + "Element" + ], + [ + "step", + "Element" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorLinspace", + "python": "tensor_linspace", + "c": "hmath_tensor_object_tensor_linspace", + "arguments": [ + [ + "start", + "Element" + ], + [ + "end", + "Element" + ], + [ + "count", + "Int" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorLogspace", + "python": "tensor_logspace", + "c": "hmath_tensor_object_tensor_logspace", + "arguments": [ + [ + "base", + "Element" + ], + [ + "start", + "Element" + ], + [ + "end", + "Element" + ], + [ + "count", + "Int" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorRandom", + "python": "tensor_random", + "c": "hmath_tensor_object_tensor_random", + "arguments": [ + [ + "seed", + "Integer" + ], + [ + "shape", + "[Int]" + ] + ], + "result": "(Tensor,Integer)" + }, + { + "module": "HMath.Tensor", + "name": "tensorValues", + "python": "tensor_values", + "c": "hmath_tensor_object_tensor_values", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Elements" + }, + { + "module": "HMath.Tensor", + "name": "tensorShape", + "python": "tensor_shape", + "c": "hmath_tensor_object_tensor_shape", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "[Int]" + }, + { + "module": "HMath.Tensor", + "name": "tensorStrides", + "python": "tensor_strides", + "c": "hmath_tensor_object_tensor_strides", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "[Int]" + }, + { + "module": "HMath.Tensor", + "name": "tensorOffset", + "python": "tensor_offset", + "c": "hmath_tensor_object_tensor_offset", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor", + "name": "tensorDType", + "python": "tensor_dtype", + "c": "hmath_tensor_object_tensor_d_type", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "String" + }, + { + "module": "HMath.Tensor", + "name": "tensorDevice", + "python": "tensor_device", + "c": "hmath_tensor_object_tensor_device", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Device" + }, + { + "module": "HMath.Tensor", + "name": "tensorLayout", + "python": "tensor_layout", + "c": "hmath_tensor_object_tensor_layout", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Layout" + }, + { + "module": "HMath.Tensor", + "name": "numel", + "python": "numel", + "c": "hmath_tensor_object_numel", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor", + "name": "isContiguous", + "python": "is_contiguous", + "c": "hmath_tensor_object_is_contiguous", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Bool" + }, + { + "module": "HMath.Tensor", + "name": "shapeSize", + "python": "shape_size", + "c": "hmath_tensor_object_shape_size", + "arguments": [ + [ + "shape", + "[Int]" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor", + "name": "inferBroadcast", + "python": "infer_broadcast", + "c": "hmath_tensor_object_infer_broadcast", + "arguments": [ + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "[Int]" + }, + { + "module": "HMath.Tensor", + "name": "contiguous", + "python": "contiguous", + "c": "hmath_tensor_object_contiguous", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "indexTensor", + "python": "index_tensor", + "c": "hmath_tensor_object_index_tensor", + "arguments": [ + [ + "input", + "Tensor" + ], + [ + "index", + "[Int]" + ] + ], + "result": "Element" + }, + { + "module": "HMath.Tensor", + "name": "sliceTensor", + "python": "slice_tensor", + "c": "hmath_tensor_object_slice_tensor", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "start", + "Int" + ], + [ + "count", + "Int" + ], + [ + "step", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "fancyIndex", + "python": "fancy_index", + "c": "hmath_tensor_object_fancy_index", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "indices", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "gather", + "python": "gather", + "c": "hmath_tensor_object_gather", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "indices", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "booleanIndex", + "python": "boolean_index", + "c": "hmath_tensor_object_boolean_index", + "arguments": [ + [ + "mask", + "Tensor" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "scatter", + "python": "scatter", + "c": "hmath_tensor_object_scatter", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "indices", + "[Int]" + ], + [ + "updates", + "Tensor" + ], + [ + "target", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "scatterAdd", + "python": "scatter_add", + "c": "hmath_tensor_object_scatter_add", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "indices", + "[Int]" + ], + [ + "updates", + "Tensor" + ], + [ + "target", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "reshapeTensor", + "python": "reshape_tensor", + "c": "hmath_tensor_object_reshape_tensor", + "arguments": [ + [ + "shape", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "flattenTensor", + "python": "flatten_tensor", + "c": "hmath_tensor_object_flatten_tensor", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "squeeze", + "python": "squeeze", + "c": "hmath_tensor_object_squeeze", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "unsqueeze", + "python": "unsqueeze", + "c": "hmath_tensor_object_unsqueeze", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "expand", + "python": "expand", + "c": "hmath_tensor_object_expand", + "arguments": [ + [ + "shape", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "permute", + "python": "permute", + "c": "hmath_tensor_object_permute", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "transposeTensor", + "python": "transpose_tensor", + "c": "hmath_tensor_object_transpose_tensor", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "moveAxis", + "python": "move_axis", + "c": "hmath_tensor_object_move_axis", + "arguments": [ + [ + "from", + "Int" + ], + [ + "to", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "swapAxes", + "python": "swap_axes", + "c": "hmath_tensor_object_swap_axes", + "arguments": [ + [ + "from", + "Int" + ], + [ + "to", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "broadcastTo", + "python": "broadcast_to", + "c": "hmath_tensor_object_broadcast_to", + "arguments": [ + [ + "shape", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "repeatTensor", + "python": "repeat_tensor", + "c": "hmath_tensor_object_repeat_tensor", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "count", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tile", + "python": "tile", + "c": "hmath_tensor_object_tile", + "arguments": [ + [ + "counts", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "concatenate", + "python": "concatenate", + "c": "hmath_tensor_object_concatenate", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "axis", + "Int" + ], + [ + "inputs", + "[Tensor]" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "stack", + "python": "stack", + "c": "hmath_tensor_object_stack", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "axis", + "Int" + ], + [ + "inputs", + "[Tensor]" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "splitTensor", + "python": "split_tensor", + "c": "hmath_tensor_object_split_tensor", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "segments", + "[Int]" + ], + [ + "input", + "Tensor" + ] + ], + "result": "[Tensor]" + }, + { + "module": "HMath.Tensor", + "name": "chunkTensor", + "python": "chunk_tensor", + "c": "hmath_tensor_object_chunk_tensor", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "count", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "[Tensor]" + }, + { + "module": "HMath.Tensor", + "name": "padTensor", + "python": "pad_tensor", + "c": "hmath_tensor_object_pad_tensor", + "arguments": [ + [ + "padding", + "[(Int,Int)]" + ], + [ + "fill", + "Element" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "roll", + "python": "roll", + "c": "hmath_tensor_object_roll", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "shift", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "flipTensor", + "python": "flip_tensor", + "c": "hmath_tensor_object_flip_tensor", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "rotate", + "python": "rotate", + "c": "hmath_tensor_object_rotate", + "arguments": [ + [ + "first", + "Int" + ], + [ + "second", + "Int" + ], + [ + "turns", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "sortTensor", + "python": "sort_tensor", + "c": "hmath_tensor_object_sort_tensor", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "unique", + "python": "unique", + "c": "hmath_tensor_object_unique", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "argsort", + "python": "argsort", + "c": "hmath_tensor_object_argsort", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "topk", + "python": "topk", + "c": "hmath_tensor_object_topk", + "arguments": [ + [ + "count", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "(Tensor,Tensor)" + }, + { + "module": "HMath.Tensor", + "name": "nonzero", + "python": "nonzero", + "c": "hmath_tensor_object_nonzero", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "whereTensor", + "python": "where_tensor", + "c": "hmath_tensor_object_where_tensor", + "arguments": [ + [ + "mask", + "Tensor" + ], + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "maskedFill", + "python": "masked_fill", + "c": "hmath_tensor_object_masked_fill", + "arguments": [ + [ + "mask", + "Tensor" + ], + [ + "fill", + "Element" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "maskedSelect", + "python": "masked_select", + "c": "hmath_tensor_object_masked_select", + "arguments": [ + [ + "mask", + "Tensor" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "mapTensor", + "python": "map_tensor", + "c": "hmath_tensor_object_map_tensor", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "cb", + "Callback" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "zipTensor", + "python": "zip_tensor", + "c": "hmath_tensor_object_zip_tensor", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "cb", + "Callback" + ], + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorAdd", + "python": "tensor_add", + "c": "hmath_tensor_object_tensor_add", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorSubtract", + "python": "tensor_subtract", + "c": "hmath_tensor_object_tensor_subtract", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorMultiply", + "python": "tensor_multiply", + "c": "hmath_tensor_object_tensor_multiply", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorDivide", + "python": "tensor_divide", + "c": "hmath_tensor_object_tensor_divide", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorEqual", + "python": "tensor_equal", + "c": "hmath_tensor_object_tensor_equal", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorLess", + "python": "tensor_less", + "c": "hmath_tensor_object_tensor_less", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorAnd", + "python": "tensor_and", + "c": "hmath_tensor_object_tensor_and", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorOr", + "python": "tensor_or", + "c": "hmath_tensor_object_tensor_or", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorNot", + "python": "tensor_not", + "c": "hmath_tensor_object_tensor_not", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "promoteTensor", + "python": "promote_tensor", + "c": "hmath_tensor_object_promote_tensor", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "sumAxes", + "python": "sum_axes", + "c": "hmath_tensor_object_sum_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "productAxes", + "python": "product_axes", + "c": "hmath_tensor_object_product_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "meanAxes", + "python": "mean_axes", + "c": "hmath_tensor_object_mean_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "varianceAxes", + "python": "variance_axes", + "c": "hmath_tensor_object_variance_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "normAxes", + "python": "norm_axes", + "c": "hmath_tensor_object_norm_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "minAxes", + "python": "min_axes", + "c": "hmath_tensor_object_min_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "maxAxes", + "python": "max_axes", + "c": "hmath_tensor_object_max_axes", + "arguments": [ + [ + "axes", + "[Int]" + ], + [ + "keep", + "Bool" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "argmin", + "python": "argmin", + "c": "hmath_tensor_object_argmin", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor", + "name": "argmax", + "python": "argmax", + "c": "hmath_tensor_object_argmax", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor", + "name": "cumulativeSum", + "python": "cumulative_sum", + "c": "hmath_tensor_object_cumulative_sum", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "cumulativeProduct", + "python": "cumulative_product", + "c": "hmath_tensor_object_cumulative_product", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "input", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensordot", + "python": "tensordot", + "c": "hmath_tensor_object_tensordot", + "arguments": [ + [ + "leftAxes", + "[Int]" + ], + [ + "rightAxes", + "[Int]" + ], + [ + "left", + "Tensor" + ], + [ + "right", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "einsum", + "python": "einsum", + "c": "hmath_tensor_object_einsum", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "labels", + "[String]" + ], + [ + "outputLabels", + "String" + ], + [ + "inputs", + "[Tensor]" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "batchedMatmul", + "python": "batched_matmul", + "c": "hmath_tensor_object_batched_matmul", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "tensorKronecker", + "python": "tensor_kronecker", + "c": "hmath_tensor_object_tensor_kronecker", + "arguments": [ + [ + "a", + "Tensor" + ], + [ + "b", + "Tensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "serializeTensor", + "python": "serialize_tensor", + "c": "hmath_tensor_object_serialize_tensor", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "String" + }, + { + "module": "HMath.Tensor", + "name": "deserializeTensor", + "python": "deserialize_tensor", + "c": "hmath_tensor_object_deserialize_tensor", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "text", + "String" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor", + "name": "inputGraph", + "python": "input_graph", + "c": "hmath_tensor_object_input_graph", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "TensorGraph" + }, + { + "module": "HMath.Tensor", + "name": "mapGraph", + "python": "map_graph", + "c": "hmath_tensor_object_map_graph", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "cb", + "Callback" + ], + [ + "input", + "TensorGraph" + ] + ], + "result": "TensorGraph" + }, + { + "module": "HMath.Tensor", + "name": "zipGraph", + "python": "zip_graph", + "c": "hmath_tensor_object_zip_graph", + "arguments": [ + [ + "kind", + "Prototype" + ], + [ + "cb", + "Callback" + ], + [ + "left", + "TensorGraph" + ], + [ + "right", + "TensorGraph" + ] + ], + "result": "TensorGraph" + }, + { + "module": "HMath.Tensor", + "name": "evaluateGraph", + "python": "evaluate_graph", + "c": "hmath_tensor_object_evaluate_graph", + "arguments": [ + [ + "input", + "TensorGraph" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "newMutable", + "python": "new_mutable", + "c": "hmath_tensor_object_new_mutable", + "arguments": [ + [ + "shape", + "[Int]" + ], + [ + "fill", + "Element" + ] + ], + "result": "MutableTensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "thawTensor", + "python": "thaw_tensor", + "c": "hmath_tensor_object_thaw_tensor", + "arguments": [ + [ + "input", + "Tensor" + ] + ], + "result": "MutableTensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "freezeTensor", + "python": "freeze_tensor", + "c": "hmath_tensor_object_freeze_tensor", + "arguments": [ + [ + "input", + "MutableTensor" + ] + ], + "result": "Tensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "mutableShape", + "python": "mutable_shape", + "c": "hmath_tensor_object_mutable_shape", + "arguments": [ + [ + "input", + "MutableTensor" + ] + ], + "result": "[Int]" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "readMutable", + "python": "read_mutable", + "c": "hmath_tensor_object_read_mutable", + "arguments": [ + [ + "input", + "MutableTensor" + ], + [ + "index", + "[Int]" + ] + ], + "result": "Element" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "writeMutable", + "python": "write_mutable", + "c": "hmath_tensor_object_write_mutable", + "arguments": [ + [ + "input", + "MutableTensor" + ], + [ + "index", + "[Int]" + ], + [ + "fill", + "Element" + ] + ], + "result": "Unit" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "modifyMutable", + "python": "modify_mutable", + "c": "hmath_tensor_object_modify_mutable", + "arguments": [ + [ + "input", + "MutableTensor" + ], + [ + "index", + "[Int]" + ], + [ + "cb", + "Callback" + ] + ], + "result": "Unit" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "sliceMutable", + "python": "slice_mutable", + "c": "hmath_tensor_object_slice_mutable", + "arguments": [ + [ + "axis", + "Int" + ], + [ + "start", + "Int" + ], + [ + "count", + "Int" + ], + [ + "step", + "Int" + ], + [ + "input", + "MutableTensor" + ] + ], + "result": "MutableTensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "transposeMutable", + "python": "transpose_mutable", + "c": "hmath_tensor_object_transpose_mutable", + "arguments": [ + [ + "input", + "MutableTensor" + ] + ], + "result": "MutableTensor" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "mutableAlignment", + "python": "mutable_alignment", + "c": "hmath_tensor_object_mutable_alignment", + "arguments": [ + [ + "kind", + "Prototype" + ] + ], + "result": "Int" + }, + { + "module": "HMath.Tensor.Mutable", + "name": "withMutableBuffer", + "python": "with_mutable_buffer", + "c": "hmath_tensor_object_with_mutable_buffer", + "arguments": [ + [ + "input", + "MutableTensor" + ], + [ + "cb", + "BufferCallback" + ] + ], + "result": "Generic" + } + ] +} diff --git a/bindings/schema/timeseries-functions.json b/bindings/schema/timeseries-functions.json new file mode 100644 index 0000000..62718d8 --- /dev/null +++ b/bindings/schema/timeseries-functions.json @@ -0,0 +1,510 @@ +{ + "schema": 1, + "functions": [ + { + "module": "HMath.TimeSeries.Core", + "name": "BackwardFill", + "signature": "Fill" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "BinLast", + "signature": "Resampling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "BinMean", + "signature": "Resampling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "ForwardFill", + "signature": "Fill" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "Inner", + "signature": "Alignment" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "LeftAligned", + "signature": "Alignment" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "LinearFill", + "signature": "Fill" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "LinearSamples", + "signature": "Resampling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "MovingMaximum", + "signature": "Rolling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "MovingMean", + "signature": "Rolling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "MovingMinimum", + "signature": "Rolling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "MovingSD", + "signature": "Rolling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "MovingVariance", + "signature": "Rolling" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "Outer", + "signature": "Alignment" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "align", + "signature": "Alignment -> Series -> Series -> Either MathError (Series, Series)" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "autocorrelation", + "signature": "Int -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "crossCorrelation", + "signature": "Int -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "cumulativeReturns", + "signature": "[Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "difference", + "signature": "Int -> Int -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "durbinLevinson", + "signature": "[Double] -> Either MathError ([Double], Double, [Double])" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "exponentialAverage", + "signature": "Double -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "fillMissing", + "signature": "Fill -> Series -> Either MathError Series" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "isRegular", + "signature": "Double -> Series -> Either MathError Bool" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "logarithmicReturns", + "signature": "[Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "observations", + "signature": "Series -> [(Double, Maybe Double)]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "partialAutocorrelation", + "signature": "Int -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "regularSeries", + "signature": "Double -> Double -> [Maybe Double] -> Either MathError Series" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "resample", + "signature": "Resampling -> Double -> Double -> Int -> Series -> Either MathError Series" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "rolling", + "signature": "Rolling -> Int -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "series", + "signature": "[(Double, Maybe Double)] -> Either MathError Series" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "seriesValues", + "signature": "Series -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "weightedAverage", + "signature": "[Double] -> [Double] -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Core", + "name": "yuleWalker", + "signature": "Int -> [Double] -> Either MathError ([Double], Double, Double)" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "DTWResult", + "signature": "Double -> [(Int, Int)] -> DTWResult" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "Level", + "signature": "Deterministic" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "LinearTrend", + "signature": "Deterministic" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "MAE", + "signature": "ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "MAPE", + "signature": "ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "MASE", + "signature": "Int -> [Double] -> ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "MSE", + "signature": "ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "RMSE", + "signature": "ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "SMAPE", + "signature": "ForecastMetric" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "Stationarity", + "signature": "Double -> [(Double, Double)] -> Int -> String -> Stationarity" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "anomalies", + "signature": "Double -> [Double] -> Either MathError [Int]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "augmentedDickeyFuller", + "signature": "Deterministic -> Int -> [Double] -> Either MathError Stationarity" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "changePoints", + "signature": "Double -> Int -> [Double] -> Either MathError [Int]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "cusum", + "signature": "Double -> Double -> Double -> Double -> [Double] -> Either MathError [Int]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "dtwDistance", + "signature": "DTWResult -> Double" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "dtwPath", + "signature": "DTWResult -> [(Int, Int)]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "dynamicTimeWarping", + "signature": "Int -> [Double] -> [Double] -> Either MathError DTWResult" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "forecastError", + "signature": "ForecastMetric -> [Double] -> [Double] -> Either MathError Double" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "kpss", + "signature": "Deterministic -> Int -> [Double] -> Either MathError Stationarity" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "spectrum", + "signature": "Double -> [Double] -> Either MathError [(Double, Double)]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "stationarityCriticalValues", + "signature": "Stationarity -> [(Double, Double)]" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "stationarityNull", + "signature": "Stationarity -> String" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "stationarityObservations", + "signature": "Stationarity -> Int" + }, + { + "module": "HMath.TimeSeries.Diagnostics", + "name": "stationarityStatistic", + "signature": "Stationarity -> Double" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "Decomposition", + "signature": "[Double] -> [Double] -> [Double] -> Decomposition" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "Holt", + "signature": "Double -> Double -> Smoothing" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "HoltWinters", + "signature": "Int -> Double -> Double -> Double -> Smoothing" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "SARIMAOrder", + "signature": "Int -> Int -> Int -> Int -> Int -> Int -> Int -> SARIMAOrder" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "STLConfig", + "signature": "Int -> Int -> Int -> Int -> Int -> Int -> STLConfig" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "Simple", + "signature": "Double -> Smoothing" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "arCoefficients", + "signature": "ARModel -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "arOrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "arimaInnovationVariance", + "signature": "ARIMAModel -> Double" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "arimaParameters", + "signature": "ARIMAModel -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "arimaResiduals", + "signature": "ARIMAModel -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "decompose", + "signature": "Int -> [Double] -> Either MathError Decomposition" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "defaultSTLConfig", + "signature": "Int -> STLConfig" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "differenceOrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitAR", + "signature": "Int -> [Double] -> Either MathError ARModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitARIMA", + "signature": "OptimizeOptions -> Int -> Int -> Int -> [Double] -> Either MathError ARIMAModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitARMA", + "signature": "OptimizeOptions -> Int -> Int -> [Double] -> Either MathError ARIMAModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitMA", + "signature": "OptimizeOptions -> Int -> [Double] -> Either MathError ARIMAModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitSARIMA", + "signature": "OptimizeOptions -> SARIMAOrder -> [Double] -> Either MathError ARIMAModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "fitVAR", + "signature": "Int -> [[Double]] -> Either MathError VARModel" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "forecastAR", + "signature": "Int -> ARModel -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "forecastARIMA", + "signature": "Int -> ARIMAModel -> Either MathError [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "forecastVAR", + "signature": "Int -> VARModel -> Either MathError [[Double]]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "kalmanSeries", + "signature": "[[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> GaussianState -> [[Double]] -> Either MathError [GaussianState]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "maOrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "remainderComponent", + "signature": "Decomposition -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "seasonalAROrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "seasonalComponent", + "signature": "Decomposition -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "seasonalDifferenceOrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "seasonalMAOrder", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "seasonalPeriod", + "signature": "SARIMAOrder -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "smoothForecast", + "signature": "Smoothing -> Int -> [Double] -> Either MathError ([Double], [Double])" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stl", + "signature": "STLConfig -> [Double] -> Either MathError Decomposition" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlInnerIterations", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlLowPassWindow", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlPeriod", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlRobustIterations", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlSeasonalWindow", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "stlTrendWindow", + "signature": "STLConfig -> Int" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "trendComponent", + "signature": "Decomposition -> [Double]" + }, + { + "module": "HMath.TimeSeries.Models", + "name": "varCoefficients", + "signature": "VARModel -> [[Double]]" + }, + { + "module": "HMath.Signal", + "name": "gaussianState", + "signature": "[Double] -> [[Double]] -> Either MathError GaussianState" + }, + { + "module": "HMath.Signal", + "name": "stateMean", + "signature": "GaussianState -> [Double]" + }, + { + "module": "HMath.Signal", + "name": "stateCovariance", + "signature": "GaussianState -> [[Double]]" + } + ] +} diff --git a/bindings/schema/timeseries-objects.json b/bindings/schema/timeseries-objects.json new file mode 100644 index 0000000..6e7b984 --- /dev/null +++ b/bindings/schema/timeseries-objects.json @@ -0,0 +1,1025 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.TimeSeries.Core.Series", + "c": [ + "hmath_timeseries_series_object" + ], + "python": "hmath.timeseries.Series", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Alignment", + "c": [ + "hmath_timeseries_alignment_object" + ], + "python": "hmath.timeseries.Alignment", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Fill", + "c": [ + "hmath_timeseries_fill_object" + ], + "python": "hmath.timeseries.Fill", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Resampling", + "c": [ + "hmath_timeseries_resampling_object" + ], + "python": "hmath.timeseries.Resampling", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Rolling", + "c": [ + "hmath_timeseries_rolling_object" + ], + "python": "hmath.timeseries.Rolling", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Deterministic", + "c": [ + "hmath_timeseries_deterministic_object" + ], + "python": "hmath.timeseries.Deterministic", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.ForecastMetric", + "c": [ + "hmath_timeseries_forecast_metric_object" + ], + "python": "hmath.timeseries.ForecastMetric", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.ARIMAModel", + "c": [ + "hmath_timeseries_arima_model_object" + ], + "python": "hmath.timeseries.ARIMAModel", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.ARModel", + "c": [ + "hmath_timeseries_ar_model_object" + ], + "python": "hmath.timeseries.ARModel", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Smoothing", + "c": [ + "hmath_timeseries_smoothing_object" + ], + "python": "hmath.timeseries.Smoothing", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.VARModel", + "c": [ + "hmath_timeseries_var_model_object" + ], + "python": "hmath.timeseries.VARModel", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.Signal.GaussianState", + "c": [ + "hmath_timeseries_gaussian_state_object" + ], + "python": "hmath.timeseries.GaussianState", + "specializations": [ + "original concrete type" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BackwardFill", + "c": [ + "hmath_timeseries_backward_fill" + ], + "python": "hmath.timeseries.backward_fill", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BinLast", + "c": [ + "hmath_timeseries_bin_last" + ], + "python": "hmath.timeseries.bin_last", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.BinMean", + "c": [ + "hmath_timeseries_bin_mean" + ], + "python": "hmath.timeseries.bin_mean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.ForwardFill", + "c": [ + "hmath_timeseries_forward_fill" + ], + "python": "hmath.timeseries.forward_fill", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Inner", + "c": [ + "hmath_timeseries_inner" + ], + "python": "hmath.timeseries.inner", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LeftAligned", + "c": [ + "hmath_timeseries_left_aligned" + ], + "python": "hmath.timeseries.left_aligned", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LinearFill", + "c": [ + "hmath_timeseries_linear_fill" + ], + "python": "hmath.timeseries.linear_fill", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.LinearSamples", + "c": [ + "hmath_timeseries_linear_samples" + ], + "python": "hmath.timeseries.linear_samples", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMaximum", + "c": [ + "hmath_timeseries_moving_maximum" + ], + "python": "hmath.timeseries.moving_maximum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMean", + "c": [ + "hmath_timeseries_moving_mean" + ], + "python": "hmath.timeseries.moving_mean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingMinimum", + "c": [ + "hmath_timeseries_moving_minimum" + ], + "python": "hmath.timeseries.moving_minimum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingSD", + "c": [ + "hmath_timeseries_moving_sd" + ], + "python": "hmath.timeseries.moving_sd", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.MovingVariance", + "c": [ + "hmath_timeseries_moving_variance" + ], + "python": "hmath.timeseries.moving_variance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.Outer", + "c": [ + "hmath_timeseries_outer" + ], + "python": "hmath.timeseries.outer", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.align", + "c": [ + "hmath_timeseries_align" + ], + "python": "hmath.timeseries.align", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.durbinLevinson", + "c": [ + "hmath_timeseries_durbin_levinson" + ], + "python": "hmath.timeseries.durbin_levinson", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.fillMissing", + "c": [ + "hmath_timeseries_fill_missing" + ], + "python": "hmath.timeseries.fill_missing", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.isRegular", + "c": [ + "hmath_timeseries_is_regular" + ], + "python": "hmath.timeseries.is_regular", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.observations", + "c": [ + "hmath_timeseries_observations" + ], + "python": "hmath.timeseries.observations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.regularSeries", + "c": [ + "hmath_timeseries_regular_series" + ], + "python": "hmath.timeseries.regular_series", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.resample", + "c": [ + "hmath_timeseries_resample" + ], + "python": "hmath.timeseries.resample", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.rolling", + "c": [ + "hmath_timeseries_rolling" + ], + "python": "hmath.timeseries.rolling", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.series", + "c": [ + "hmath_timeseries_series" + ], + "python": "hmath.timeseries.series", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.seriesValues", + "c": [ + "hmath_timeseries_series_values" + ], + "python": "hmath.timeseries.series_values", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Core.yuleWalker", + "c": [ + "hmath_timeseries_yule_walker" + ], + "python": "hmath.timeseries.yule_walker", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.DTWResult", + "c": [ + "hmath_timeseries_dtw_result" + ], + "python": "hmath.timeseries.dtw_result", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Level", + "c": [ + "hmath_timeseries_level" + ], + "python": "hmath.timeseries.level", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.LinearTrend", + "c": [ + "hmath_timeseries_linear_trend" + ], + "python": "hmath.timeseries.linear_trend", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MAE", + "c": [ + "hmath_timeseries_mae" + ], + "python": "hmath.timeseries.mae", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MAPE", + "c": [ + "hmath_timeseries_mape" + ], + "python": "hmath.timeseries.mape", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MASE", + "c": [ + "hmath_timeseries_mase" + ], + "python": "hmath.timeseries.mase", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.MSE", + "c": [ + "hmath_timeseries_mse" + ], + "python": "hmath.timeseries.mse", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.RMSE", + "c": [ + "hmath_timeseries_rmse" + ], + "python": "hmath.timeseries.rmse", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.SMAPE", + "c": [ + "hmath_timeseries_smape" + ], + "python": "hmath.timeseries.smape", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.Stationarity", + "c": [ + "hmath_timeseries_stationarity" + ], + "python": "hmath.timeseries.stationarity", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.augmentedDickeyFuller", + "c": [ + "hmath_timeseries_augmented_dickey_fuller" + ], + "python": "hmath.timeseries.augmented_dickey_fuller", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dtwDistance", + "c": [ + "hmath_timeseries_dtw_distance" + ], + "python": "hmath.timeseries.dtw_distance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dtwPath", + "c": [ + "hmath_timeseries_dtw_path" + ], + "python": "hmath.timeseries.dtw_path", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.dynamicTimeWarping", + "c": [ + "hmath_timeseries_dynamic_time_warping" + ], + "python": "hmath.timeseries.dynamic_time_warping", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.forecastError", + "c": [ + "hmath_timeseries_forecast_error" + ], + "python": "hmath.timeseries.forecast_error", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.kpss", + "c": [ + "hmath_timeseries_kpss" + ], + "python": "hmath.timeseries.kpss", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.spectrum", + "c": [ + "hmath_timeseries_spectrum" + ], + "python": "hmath.timeseries.spectrum", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityCriticalValues", + "c": [ + "hmath_timeseries_stationarity_critical_values" + ], + "python": "hmath.timeseries.stationarity_critical_values", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityNull", + "c": [ + "hmath_timeseries_stationarity_null" + ], + "python": "hmath.timeseries.stationarity_null", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityObservations", + "c": [ + "hmath_timeseries_stationarity_observations" + ], + "python": "hmath.timeseries.stationarity_observations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Diagnostics.stationarityStatistic", + "c": [ + "hmath_timeseries_stationarity_statistic" + ], + "python": "hmath.timeseries.stationarity_statistic", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Decomposition", + "c": [ + "hmath_timeseries_decomposition" + ], + "python": "hmath.timeseries.decomposition", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Holt", + "c": [ + "hmath_timeseries_holt" + ], + "python": "hmath.timeseries.holt", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.HoltWinters", + "c": [ + "hmath_timeseries_holt_winters" + ], + "python": "hmath.timeseries.holt_winters", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.SARIMAOrder", + "c": [ + "hmath_timeseries_sarima_order" + ], + "python": "hmath.timeseries.sarima_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.STLConfig", + "c": [ + "hmath_timeseries_stl_config" + ], + "python": "hmath.timeseries.stl_config", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.Simple", + "c": [ + "hmath_timeseries_simple" + ], + "python": "hmath.timeseries.simple", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arCoefficients", + "c": [ + "hmath_timeseries_ar_coefficients" + ], + "python": "hmath.timeseries.ar_coefficients", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arOrder", + "c": [ + "hmath_timeseries_ar_order" + ], + "python": "hmath.timeseries.ar_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaInnovationVariance", + "c": [ + "hmath_timeseries_arima_innovation_variance" + ], + "python": "hmath.timeseries.arima_innovation_variance", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaParameters", + "c": [ + "hmath_timeseries_arima_parameters" + ], + "python": "hmath.timeseries.arima_parameters", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.arimaResiduals", + "c": [ + "hmath_timeseries_arima_residuals" + ], + "python": "hmath.timeseries.arima_residuals", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.decompose", + "c": [ + "hmath_timeseries_decompose" + ], + "python": "hmath.timeseries.decompose", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.defaultSTLConfig", + "c": [ + "hmath_timeseries_default_stl_config" + ], + "python": "hmath.timeseries.default_stl_config", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.differenceOrder", + "c": [ + "hmath_timeseries_difference_order" + ], + "python": "hmath.timeseries.difference_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitAR", + "c": [ + "hmath_timeseries_fit_ar" + ], + "python": "hmath.timeseries.fit_ar", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitARIMA", + "c": [ + "hmath_timeseries_fit_arima" + ], + "python": "hmath.timeseries.fit_arima", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitARMA", + "c": [ + "hmath_timeseries_fit_arma" + ], + "python": "hmath.timeseries.fit_arma", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitMA", + "c": [ + "hmath_timeseries_fit_ma" + ], + "python": "hmath.timeseries.fit_ma", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitSARIMA", + "c": [ + "hmath_timeseries_fit_sarima" + ], + "python": "hmath.timeseries.fit_sarima", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.fitVAR", + "c": [ + "hmath_timeseries_fit_var" + ], + "python": "hmath.timeseries.fit_var", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastAR", + "c": [ + "hmath_timeseries_forecast_ar" + ], + "python": "hmath.timeseries.forecast_ar", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastARIMA", + "c": [ + "hmath_timeseries_forecast_arima" + ], + "python": "hmath.timeseries.forecast_arima", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.forecastVAR", + "c": [ + "hmath_timeseries_forecast_var" + ], + "python": "hmath.timeseries.forecast_var", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.kalmanSeries", + "c": [ + "hmath_timeseries_kalman_series" + ], + "python": "hmath.timeseries.kalman_series", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.maOrder", + "c": [ + "hmath_timeseries_ma_order" + ], + "python": "hmath.timeseries.ma_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.remainderComponent", + "c": [ + "hmath_timeseries_remainder_component" + ], + "python": "hmath.timeseries.remainder_component", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalAROrder", + "c": [ + "hmath_timeseries_seasonal_ar_order" + ], + "python": "hmath.timeseries.seasonal_ar_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalComponent", + "c": [ + "hmath_timeseries_seasonal_component" + ], + "python": "hmath.timeseries.seasonal_component", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalDifferenceOrder", + "c": [ + "hmath_timeseries_seasonal_difference_order" + ], + "python": "hmath.timeseries.seasonal_difference_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalMAOrder", + "c": [ + "hmath_timeseries_seasonal_ma_order" + ], + "python": "hmath.timeseries.seasonal_ma_order", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.seasonalPeriod", + "c": [ + "hmath_timeseries_seasonal_period" + ], + "python": "hmath.timeseries.seasonal_period", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.smoothForecast", + "c": [ + "hmath_timeseries_smooth_forecast" + ], + "python": "hmath.timeseries.smooth_forecast", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stl", + "c": [ + "hmath_timeseries_stl" + ], + "python": "hmath.timeseries.stl", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlInnerIterations", + "c": [ + "hmath_timeseries_stl_inner_iterations" + ], + "python": "hmath.timeseries.stl_inner_iterations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlLowPassWindow", + "c": [ + "hmath_timeseries_stl_low_pass_window" + ], + "python": "hmath.timeseries.stl_low_pass_window", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlPeriod", + "c": [ + "hmath_timeseries_stl_period" + ], + "python": "hmath.timeseries.stl_period", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlRobustIterations", + "c": [ + "hmath_timeseries_stl_robust_iterations" + ], + "python": "hmath.timeseries.stl_robust_iterations", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlSeasonalWindow", + "c": [ + "hmath_timeseries_stl_seasonal_window" + ], + "python": "hmath.timeseries.stl_seasonal_window", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.stlTrendWindow", + "c": [ + "hmath_timeseries_stl_trend_window" + ], + "python": "hmath.timeseries.stl_trend_window", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.trendComponent", + "c": [ + "hmath_timeseries_trend_component" + ], + "python": "hmath.timeseries.trend_component", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.TimeSeries.Models.varCoefficients", + "c": [ + "hmath_timeseries_var_coefficients" + ], + "python": "hmath.timeseries.var_coefficients", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Signal.gaussianState", + "c": [ + "hmath_timeseries_gaussian_state" + ], + "python": "hmath.timeseries.gaussian_state", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Signal.stateMean", + "c": [ + "hmath_timeseries_state_mean" + ], + "python": "hmath.timeseries.state_mean", + "specializations": [ + "original concrete types" + ] + }, + { + "symbol": "HMath.Signal.stateCovariance", + "c": [ + "hmath_timeseries_state_covariance" + ], + "python": "hmath.timeseries.state_covariance", + "specializations": [ + "original concrete types" + ] + } + ] +} diff --git a/bindings/schema/units-values-objects.json b/bindings/schema/units-values-objects.json new file mode 100644 index 0000000..9672987 --- /dev/null +++ b/bindings/schema/units-values-objects.json @@ -0,0 +1,809 @@ +{ + "schema": 1, + "bindings": [ + { + "symbol": "HMath.Units.Dimension", + "c": [ + "hmath_value", + "hmath_units_value_dimension" + ], + "python": "hmath.units.Dimension", + "specializations": [ + "immutable exact Units Value kind68" + ] + }, + { + "symbol": "HMath.Units.Quantity", + "c": [ + "hmath_value", + "hmath_units_value_quantity" + ], + "python": "hmath.units.Quantity", + "specializations": [ + "immutable exact Units Value kind70" + ] + }, + { + "symbol": "HMath.Units.SIPrefix", + "c": [ + "hmath_value", + "hmath_units_value_si_prefix" + ], + "python": "hmath.units.SIPrefix", + "specializations": [ + "immutable exact Units Value kind71" + ] + }, + { + "symbol": "HMath.Units.Unit", + "c": [ + "hmath_value", + "hmath_units_value_unit" + ], + "python": "hmath.units.Unit", + "specializations": [ + "immutable exact Units Value kind69" + ] + }, + { + "symbol": "HMath.Units.addQuantity", + "c": [ + "hmath_units_value_add_quantity" + ], + "python": "hmath.units.add_quantity", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.angleDimension", + "c": [ + "hmath_units_value_angle_dimension" + ], + "python": "hmath.units.angle_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.atmosphere", + "c": [ + "hmath_units_value_atmosphere" + ], + "python": "hmath.units.atmosphere", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.bar", + "c": [ + "hmath_units_value_bar" + ], + "python": "hmath.units.bar", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.bit", + "c": [ + "hmath_units_value_bit" + ], + "python": "hmath.units.bit", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.byte", + "c": [ + "hmath_units_value_byte" + ], + "python": "hmath.units.byte", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.celsius", + "c": [ + "hmath_units_value_celsius" + ], + "python": "hmath.units.celsius", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.centimetre", + "c": [ + "hmath_units_value_centimetre" + ], + "python": "hmath.units.centimetre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.convert", + "c": [ + "hmath_units_value_convert" + ], + "python": "hmath.units.convert", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.cubicMetre", + "c": [ + "hmath_units_value_cubic_metre" + ], + "python": "hmath.units.cubic_metre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.dataDimension", + "c": [ + "hmath_units_value_data_dimension" + ], + "python": "hmath.units.data_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.day", + "c": [ + "hmath_units_value_day" + ], + "python": "hmath.units.day", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.degree", + "c": [ + "hmath_units_value_degree" + ], + "python": "hmath.units.degree", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.dimension", + "c": [ + "hmath_units_value_dimension" + ], + "python": "hmath.units.dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.dimensionExponents", + "c": [ + "hmath_units_value_dimension_exponents" + ], + "python": "hmath.units.dimension_exponents", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.dimensionless", + "c": [ + "hmath_units_value_dimensionless" + ], + "python": "hmath.units.dimensionless", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.divideQuantity", + "c": [ + "hmath_units_value_divide_quantity" + ], + "python": "hmath.units.divide_quantity", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.fahrenheit", + "c": [ + "hmath_units_value_fahrenheit" + ], + "python": "hmath.units.fahrenheit", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.foot", + "c": [ + "hmath_units_value_foot" + ], + "python": "hmath.units.foot", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.gigabyte", + "c": [ + "hmath_units_value_gigabyte" + ], + "python": "hmath.units.gigabyte", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.gradian", + "c": [ + "hmath_units_value_gradian" + ], + "python": "hmath.units.gradian", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.gram", + "c": [ + "hmath_units_value_gram" + ], + "python": "hmath.units.gram", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.hectare", + "c": [ + "hmath_units_value_hectare" + ], + "python": "hmath.units.hectare", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.hertz", + "c": [ + "hmath_units_value_hertz" + ], + "python": "hmath.units.hertz", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.hour", + "c": [ + "hmath_units_value_hour" + ], + "python": "hmath.units.hour", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.inUnit", + "c": [ + "hmath_units_value_in_unit" + ], + "python": "hmath.units.in_unit", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.inch", + "c": [ + "hmath_units_value_inch" + ], + "python": "hmath.units.inch", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.joule", + "c": [ + "hmath_units_value_joule" + ], + "python": "hmath.units.joule", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.kelvin", + "c": [ + "hmath_units_value_kelvin" + ], + "python": "hmath.units.kelvin", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.kibibyte", + "c": [ + "hmath_units_value_kibibyte" + ], + "python": "hmath.units.kibibyte", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.kilogram", + "c": [ + "hmath_units_value_kilogram" + ], + "python": "hmath.units.kilogram", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.kilometre", + "c": [ + "hmath_units_value_kilometre" + ], + "python": "hmath.units.kilometre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.kilometresPerHour", + "c": [ + "hmath_units_value_kilometres_per_hour" + ], + "python": "hmath.units.kilometres_per_hour", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.lengthDimension", + "c": [ + "hmath_units_value_length_dimension" + ], + "python": "hmath.units.length_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.litre", + "c": [ + "hmath_units_value_litre" + ], + "python": "hmath.units.litre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.massDimension", + "c": [ + "hmath_units_value_mass_dimension" + ], + "python": "hmath.units.mass_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.mebibyte", + "c": [ + "hmath_units_value_mebibyte" + ], + "python": "hmath.units.mebibyte", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.metre", + "c": [ + "hmath_units_value_metre" + ], + "python": "hmath.units.metre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.metresPerSecond", + "c": [ + "hmath_units_value_metres_per_second" + ], + "python": "hmath.units.metres_per_second", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.metresPerSecondSquared", + "c": [ + "hmath_units_value_metres_per_second_squared" + ], + "python": "hmath.units.metres_per_second_squared", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.mile", + "c": [ + "hmath_units_value_mile" + ], + "python": "hmath.units.mile", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.milesPerHour", + "c": [ + "hmath_units_value_miles_per_hour" + ], + "python": "hmath.units.miles_per_hour", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.millilitre", + "c": [ + "hmath_units_value_millilitre" + ], + "python": "hmath.units.millilitre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.millimetre", + "c": [ + "hmath_units_value_millimetre" + ], + "python": "hmath.units.millimetre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.minute", + "c": [ + "hmath_units_value_minute" + ], + "python": "hmath.units.minute", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.multiplyQuantity", + "c": [ + "hmath_units_value_multiply_quantity" + ], + "python": "hmath.units.multiply_quantity", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.nauticalMile", + "c": [ + "hmath_units_value_nautical_mile" + ], + "python": "hmath.units.nautical_mile", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.newton", + "c": [ + "hmath_units_value_newton" + ], + "python": "hmath.units.newton", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.pascal", + "c": [ + "hmath_units_value_pascal" + ], + "python": "hmath.units.pascal", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.pound", + "c": [ + "hmath_units_value_pound" + ], + "python": "hmath.units.pound", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.prefixExponent", + "c": [ + "hmath_units_value_prefix_exponent" + ], + "python": "hmath.units.prefix_exponent", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.prefixName", + "c": [ + "hmath_units_value_prefix_name" + ], + "python": "hmath.units.prefix_name", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.prefixSymbol", + "c": [ + "hmath_units_value_prefix_symbol" + ], + "python": "hmath.units.prefix_symbol", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.prefixed", + "c": [ + "hmath_units_value_prefixed" + ], + "python": "hmath.units.prefixed", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.quantity", + "c": [ + "hmath_units_value_quantity" + ], + "python": "hmath.units.quantity", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.quantityDimension", + "c": [ + "hmath_units_value_quantity_dimension" + ], + "python": "hmath.units.quantity_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.radian", + "c": [ + "hmath_units_value_radian" + ], + "python": "hmath.units.radian", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.second", + "c": [ + "hmath_units_value_second" + ], + "python": "hmath.units.second", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.siPrefixes", + "c": [ + "hmath_units_value_si_prefixes" + ], + "python": "hmath.units.si_prefixes", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.siValue", + "c": [ + "hmath_units_value_si_value" + ], + "python": "hmath.units.si_value", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.squareMetre", + "c": [ + "hmath_units_value_square_metre" + ], + "python": "hmath.units.square_metre", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.subtractQuantity", + "c": [ + "hmath_units_value_subtract_quantity" + ], + "python": "hmath.units.subtract_quantity", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.temperatureDifference", + "c": [ + "hmath_units_value_temperature_difference" + ], + "python": "hmath.units.temperature_difference", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.temperatureDimension", + "c": [ + "hmath_units_value_temperature_dimension" + ], + "python": "hmath.units.temperature_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.timeDimension", + "c": [ + "hmath_units_value_time_dimension" + ], + "python": "hmath.units.time_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.tonne", + "c": [ + "hmath_units_value_tonne" + ], + "python": "hmath.units.tonne", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unit", + "c": [ + "hmath_units_value_unit" + ], + "python": "hmath.units.unit", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitDimension", + "c": [ + "hmath_units_value_unit_dimension" + ], + "python": "hmath.units.unit_dimension", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitName", + "c": [ + "hmath_units_value_unit_name" + ], + "python": "hmath.units.unit_name", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitOffset", + "c": [ + "hmath_units_value_unit_offset" + ], + "python": "hmath.units.unit_offset", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitPower", + "c": [ + "hmath_units_value_unit_power" + ], + "python": "hmath.units.unit_power", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitProduct", + "c": [ + "hmath_units_value_unit_product" + ], + "python": "hmath.units.unit_product", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitQuotient", + "c": [ + "hmath_units_value_unit_quotient" + ], + "python": "hmath.units.unit_quotient", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.unitScale", + "c": [ + "hmath_units_value_unit_scale" + ], + "python": "hmath.units.unit_scale", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.watt", + "c": [ + "hmath_units_value_watt" + ], + "python": "hmath.units.watt", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + }, + { + "symbol": "HMath.Units.yard", + "c": [ + "hmath_units_value_yard" + ], + "python": "hmath.units.yard", + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ] + } + ] +} diff --git a/cbits/algebra.c b/cbits/algebra.c new file mode 100644 index 0000000..b2735d4 --- /dev/null +++ b/cbits/algebra.c @@ -0,0 +1,771 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_algebra.h" +#include "value_internal.h" +extern int hm_algebra_apply(int, void *const *, size_t, void **); +hmath_status hmath_algebra_core_linear_combination(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(0, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_semiring_laws(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(1, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_ring_laws(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(2, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_field_laws(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(3, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_group_laws(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(4, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_module_laws(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(5, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(6, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_modular_value(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(7, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_modular_modulus(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(8, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_add_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(9, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_subtract_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(10, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_multiply_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(11, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_inverse_modular(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(12, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_power_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(13, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_finite_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_algebra_apply(14, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_prime_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(15, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_field_characteristic(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(16, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_field_degree(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(17, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_field_cardinality(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(18, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_field_modulus(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(19, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_field_element(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(20, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_field_element_coefficients(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(21, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_field_elements(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(22, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_add_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(23, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_negate_field(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(24, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_subtract_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(25, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_multiply_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(26, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_inverse_field_element(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(27, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_power_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(28, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_finite_field_laws(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(29, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_get_additive(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(30, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_new_additive(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(31, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_horner(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(32, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_inner_product(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(33, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_get_exact(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(34, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_new_exact(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(35, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_zero(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(36, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_one(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(37, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_plus(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(38, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_times(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(39, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_negate_ring(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(40, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_inverse_field(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(41, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_group_identity(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(42, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_core_group_combine(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(43, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_group_inverse(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(44, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_core_module_scale(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(45, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_core_module_add(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(46, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_zero(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(47, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_one(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(48, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_plus(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(49, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_times(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(50, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_negative(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(51, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_integer(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(52, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_invert(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(53, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_conjugate_scalar(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(54, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_machine_epsilon(hmath_context *context, const hmath_value *prototype, + hmath_value **out) { + if (!out || !prototype) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype)}; + return hm_value_finish(result, hm_algebra_apply(55, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_finite_scalar(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(56, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_rational(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(57, args, 2, &result->stable), out); +} +hmath_status hmath_algebra_api_matrix_dimensions(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(58, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_matrix_elements(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(59, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_matrix_construct(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1), + hm_value_stable(a2)}; + return hm_value_finish(result, hm_algebra_apply(60, args, 4, &result->stable), out); +} +hmath_status hmath_algebra_api_tensor_dimensions(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(61, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_tensor_elements(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(62, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_tensor_construct(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(63, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_vector_plus(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(64, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_vector_scale(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_algebra_apply(65, args, 3, &result->stable), out); +} +hmath_status hmath_algebra_api_differential(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL algebra argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_algebra_apply(66, args, 1, &result->stable), out); +} +hmath_status hmath_algebra_api_exact_element_type(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL element type output"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_algebra_apply(-1, NULL, 0, &result->stable), out); +} diff --git a/cbits/autodiff_bindings.c b/cbits/autodiff_bindings.c new file mode 100644 index 0000000..4880a41 --- /dev/null +++ b/cbits/autodiff_bindings.c @@ -0,0 +1,819 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_autodiff.h" +#include "native_internal.h" +#include "value_internal.h" +#include +#include +enum { EXPR, GRAPH, GRADIENT, TENSOR, DUAL }; +struct hmath_ad_handle { + atomic_size_t refs; + int kind; + void *stable; +}; +extern void hm_ad_free(void *); +extern int hm_ad_make(int, void *const *, size_t, ptrdiff_t, double, const double *, size_t, + const ptrdiff_t *, size_t, const ptrdiff_t *, size_t, void **); +extern int hm_ad_metadata(void *, size_t *, size_t *); +extern int hm_ad_data(void *, double *, ptrdiff_t *); +extern int hm_ad_tensor_values(void *, void **); +extern int hm_ad_run(int, void *const *, size_t, const double *, size_t, const double *, size_t, + double, double *); +static int is_kind(const hmath_ad_handle *v, int kind) { return v && v->kind == kind; } +static int all_kind(const hmath_ad_handle *const *vs, size_t count, int kind) { + if (count > (size_t)PTRDIFF_MAX / sizeof(void *) || (count && !vs)) + return 0; + for (size_t i = 0; i < count; ++i) + if (!is_kind(vs[i], kind)) + return 0; + return 1; +} +static hmath_status bad_kind(void) { + return hm_error(HMATH_INVALID_ARGUMENT, "incorrect AD handle kind"); +} +static int span(const void *p, size_t n, size_t item) { + return n <= (size_t)PTRDIFF_MAX / item && (!n || p); +} +static void **stable_inputs(const hmath_ad_handle *const *inputs, size_t count) { + void **p = malloc((count ? count : 1) * sizeof *p); + if (p) + for (size_t i = 0; i < count; ++i) + p[i] = inputs[i]->stable; + return p; +} +void hmath_ad_retain(hmath_ad_handle *v) { + if (v) + atomic_fetch_add_explicit(&v->refs, 1, memory_order_relaxed); +} +void hmath_ad_release(hmath_ad_handle *v) { + if (v && atomic_fetch_sub_explicit(&v->refs, 1, memory_order_acq_rel) == 1) { + hm_ad_free(v->stable); + free(v); + hm_leave(); + } +} +static hmath_status make(hmath_context *context, int kind, int op, + const hmath_ad_handle *const *inputs, size_t count, ptrdiff_t index, + double scalar, const double *values, size_t value_count, + const ptrdiff_t *shape, size_t rank, const ptrdiff_t *axes, + size_t axis_count, hmath_ad_handle **out) { + if (!out || !span(inputs, count, sizeof(void *)) || + !span(values, value_count, sizeof(double)) || !span(shape, rank, sizeof(ptrdiff_t)) || + !span(axes, axis_count, sizeof(ptrdiff_t))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD array span or output"); + for (size_t i = 0; i < count; ++i) + if (!inputs[i]) + return bad_kind(); + hmath_ad_handle *value = malloc(sizeof *value); + void **stable = stable_inputs(inputs, count); + if (!value || !stable) { + free(value); + free(stable); + return hm_error(HMATH_ALLOCATION_FAILED, "AD handle allocation failed"); + } + hmath_status status = hm_enter(context); + if (status) { + free(value); + free(stable); + return status; + } + status = (hmath_status)hm_ad_make(op, stable, count, index, scalar, values, value_count, shape, + rank, axes, axis_count, &value->stable); + free(stable); + if (status) { + free(value); + hm_leave(); + return status; + } + value->kind = kind; + atomic_init(&value->refs, 1); + *out = value; + return HMATH_OK; +} +static hmath_status run(hmath_context *context, int operation, const hmath_ad_handle *const *inputs, + size_t count, const double *values, size_t n, const double *direction, + size_t direction_count, double scalar, double *out, size_t capacity, + size_t required) { + if (!span(inputs, count, sizeof(void *)) || !span(values, n, sizeof(double)) || + !span(direction, direction_count, sizeof(double)) || !span(out, required, sizeof(double))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD evaluation span"); + if (capacity < required) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient AD result capacity"); + void **stable = stable_inputs(inputs, count); + if (!stable) + return hm_error(HMATH_ALLOCATION_FAILED, "AD input allocation failed"); + hmath_status status = hm_enter(context); + if (!status) { + status = (hmath_status)hm_ad_run(operation, stable, count, values, n, direction, + direction_count, scalar, out); + hm_leave(); + } + free(stable); + return status; +} +hmath_status hmath_ad_variable(hmath_context *context, ptrdiff_t index, hmath_ad_expr **out) { + return make(context, EXPR, 0, NULL, 0, index, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_constant(hmath_context *context, double value, hmath_ad_expr **out) { + return make(context, EXPR, 1, NULL, 0, 0, value, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_dual_create(hmath_context *context, double primal, double tangent, + hmath_ad_dual **out) { + double values[] = {primal, tangent}; + return make(context, DUAL, 2, NULL, 0, 0, 0, values, 2, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_unary(hmath_context *context, hmath_ad_unary_operation operation, + const hmath_ad_handle *value, hmath_ad_handle **out) { + if (!value || (value->kind != EXPR && value->kind != DUAL) || + (unsigned)operation > HMATH_AD_STOP_GRADIENT || + (value->kind == DUAL && operation >= HMATH_AD_DETACH)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD unary input"); + const hmath_ad_handle *inputs[] = {value}; + return make(context, value->kind, 3, inputs, 1, operation, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_binary(hmath_context *context, hmath_ad_binary_operation operation, + const hmath_ad_handle *left, const hmath_ad_handle *right, + hmath_ad_handle **out) { + if (!left || !right || left->kind != right->kind || + (left->kind != EXPR && left->kind != DUAL) || (unsigned)operation > HMATH_AD_POWER) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD binary input"); + const hmath_ad_handle *inputs[] = {left, right}; + return make(context, left->kind, 4, inputs, 2, operation, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_compile_graph(hmath_context *context, ptrdiff_t index, + const hmath_ad_expr *expression, hmath_ad_graph **out) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return make(context, GRAPH, 5, inputs, 1, index, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_differentiate(hmath_context *context, ptrdiff_t index, + const hmath_ad_expr *expression, hmath_ad_expr **out) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return make(context, EXPR, 6, inputs, 1, index, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_zero_gradients(hmath_context *context, ptrdiff_t count, + hmath_ad_gradient_state **out) { + return make(context, GRADIENT, 7, NULL, 0, count, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_gradient_state_create(hmath_context *context, const double *values, + size_t count, hmath_ad_gradient_state **out) { + return make(context, GRADIENT, 20, NULL, 0, 0, 0, values, count, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_accumulate_gradients(hmath_context *context, + const hmath_ad_gradient_state *state, + const double *values, size_t count, + hmath_ad_gradient_state **out) { + if (!is_kind(state, GRADIENT)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {state}; + return make(context, GRADIENT, 8, inputs, 1, 0, 0, values, count, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_gradient_hook_result(hmath_context *context, + const hmath_ad_gradient_state *state, + const double *values, size_t count, + hmath_ad_gradient_state **out) { + if (!is_kind(state, GRADIENT)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {state}; + return make(context, GRADIENT, 19, inputs, 1, 0, 0, values, count, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_reset_gradients(hmath_context *context, const hmath_ad_gradient_state *state, + hmath_ad_gradient_state **out) { + if (!is_kind(state, GRADIENT)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {state}; + return make(context, GRADIENT, 9, inputs, 1, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_clip_gradient(hmath_context *context, double limit, const double *values, + size_t count, hmath_ad_gradient_state **out) { + return make(context, GRADIENT, 10, NULL, 0, 0, limit, values, count, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_tensor_create(hmath_context *context, const ptrdiff_t *shape, size_t rank, + const hmath_ad_expr *const *values, size_t count, + hmath_ad_tensor **out) { + if (!all_kind(values, count, EXPR)) + return bad_kind(); + return make(context, TENSOR, 11, values, count, 0, 0, NULL, 0, shape, rank, NULL, 0, out); +} +hmath_status hmath_ad_broadcast(hmath_context *context, const ptrdiff_t *shape, size_t rank, + const hmath_ad_tensor *tensor, hmath_ad_tensor **out) { + if (!is_kind(tensor, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {tensor}; + return make(context, TENSOR, 12, inputs, 1, 0, 0, NULL, 0, shape, rank, NULL, 0, out); +} +hmath_status hmath_ad_tensor_add(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out) { + if (!is_kind(left, TENSOR) || !is_kind(right, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {left, right}; + return make(context, TENSOR, 13, inputs, 2, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_tensor_multiply(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out) { + if (!is_kind(left, TENSOR) || !is_kind(right, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {left, right}; + return make(context, TENSOR, 14, inputs, 2, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_matmul(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out) { + if (!is_kind(left, TENSOR) || !is_kind(right, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {left, right}; + return make(context, TENSOR, 15, inputs, 2, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_contract(hmath_context *context, const ptrdiff_t *left_axes, + size_t left_count, const ptrdiff_t *right_axes, size_t right_count, + const hmath_ad_tensor *left, const hmath_ad_tensor *right, + hmath_ad_tensor **out) { + if (!is_kind(left, TENSOR) || !is_kind(right, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {left, right}; + return make(context, TENSOR, 16, inputs, 2, 0, 0, NULL, 0, left_axes, left_count, right_axes, + right_count, out); +} +hmath_status hmath_ad_sum(hmath_context *context, const hmath_ad_tensor *tensor, + hmath_ad_expr **out) { + if (!is_kind(tensor, TENSOR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {tensor}; + return make(context, EXPR, 17, inputs, 1, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_evaluate_graph(hmath_context *context, const hmath_ad_graph *expression, + const double *values, size_t n, double *out, size_t capacity) { + if (!is_kind(expression, GRAPH)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 0, inputs, 1, values, n, NULL, 0, 0, out, capacity, 1); +} +hmath_status hmath_ad_value_and_gradient(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + if (n == SIZE_MAX) + return hm_error(HMATH_OVERFLOW, "gradient size overflow"); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 1, inputs, 1, values, n, NULL, 0, 0, out, capacity, n + 1); +} +hmath_status hmath_ad_gradient(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 2, inputs, 1, values, n, NULL, 0, 0, out, capacity, n); +} +hmath_status hmath_ad_hessian(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + if (n && n > SIZE_MAX / n) + return hm_error(HMATH_OVERFLOW, "Hessian size overflow"); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 3, inputs, 1, values, n, NULL, 0, 0, out, capacity, n * n); +} +hmath_status hmath_ad_hvp(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, const double *direction, + size_t direction_count, double *out, size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 7, inputs, 1, values, n, direction, direction_count, 0, out, capacity, n); +} +hmath_status hmath_ad_gradient_check(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double step, double *out, + size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 8, inputs, 1, values, n, NULL, 0, step, out, capacity, 1); +} +hmath_status hmath_ad_complex_gradient(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity) { + if (!is_kind(expression, EXPR)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {expression}; + return run(context, 9, inputs, 1, values, n, NULL, 0, 0, out, capacity, 2); +} +hmath_status hmath_ad_jacobian(hmath_context *context, const hmath_ad_expr *const *expressions, + size_t count, const double *values, size_t n, double *out, + size_t capacity) { + if (!all_kind(expressions, count, EXPR)) + return bad_kind(); + if (n && count > SIZE_MAX / n) + return hm_error(HMATH_OVERFLOW, "Jacobian size overflow"); + return run(context, 4, expressions, count, values, n, NULL, 0, 0, out, capacity, count * n); +} +hmath_status hmath_ad_jvp(hmath_context *context, const hmath_ad_expr *const *expressions, + size_t count, const double *values, size_t n, const double *direction, + size_t direction_count, double *out, size_t capacity) { + if (!all_kind(expressions, count, EXPR)) + return bad_kind(); + return run(context, 5, expressions, count, values, n, direction, direction_count, 0, out, + capacity, count); +} +hmath_status hmath_ad_vjp(hmath_context *context, const hmath_ad_expr *const *expressions, + size_t count, const double *values, size_t n, const double *direction, + size_t direction_count, double *out, size_t capacity) { + if (!all_kind(expressions, count, EXPR)) + return bad_kind(); + return run(context, 6, expressions, count, values, n, direction, direction_count, 0, out, + capacity, n); +} +hmath_status hmath_ad_forward_jvp_result(hmath_context *context, + const hmath_ad_dual *const *expressions, size_t count, + const double *values, size_t n, const double *direction, + size_t direction_count, double *out, size_t capacity) { + if (!all_kind(expressions, count, DUAL)) + return bad_kind(); + if (count > SIZE_MAX / 2) + return hm_error(HMATH_OVERFLOW, "dual result size overflow"); + return run(context, 10, expressions, count, values, n, direction, direction_count, 0, out, + capacity, count * 2); +} + +hmath_status hmath_ad_metadata(const hmath_ad_handle *v, size_t *count, size_t *rank) { + if (!v || !count || !rank) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL AD metadata argument"); + hmath_status status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_metadata(v->stable, count, rank); + hm_leave(); + } + return status ? status : hm_error(HMATH_OK, ""); +} +hmath_status hmath_ad_values_copy(const hmath_ad_handle *v, double *out, size_t capacity) { + if (!v || (v->kind != GRADIENT && v->kind != DUAL)) + return bad_kind(); + size_t n, rank; + hmath_status status = hmath_ad_metadata(v, &n, &rank); + if (status) + return status ? status : hm_error(HMATH_OK, ""); + if (!span(out, n, sizeof(double))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD value output span"); + if (capacity < n) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient AD value capacity"); + status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_data(v->stable, out, NULL); + hm_leave(); + } + return status ? status : hm_error(HMATH_OK, ""); +} +hmath_status hmath_ad_shape_copy(const hmath_ad_tensor *v, ptrdiff_t *out, size_t capacity) { + if (!is_kind(v, TENSOR)) + return bad_kind(); + size_t n, rank; + hmath_status status = hmath_ad_metadata(v, &n, &rank); + if (status) + return status ? status : hm_error(HMATH_OK, ""); + if (!span(out, rank, sizeof(ptrdiff_t))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD shape output span"); + if (capacity < rank) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient AD shape capacity"); + status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_data(v->stable, NULL, out); + hm_leave(); + } + return status ? status : hm_error(HMATH_OK, ""); +} +hmath_status hmath_ad_tensor_values(const hmath_ad_tensor *v, hmath_ad_expr **out, + size_t capacity) { + if (!is_kind(v, TENSOR)) + return bad_kind(); + size_t n, rank; + hmath_status status = hmath_ad_metadata(v, &n, &rank); + if (status) + return status ? status : hm_error(HMATH_OK, ""); + if (!span(out, n, sizeof(void *))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid AD expression output span"); + if (capacity < n) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient AD expression capacity"); + hmath_ad_handle **handles = calloc(n ? n : 1, sizeof *handles); + void **raw = malloc((n ? n : 1) * sizeof *raw); + if (!handles || !raw) { + free(handles); + free(raw); + return hm_error(HMATH_ALLOCATION_FAILED, "AD expression array allocation failed"); + } + size_t allocated = 0; + for (; allocated < n; ++allocated) { + handles[allocated] = malloc(sizeof *handles[allocated]); + if (!handles[allocated]) { + status = hm_error(HMATH_ALLOCATION_FAILED, "AD expression handle allocation failed"); + break; + } + status = hm_enter(NULL); + if (status) { + free(handles[allocated]); + break; + } + } + if (!status) + status = (hmath_status)hm_ad_tensor_values(v->stable, raw); + if (!status) { + for (size_t i = 0; i < n; ++i) { + handles[i]->kind = EXPR; + handles[i]->stable = raw[i]; + atomic_init(&handles[i]->refs, 1); + out[i] = handles[i]; + } + } else + for (size_t i = 0; i < allocated; ++i) { + free(handles[i]); + hm_leave(); + } + free(raw); + free(handles); + return status ? status : hm_error(HMATH_OK, ""); +} + +hmath_status hmath_ad_differentiable_step(hmath_context *context, double rate, + const hmath_ad_expr *expression, + const hmath_ad_expr *const *points, size_t count, + hmath_ad_tensor **out) { + if (!is_kind(expression, EXPR) || !all_kind(points, count, EXPR)) + return bad_kind(); + if (count >= (size_t)PTRDIFF_MAX / sizeof(void *)) + return hm_error(HMATH_OVERFLOW, "differentiable step input size overflow"); + const hmath_ad_handle **inputs = malloc((count + 1) * sizeof *inputs); + if (!inputs) + return hm_error(HMATH_ALLOCATION_FAILED, "AD step input allocation failed"); + inputs[0] = expression; + for (size_t i = 0; i < count; ++i) + inputs[i + 1] = points[i]; + hmath_status status = + make(context, TENSOR, 18, inputs, count + 1, 0, rate, NULL, 0, NULL, 0, NULL, 0, out); + free(inputs); + return status ? status : hm_error(HMATH_OK, ""); +} + +extern int hm_ad_clone(void *value, void **out); +extern int hm_ad_callbacks(int operation, void *const *values, size_t count, + hmath_ad_rule_callback rule, hmath_ad_unary_callback function, + hmath_ad_unary_callback derivative, hmath_ad_builder_callback builder, + void *userdata, void **out); + +static hmath_status make_callback(hmath_context *context, int operation, + hmath_ad_rule_callback rule, hmath_ad_unary_callback function, + hmath_ad_unary_callback derivative, + hmath_ad_builder_callback builder, void *userdata, + const hmath_ad_expr *const *values, size_t count, + hmath_ad_expr **out) { + if (!out || !all_kind(values, count, EXPR)) + return bad_kind(); + hmath_ad_handle *value = malloc(sizeof *value); + void **inputs = stable_inputs(values, count); + if (!value || !inputs) { + free(value); + free(inputs); + return hm_error(HMATH_ALLOCATION_FAILED, "AD callback allocation failed"); + } + hmath_status status = hm_enter(context); + if (status) { + free(value); + free(inputs); + return status; + } + status = (hmath_status)hm_ad_callbacks(operation, inputs, count, rule, function, derivative, + builder, userdata, &value->stable); + free(inputs); + if (status) { + free(value); + hm_leave(); + return status; + } + value->kind = EXPR; + atomic_init(&value->refs, 1); + *out = value; + return HMATH_OK; +} +hmath_status hmath_ad_custom_operation(hmath_context *context, hmath_ad_rule_callback callback, + void *userdata, const hmath_ad_expr *const *values, + size_t count, hmath_ad_expr **out) { + if (!callback) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL custom operation callback"); + return make_callback(context, 0, callback, NULL, NULL, NULL, userdata, values, count, out); +} +hmath_status hmath_ad_custom_unary(hmath_context *context, hmath_ad_unary_callback function, + hmath_ad_unary_callback derivative, void *userdata, + const hmath_ad_expr *value, hmath_ad_expr **out) { + if (!function || !derivative) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL custom unary callback"); + const hmath_ad_expr *inputs[] = {value}; + return make_callback(context, 1, NULL, function, derivative, NULL, userdata, inputs, 1, out); +} +hmath_status hmath_ad_checkpoint(hmath_context *context, hmath_ad_builder_callback callback, + void *userdata, const hmath_ad_expr *const *values, size_t count, + hmath_ad_expr **out) { + if (!callback) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL checkpoint callback"); + return make_callback(context, 2, NULL, NULL, NULL, callback, userdata, values, count, out); +} + +/* Internal helper called safely from Haskell, allowing a checkpoint builder to + * reenter the public ABI. Input/output stable pointers are independently cloned + * so a borrowed callback input cannot outlive the Haskell temporary it came from. */ +int hm_ad_invoke_builder(hmath_ad_builder_callback callback, void *userdata, void *const *values, + size_t count, void **out, const char **error_message) { + hmath_ad_handle **inputs = calloc(count ? count : 1, sizeof *inputs); + if (!inputs) { + *error_message = "checkpoint input allocation failed"; + return HMATH_ALLOCATION_FAILED; + } + size_t allocated = 0; + hmath_status status = HMATH_OK; + for (; allocated < count; ++allocated) { + hmath_ad_handle *value = malloc(sizeof *value); + if (!value) { + status = HMATH_ALLOCATION_FAILED; + *error_message = "checkpoint handle allocation failed"; + break; + } + status = hm_enter(NULL); + if (status) { + free(value); + *error_message = "checkpoint runtime reservation failed"; + break; + } + status = (hmath_status)hm_ad_clone(values[allocated], &value->stable); + if (status) { + free(value); + hm_leave(); + *error_message = "checkpoint input clone failed"; + break; + } + value->kind = EXPR; + atomic_init(&value->refs, 1); + inputs[allocated] = value; + } + hmath_ad_expr *result = NULL; + if (!status) + status = + callback((const hmath_ad_expr *const *)inputs, count, userdata, &result, error_message); + if (!status) { + if (!is_kind(result, EXPR)) { + status = HMATH_INVALID_ARGUMENT; + *error_message = "checkpoint builder must return an owned Expr"; + } else + status = (hmath_status)hm_ad_clone(result->stable, out); + } + if (result) + hmath_ad_release(result); + for (size_t i = 0; i < allocated; ++i) + hmath_ad_release(inputs[i]); + free(inputs); + return status; +} + +extern int hm_ad_dual_depth(void *value, size_t *depth); +extern int hm_ad_dual_parts(void *value, void **primal, void **tangent); + +hmath_status hmath_ad_dual_nested(hmath_context *context, const hmath_ad_dual *primal, + const hmath_ad_dual *tangent, hmath_ad_dual **out) { + if (!is_kind(primal, DUAL) || !is_kind(tangent, DUAL)) + return bad_kind(); + const hmath_ad_handle *inputs[] = {primal, tangent}; + return make(context, DUAL, 21, inputs, 2, 0, 0, NULL, 0, NULL, 0, NULL, 0, out); +} +hmath_status hmath_ad_dual_depth(const hmath_ad_dual *value, size_t *out) { + if (!is_kind(value, DUAL) || !out) + return bad_kind(); + hmath_status status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_dual_depth(value->stable, out); + hm_leave(); + } + return status; +} +hmath_status hmath_ad_dual_parts(const hmath_ad_dual *value, hmath_ad_dual **out_primal, + hmath_ad_dual **out_tangent) { + if (!is_kind(value, DUAL) || !out_primal || !out_tangent) + return bad_kind(); + hmath_ad_handle *primal = malloc(sizeof *primal), *tangent = malloc(sizeof *tangent); + if (!primal || !tangent) { + free(primal); + free(tangent); + return hm_error(HMATH_ALLOCATION_FAILED, "Dual component allocation failed"); + } + hmath_status status = hm_enter(NULL); + if (status) { + free(primal); + free(tangent); + return status; + } + status = hm_enter(NULL); + if (status) { + free(primal); + free(tangent); + hm_leave(); + return status; + } + status = (hmath_status)hm_ad_dual_parts(value->stable, &primal->stable, &tangent->stable); + if (status) { + free(primal); + free(tangent); + hm_leave(); + hm_leave(); + return status; + } + primal->kind = tangent->kind = DUAL; + atomic_init(&primal->refs, 1); + atomic_init(&tangent->refs, 1); + *out_primal = primal; + *out_tangent = tangent; + return HMATH_OK; +} + +extern int hm_ad_dual_f32(float primal, float tangent, void **out); +extern int hm_ad_dual_exact(int kind, const char *pn, const char *pd, const char *tn, + const char *td, void **out); +extern int hm_ad_dual_kind(void *value, int *out); +extern int hm_ad_scalar_text(void *value, char **numerator, char **denominator); + +static hmath_status begin_dual(hmath_context *context, hmath_ad_handle **value) { + *value = malloc(sizeof **value); + if (!*value) + return hm_error(HMATH_ALLOCATION_FAILED, "Dual handle allocation failed"); + hmath_status status = hm_enter(context); + if (status) { + free(*value); + *value = NULL; + } + return status; +} +static hmath_status finish_dual(hmath_status status, hmath_ad_handle *value, hmath_ad_dual **out) { + if (status) { + free(value); + hm_leave(); + return status; + } + value->kind = DUAL; + atomic_init(&value->refs, 1); + *out = value; + return hm_error(HMATH_OK, ""); +} +hmath_status hmath_ad_dual_create_f32(hmath_context *context, float primal, float tangent, + hmath_ad_dual **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Dual output"); + hmath_ad_handle *value; + hmath_status status = begin_dual(context, &value); + if (status) + return status; + status = (hmath_status)hm_ad_dual_f32(primal, tangent, &value->stable); + return finish_dual(status, value, out); +} +static int decimal(const char *text) { + if (!text) + return 0; + if (*text == '-') + ++text; + if (!*text) + return 0; + for (; *text; ++text) + if (*text < '0' || *text > '9') + return 0; + return 1; +} +static hmath_status exact_dual(hmath_context *context, int kind, const char *pn, const char *pd, + const char *tn, const char *td, hmath_ad_dual **out) { + if (!out || !decimal(pn) || !decimal(tn) || (kind == 3 && (!decimal(pd) || !decimal(td)))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid exact Dual representation"); + hmath_ad_handle *value; + hmath_status status = begin_dual(context, &value); + if (status) + return status; + status = (hmath_status)hm_ad_dual_exact(kind, pn, pd, tn, td, &value->stable); + return finish_dual(status, value, out); +} +hmath_status hmath_ad_dual_create_integer(hmath_context *context, const char *primal, + const char *tangent, hmath_ad_dual **out) { + return exact_dual(context, 2, primal, NULL, tangent, NULL, out); +} +hmath_status hmath_ad_dual_create_rational(hmath_context *context, const char *pn, const char *pd, + const char *tn, const char *td, hmath_ad_dual **out) { + return exact_dual(context, 3, pn, pd, tn, td, out); +} +hmath_status hmath_ad_dual_kind(const hmath_ad_dual *value, int *out) { + if (!is_kind(value, DUAL) || !out) + return bad_kind(); + hmath_status status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_dual_kind(value->stable, out); + hm_leave(); + } + return status; +} +hmath_status hmath_ad_scalar_text(const hmath_ad_dual *value, char **numerator, + char **denominator) { + if (!is_kind(value, DUAL) || !numerator || !denominator) + return bad_kind(); + hmath_status status = hm_enter(NULL); + if (!status) { + status = (hmath_status)hm_ad_scalar_text(value->stable, numerator, denominator); + hm_leave(); + } + return status; +} +void hmath_ad_string_free(char *value) { free(value); } + +extern int hm_ad_dual_relation(int operation, void *left, void *right, int *out); +hmath_status hmath_ad_dual_relation(hmath_context *context, int operation, + const hmath_ad_dual *left, const hmath_ad_dual *right, + int *out) { + if (!is_kind(left, DUAL) || !is_kind(right, DUAL) || !out || (unsigned)operation > 4) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Dual relation input"); + hmath_status status = hm_enter(context); + if (!status) { + status = (hmath_status)hm_ad_dual_relation(operation, left->stable, right->stable, out); + hm_leave(); + } + return status; +} + +extern int hm_ad_value_import(void *input,void **out); +extern int hm_ad_value_export(void *input,void **out,int *kind); +hmath_status hmath_ad_value_import(hmath_context *context,const hmath_ad_handle *input,hmath_value **out) { + if(!input || !out || (input->kind!=EXPR && input->kind!=TENSOR && input->kind!=DUAL)) + return hm_error(HMATH_INVALID_ARGUMENT,"AD Value interchange requires Expr, ADTensor or original Dual"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_ad_value_import(input->stable,&result->stable),out); +} +hmath_status hmath_ad_value_export(hmath_context *context,const hmath_value *input,hmath_ad_handle **out) { + if(!input || !out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL AD Value interchange argument/output"); + hmath_ad_handle *result=calloc(1,sizeof *result); + if(!result)return hm_error(HMATH_ALLOCATION_FAILED,"AD Value handle allocation failed"); + hmath_status status=hm_enter(context); + if(status){free(result);return status;} + status=(hmath_status)hm_ad_value_export(hm_value_stable(input),&result->stable,&result->kind); + if(status){free(result);hm_leave();return status;} + atomic_init(&result->refs,1); + *out=result; + return HMATH_OK; +} + +extern int hm_ad_custom_checked(int operation,void (*callback)(void),void (*derivative)(void), + void *userdata,void *const *inputs,size_t count,void **out); +static hmath_status make_checked_callback(hmath_context *context,int operation, + void (*callback)(void),void (*derivative)(void), + void *userdata,const hmath_ad_expr *const *inputs, + size_t count,hmath_ad_expr **out) { + if(!out || !callback || (operation==1 && !derivative) || !all_kind(inputs,count,EXPR)) + return hm_error(HMATH_INVALID_ARGUMENT,"invalid checked AD callback input/output"); + hmath_ad_handle *value=malloc(sizeof *value); + void **stable=stable_inputs(inputs,count); + if(!value || !stable){free(value);free(stable);return hm_error(HMATH_ALLOCATION_FAILED,"checked AD callback allocation failed");} + hmath_status status=hm_enter(context); + if(status){free(value);free(stable);return status;} + status=(hmath_status)hm_ad_custom_checked(operation,callback,derivative,userdata,stable,count,&value->stable); + free(stable); + if(status){free(value);hm_leave();return status;} + value->kind=EXPR;atomic_init(&value->refs,1);*out=value; + return HMATH_OK; +} +hmath_status hmath_ad_custom_operation_checked(hmath_context *context,hmath_ad_rule_checked_callback callback,void *userdata,const hmath_ad_expr *const *inputs,size_t count,hmath_ad_expr **out) { + return make_checked_callback(context,0,(void (*)(void))callback,NULL,userdata,inputs,count,out); +} +hmath_status hmath_ad_custom_unary_checked(hmath_context *context,hmath_ad_unary_checked_callback callback,hmath_ad_unary_checked_callback derivative,void *userdata,const hmath_ad_expr *input,hmath_ad_expr **out) { + return make_checked_callback(context,1,(void (*)(void))callback,(void (*)(void))derivative,userdata,&input,1,out); +} +hmath_status hmath_ad_checkpoint_checked(hmath_context *context,hmath_ad_builder_checked_callback callback,void *userdata,const hmath_ad_expr *const *inputs,size_t count,hmath_ad_expr **out) { + return make_checked_callback(context,2,(void (*)(void))callback,NULL,userdata,inputs,count,out); +} +static hmath_status builder_checked_error(hmath_callback_error *error,hmath_status status,const char *message) { + error->kind=0;error->message=message;error->message_length=strlen(message);return status; +} +int hm_ad_invoke_builder_checked(hmath_ad_builder_checked_callback callback,void *userdata, + void *const *values,size_t count,void **out,hmath_callback_error *error) { + hmath_ad_handle **inputs=calloc(count?count:1,sizeof *inputs); + if(!inputs)return builder_checked_error(error,HMATH_ALLOCATION_FAILED,"checkpoint input allocation failed"); + size_t allocated=0; + hmath_status status=HMATH_OK; + for(;allocatedstable); + if(status){free(value);hm_leave();builder_checked_error(error,status,"checkpoint input clone failed");break;} + value->kind=EXPR;atomic_init(&value->refs,1);inputs[allocated]=value; + } + hmath_ad_expr *result=NULL; + if(!status)status=callback((const hmath_ad_expr *const *)inputs,count,userdata,&result,error); + if(!status){ + if(!is_kind(result,EXPR))status=builder_checked_error(error,HMATH_INVALID_ARGUMENT,"checkpoint builder must return an owned Expr"); + else status=(hmath_status)hm_ad_clone(result->stable,out); + } + hmath_ad_release(result); + for(size_t i=0;i INT32_MAX || result < INT32_MIN ? -10001 : (int32_t)result; } + +int hm_backend_has_real_gemm(hmath_backend *backend, int precision) { + return backend && (precision == 32 || precision == 64) && + bsym(backend, precision == 32 ? "cblas_sgemm" : "cblas_dgemm") != NULL; +} +int hm_backend_real_gemm(hmath_backend *backend, int precision, int64_t m, int64_t n, int64_t k, + const void *alpha, const void *a, int64_t lda, + const void *b, int64_t ldb, const void *beta, void *c, int64_t ldc) { + if (!backend || m < 0 || n < 0 || k < 0 || lda < k || ldb < n || ldc < n || + (backend->bits == 32 && (m > INT32_MAX || n > INT32_MAX || k > INT32_MAX || + lda > INT32_MAX || ldb > INT32_MAX || ldc > INT32_MAX))) + return 2; + if (!hm_backend_has_real_gemm(backend, precision)) + return 1; +#define REAL_GEMM(real, integer, symbol_name) \ + ((void (*)(int, int, int, integer, integer, integer, real, const real *, integer, \ + const real *, integer, real, real *, integer))bsym(backend, symbol_name))( \ + 101, 111, 111, (integer)m, (integer)n, (integer)k, *(const real *)alpha, \ + a, (integer)lda, b, (integer)ldb, *(const real *)beta, c, (integer)ldc) + if (backend->bits == 32) { + if (precision == 32) { REAL_GEMM(float, int32_t, "cblas_sgemm"); } + else { REAL_GEMM(double, int32_t, "cblas_dgemm"); } + } else { + if (precision == 32) { REAL_GEMM(float, int64_t, "cblas_sgemm"); } + else { REAL_GEMM(double, int64_t, "cblas_dgemm"); } + } +#undef REAL_GEMM + return 0; +} diff --git a/cbits/buffer.c b/cbits/buffer.c new file mode 100644 index 0000000..683e98d --- /dev/null +++ b/cbits/buffer.c @@ -0,0 +1,231 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_buffer_bindings.py. */ +#include "hmath_buffer.h" +#include "value_internal.h" +extern int hm_buffer_apply(int,void *const *,size_t,void **); +static _Thread_local unsigned char buffer_thread_token; +void *hm_buffer_thread_token(void) { return &buffer_thread_token; } +hmath_status hmath_buffer_lazy_boxed(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_buffer_apply(0,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_strict_boxed(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_buffer_apply(1,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_boxed_values(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(2,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_boxed_length(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(3,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_map_strict(hmath_context *context, const hmath_value *function, const hmath_value *value, hmath_value **out) { + if(!out||!function||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(function),hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(4,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_unboxed_double(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_buffer_apply(5,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_unboxed_values(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(6,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_run_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out) { + if(!out||!value||!callback)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(callback)}; + return hm_value_finish(result,hm_buffer_apply(7,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_thaw_st_buffer(hmath_context *context, const hmath_value *region, const hmath_value *value, hmath_value **out) { + if(!out||!region||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(region),hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(8,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_freeze_st_buffer(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(9,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_read_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out) { + if(!out||!value||!index)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index)}; + return hm_value_finish(result,hm_buffer_apply(10,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_write_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out) { + if(!out||!value||!index||!element)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index),hm_value_stable(element)}; + return hm_value_finish(result,hm_buffer_apply(11,arguments,3,&result->stable),out); +} +hmath_status hmath_buffer_new_io_buffer(hmath_context *context, const hmath_value *count, const hmath_value *initial, hmath_value **out) { + if(!out||!count||!initial)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(initial)}; + return hm_value_finish(result,hm_buffer_apply(12,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_thaw_io_buffer(hmath_context *context, const hmath_value *prototype, const hmath_value *value, hmath_value **out) { + if(!out||!prototype||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(prototype),hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(13,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_freeze_io_buffer(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(14,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_io_buffer_length(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(15,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_read_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out) { + if(!out||!value||!index)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index)}; + return hm_value_finish(result,hm_buffer_apply(16,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_write_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out) { + if(!out||!value||!index||!element)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index),hm_value_stable(element)}; + return hm_value_finish(result,hm_buffer_apply(17,arguments,3,&result->stable),out); +} +hmath_status hmath_buffer_with_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out) { + if(!out||!value||!callback)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(callback)}; + return hm_value_finish(result,hm_buffer_apply(18,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_unboxed_to_boxed(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(19,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_boxed_to_unboxed(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(20,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_storage_info(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(21,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_pointer_info(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(22,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_pointer_read(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out) { + if(!out||!value||!index)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index)}; + return hm_value_finish(result,hm_buffer_apply(23,arguments,2,&result->stable),out); +} +hmath_status hmath_buffer_pointer_write(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out) { + if(!out||!value||!index||!element)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(index),hm_value_stable(element)}; + return hm_value_finish(result,hm_buffer_apply(24,arguments,3,&result->stable),out); +} +hmath_status hmath_buffer_pointer_address(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(25,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_st_active(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(26,arguments,1,&result->stable),out); +} +hmath_status hmath_buffer_pointer_active(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_buffer_apply(27,arguments,1,&result->stable),out); +} diff --git a/cbits/bytes.c b/cbits/bytes.c new file mode 100644 index 0000000..1000e05 --- /dev/null +++ b/cbits/bytes.c @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_bytes.h" +#include "value_internal.h" +extern int hm_bytes_copy(const void *, size_t, void **); +extern int hm_bytes_data(void *, const unsigned char **, size_t *); +hmath_status hmath_bytes_copy(hmath_context *context, const void *data, size_t count, + hmath_value **out) { + if (!out || (count && !data)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid byte span/output"); + if (count > (size_t)PTRDIFF_MAX) + return hm_error(HMATH_OVERFLOW, "byte span exceeds Haskell Int"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + return hm_value_finish(temporary, hm_bytes_copy(data, count, &temporary->stable), out); +} +hmath_status hmath_bytes_data(const hmath_value *bytes, const unsigned char **data, size_t *count) { + if (!bytes || !data || !count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL byte metadata argument"); + return (hmath_status)hm_bytes_data(hm_value_stable(bytes), data, count); +} diff --git a/cbits/deeplearning.c b/cbits/deeplearning.c new file mode 100644 index 0000000..633740c --- /dev/null +++ b/cbits/deeplearning.c @@ -0,0 +1,1190 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_deeplearning.h" +#include "value_internal.h" +#include +extern int hm_neural_apply(const char *,void *const *,size_t,void **); +static hmath_status invoke(hmath_context *context,const char *name,const hmath_value *const *arguments,size_t count,hmath_value **out) { + if(!out || (count && !arguments))return hm_error(HMATH_INVALID_ARGUMENT,"NULL neural argument/output"); + if(count>(size_t)PTRDIFF_MAX/sizeof(void *))return hm_error(HMATH_OVERFLOW,"neural argument span overflow"); + for(size_t i=0;istable); + free(stable); + return hm_value_finish(result,code,out); +} +/* BEGIN GENERATED */ +hmath_status hmath_neural_core_sigmoid_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Sigmoid", NULL, 0, out); +} + +hmath_status hmath_neural_core_tanh_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Tanh", NULL, 0, out); +} + +hmath_status hmath_neural_core_relu_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.ReLU", NULL, 0, out); +} + +hmath_status hmath_neural_core_selu_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.SELU", NULL, 0, out); +} + +hmath_status hmath_neural_core_gelu_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.GELU", NULL, 0, out); +} + +hmath_status hmath_neural_core_silu_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.SiLU", NULL, 0, out); +} + +hmath_status hmath_neural_core_mish_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Mish", NULL, 0, out); +} + +hmath_status hmath_neural_core_softplus_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Softplus", NULL, 0, out); +} + +hmath_status hmath_neural_core_softsign_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Softsign", NULL, 0, out); +} + +hmath_status hmath_neural_core_hard_sigmoid_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.HardSigmoid", NULL, 0, out); +} + +hmath_status hmath_neural_core_hard_swish_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.HardSwish", NULL, 0, out); +} + +hmath_status hmath_neural_core_leaky_relu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.LeakyReLU", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_prelu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.PReLU", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_elu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.ELU", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_sum_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Sum", NULL, 0, out); +} + +hmath_status hmath_neural_core_mean_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.Mean", NULL, 0, out); +} + +hmath_status hmath_neural_core_mean_squared_error_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.MeanSquaredError", NULL, 0, out); +} + +hmath_status hmath_neural_core_mean_absolute_error_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.MeanAbsoluteError", NULL, 0, out); +} + +hmath_status hmath_neural_core_binary_cross_entropy_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.BinaryCrossEntropy", NULL, 0, out); +} + +hmath_status hmath_neural_core_categorical_cross_entropy_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.CategoricalCrossEntropy", NULL, 0, out); +} + +hmath_status hmath_neural_core_negative_log_likelihood_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.NegativeLogLikelihood", NULL, 0, out); +} + +hmath_status hmath_neural_core_kl_divergence_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.KLDivergence", NULL, 0, out); +} + +hmath_status hmath_neural_core_cosine_loss_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Core.CosineLoss", NULL, 0, out); +} + +hmath_status hmath_neural_core_huber_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.Huber", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_smooth_l1_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.SmoothL1", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_hinge_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out) { + const hmath_value *hm_arguments[]={parameter}; + return invoke(context, "HMath.DeepLearning.Core.Hinge", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_activation( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, value}; + return invoke(context, "HMath.DeepLearning.Core.activation", hm_arguments, 2, out); +} + +hmath_status hmath_neural_core_activation_derivative( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, value}; + return invoke(context, "HMath.DeepLearning.Core.activationDerivative", hm_arguments, 2, out); +} + +hmath_status hmath_neural_core_activation_expr( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, value}; + return invoke(context, "HMath.DeepLearning.Core.activationExpr", hm_arguments, 2, out); +} + +hmath_status hmath_neural_core_softmax( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.softmax", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_log_softmax( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.logSoftmax", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_sparsemax( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.sparsemax", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_gated_linear_unit( + hmath_context *context, + const hmath_value *values, + const hmath_value *gate, + hmath_value **out) { + const hmath_value *hm_arguments[]={values, gate}; + return invoke(context, "HMath.DeepLearning.Core.gatedLinearUnit", hm_arguments, 2, out); +} + +hmath_status hmath_neural_core_softmax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.softmaxExpr", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_log_softmax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.logSoftmaxExpr", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_sparsemax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out) { + const hmath_value *hm_arguments[]={values}; + return invoke(context, "HMath.DeepLearning.Core.sparsemaxExpr", hm_arguments, 1, out); +} + +hmath_status hmath_neural_core_loss( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, reduction, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.loss", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_loss_gradient( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, reduction, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.lossGradient", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_loss_expr( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, reduction, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.lossExpr", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_binary_cross_entropy_logits( + hmath_context *context, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *logits, + hmath_value **out) { + const hmath_value *hm_arguments[]={reduction, target, logits}; + return invoke(context, "HMath.DeepLearning.Core.binaryCrossEntropyLogits", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_categorical_cross_entropy_logits( + hmath_context *context, + const hmath_value *target, + const hmath_value *logits, + hmath_value **out) { + const hmath_value *hm_arguments[]={target, logits}; + return invoke(context, "HMath.DeepLearning.Core.categoricalCrossEntropyLogits", hm_arguments, 2, out); +} + +hmath_status hmath_neural_core_regularization( + hmath_context *context, + const hmath_value *l1, + const hmath_value *l2, + const hmath_value *weights, + hmath_value **out) { + const hmath_value *hm_arguments[]={l1, l2, weights}; + return invoke(context, "HMath.DeepLearning.Core.regularization", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_contrastive_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *similar, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[]={margin, similar, left, right}; + return invoke(context, "HMath.DeepLearning.Core.contrastiveLoss", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_triplet_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *anchor, + const hmath_value *positive, + const hmath_value *negative, + hmath_value **out) { + const hmath_value *hm_arguments[]={margin, anchor, positive, negative}; + return invoke(context, "HMath.DeepLearning.Core.tripletLoss", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_focal_loss( + hmath_context *context, + const hmath_value *alpha, + const hmath_value *gamma, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={alpha, gamma, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.focalLoss", hm_arguments, 4, out); +} + +hmath_status hmath_neural_core_dice_loss( + hmath_context *context, + const hmath_value *smooth, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={smooth, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.diceLoss", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_iou_loss( + hmath_context *context, + const hmath_value *smooth, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={smooth, target, prediction}; + return invoke(context, "HMath.DeepLearning.Core.iouLoss", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_ctc_loss( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out) { + const hmath_value *hm_arguments[]={blank, labels, log_probabilities}; + return invoke(context, "HMath.DeepLearning.Core.ctcLoss", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_ctc_loss_gradient( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out) { + const hmath_value *hm_arguments[]={blank, labels, log_probabilities}; + return invoke(context, "HMath.DeepLearning.Core.ctcLossGradient", hm_arguments, 3, out); +} + +hmath_status hmath_neural_core_ctc_loss_expr( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out) { + const hmath_value *hm_arguments[]={blank, labels, log_probabilities}; + return invoke(context, "HMath.DeepLearning.Core.ctcLossExpr", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_training_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.Training", NULL, 0, out); +} + +hmath_status hmath_neural_layers_inference_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.Inference", NULL, 0, out); +} + +hmath_status hmath_neural_layers_dropout( + hmath_context *context, + const hmath_value *mode, + const hmath_value *probability, + const hmath_value *rng, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, probability, rng, input}; + return invoke(context, "HMath.DeepLearning.Layers.dropout", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_spatial_dropout( + hmath_context *context, + const hmath_value *mode, + const hmath_value *probability, + const hmath_value *rng, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, probability, rng, input}; + return invoke(context, "HMath.DeepLearning.Layers.spatialDropout", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_batch_norm_state_create( + hmath_context *context, + const hmath_value *running_mean, + const hmath_value *running_variance, + const hmath_value *batches_seen, + hmath_value **out) { + const hmath_value *hm_arguments[]={running_mean, running_variance, batches_seen}; + return invoke(context, "HMath.DeepLearning.Layers.BatchNormState", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_running_mean( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Layers.runningMean", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_running_variance( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Layers.runningVariance", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_batches_seen( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Layers.batchesSeen", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_batch_norm( + hmath_context *context, + const hmath_value *mode, + const hmath_value *momentum, + const hmath_value *epsilon, + const hmath_value *gamma, + const hmath_value *beta, + const hmath_value *state, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, momentum, epsilon, gamma, beta, state, input}; + return invoke(context, "HMath.DeepLearning.Layers.batchNorm", hm_arguments, 7, out); +} + +hmath_status hmath_neural_layers_layer_norm( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={axes, epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.layerNorm", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_rms_norm( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={axes, epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.rmsNorm", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_instance_norm( + hmath_context *context, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.instanceNorm", hm_arguments, 2, out); +} + +hmath_status hmath_neural_layers_group_norm( + hmath_context *context, + const hmath_value *groups, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={groups, epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.groupNorm", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_weight_norm( + hmath_context *context, + const hmath_value *axis, + const hmath_value *scales, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={axis, scales, input}; + return invoke(context, "HMath.DeepLearning.Layers.weightNorm", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_xavier_uniform_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.XavierUniform", NULL, 0, out); +} + +hmath_status hmath_neural_layers_xavier_normal_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.XavierNormal", NULL, 0, out); +} + +hmath_status hmath_neural_layers_kaiming_uniform_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.KaimingUniform", NULL, 0, out); +} + +hmath_status hmath_neural_layers_kaiming_normal_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.KaimingNormal", NULL, 0, out); +} + +hmath_status hmath_neural_layers_orthogonal_create( + hmath_context *context, + const hmath_value *scale, + hmath_value **out) { + const hmath_value *hm_arguments[]={scale}; + return invoke(context, "HMath.DeepLearning.Layers.Orthogonal", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_truncated_normal_create( + hmath_context *context, + const hmath_value *mean, + const hmath_value *standard_deviation, + const hmath_value *bound, + hmath_value **out) { + const hmath_value *hm_arguments[]={mean, standard_deviation, bound}; + return invoke(context, "HMath.DeepLearning.Layers.TruncatedNormal", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_initialize_weights( + hmath_context *context, + const hmath_value *method, + const hmath_value *fan_in, + const hmath_value *fan_out, + const hmath_value *shape, + const hmath_value *rng, + hmath_value **out) { + const hmath_value *hm_arguments[]={method, fan_in, fan_out, shape, rng}; + return invoke(context, "HMath.DeepLearning.Layers.initializeWeights", hm_arguments, 5, out); +} + +hmath_status hmath_neural_layers_embedding( + hmath_context *context, + const hmath_value *weights, + const hmath_value *indices, + hmath_value **out) { + const hmath_value *hm_arguments[]={weights, indices}; + return invoke(context, "HMath.DeepLearning.Layers.embedding", hm_arguments, 2, out); +} + +hmath_status hmath_neural_layers_dense( + hmath_context *context, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.dense", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_dense_ad( + hmath_context *context, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.denseAD", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_conv_options_create( + hmath_context *context, + const hmath_value *stride, + const hmath_value *padding, + const hmath_value *dilation, + const hmath_value *groups, + hmath_value **out) { + const hmath_value *hm_arguments[]={stride, padding, dilation, groups}; + return invoke(context, "HMath.DeepLearning.Layers.ConvOptions", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_convolution_stride( + hmath_context *context, + const hmath_value *options, + hmath_value **out) { + const hmath_value *hm_arguments[]={options}; + return invoke(context, "HMath.DeepLearning.Layers.convolutionStride", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_convolution_padding( + hmath_context *context, + const hmath_value *options, + hmath_value **out) { + const hmath_value *hm_arguments[]={options}; + return invoke(context, "HMath.DeepLearning.Layers.convolutionPadding", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_convolution_dilation( + hmath_context *context, + const hmath_value *options, + hmath_value **out) { + const hmath_value *hm_arguments[]={options}; + return invoke(context, "HMath.DeepLearning.Layers.convolutionDilation", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_convolution_groups( + hmath_context *context, + const hmath_value *options, + hmath_value **out) { + const hmath_value *hm_arguments[]={options}; + return invoke(context, "HMath.DeepLearning.Layers.convolutionGroups", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_convolution( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={options, input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.convolution", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_depthwise_convolution( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={options, input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.depthwiseConvolution", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_convolution_ad( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={options, input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.convolutionAD", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_transposed_convolution( + hmath_context *context, + const hmath_value *output_padding, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={output_padding, options, input, weights, bias}; + return invoke(context, "HMath.DeepLearning.Layers.transposedConvolution", hm_arguments, 5, out); +} + +hmath_status hmath_neural_layers_max_pool_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.MaxPool", NULL, 0, out); +} + +hmath_status hmath_neural_layers_average_pool_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Layers.AveragePool", NULL, 0, out); +} + +hmath_status hmath_neural_layers_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *kernel, + const hmath_value *stride, + const hmath_value *padding, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, kernel, stride, padding, input}; + return invoke(context, "HMath.DeepLearning.Layers.pooling", hm_arguments, 5, out); +} + +hmath_status hmath_neural_layers_adaptive_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *shape, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, shape, input}; + return invoke(context, "HMath.DeepLearning.Layers.adaptivePooling", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_global_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={mode, input}; + return invoke(context, "HMath.DeepLearning.Layers.globalPooling", hm_arguments, 2, out); +} + +hmath_status hmath_neural_layers_scaled_dot_product_attention( + hmath_context *context, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + const hmath_value *bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={query, key, value, mask, bias}; + return invoke(context, "HMath.DeepLearning.Layers.scaledDotProductAttention", hm_arguments, 5, out); +} + +hmath_status hmath_neural_layers_multihead_attention( + hmath_context *context, + const hmath_value *heads, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + hmath_value **out) { + const hmath_value *hm_arguments[]={heads, query, key, value, mask}; + return invoke(context, "HMath.DeepLearning.Layers.multiheadAttention", hm_arguments, 5, out); +} + +hmath_status hmath_neural_layers_causal_mask( + hmath_context *context, + const hmath_value *queries, + const hmath_value *keys, + const hmath_value *offset, + hmath_value **out) { + const hmath_value *hm_arguments[]={queries, keys, offset}; + return invoke(context, "HMath.DeepLearning.Layers.causalMask", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_rotary_embedding( + hmath_context *context, + const hmath_value *base, + const hmath_value *offset, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={base, offset, input}; + return invoke(context, "HMath.DeepLearning.Layers.rotaryEmbedding", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_sinusoidal_encoding( + hmath_context *context, + const hmath_value *length, + const hmath_value *dimensions, + const hmath_value *offset, + hmath_value **out) { + const hmath_value *hm_arguments[]={length, dimensions, offset}; + return invoke(context, "HMath.DeepLearning.Layers.sinusoidalEncoding", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_alibi_bias( + hmath_context *context, + const hmath_value *slope, + const hmath_value *queries, + const hmath_value *keys, + const hmath_value *offset, + hmath_value **out) { + const hmath_value *hm_arguments[]={slope, queries, keys, offset}; + return invoke(context, "HMath.DeepLearning.Layers.alibiBias", hm_arguments, 4, out); +} + +hmath_status hmath_neural_layers_empty_cache( + hmath_context *context, + const hmath_value *capacity, + const hmath_value *key_dimensions, + const hmath_value *value_dimensions, + hmath_value **out) { + const hmath_value *hm_arguments[]={capacity, key_dimensions, value_dimensions}; + return invoke(context, "HMath.DeepLearning.Layers.emptyCache", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_append_cache( + hmath_context *context, + const hmath_value *cache, + const hmath_value *key, + const hmath_value *value, + hmath_value **out) { + const hmath_value *hm_arguments[]={cache, key, value}; + return invoke(context, "HMath.DeepLearning.Layers.appendCache", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_cache_values( + hmath_context *context, + const hmath_value *cache, + hmath_value **out) { + const hmath_value *hm_arguments[]={cache}; + return invoke(context, "HMath.DeepLearning.Layers.cacheValues", hm_arguments, 1, out); +} + +hmath_status hmath_neural_layers_transformer_feed_forward( + hmath_context *context, + const hmath_value *activation, + const hmath_value *input, + const hmath_value *first_weights, + const hmath_value *first_bias, + const hmath_value *second_weights, + const hmath_value *second_bias, + hmath_value **out) { + const hmath_value *hm_arguments[]={activation, input, first_weights, first_bias, second_weights, second_bias}; + return invoke(context, "HMath.DeepLearning.Layers.transformerFeedForward", hm_arguments, 6, out); +} + +hmath_status hmath_neural_layers_layer_norm_ad( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={axes, epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.layerNormAD", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_rms_norm_ad( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={axes, epsilon, input}; + return invoke(context, "HMath.DeepLearning.Layers.rmsNormAD", hm_arguments, 3, out); +} + +hmath_status hmath_neural_layers_scaled_dot_product_attention_ad( + hmath_context *context, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + hmath_value **out) { + const hmath_value *hm_arguments[]={query, key, value, mask}; + return invoke(context, "HMath.DeepLearning.Layers.scaledDotProductAttentionAD", hm_arguments, 4, out); +} + +hmath_status hmath_neural_precision_symmetric_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Precision.Symmetric", NULL, 0, out); +} + +hmath_status hmath_neural_precision_asymmetric_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Precision.Asymmetric", NULL, 0, out); +} + +hmath_status hmath_neural_precision_quantize( + hmath_context *context, + const hmath_value *scheme, + const hmath_value *axis, + const hmath_value *input, + hmath_value **out) { + const hmath_value *hm_arguments[]={scheme, axis, input}; + return invoke(context, "HMath.DeepLearning.Precision.quantize", hm_arguments, 3, out); +} + +hmath_status hmath_neural_precision_dequantize( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out) { + const hmath_value *hm_arguments[]={quantized}; + return invoke(context, "HMath.DeepLearning.Precision.dequantize", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_quantized_values( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out) { + const hmath_value *hm_arguments[]={quantized}; + return invoke(context, "HMath.DeepLearning.Precision.quantizedValues", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_quantization_scales( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out) { + const hmath_value *hm_arguments[]={quantized}; + return invoke(context, "HMath.DeepLearning.Precision.quantizationScales", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_quantization_zero_points( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out) { + const hmath_value *hm_arguments[]={quantized}; + return invoke(context, "HMath.DeepLearning.Precision.quantizationZeroPoints", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_int8_gemm( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[]={left, right}; + return invoke(context, "HMath.DeepLearning.Precision.int8Gemm", hm_arguments, 2, out); +} + +hmath_status hmath_neural_precision_fp16_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Precision.FP16", NULL, 0, out); +} + +hmath_status hmath_neural_precision_bf16_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "HMath.DeepLearning.Precision.BF16", NULL, 0, out); +} + +hmath_status hmath_neural_precision_reduced_gemm( + hmath_context *context, + const hmath_value *precision, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[]={precision, left, right}; + return invoke(context, "HMath.DeepLearning.Precision.reducedGemm", hm_arguments, 3, out); +} + +hmath_status hmath_neural_precision_loss_scaler_create( + hmath_context *context, + const hmath_value *scale, + const hmath_value *growth_interval, + const hmath_value *finite_steps, + hmath_value **out) { + const hmath_value *hm_arguments[]={scale, growth_interval, finite_steps}; + return invoke(context, "HMath.DeepLearning.Precision.LossScaler", hm_arguments, 3, out); +} + +hmath_status hmath_neural_precision_loss_scale( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Precision.lossScale", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_scale_growth_interval( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Precision.scaleGrowthInterval", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_finite_steps( + hmath_context *context, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={state}; + return invoke(context, "HMath.DeepLearning.Precision.finiteSteps", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_initial_loss_scaler( + hmath_context *context, + const hmath_value *scale, + const hmath_value *growth_interval, + hmath_value **out) { + const hmath_value *hm_arguments[]={scale, growth_interval}; + return invoke(context, "HMath.DeepLearning.Precision.initialLossScaler", hm_arguments, 2, out); +} + +hmath_status hmath_neural_precision_scale_loss( + hmath_context *context, + const hmath_value *state, + const hmath_value *loss, + hmath_value **out) { + const hmath_value *hm_arguments[]={state, loss}; + return invoke(context, "HMath.DeepLearning.Precision.scaleLoss", hm_arguments, 2, out); +} + +hmath_status hmath_neural_precision_unscale_gradients( + hmath_context *context, + const hmath_value *state, + const hmath_value *gradients, + hmath_value **out) { + const hmath_value *hm_arguments[]={state, gradients}; + return invoke(context, "HMath.DeepLearning.Precision.unscaleGradients", hm_arguments, 2, out); +} + +hmath_status hmath_neural_precision_update_loss_scaler( + hmath_context *context, + const hmath_value *finite, + const hmath_value *state, + hmath_value **out) { + const hmath_value *hm_arguments[]={finite, state}; + return invoke(context, "HMath.DeepLearning.Precision.updateLossScaler", hm_arguments, 2, out); +} + +hmath_status hmath_neural_precision_gradient_norm( + hmath_context *context, + const hmath_value *gradient, + hmath_value **out) { + const hmath_value *hm_arguments[]={gradient}; + return invoke(context, "HMath.DeepLearning.Precision.gradientNorm", hm_arguments, 1, out); +} + +hmath_status hmath_neural_precision_clip_gradients( + hmath_context *context, + const hmath_value *maximum, + const hmath_value *gradient, + hmath_value **out) { + const hmath_value *hm_arguments[]={maximum, gradient}; + return invoke(context, "HMath.DeepLearning.Precision.clipGradients", hm_arguments, 2, out); +} + +hmath_status hmath_neural_metrics_classification_metrics_create( + hmath_context *context, + const hmath_value *accuracy, + const hmath_value *precision, + const hmath_value *recall, + const hmath_value *f1, + hmath_value **out) { + const hmath_value *hm_arguments[]={accuracy, precision, recall, f1}; + return invoke(context, "HMath.DeepLearning.Metrics.ClassificationMetrics", hm_arguments, 4, out); +} + +hmath_status hmath_neural_metrics_accuracy( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out) { + const hmath_value *hm_arguments[]={metrics}; + return invoke(context, "HMath.DeepLearning.Metrics.accuracy", hm_arguments, 1, out); +} + +hmath_status hmath_neural_metrics_precision_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out) { + const hmath_value *hm_arguments[]={metrics}; + return invoke(context, "HMath.DeepLearning.Metrics.precisionByClass", hm_arguments, 1, out); +} + +hmath_status hmath_neural_metrics_recall_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out) { + const hmath_value *hm_arguments[]={metrics}; + return invoke(context, "HMath.DeepLearning.Metrics.recallByClass", hm_arguments, 1, out); +} + +hmath_status hmath_neural_metrics_f1_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out) { + const hmath_value *hm_arguments[]={metrics}; + return invoke(context, "HMath.DeepLearning.Metrics.f1ByClass", hm_arguments, 1, out); +} + +hmath_status hmath_neural_metrics_confusion_matrix( + hmath_context *context, + const hmath_value *classes, + const hmath_value *truth, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={classes, truth, prediction}; + return invoke(context, "HMath.DeepLearning.Metrics.confusionMatrix", hm_arguments, 3, out); +} + +hmath_status hmath_neural_metrics_classification_metrics( + hmath_context *context, + const hmath_value *classes, + const hmath_value *truth, + const hmath_value *prediction, + hmath_value **out) { + const hmath_value *hm_arguments[]={classes, truth, prediction}; + return invoke(context, "HMath.DeepLearning.Metrics.classificationMetrics", hm_arguments, 3, out); +} + +hmath_status hmath_neural_metrics_top_k_accuracy( + hmath_context *context, + const hmath_value *k, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out) { + const hmath_value *hm_arguments[]={k, truth, scores}; + return invoke(context, "HMath.DeepLearning.Metrics.topKAccuracy", hm_arguments, 3, out); +} + +hmath_status hmath_neural_metrics_roc_auc( + hmath_context *context, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out) { + const hmath_value *hm_arguments[]={truth, scores}; + return invoke(context, "HMath.DeepLearning.Metrics.rocAUC", hm_arguments, 2, out); +} + +hmath_status hmath_neural_metrics_pr_auc( + hmath_context *context, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out) { + const hmath_value *hm_arguments[]={truth, scores}; + return invoke(context, "HMath.DeepLearning.Metrics.prAUC", hm_arguments, 2, out); +} + +hmath_status hmath_neural_metrics_perplexity( + hmath_context *context, + const hmath_value *negative_log_probabilities, + hmath_value **out) { + const hmath_value *hm_arguments[]={negative_log_probabilities}; + return invoke(context, "HMath.DeepLearning.Metrics.perplexity", hm_arguments, 1, out); +} + +hmath_status hmath_neural_metrics_cosine_similarity_matrix( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[]={left, right}; + return invoke(context, "HMath.DeepLearning.Metrics.cosineSimilarityMatrix", hm_arguments, 2, out); +} + +hmath_status hmath_neural_metrics_margin_ranking_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *left, + const hmath_value *right, + const hmath_value *labels, + hmath_value **out) { + const hmath_value *hm_arguments[]={margin, left, right, labels}; + return invoke(context, "HMath.DeepLearning.Metrics.marginRankingLoss", hm_arguments, 4, out); +} +/* END GENERATED */ diff --git a/cbits/error_wire.c b/cbits/error_wire.c new file mode 100644 index 0000000..268074a --- /dev/null +++ b/cbits/error_wire.c @@ -0,0 +1,219 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_error.h" +#include "hmath_expression_error.h" +#include "hmath_interchange_error.h" +#include "hmath_callback.h" +#include +#include +#ifdef _WIN32 +#include +static INIT_ONCE error_once = INIT_ONCE_STATIC_INIT; +static DWORD error_key = FLS_OUT_OF_INDEXES; +#else +#include +static pthread_once_t error_once = PTHREAD_ONCE_INIT; +static pthread_key_t error_key; +static int key_ready; +#endif +struct error_cell { + hmath_math_error value; + hmath_expression_error expression; + hmath_interchange_error interchange; + char *owned_message; + int valid; +}; +static void destroy_cell(void *pointer) { + struct error_cell *cell = pointer; + if (cell) { + free(cell->owned_message); + free(cell); + } +} +#ifdef _WIN32 +static void WINAPI destroy_fiber(void *pointer) { destroy_cell(pointer); } +static BOOL CALLBACK initialize_error_key(PINIT_ONCE once, PVOID parameter, PVOID *context) { + (void)once; + (void)parameter; + (void)context; + error_key = FlsAlloc(destroy_fiber); + return TRUE; +} +static struct error_cell *get_cell(int create) { + if (!InitOnceExecuteOnce(&error_once, initialize_error_key, NULL, NULL) || + error_key == FLS_OUT_OF_INDEXES) + return NULL; + struct error_cell *cell = FlsGetValue(error_key); + if (!cell && create) { + cell = calloc(1, sizeof *cell); + if (cell && !FlsSetValue(error_key, cell)) { + free(cell); + cell = NULL; + } + } + return cell; +} +#else +static void initialize_error_key(void) { + key_ready = pthread_key_create(&error_key, destroy_cell) == 0; +} +static struct error_cell *get_cell(int create) { + if (pthread_once(&error_once, initialize_error_key) || !key_ready) + return NULL; + struct error_cell *cell = pthread_getspecific(error_key); + if (!cell && create) { + cell = calloc(1, sizeof *cell); + if (cell && pthread_setspecific(error_key, cell)) { + free(cell); + cell = NULL; + } + } + return cell; +} +#endif +/* Internal hooks: cleanup is pure C and never calls the Haskell runtime. */ +void hm_clear_math_error(void) { + struct error_cell *cell = get_cell(0); + if (!cell) + return; +#ifdef _WIN32 + int detached = FlsSetValue(error_key, NULL) != 0; +#else + int detached = pthread_setspecific(error_key, NULL) == 0; +#endif + if (detached) { + destroy_cell(cell); + } else { + /* A failed TLS update must not leave a dangling destructor pointer. */ + free(cell->owned_message); + cell->owned_message = NULL; + memset(&cell->value, 0, sizeof cell->value); + memset(&cell->expression, 0, sizeof cell->expression); + memset(&cell->interchange, 0, sizeof cell->interchange); + cell->valid = 0; + } +} + +int hm_record_math_error(int kind, const ptrdiff_t *details, const char *message, size_t length) { + if (kind < 1 || kind > 21 || (length && !message) || length == SIZE_MAX) + return HMATH_INVALID_ARGUMENT; + struct error_cell *cell = get_cell(1); + if (!cell) + return HMATH_ALLOCATION_FAILED; + char *copy = malloc(length + 1); + if (!copy) + return HMATH_ALLOCATION_FAILED; + if (length) + memcpy(copy, message, length); + copy[length] = '\0'; + free(cell->owned_message); + cell->owned_message = copy; + cell->value.kind = (uint32_t)kind; + memcpy(cell->value.details, details, sizeof cell->value.details); + cell->value.message = copy; + cell->value.message_length = length; + cell->valid = 1; + return HMATH_OK; +} +int hmath_last_math_error(hmath_math_error *out) { + struct error_cell *cell = get_cell(0); + if (!out || !cell || cell->valid != 1) + return 0; + *out = cell->value; + return 1; +} +int hm_record_expression_error(int kind, const ptrdiff_t *position, + const char *message, size_t length) { + if ((unsigned)kind > 9 || !position || (length && !message) || length == SIZE_MAX) + return HMATH_INVALID_ARGUMENT; + struct error_cell *cell = get_cell(1); + if (!cell) + return HMATH_ALLOCATION_FAILED; + char *copy = malloc(length + 1); + if (!copy) + return HMATH_ALLOCATION_FAILED; + if (length) + memcpy(copy, message, length); + copy[length] = '\0'; + free(cell->owned_message); + cell->owned_message = copy; + cell->expression.kind = (uint32_t)kind; + cell->expression.source_offset = position[0]; + cell->expression.source_line = position[1]; + cell->expression.source_column = position[2]; + cell->expression.message = copy; + cell->expression.message_length = length; + cell->valid = 2; + return HMATH_OK; +} +int hmath_last_expression_error(hmath_expression_error *out) { + struct error_cell *cell = get_cell(0); + if (!out || !cell || cell->valid != 2) + return 0; + *out = cell->expression; + return 1; +} +int hm_record_interchange_error(int kind, const char *message, size_t length) { + if ((unsigned)kind > 3 || (length && !message) || length == SIZE_MAX) + return HMATH_INVALID_ARGUMENT; + struct error_cell *cell = get_cell(1); + if (!cell) + return HMATH_ALLOCATION_FAILED; + char *copy = malloc(length + 1); + if (!copy) + return HMATH_ALLOCATION_FAILED; + if (length) + memcpy(copy, message, length); + copy[length] = '\0'; + free(cell->owned_message); + cell->owned_message = copy; + cell->interchange.kind = (uint32_t)kind; + cell->interchange.message = copy; + cell->interchange.message_length = length; + cell->valid = 3; + return HMATH_OK; +} +int hmath_last_interchange_error(hmath_interchange_error *out) { + struct error_cell *cell = get_cell(0); + if (!out || !cell || cell->valid != 3) + return 0; + *out = cell->interchange; + return 1; +} +int hmath_callback_capture_error(hmath_status status,hmath_callback_error *out) { + if (!out) + return 0; + hmath_callback_error result = {0}; + if (status == HMATH_MATH_ERROR) { + if (!hmath_last_math_error(&result)) + return 0; + } else if (status == HMATH_EXPRESSION_ERROR) { + hmath_expression_error error; + if (!hmath_last_expression_error(&error)) + return 0; + result.kind = error.kind; + result.details[0] = error.source_offset; + result.details[1] = error.source_line; + result.details[2] = error.source_column; + result.message = error.message; + result.message_length = error.message_length; + } else if (status == HMATH_INTERCHANGE_ERROR) { + hmath_interchange_error error; + if (!hmath_last_interchange_error(&error)) + return 0; + result.kind = error.kind; + result.message = error.message; + result.message_length = error.message_length; + } else { + return 0; + } + *out = result; + return 1; +} +size_t hm_math_error_size(void) { return sizeof(hmath_math_error); } +void hm_math_error_reset(hmath_math_error *error) { memset(error, 0, sizeof *error); } +int hm_math_error_kind(const hmath_math_error *error) { return (int)error->kind; } +ptrdiff_t hm_math_error_detail(const hmath_math_error *error, int index) { + return error->details[index]; +} +const char *hm_math_error_message(const hmath_math_error *error) { return error->message; } +size_t hm_math_error_message_length(const hmath_math_error *error) { return error->message_length; } diff --git a/cbits/execution.c b/cbits/execution.c new file mode 100644 index 0000000..b63c826 --- /dev/null +++ b/cbits/execution.c @@ -0,0 +1,227 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_backend.h" +#include "hmath_execution.h" +#include "native_internal.h" +#include +#include +#include + +struct hmath_execution { + atomic_size_t refs; + hmath_backend *backend; + size_t max_elements, max_multiply_adds; +}; +extern int hm_execution_reference_f32(size_t m, size_t n, size_t k, float alpha, const float *a, + size_t lda, const float *b, size_t ldb, float beta, float *c, + size_t ldc); +extern int hm_execution_reference_f64(size_t m, size_t n, size_t k, double alpha, const double *a, + size_t lda, const double *b, size_t ldb, double beta, + double *c, size_t ldc); + +hmath_status hmath_execution_create(const hmath_execution_options *options, hmath_execution **out) { + hmath_execution_options defaults = {HMATH_EXECUTION_REFERENCE, 32, NULL, 0, 0}; + if (!options) + options = &defaults; + if (!out || options->provider < HMATH_EXECUTION_REFERENCE || + options->provider > HMATH_EXECUTION_ACCELERATE || + (options->integer_bits != 0 && options->integer_bits != 32 && + options->integer_bits != 64) || + (options->provider == HMATH_EXECUTION_REFERENCE && options->library_path && + *options->library_path)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid execution options"); + hmath_execution *value = calloc(1, sizeof *value); + if (!value) + return hm_error(HMATH_ALLOCATION_FAILED, "execution allocation failed"); + atomic_init(&value->refs, 1); + value->max_elements = options->max_elements; + value->max_multiply_adds = options->max_multiply_adds; + if (options->provider != HMATH_EXECUTION_REFERENCE) { + int code; + value->backend = hmath_backend_open(options->provider, + options->integer_bits ? (int)options->integer_bits : 32, + options->library_path, &code); + if (!value->backend) { + free(value); + return hm_error( + code == 2 ? HMATH_INVALID_ARGUMENT + : code == 3 ? HMATH_ALLOCATION_FAILED + : HMATH_UNSUPPORTED, + "requested BLAS provider unavailable or incompatible; no fallback selected"); + } + } + *out = value; + return hm_error(HMATH_OK, ""); +} +void hmath_execution_retain(hmath_execution *execution) { + if (execution) + atomic_fetch_add_explicit(&execution->refs, 1, memory_order_relaxed); +} +void hmath_execution_release(hmath_execution *execution) { + if (execution && atomic_fetch_sub_explicit(&execution->refs, 1, memory_order_acq_rel) == 1) { + hmath_backend_close(execution->backend); + free(execution); + } +} + +typedef struct validated_view { + hmath_execution_view view; + size_t count, span; + uintptr_t begin, end; +} validated_view; +static hmath_status validate_view(const hmath_execution_view *view, size_t bytes, size_t limit, + validated_view *out) { + if (!view) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL execution view"); + if (view->rows > (size_t)PTRDIFF_MAX || view->columns > (size_t)PTRDIFF_MAX || + view->leading_dimension > (size_t)PTRDIFF_MAX) + return hm_error(HMATH_OVERFLOW, "view dimension exceeds Haskell Int"); + if (view->columns && view->rows > (size_t)PTRDIFF_MAX / bytes / view->columns) + return hm_error(HMATH_OVERFLOW, "view logical byte count overflows ptrdiff_t"); + size_t count = view->rows * view->columns, span = 0; + if (limit && count > limit) + return hm_error(HMATH_OVERFLOW, "configured element limit exceeded"); + if (count) { + if (view->leading_dimension < view->columns) + return hm_error(HMATH_INVALID_ARGUMENT, + "row-major leading dimension is smaller than columns"); + if (view->rows - 1 > + ((size_t)PTRDIFF_MAX / bytes - view->columns) / view->leading_dimension) + return hm_error(HMATH_OVERFLOW, "view reachable byte span overflows ptrdiff_t"); + span = (view->rows - 1) * view->leading_dimension + view->columns; + } + if (span > view->storage_count) + return hm_error(HMATH_BOUNDS_ERROR, "view span exceeds backing storage"); + if ((span && !view->data) || (view->data && (uintptr_t)view->data % bytes)) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL or misaligned execution storage"); + uintptr_t begin = (uintptr_t)view->data; + if (span && begin > UINTPTR_MAX - span * bytes) + return hm_error(HMATH_OVERFLOW, "view address span overflows uintptr_t"); + *out = (validated_view){*view, count, span, begin, begin + span * bytes}; + return HMATH_OK; +} +static int overlap(const validated_view *a, const validated_view *b) { + return a->span && b->span && a->begin < b->end && b->begin < a->end; +} +static hmath_status nonfinite(size_t index) { + char message[96]; + (void)snprintf(message, sizeof message, "NonFiniteVectorEntry %zu", index); + return hm_error(HMATH_MATH_ERROR, message); +} +static size_t first_nonfinite(const validated_view *view, int precision) { + if (!view->count) + return SIZE_MAX; + for (size_t row = 0; row < view->view.rows; ++row) + for (size_t column = 0; column < view->view.columns; ++column) { + size_t index = row * view->view.leading_dimension + column; + if (precision == 32 ? !isfinite(((const float *)view->view.data)[index]) + : !isfinite(((const double *)view->view.data)[index])) + return row * view->view.columns + column; + } + return SIZE_MAX; +} +static hmath_status gemm(hmath_execution *execution, hmath_context *context, int precision, + const void *alpha, const hmath_execution_view *a, + const hmath_execution_view *b, const void *beta, + const hmath_execution_output *output) { + if (!execution || !a || !b || !output) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL execution argument"); + if (a->columns != b->rows) + return hm_error(HMATH_SHAPE_ERROR, "GEMM inner dimensions differ"); + if (output->rows != a->rows || output->columns != b->columns) + return hm_error(HMATH_SHAPE_ERROR, "GEMM output shape differs"); + hmath_execution_view c = {output->data, output->storage_count, output->rows, output->columns, + output->leading_dimension}; + validated_view aa, bb, cc; + size_t bytes = precision == 32 ? sizeof(float) : sizeof(double); + hmath_status status = validate_view(a, bytes, execution->max_elements, &aa); + if (!status) + status = validate_view(b, bytes, execution->max_elements, &bb); + if (!status) + status = validate_view(&c, bytes, execution->max_elements, &cc); + if (status) + return status; + if (overlap(&aa, &cc) || overlap(&bb, &cc)) + return hm_error(HMATH_INVALID_ARGUMENT, "GEMM output overlaps an input span"); + if (a->columns && cc.count > SIZE_MAX / a->columns) + return hm_error(HMATH_OVERFLOW, "GEMM work count overflows size_t"); + size_t work = cc.count * a->columns; + if (execution->max_multiply_adds && work > execution->max_multiply_adds) + return hm_error(HMATH_OVERFLOW, "configured multiply-add limit exceeded"); + status = hm_enter(context); + if (status) + return status; + if (precision == 32 ? !isfinite(*(const float *)alpha) : !isfinite(*(const double *)alpha)) { + status = nonfinite(0); + goto done; + } + if (precision == 32 ? !isfinite(*(const float *)beta) : !isfinite(*(const double *)beta)) { + status = nonfinite(1); + goto done; + } + size_t offset = first_nonfinite(&aa, precision); + if (offset != SIZE_MAX) { + status = nonfinite(2 + offset); + goto done; + } + offset = first_nonfinite(&bb, precision); + if (offset != SIZE_MAX) { + status = nonfinite(2 + aa.count + offset); + goto done; + } + offset = first_nonfinite(&cc, precision); + if (offset != SIZE_MAX) { + status = nonfinite(2 + aa.count + bb.count + offset); + goto done; + } + int code; + if (execution->backend && a->rows && b->columns && a->columns) { + code = hm_backend_real_gemm( + execution->backend, precision, (int64_t)a->rows, (int64_t)b->columns, + (int64_t)a->columns, alpha, a->data, (int64_t)a->leading_dimension, b->data, + (int64_t)b->leading_dimension, beta, output->data, (int64_t)output->leading_dimension); + if (code) { + status = hm_error(code == 2 ? HMATH_INVALID_ARGUMENT : HMATH_UNSUPPORTED, + "selected provider cannot execute this GEMM dtype/extent"); + goto done; + } + offset = first_nonfinite(&cc, precision); + if (offset != SIZE_MAX) { + status = nonfinite(offset); + goto done; + } + } else { + if (precision == 32) + code = hm_execution_reference_f32(a->rows, b->columns, a->columns, + *(const float *)alpha, a->data, a->leading_dimension, + b->data, b->leading_dimension, *(const float *)beta, + output->data, output->leading_dimension); + else + code = hm_execution_reference_f64(a->rows, b->columns, a->columns, + *(const double *)alpha, a->data, a->leading_dimension, + b->data, b->leading_dimension, *(const double *)beta, + output->data, output->leading_dimension); + if (code) { + status = (hmath_status)code; + goto done; + } + } + status = + hm_cancelled(context) + ? hm_error(HMATH_CANCELLED, "execution cancelled after kernel; output may be modified") + : hm_error(HMATH_OK, ""); +done: + hm_leave(); + return status; +} +hmath_status hmath_execution_gemm_f32(hmath_execution *execution, hmath_context *context, + float alpha, const hmath_execution_view *a, + const hmath_execution_view *b, float beta, + const hmath_execution_output *c) { + return gemm(execution, context, 32, &alpha, a, b, &beta, c); +} +hmath_status hmath_execution_gemm_f64(hmath_execution *execution, hmath_context *context, + double alpha, const hmath_execution_view *a, + const hmath_execution_view *b, double beta, + const hmath_execution_output *c) { + return gemm(execution, context, 64, &alpha, a, b, &beta, c); +} diff --git a/cbits/expression.c b/cbits/expression.c new file mode 100644 index 0000000..ca14d4e --- /dev/null +++ b/cbits/expression.c @@ -0,0 +1,923 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_expression.h" +#include "value_internal.h" +#include +extern int hm_expression_apply(const char *,void *const *,size_t,void **); +static hmath_status invoke(hmath_context *context,const char *name, + const hmath_value *const *arguments,size_t count,hmath_value **out) { + if (!out || (count && !arguments)) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL expression argument/output"); + if (count > (size_t)PTRDIFF_MAX/sizeof(void *)) + return hm_error(HMATH_OVERFLOW,"expression argument span overflow"); + for(size_t i=0;istable); + free(stable); + return hm_value_finish(result,code,out); +} +hmath_status hmath_expression_node_fields(hmath_context *ctx,const hmath_value *value,hmath_value **out){const hmath_value *args[]={value};return invoke(ctx,"__node_fields",args,1,out);} +hmath_status hmath_symbolic_pattern_fields(hmath_context *ctx,const hmath_value *value,hmath_value **out){const hmath_value *args[]={value};return invoke(ctx,"__pattern_fields",args,1,out);} +hmath_status hmath_expression_compare(hmath_context *ctx,const hmath_value *a,const hmath_value *b,hmath_value **out){const hmath_value *args[]={a,b};return invoke(ctx,"__compare_expr",args,2,out);} +hmath_status hmath_expression_node_compare(hmath_context *ctx,const hmath_value *a,const hmath_value *b,hmath_value **out){const hmath_value *args[]={a,b};return invoke(ctx,"__compare_node",args,2,out);} +hmath_status hmath_symbolic_pattern_equal(hmath_context *ctx,const hmath_value *a,const hmath_value *b,hmath_value **out){const hmath_value *args[]={a,b};return invoke(ctx,"__equal_pattern",args,2,out);} +/* BEGIN GENERATED */ +hmath_status hmath_expression_source_pos_create(hmath_context *context, const hmath_value *offset, const hmath_value *line, const hmath_value *column, hmath_value **out) { + const hmath_value *hm_arguments[] = {offset, line, column}; + return invoke(context, "HMath.Expression.SourcePos", hm_arguments, 3, out); +} + +hmath_status hmath_expression_unknown_position(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.unknownPosition", NULL, 0, out); +} + +hmath_status hmath_expression_source_offset(hmath_context *context, const hmath_value *position, hmath_value **out) { + const hmath_value *hm_arguments[] = {position}; + return invoke(context, "HMath.Expression.sourceOffset", hm_arguments, 1, out); +} + +hmath_status hmath_expression_source_line(hmath_context *context, const hmath_value *position, hmath_value **out) { + const hmath_value *hm_arguments[] = {position}; + return invoke(context, "HMath.Expression.sourceLine", hm_arguments, 1, out); +} + +hmath_status hmath_expression_source_column(hmath_context *context, const hmath_value *position, hmath_value **out) { + const hmath_value *hm_arguments[] = {position}; + return invoke(context, "HMath.Expression.sourceColumn", hm_arguments, 1, out); +} + +hmath_status hmath_expression_negate_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Negate", NULL, 0, out); +} + +hmath_status hmath_expression_add_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Add", NULL, 0, out); +} + +hmath_status hmath_expression_subtract_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Subtract", NULL, 0, out); +} + +hmath_status hmath_expression_multiply_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Multiply", NULL, 0, out); +} + +hmath_status hmath_expression_divide_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Divide", NULL, 0, out); +} + +hmath_status hmath_expression_power_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Power", NULL, 0, out); +} + +hmath_status hmath_expression_pi_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Pi", NULL, 0, out); +} + +hmath_status hmath_expression_euler_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Euler", NULL, 0, out); +} + +hmath_status hmath_expression_tau_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Tau", NULL, 0, out); +} + +hmath_status hmath_expression_exact_rational_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.ExactRational", NULL, 0, out); +} + +hmath_status hmath_expression_float64_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Float64", NULL, 0, out); +} + +hmath_status hmath_expression_syntax_error_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.SyntaxError", NULL, 0, out); +} + +hmath_status hmath_expression_unknown_name_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.UnknownName", NULL, 0, out); +} + +hmath_status hmath_expression_type_mismatch_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.TypeMismatch", NULL, 0, out); +} + +hmath_status hmath_expression_domain_failure_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.DomainFailure", NULL, 0, out); +} + +hmath_status hmath_expression_non_finite_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.NonFinite", NULL, 0, out); +} + +hmath_status hmath_expression_step_limit_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.StepLimit", NULL, 0, out); +} + +hmath_status hmath_expression_depth_limit_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.DepthLimit", NULL, 0, out); +} + +hmath_status hmath_expression_memory_limit_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.MemoryLimit", NULL, 0, out); +} + +hmath_status hmath_expression_invalid_limits_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.InvalidLimits", NULL, 0, out); +} + +hmath_status hmath_expression_unsupported_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Unsupported", NULL, 0, out); +} + +hmath_status hmath_expression_sin_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Sin", NULL, 0, out); +} + +hmath_status hmath_expression_cos_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Cos", NULL, 0, out); +} + +hmath_status hmath_expression_tan_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Tan", NULL, 0, out); +} + +hmath_status hmath_expression_exp_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Exp", NULL, 0, out); +} + +hmath_status hmath_expression_log_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Log", NULL, 0, out); +} + +hmath_status hmath_expression_sqrt_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Sqrt", NULL, 0, out); +} + +hmath_status hmath_expression_abs_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Abs", NULL, 0, out); +} + +hmath_status hmath_expression_signum_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Signum", NULL, 0, out); +} + +hmath_status hmath_expression_floor_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Floor", NULL, 0, out); +} + +hmath_status hmath_expression_ceiling_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Ceiling", NULL, 0, out); +} + +hmath_status hmath_expression_min_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Min", NULL, 0, out); +} + +hmath_status hmath_expression_max_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Max", NULL, 0, out); +} + +hmath_status hmath_expression_asin_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Asin", NULL, 0, out); +} + +hmath_status hmath_expression_acos_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Acos", NULL, 0, out); +} + +hmath_status hmath_expression_atan_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Atan", NULL, 0, out); +} + +hmath_status hmath_expression_sinh_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Sinh", NULL, 0, out); +} + +hmath_status hmath_expression_cosh_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Cosh", NULL, 0, out); +} + +hmath_status hmath_expression_tanh_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.Tanh", NULL, 0, out); +} + +hmath_status hmath_expression_expr_create(hmath_context *context, const hmath_value *position, const hmath_value *node, hmath_value **out) { + const hmath_value *hm_arguments[] = {position, node}; + return invoke(context, "HMath.Expression.Expr", hm_arguments, 2, out); +} + +hmath_status hmath_expression_expression_position(hmath_context *context, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {expression}; + return invoke(context, "HMath.Expression.expressionPosition", hm_arguments, 1, out); +} + +hmath_status hmath_expression_expression_node(hmath_context *context, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {expression}; + return invoke(context, "HMath.Expression.expressionNode", hm_arguments, 1, out); +} + +hmath_status hmath_expression_literal_create(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Expression.Literal", hm_arguments, 1, out); +} + +hmath_status hmath_expression_variable_create(hmath_context *context, const hmath_value *name, hmath_value **out) { + const hmath_value *hm_arguments[] = {name}; + return invoke(context, "HMath.Expression.Variable", hm_arguments, 1, out); +} + +hmath_status hmath_expression_constant_create(hmath_context *context, const hmath_value *constant, hmath_value **out) { + const hmath_value *hm_arguments[] = {constant}; + return invoke(context, "HMath.Expression.Constant", hm_arguments, 1, out); +} + +hmath_status hmath_expression_unary_create(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, child}; + return invoke(context, "HMath.Expression.Unary", hm_arguments, 2, out); +} + +hmath_status hmath_expression_binary_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, left, right}; + return invoke(context, "HMath.Expression.Binary", hm_arguments, 3, out); +} + +hmath_status hmath_expression_call_create(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, arguments}; + return invoke(context, "HMath.Expression.Call", hm_arguments, 2, out); +} + +hmath_status hmath_expression_let_create(hmath_context *context, const hmath_value *name, const hmath_value *value, const hmath_value *body, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, value, body}; + return invoke(context, "HMath.Expression.Let", hm_arguments, 3, out); +} + +hmath_status hmath_expression_literal(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Expression.literal", hm_arguments, 1, out); +} + +hmath_status hmath_expression_variable(hmath_context *context, const hmath_value *name, hmath_value **out) { + const hmath_value *hm_arguments[] = {name}; + return invoke(context, "HMath.Expression.variable", hm_arguments, 1, out); +} + +hmath_status hmath_expression_constant(hmath_context *context, const hmath_value *constant, hmath_value **out) { + const hmath_value *hm_arguments[] = {constant}; + return invoke(context, "HMath.Expression.constant", hm_arguments, 1, out); +} + +hmath_status hmath_expression_unary(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, child}; + return invoke(context, "HMath.Expression.unary", hm_arguments, 2, out); +} + +hmath_status hmath_expression_binary(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, left, right}; + return invoke(context, "HMath.Expression.binary", hm_arguments, 3, out); +} + +hmath_status hmath_expression_call(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, arguments}; + return invoke(context, "HMath.Expression.call", hm_arguments, 2, out); +} + +hmath_status hmath_expression_let_in(hmath_context *context, const hmath_value *name, const hmath_value *value, const hmath_value *body, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, value, body}; + return invoke(context, "HMath.Expression.letIn", hm_arguments, 3, out); +} + +hmath_status hmath_expression_limits_create(hmath_context *context, const hmath_value *maximum_steps, const hmath_value *maximum_depth, const hmath_value *maximum_nodes, const hmath_value *maximum_input_chars, const hmath_value *maximum_integer_bits, const hmath_value *maximum_cache_entries, hmath_value **out) { + const hmath_value *hm_arguments[] = {maximum_steps, maximum_depth, maximum_nodes, maximum_input_chars, maximum_integer_bits, maximum_cache_entries}; + return invoke(context, "HMath.Expression.Limits", hm_arguments, 6, out); +} + +hmath_status hmath_expression_default_limits(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.defaultLimits", NULL, 0, out); +} + +hmath_status hmath_expression_maximum_steps(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumSteps", hm_arguments, 1, out); +} + +hmath_status hmath_expression_maximum_depth(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumDepth", hm_arguments, 1, out); +} + +hmath_status hmath_expression_maximum_nodes(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumNodes", hm_arguments, 1, out); +} + +hmath_status hmath_expression_maximum_input_chars(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumInputChars", hm_arguments, 1, out); +} + +hmath_status hmath_expression_maximum_integer_bits(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumIntegerBits", hm_arguments, 1, out); +} + +hmath_status hmath_expression_maximum_cache_entries(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.maximumCacheEntries", hm_arguments, 1, out); +} + +hmath_status hmath_expression_expr_error_create(hmath_context *context, const hmath_value *kind, const hmath_value *position, const hmath_value *message, hmath_value **out) { + const hmath_value *hm_arguments[] = {kind, position, message}; + return invoke(context, "HMath.Expression.ExprError", hm_arguments, 3, out); +} + +hmath_status hmath_expression_error_kind_get(hmath_context *context, const hmath_value *error, hmath_value **out) { + const hmath_value *hm_arguments[] = {error}; + return invoke(context, "HMath.Expression.errorKind", hm_arguments, 1, out); +} + +hmath_status hmath_expression_error_position(hmath_context *context, const hmath_value *error, hmath_value **out) { + const hmath_value *hm_arguments[] = {error}; + return invoke(context, "HMath.Expression.errorPosition", hm_arguments, 1, out); +} + +hmath_status hmath_expression_error_message(hmath_context *context, const hmath_value *error, hmath_value **out) { + const hmath_value *hm_arguments[] = {error}; + return invoke(context, "HMath.Expression.errorMessage", hm_arguments, 1, out); +} + +hmath_status hmath_expression_validate_limits(hmath_context *context, const hmath_value *limits, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits}; + return invoke(context, "HMath.Expression.validateLimits", hm_arguments, 1, out); +} + +hmath_status hmath_expression_validate_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Expression.validateExpression", hm_arguments, 2, out); +} + +hmath_status hmath_expression_parse_expression(hmath_context *context, const hmath_value *limits, const hmath_value *source, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, source}; + return invoke(context, "HMath.Expression.parseExpression", hm_arguments, 2, out); +} + +hmath_status hmath_expression_pretty_expression(hmath_context *context, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {expression}; + return invoke(context, "HMath.Expression.prettyExpression", hm_arguments, 1, out); +} + +hmath_status hmath_expression_free_variables(hmath_context *context, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {expression}; + return invoke(context, "HMath.Expression.freeVariables", hm_arguments, 1, out); +} + +hmath_status hmath_expression_exact_value_create(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Expression.ExactValue", hm_arguments, 1, out); +} + +hmath_status hmath_expression_float_value_create(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Expression.FloatValue", hm_arguments, 1, out); +} + +hmath_status hmath_expression_default_registry(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.defaultRegistry", NULL, 0, out); +} + +hmath_status hmath_expression_empty_registry(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.emptyRegistry", NULL, 0, out); +} + +hmath_status hmath_expression_register_function(hmath_context *context, const hmath_value *name, const hmath_value *builtin, const hmath_value *registry, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, builtin, registry}; + return invoke(context, "HMath.Expression.registerFunction", hm_arguments, 3, out); +} + +hmath_status hmath_expression_allowed_functions(hmath_context *context, const hmath_value *registry, hmath_value **out) { + const hmath_value *hm_arguments[] = {registry}; + return invoke(context, "HMath.Expression.allowedFunctions", hm_arguments, 1, out); +} + +hmath_status hmath_expression_type_check_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, precision, registry, bindings, expression}; + return invoke(context, "HMath.Expression.typeCheckExpression", hm_arguments, 5, out); +} + +hmath_status hmath_expression_evaluate_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, precision, registry, bindings, expression}; + return invoke(context, "HMath.Expression.evaluateExpression", hm_arguments, 5, out); +} + +hmath_status hmath_expression_evaluate_text(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *source, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, precision, registry, bindings, source}; + return invoke(context, "HMath.Expression.evaluateText", hm_arguments, 5, out); +} + +hmath_status hmath_expression_evaluate_compiled(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *compiled, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, precision, registry, bindings, compiled}; + return invoke(context, "HMath.Expression.evaluateCompiled", hm_arguments, 5, out); +} + +hmath_status hmath_expression_compile_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Expression.compileExpression", hm_arguments, 2, out); +} + +hmath_status hmath_expression_compiled_node_count(hmath_context *context, const hmath_value *compiled, hmath_value **out) { + const hmath_value *hm_arguments[] = {compiled}; + return invoke(context, "HMath.Expression.compiledNodeCount", hm_arguments, 1, out); +} + +hmath_status hmath_expression_optimize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, precision, expression}; + return invoke(context, "HMath.Expression.optimizeExpression", hm_arguments, 3, out); +} + +hmath_status hmath_expression_empty_expression_cache(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Expression.emptyExpressionCache", NULL, 0, out); +} + +hmath_status hmath_expression_cache_size(hmath_context *context, const hmath_value *cache, hmath_value **out) { + const hmath_value *hm_arguments[] = {cache}; + return invoke(context, "HMath.Expression.cacheSize", hm_arguments, 1, out); +} + +hmath_status hmath_expression_cached_expression(hmath_context *context, const hmath_value *limits, const hmath_value *source, const hmath_value *cache, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, source, cache}; + return invoke(context, "HMath.Expression.cachedExpression", hm_arguments, 3, out); +} + +hmath_status hmath_expression_format_scientific(hmath_context *context, const hmath_value *digits, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {digits, value}; + return invoke(context, "HMath.Expression.formatScientific", hm_arguments, 2, out); +} + +hmath_status hmath_expression_format_radix(hmath_context *context, const hmath_value *radix, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {radix, value}; + return invoke(context, "HMath.Expression.formatRadix", hm_arguments, 2, out); +} + +hmath_status hmath_expression_serialize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Expression.serializeExpression", hm_arguments, 2, out); +} + +hmath_status hmath_expression_deserialize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *serialized, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, serialized}; + return invoke(context, "HMath.Expression.deserializeExpression", hm_arguments, 2, out); +} + +hmath_status hmath_expression_expression_hash(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Expression.expressionHash", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_real_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Real", NULL, 0, out); +} + +hmath_status hmath_symbolic_non_zero_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.NonZero", NULL, 0, out); +} + +hmath_status hmath_symbolic_positive_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Positive", NULL, 0, out); +} + +hmath_status hmath_symbolic_non_negative_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.NonNegative", NULL, 0, out); +} + +hmath_status hmath_symbolic_integral_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Integral", NULL, 0, out); +} + +hmath_status hmath_symbolic_negative_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Negative", NULL, 0, out); +} + +hmath_status hmath_symbolic_non_positive_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.NonPositive", NULL, 0, out); +} + +hmath_status hmath_symbolic_from_left_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.FromLeft", NULL, 0, out); +} + +hmath_status hmath_symbolic_from_right_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.FromRight", NULL, 0, out); +} + +hmath_status hmath_symbolic_two_sided_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.TwoSided", NULL, 0, out); +} + +hmath_status hmath_symbolic_equal_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Equal", NULL, 0, out); +} + +hmath_status hmath_symbolic_not_equal_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.NotEqual", NULL, 0, out); +} + +hmath_status hmath_symbolic_less_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Less", NULL, 0, out); +} + +hmath_status hmath_symbolic_less_equal_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.LessEqual", NULL, 0, out); +} + +hmath_status hmath_symbolic_greater_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Greater", NULL, 0, out); +} + +hmath_status hmath_symbolic_greater_equal_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.GreaterEqual", NULL, 0, out); +} + +hmath_status hmath_symbolic_assumptions(hmath_context *context, const hmath_value *entries, hmath_value **out) { + const hmath_value *hm_arguments[] = {entries}; + return invoke(context, "HMath.Symbolic.assumptions", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_no_assumptions(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.noAssumptions", NULL, 0, out); +} + +hmath_status hmath_symbolic_proves(hmath_context *context, const hmath_value *assumptions, const hmath_value *property, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {assumptions, property, expression}; + return invoke(context, "HMath.Symbolic.proves", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_symbolic_options_create(hmath_context *context, const hmath_value *limits, const hmath_value *assumptions, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, assumptions}; + return invoke(context, "HMath.Symbolic.SymbolicOptions", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_default_symbolic_options(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.defaultSymbolicOptions", NULL, 0, out); +} + +hmath_status hmath_symbolic_symbolic_limits(hmath_context *context, const hmath_value *options, hmath_value **out) { + const hmath_value *hm_arguments[] = {options}; + return invoke(context, "HMath.Symbolic.symbolicLimits", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_symbolic_assumptions(hmath_context *context, const hmath_value *options, hmath_value **out) { + const hmath_value *hm_arguments[] = {options}; + return invoke(context, "HMath.Symbolic.symbolicAssumptions", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_normalize(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.normalize", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.simplify", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_expand(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.expand", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_collect_terms(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.collectTerms", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_trigonometric_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.trigonometricSimplify", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_logarithmic_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, expression}; + return invoke(context, "HMath.Symbolic.logarithmicSimplify", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_factor_polynomial(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.factorPolynomial", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_rational_simplify(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.rationalSimplify", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_differentiate(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.differentiate", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_integrate_basic(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.integrateBasic", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_to_polynomial(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.toPolynomial", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_exact_polynomial_roots(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.exactPolynomialRoots", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_numerical_polynomial_roots(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, expression}; + return invoke(context, "HMath.Symbolic.numericalPolynomialRoots", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_polynomial_factorization_create(hmath_context *context, const hmath_value *leading, const hmath_value *terms, hmath_value **out) { + const hmath_value *hm_arguments[] = {leading, terms}; + return invoke(context, "HMath.Symbolic.PolynomialFactorization", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_factor_leading(hmath_context *context, const hmath_value *factorization, hmath_value **out) { + const hmath_value *hm_arguments[] = {factorization}; + return invoke(context, "HMath.Symbolic.factorLeading", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_factor_terms(hmath_context *context, const hmath_value *factorization, hmath_value **out) { + const hmath_value *hm_arguments[] = {factorization}; + return invoke(context, "HMath.Symbolic.factorTerms", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_substitute(hmath_context *context, const hmath_value *limits, const hmath_value *bindings, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, bindings, expression}; + return invoke(context, "HMath.Symbolic.substitute", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_any_create(hmath_context *context, const hmath_value *name, hmath_value **out) { + const hmath_value *hm_arguments[] = {name}; + return invoke(context, "HMath.Symbolic.Any", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_exactly_create(hmath_context *context, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {expression}; + return invoke(context, "HMath.Symbolic.Exactly", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_unary_pattern_create(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, child}; + return invoke(context, "HMath.Symbolic.UnaryPattern", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_binary_pattern_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, left, right}; + return invoke(context, "HMath.Symbolic.BinaryPattern", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_call_pattern_create(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out) { + const hmath_value *hm_arguments[] = {name, arguments}; + return invoke(context, "HMath.Symbolic.CallPattern", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_match_pattern(hmath_context *context, const hmath_value *limits, const hmath_value *pattern, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, pattern, expression}; + return invoke(context, "HMath.Symbolic.matchPattern", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_rewrite_rule_create(hmath_context *context, const hmath_value *pattern, const hmath_value *replacement, const hmath_value *requirements, hmath_value **out) { + const hmath_value *hm_arguments[] = {pattern, replacement, requirements}; + return invoke(context, "HMath.Symbolic.RewriteRule", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_rewrite_pattern(hmath_context *context, const hmath_value *rule, hmath_value **out) { + const hmath_value *hm_arguments[] = {rule}; + return invoke(context, "HMath.Symbolic.rewritePattern", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_rewrite_replacement(hmath_context *context, const hmath_value *rule, hmath_value **out) { + const hmath_value *hm_arguments[] = {rule}; + return invoke(context, "HMath.Symbolic.rewriteReplacement", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_rewrite_requirements(hmath_context *context, const hmath_value *rule, hmath_value **out) { + const hmath_value *hm_arguments[] = {rule}; + return invoke(context, "HMath.Symbolic.rewriteRequirements", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_apply_rewrite(hmath_context *context, const hmath_value *options, const hmath_value *rule, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, rule, expression}; + return invoke(context, "HMath.Symbolic.applyRewrite", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_gradient(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variables, expression}; + return invoke(context, "HMath.Symbolic.gradient", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_hessian(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variables, expression}; + return invoke(context, "HMath.Symbolic.hessian", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_jacobian(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expressions, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variables, expressions}; + return invoke(context, "HMath.Symbolic.jacobian", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_integrate_by_parts(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *u, const hmath_value *dv, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, u, dv}; + return invoke(context, "HMath.Symbolic.integrateByParts", hm_arguments, 4, out); +} + +hmath_status hmath_symbolic_integrate_substitution(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *temporary, const hmath_value *inner, const hmath_value *outer, const hmath_value *integrand, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, temporary, inner, outer, integrand}; + return invoke(context, "HMath.Symbolic.integrateSubstitution", hm_arguments, 6, out); +} + +hmath_status hmath_symbolic_integrate_rational(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, numerator, denominator}; + return invoke(context, "HMath.Symbolic.integrateRational", hm_arguments, 4, out); +} + +hmath_status hmath_symbolic_finite_limit_create(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Symbolic.FiniteLimit", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_positive_infinity_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.PositiveInfinity", NULL, 0, out); +} + +hmath_status hmath_symbolic_negative_infinity_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.NegativeInfinity", NULL, 0, out); +} + +hmath_status hmath_symbolic_does_not_exist_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.DoesNotExist", NULL, 0, out); +} + +hmath_status hmath_symbolic_symbolic_limit(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *direction, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, center, direction, expression}; + return invoke(context, "HMath.Symbolic.symbolicLimit", hm_arguments, 5, out); +} + +hmath_status hmath_symbolic_series_create(hmath_context *context, const hmath_value *center, const hmath_value *minimum_power, const hmath_value *terms, hmath_value **out) { + const hmath_value *hm_arguments[] = {center, minimum_power, terms}; + return invoke(context, "HMath.Symbolic.Series", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_series_center(hmath_context *context, const hmath_value *series, hmath_value **out) { + const hmath_value *hm_arguments[] = {series}; + return invoke(context, "HMath.Symbolic.seriesCenter", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_series_minimum_power(hmath_context *context, const hmath_value *series, hmath_value **out) { + const hmath_value *hm_arguments[] = {series}; + return invoke(context, "HMath.Symbolic.seriesMinimumPower", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_series_terms(hmath_context *context, const hmath_value *series, hmath_value **out) { + const hmath_value *hm_arguments[] = {series}; + return invoke(context, "HMath.Symbolic.seriesTerms", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_taylor_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *order, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, center, order, expression}; + return invoke(context, "HMath.Symbolic.taylorSeries", hm_arguments, 5, out); +} + +hmath_status hmath_symbolic_laurent_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *order, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, center, order, expression}; + return invoke(context, "HMath.Symbolic.laurentSeries", hm_arguments, 5, out); +} + +hmath_status hmath_symbolic_maclaurin_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *order, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, order, expression}; + return invoke(context, "HMath.Symbolic.maclaurinSeries", hm_arguments, 4, out); +} + +hmath_status hmath_symbolic_formal_power_series(hmath_context *context, const hmath_value *options, const hmath_value *coefficients, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, coefficients}; + return invoke(context, "HMath.Symbolic.formalPowerSeries", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_multiply_formal_series(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, left, right}; + return invoke(context, "HMath.Symbolic.multiplyFormalSeries", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_reciprocal_formal_series(hmath_context *context, const hmath_value *options, const hmath_value *series, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, series}; + return invoke(context, "HMath.Symbolic.reciprocalFormalSeries", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_from_polynomial(hmath_context *context, const hmath_value *variable, const hmath_value *polynomial, hmath_value **out) { + const hmath_value *hm_arguments[] = {variable, polynomial}; + return invoke(context, "HMath.Symbolic.fromPolynomial", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_relation_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {operator_, left, right}; + return invoke(context, "HMath.Symbolic.Relation", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_truth_create(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *hm_arguments[] = {value}; + return invoke(context, "HMath.Symbolic.Truth", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_unresolved_create(hmath_context *context, const hmath_value *relation, hmath_value **out) { + const hmath_value *hm_arguments[] = {relation}; + return invoke(context, "HMath.Symbolic.Unresolved", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_simplify_relation(hmath_context *context, const hmath_value *options, const hmath_value *relation, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, relation}; + return invoke(context, "HMath.Symbolic.simplifyRelation", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_solve_linear_inequality(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *relation, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variable, relation}; + return invoke(context, "HMath.Symbolic.solveLinearInequality", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_inconsistent_create(hmath_context *context, hmath_value **out) { + return invoke(context, "HMath.Symbolic.Inconsistent", NULL, 0, out); +} + +hmath_status hmath_symbolic_parametric_solution_create(hmath_context *context, const hmath_value *bindings, const hmath_value *free_variables, hmath_value **out) { + const hmath_value *hm_arguments[] = {bindings, free_variables}; + return invoke(context, "HMath.Symbolic.ParametricSolution", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_solve_linear_equations(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *equations, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, variables, equations}; + return invoke(context, "HMath.Symbolic.solveLinearEquations", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_symbolic_matrix(hmath_context *context, const hmath_value *options, const hmath_value *rows, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, rows}; + return invoke(context, "HMath.Symbolic.symbolicMatrix", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_matrix_expressions(hmath_context *context, const hmath_value *matrix, hmath_value **out) { + const hmath_value *hm_arguments[] = {matrix}; + return invoke(context, "HMath.Symbolic.matrixExpressions", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_matrix_add(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, left, right}; + return invoke(context, "HMath.Symbolic.matrixAdd", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_matrix_multiply(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, left, right}; + return invoke(context, "HMath.Symbolic.matrixMultiply", hm_arguments, 3, out); +} + +hmath_status hmath_symbolic_symbolic_determinant(hmath_context *context, const hmath_value *options, const hmath_value *matrix, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, matrix}; + return invoke(context, "HMath.Symbolic.symbolicDeterminant", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_guarded_create(hmath_context *context, const hmath_value *value, const hmath_value *conditions, hmath_value **out) { + const hmath_value *hm_arguments[] = {value, conditions}; + return invoke(context, "HMath.Symbolic.Guarded", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_guarded_value(hmath_context *context, const hmath_value *guarded, hmath_value **out) { + const hmath_value *hm_arguments[] = {guarded}; + return invoke(context, "HMath.Symbolic.guardedValue", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_required_conditions(hmath_context *context, const hmath_value *guarded, hmath_value **out) { + const hmath_value *hm_arguments[] = {guarded}; + return invoke(context, "HMath.Symbolic.requiredConditions", hm_arguments, 1, out); +} + +hmath_status hmath_symbolic_symbolic_eigenvalues(hmath_context *context, const hmath_value *options, const hmath_value *matrix, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, matrix}; + return invoke(context, "HMath.Symbolic.symbolicEigenvalues", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_numerical_substitution(hmath_context *context, const hmath_value *options, const hmath_value *precision, const hmath_value *bindings, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {options, precision, bindings, expression}; + return invoke(context, "HMath.Symbolic.numericalSubstitution", hm_arguments, 4, out); +} + +hmath_status hmath_symbolic_to_la_te_x(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Symbolic.toLaTeX", hm_arguments, 2, out); +} + +hmath_status hmath_symbolic_to_math_ml(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out) { + const hmath_value *hm_arguments[] = {limits, expression}; + return invoke(context, "HMath.Symbolic.toMathML", hm_arguments, 2, out); +} +/* END GENERATED */ diff --git a/cbits/foundation.c b/cbits/foundation.c new file mode 100644 index 0000000..9bc2e28 --- /dev/null +++ b/cbits/foundation.c @@ -0,0 +1,1733 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; original operation dispatch only. */ +#include "hmath_foundation.h" +#include "value_internal.h" +extern int hm_foundation_apply(int, void *const *, size_t, void **); +hmath_status hmath_foundation_datastructure_fenwick(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(0, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_fenwick_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(1, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_fenwick_prefix(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(2, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_fenwick_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(3, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_segment_tree(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(4, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_segment_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(5, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_segment_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(6, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_sparse_table(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(7, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_sparse_minimum(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(8, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_disjoint_sparse_table(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(9, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_disjoint_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(10, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_next_greater(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(11, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_empty_heap(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(12, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_heap_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(13, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_heap_pop(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(14, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_heap_from_list(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(15, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_binary_heap(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(16, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_binary_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(17, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_binary_pop(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(18, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_indexed_heap(hmath_context *context, + hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(19, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_indexed_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(20, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_indexed_pop(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(21, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_union_find(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(22, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_find_root(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(23, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_union(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(24, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_connected(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(25, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_components(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(26, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_bloom(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(27, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_bloom_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(28, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_bloom_member(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(29, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_bloom_false_positive_bound(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(30, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_count_min(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(31, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_count_min_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(32, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_count_min_estimate(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(33, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_count_min_error_bound(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(34, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_hyper_log_log(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(35, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_hll_add(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(36, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_hll_estimate(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(37, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_reservoir(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(38, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_reservoir_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(39, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_reservoir_values(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(40, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_online_quantiles(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(41, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_quantile_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(42, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_online_quantile(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(43, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(44, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiplicity(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(45, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_entries(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(46, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_insert(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(47, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_delete(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(48, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_union(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(49, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_intersection(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(50, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_multiset_difference(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(51, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_set(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(52, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_width(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(53, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_value(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(54, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_member(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(55, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_insert(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(56, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_delete(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(57, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_union(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(58, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_intersection(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(59, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_bit_difference(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(60, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_resize_bit_set(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(61, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_population_count(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(62, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_leading_zeros(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(63, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_trailing_zeros(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(64, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_rotate_bits(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(65, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_reverse_bits(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(66, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_gray_encode(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(67, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_gray_decode(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(68, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_hamming_distance(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(69, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_transitive_closure(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(70, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_equivalence_closure(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(71, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_is_equivalence(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(72, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_boolean_multiply(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(73, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_evaluate_prop(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(74, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_truth_table(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(75, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_implicant_covers(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(76, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_quine_mc_cluskey(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + if (!out || !a0 || !a1 || !a2 || !a3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2), + hm_value_stable(a3)}; + return hm_value_finish(result, hm_foundation_apply(77, args, 4, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_literal(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(78, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_variable(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(79, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_not(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(80, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_and(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(81, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_or(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(82, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_xor(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(83, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_implies(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(84, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_iff(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(85, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_discrete_implicant_value(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(86, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_implicant_mask(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(87, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_discrete_new_implicant(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(88, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_binary_search(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(89, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_interpolation_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(90, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_exponential_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(91, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_ternary_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + if (!out || !a0 || !a1 || !a2 || !a3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2), + hm_value_stable(a3)}; + return hm_value_finish(result, hm_foundation_apply(92, args, 4, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_numeric_groups(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(93, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_run_length_encode(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(94, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_run_length_decode(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(95, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_coordinate_compression(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(96, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_interval_sweep(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(97, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_divide_conquer_dp(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(98, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_tabulate_dp(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(99, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_memoized_dp(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(100, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_integer_matrix_power(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(101, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_permutations_of(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(102, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_combinations_of(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(103, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_derangements(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(104, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_integer_partitions(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(105, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_set_partitions(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(106, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_pascal_triangle(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(107, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_subsets(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(108, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_cartesian_product(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(109, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_multiset_permutations(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(110, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_generating_coefficients(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(111, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_finite_differences(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(112, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_convergence_default_iteration_options(hmath_context *context, + hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(113, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_convergence_iterate_until( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out) { + if (!out || !a0 || !a1 || !a2 || !a3 || !a4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2), + hm_value_stable(a3), hm_value_stable(a4)}; + return hm_value_finish(result, hm_foundation_apply(114, args, 5, &result->stable), out); +} +hmath_status hmath_foundation_convergence_require_convergence(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(115, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_convergence_result_maybe(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(116, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_from_maybe_error(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(117, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_convergence_new_residual_satisfied(hmath_context *context, + hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(118, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_convergence_new_iteration_limit(hmath_context *context, + hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(119, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_convergence_new_stagnation(hmath_context *context, + hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_foundation_apply(120, NULL, 0, &result->stable), out); +} +hmath_status hmath_foundation_convergence_estimate(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(121, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_iteration_count(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(122, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_final_residual(hmath_context *context, + const hmath_value *a0, hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(123, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_stop_reason(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(124, args, 1, &result->stable), out); +} +hmath_status +hmath_foundation_convergence_new_convergence(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + if (!out || !a0 || !a1 || !a2 || !a3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2), + hm_value_stable(a3)}; + return hm_value_finish(result, hm_foundation_apply(125, args, 4, &result->stable), out); +} +hmath_status hmath_foundation_convergence_maximum_iterations(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(126, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_absolute_tolerance(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(127, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_relative_tolerance(hmath_context *context, + const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(128, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_convergence_new_iteration_options(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out) { + if (!out || !a0 || !a1 || !a2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0), hm_value_stable(a1), hm_value_stable(a2)}; + return hm_value_finish(result, hm_foundation_apply(129, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_convergence_converged(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + if (!out || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(130, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_datastructure_next_greater_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(131, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_binary_search_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(132, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_exponential_search_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(133, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_numeric_groups_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(134, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_algorithms_coordinate_compression_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + hmath_value **out) { + if (!out || !prototype || !a0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0)}; + return hm_value_finish(result, hm_foundation_apply(135, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_combinatorics_multiset_permutations_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + if (!out || !prototype || !a0 || !a1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(a0), hm_value_stable(a1)}; + return hm_value_finish(result, hm_foundation_apply(136, args, 3, &result->stable), out); +} +hmath_status hmath_foundation_object_type(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-1, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_object_parts(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-2, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_left(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-3, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_right(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-4, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_just(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-5, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_ordered_type(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-6, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_optional_type(hmath_context *context, const hmath_value *value, + hmath_value **out) { + if (!value || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL foundation query"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(value)}; + return hm_value_finish(result, hm_foundation_apply(-7, args, 1, &result->stable), out); +} +hmath_status hmath_foundation_heap_from_list_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *values, hmath_value **out) { + if (!prototype || !values || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL typed container argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(values)}; + return hm_value_finish(result, hm_foundation_apply(-8, args, 2, &result->stable), out); +} +hmath_status hmath_foundation_multiset_typed(hmath_context *context, const hmath_value *prototype, + const hmath_value *values, hmath_value **out) { + if (!prototype || !values || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL typed container argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(values)}; + return hm_value_finish(result, hm_foundation_apply(-9, args, 2, &result->stable), out); +} diff --git a/cbits/geometry.c b/cbits/geometry.c new file mode 100644 index 0000000..1c558af --- /dev/null +++ b/cbits/geometry.c @@ -0,0 +1,1037 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_geometry_bindings.py. */ +#include "hmath_geometry.h" +#include "value_internal.h" +extern int hm_geometry_apply(int,void *const *,size_t,void **); +extern int hm_geometry_parts(void *,void **); +hmath_status hmath_geometry_parts(hmath_context *context,const hmath_value *value0,hmath_value **out) { + if(!out || !value0)return hm_error(HMATH_INVALID_ARGUMENT,"NULL geometry helper argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + return hm_value_finish(temporary,hm_geometry_parts(hm_value_stable(value0),&temporary->stable),out); +} +extern int hm_geometry_describe(void *,void **); +hmath_status hmath_geometry_describe(hmath_context *context,const hmath_value *value0,hmath_value **out) { + if(!out || !value0)return hm_error(HMATH_INVALID_ARGUMENT,"NULL geometry helper argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + return hm_value_finish(temporary,hm_geometry_describe(hm_value_stable(value0),&temporary->stable),out); +} +extern int hm_geometry_equal(void *,void *,void **); +hmath_status hmath_geometry_equal(hmath_context *context,const hmath_value *value0,const hmath_value *value1,hmath_value **out) { + if(!out || !value0 || !value1)return hm_error(HMATH_INVALID_ARGUMENT,"NULL geometry helper argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + return hm_value_finish(temporary,hm_geometry_equal(hm_value_stable(value0),hm_value_stable(value1),&temporary->stable),out); +} +hmath_status hmath_geometry_penetration(hmath_context *context, const hmath_value *number, const hmath_value *point2, const hmath_value *number2, const hmath_value *count, hmath_value **out) { + if(!out || !number || !point2 || !number2 || !count)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(point2),hm_value_stable(number2),hm_value_stable(count)}; + return hm_value_finish(temporary,hm_geometry_apply(0,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_epa(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !count || !number || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(number),hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(1,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_gjk(hmath_context *context, const hmath_value *count, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !count || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(2,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_penetration_depth(hmath_context *context, const hmath_value *penetration, hmath_value **out) { + if(!out || !penetration)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(penetration)}; + return hm_value_finish(temporary,hm_geometry_apply(3,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_penetration_error(hmath_context *context, const hmath_value *penetration, hmath_value **out) { + if(!out || !penetration)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(penetration)}; + return hm_value_finish(temporary,hm_geometry_apply(4,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_penetration_iterations(hmath_context *context, const hmath_value *penetration, hmath_value **out) { + if(!out || !penetration)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(penetration)}; + return hm_value_finish(temporary,hm_geometry_apply(5,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_penetration_normal(hmath_context *context, const hmath_value *penetration, hmath_value **out) { + if(!out || !penetration)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(penetration)}; + return hm_value_finish(temporary,hm_geometry_apply(6,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_separating_axis(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(7,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_aabb(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(8,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_boundary(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(9,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_capsule(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out) { + if(!out || !point3 || !point32 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(point32),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(10,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_circle(hmath_context *context, const hmath_value *point2, const hmath_value *number, hmath_value **out) { + if(!out || !point2 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(11,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_clockwise(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(12,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_collinear(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(13,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_cone(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out) { + if(!out || !point3 || !point32 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(point32),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(14,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_counterclockwise(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(15,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_cylinder(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out) { + if(!out || !point3 || !point32 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(point32),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(16,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_ellipse(hmath_context *context, const hmath_value *point2, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out) { + if(!out || !point2 || !number || !number2 || !number3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(number),hm_value_stable(number2),hm_value_stable(number3)}; + return hm_value_finish(temporary,hm_geometry_apply(17,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_frustum(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(18,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_inside(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(19,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_line(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(20,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_obb(hmath_context *context, const hmath_value *point3, const hmath_value *values, const hmath_value *point32, hmath_value **out) { + if(!out || !point3 || !values || !point32)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(values),hm_value_stable(point32)}; + return hm_value_finish(temporary,hm_geometry_apply(21,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_outside(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(22,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_p2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out) { + if(!out || !number || !number2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2)}; + return hm_value_finish(temporary,hm_geometry_apply(23,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_p3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out) { + if(!out || !number || !number2 || !number3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2),hm_value_stable(number3)}; + return hm_value_finish(temporary,hm_geometry_apply(24,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_plane(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out) { + if(!out || !point3 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(25,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_point_nd_raw(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(26,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_polygon(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(27,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_ray(hmath_context *context, const hmath_value *point3, const hmath_value *point32, hmath_value **out) { + if(!out || !point3 || !point32)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(point32)}; + return hm_value_finish(temporary,hm_geometry_apply(28,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_rectangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out) { + if(!out || !point2 || !point22)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22)}; + return hm_value_finish(temporary,hm_geometry_apply(29,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_segment(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(30,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_sphere(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out) { + if(!out || !point3 || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(31,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_triangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out) { + if(!out || !point2 || !point22 || !point23)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22),hm_value_stable(point23)}; + return hm_value_finish(temporary,hm_geometry_apply(32,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_point2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out) { + if(!out || !number || !number2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2)}; + return hm_value_finish(temporary,hm_geometry_apply(33,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_point3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out) { + if(!out || !number || !number2 || !number3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2),hm_value_stable(number3)}; + return hm_value_finish(temporary,hm_geometry_apply(34,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_point_nd(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(35,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_difference(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(36,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_gift_wrapping(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(37,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_graham_scan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(38,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_intersection(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(39,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_monotone_chain(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(40,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_quickhull(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(41,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_union(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(42,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_clip_polygon(hmath_context *context, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out) { + if(!out || !polygon || !polygon2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon),hm_value_stable(polygon2)}; + return hm_value_finish(temporary,hm_geometry_apply(43,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_convex_hull(hmath_context *context, const hmath_value *hull_algorithm, const hmath_value *values, hmath_value **out) { + if(!out || !hull_algorithm || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(hull_algorithm),hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(44,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_minimum_bounding_circle(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(45,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_minimum_bounding_rectangle(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(46,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_minkowski_sum(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(47,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_polygon_area(hmath_context *context, const hmath_value *polygon, hmath_value **out) { + if(!out || !polygon)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon)}; + return hm_value_finish(temporary,hm_geometry_apply(48,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_polygon_boolean(hmath_context *context, const hmath_value *boolean_operation, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out) { + if(!out || !boolean_operation || !polygon || !polygon2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boolean_operation),hm_value_stable(polygon),hm_value_stable(polygon2)}; + return hm_value_finish(temporary,hm_geometry_apply(49,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_polygon_centroid(hmath_context *context, const hmath_value *polygon, hmath_value **out) { + if(!out || !polygon)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon)}; + return hm_value_finish(temporary,hm_geometry_apply(50,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_shoelace(hmath_context *context, const hmath_value *polygon, hmath_value **out) { + if(!out || !polygon)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon)}; + return hm_value_finish(temporary,hm_geometry_apply(51,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_chebyshev(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(52,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_circle_points(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(53,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_coincident_circles(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(54,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_coincident_line(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(55,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_disjoint_circles(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(56,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_euclidean(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(57,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_intersection_point(hmath_context *context, const hmath_value *point2, hmath_value **out) { + if(!out || !point2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2)}; + return hm_value_finish(temporary,hm_geometry_apply(58,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_manhattan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(59,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_minkowski(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(60,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_no_intersection(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(61,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_overlap_segment(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out) { + if(!out || !point2 || !point22)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22)}; + return hm_value_finish(temporary,hm_geometry_apply(62,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_box_contains(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out) { + if(!out || !aabb || !point_nd)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(aabb),hm_value_stable(point_nd)}; + return hm_value_finish(temporary,hm_geometry_apply(63,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_box_sdf(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out) { + if(!out || !aabb || !point_nd)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(aabb),hm_value_stable(point_nd)}; + return hm_value_finish(temporary,hm_geometry_apply(64,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_capsule_sdf(hmath_context *context, const hmath_value *capsule, const hmath_value *point3, hmath_value **out) { + if(!out || !capsule || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(capsule),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(65,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_circle_intersection(hmath_context *context, const hmath_value *circle, const hmath_value *circle2, hmath_value **out) { + if(!out || !circle || !circle2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(circle),hm_value_stable(circle2)}; + return hm_value_finish(temporary,hm_geometry_apply(66,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_circumcenter(hmath_context *context, const hmath_value *triangle, hmath_value **out) { + if(!out || !triangle)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(triangle)}; + return hm_value_finish(temporary,hm_geometry_apply(67,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_cone_sdf(hmath_context *context, const hmath_value *cone, const hmath_value *point3, hmath_value **out) { + if(!out || !cone || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(cone),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(68,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_cosine_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(69,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_cylinder_sdf(hmath_context *context, const hmath_value *cylinder, const hmath_value *point3, hmath_value **out) { + if(!out || !cylinder || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(cylinder),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(70,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_distance(hmath_context *context, const hmath_value *metric, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !metric || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(metric),hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(71,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_ellipse_contains(hmath_context *context, const hmath_value *ellipse, const hmath_value *point2, hmath_value **out) { + if(!out || !ellipse || !point2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(ellipse),hm_value_stable(point2)}; + return hm_value_finish(temporary,hm_geometry_apply(72,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_hausdorff_distance(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(73,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_incenter(hmath_context *context, const hmath_value *triangle, hmath_value **out) { + if(!out || !triangle)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(triangle)}; + return hm_value_finish(temporary,hm_geometry_apply(74,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_incircle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out) { + if(!out || !point2 || !point22 || !point23 || !point24)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22),hm_value_stable(point23),hm_value_stable(point24)}; + return hm_value_finish(temporary,hm_geometry_apply(75,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_line_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out) { + if(!out || !point2 || !point22 || !point23 || !point24)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22),hm_value_stable(point23),hm_value_stable(point24)}; + return hm_value_finish(temporary,hm_geometry_apply(76,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_line_plane_intersection(hmath_context *context, const hmath_value *line, const hmath_value *plane, hmath_value **out) { + if(!out || !line || !plane)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(line),hm_value_stable(plane)}; + return hm_value_finish(temporary,hm_geometry_apply(77,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_mahalanobis_distance(hmath_context *context, const hmath_value *values, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out) { + if(!out || !values || !point_nd || !point_nd2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(point_nd),hm_value_stable(point_nd2)}; + return hm_value_finish(temporary,hm_geometry_apply(78,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_obb_sdf(hmath_context *context, const hmath_value *obb, const hmath_value *point3, hmath_value **out) { + if(!out || !obb || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(obb),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(79,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_orientation(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out) { + if(!out || !point2 || !point22 || !point23)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22),hm_value_stable(point23)}; + return hm_value_finish(temporary,hm_geometry_apply(80,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_plane_intersection(hmath_context *context, const hmath_value *plane, const hmath_value *plane2, hmath_value **out) { + if(!out || !plane || !plane2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(plane),hm_value_stable(plane2)}; + return hm_value_finish(temporary,hm_geometry_apply(81,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_point_line_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *line, hmath_value **out) { + if(!out || !point_nd || !line)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(line)}; + return hm_value_finish(temporary,hm_geometry_apply(82,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_point_plane_distance(hmath_context *context, const hmath_value *point3, const hmath_value *plane, hmath_value **out) { + if(!out || !point3 || !plane)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(plane)}; + return hm_value_finish(temporary,hm_geometry_apply(83,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_point_segment_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *segment, hmath_value **out) { + if(!out || !point_nd || !segment)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_nd),hm_value_stable(segment)}; + return hm_value_finish(temporary,hm_geometry_apply(84,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_polygon_location(hmath_context *context, const hmath_value *polygon, const hmath_value *point2, hmath_value **out) { + if(!out || !polygon || !point2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon),hm_value_stable(point2)}; + return hm_value_finish(temporary,hm_geometry_apply(85,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_ray_box(hmath_context *context, const hmath_value *ray, const hmath_value *aabb, hmath_value **out) { + if(!out || !ray || !aabb)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(ray),hm_value_stable(aabb)}; + return hm_value_finish(temporary,hm_geometry_apply(86,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_ray_sphere(hmath_context *context, const hmath_value *ray, const hmath_value *sphere, hmath_value **out) { + if(!out || !ray || !sphere)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(ray),hm_value_stable(sphere)}; + return hm_value_finish(temporary,hm_geometry_apply(87,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_ray_triangle(hmath_context *context, const hmath_value *ray, const hmath_value *tuple_value, hmath_value **out) { + if(!out || !ray || !tuple_value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(ray),hm_value_stable(tuple_value)}; + return hm_value_finish(temporary,hm_geometry_apply(88,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_segment_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out) { + if(!out || !point2 || !point22 || !point23 || !point24)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point2),hm_value_stable(point22),hm_value_stable(point23),hm_value_stable(point24)}; + return hm_value_finish(temporary,hm_geometry_apply(89,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_sphere_contains(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out) { + if(!out || !sphere || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(sphere),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(90,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_sphere_sdf(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out) { + if(!out || !sphere || !point3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(sphere),hm_value_stable(point3)}; + return hm_value_finish(temporary,hm_geometry_apply(91,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_triangle_barycentric(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out) { + if(!out || !triangle || !point2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(triangle),hm_value_stable(point2)}; + return hm_value_finish(temporary,hm_geometry_apply(92,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_triangle_intersection(hmath_context *context, const hmath_value *triangle, const hmath_value *triangle2, hmath_value **out) { + if(!out || !triangle || !triangle2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(triangle),hm_value_stable(triangle2)}; + return hm_value_finish(temporary,hm_geometry_apply(93,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_triangle_location(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out) { + if(!out || !triangle || !point2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(triangle),hm_value_stable(point2)}; + return hm_value_finish(temporary,hm_geometry_apply(94,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_bvh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(95,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_ball_tree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(96,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_kd_tree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(97,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_neighbor_query(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out) { + if(!out || !values || !count || !flag)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(count),hm_value_stable(flag)}; + return hm_value_finish(temporary,hm_geometry_apply(98,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_octree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(99,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_quadtree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(100,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_r_tree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_geometry_apply(101,arguments,0,&temporary->stable),out); +} +hmath_status hmath_geometry_spatial_hash(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(102,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_build_spatial_index(hmath_context *context, const hmath_value *spatial_kind, const hmath_value *point_cloud, hmath_value **out) { + if(!out || !spatial_kind || !point_cloud)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(spatial_kind),hm_value_stable(point_cloud)}; + return hm_value_finish(temporary,hm_geometry_apply(103,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_cloud_points(hmath_context *context, const hmath_value *point_cloud, hmath_value **out) { + if(!out || !point_cloud)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point_cloud)}; + return hm_value_finish(temporary,hm_geometry_apply(104,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_nearest_query(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *point_nd, hmath_value **out) { + if(!out || !count || !count2 || !spatial_index || !point_nd)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(count2),hm_value_stable(spatial_index),hm_value_stable(point_nd)}; + return hm_value_finish(temporary,hm_geometry_apply(105,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_point_cloud(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(106,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_query_exhaustive(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out) { + if(!out || !neighbor_query)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_query)}; + return hm_value_finish(temporary,hm_geometry_apply(107,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_query_leaves(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out) { + if(!out || !neighbor_query)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_query)}; + return hm_value_finish(temporary,hm_geometry_apply(108,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_query_neighbors(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out) { + if(!out || !neighbor_query)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_query)}; + return hm_value_finish(temporary,hm_geometry_apply(109,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_radius_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *point_nd, const hmath_value *number, hmath_value **out) { + if(!out || !spatial_index || !point_nd || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(spatial_index),hm_value_stable(point_nd),hm_value_stable(number)}; + return hm_value_finish(temporary,hm_geometry_apply(110,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_range_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *aabb, hmath_value **out) { + if(!out || !spatial_index || !aabb)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(spatial_index),hm_value_stable(aabb)}; + return hm_value_finish(temporary,hm_geometry_apply(111,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_affine_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out) { + if(!out || !matrix || !point_nd)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(matrix),hm_value_stable(point_nd)}; + return hm_value_finish(temporary,hm_geometry_apply(112,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_apply_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out) { + if(!out || !matrix || !point_nd)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(matrix),hm_value_stable(point_nd)}; + return hm_value_finish(temporary,hm_geometry_apply(113,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_compose_transforms(hmath_context *context, const hmath_value *matrix, const hmath_value *matrix2, hmath_value **out) { + if(!out || !matrix || !matrix2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(matrix),hm_value_stable(matrix2)}; + return hm_value_finish(temporary,hm_geometry_apply(114,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_cull_box(hmath_context *context, const hmath_value *frustum, const hmath_value *aabb, hmath_value **out) { + if(!out || !frustum || !aabb)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(frustum),hm_value_stable(aabb)}; + return hm_value_finish(temporary,hm_geometry_apply(115,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_cull_sphere(hmath_context *context, const hmath_value *frustum, const hmath_value *sphere, hmath_value **out) { + if(!out || !frustum || !sphere)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(frustum),hm_value_stable(sphere)}; + return hm_value_finish(temporary,hm_geometry_apply(116,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_extract_frustum(hmath_context *context, const hmath_value *matrix, hmath_value **out) { + if(!out || !matrix)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(matrix)}; + return hm_value_finish(temporary,hm_geometry_apply(117,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_inverse_transform(hmath_context *context, const hmath_value *matrix, hmath_value **out) { + if(!out || !matrix)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(matrix)}; + return hm_value_finish(temporary,hm_geometry_apply(118,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_look_at(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *point33, hmath_value **out) { + if(!out || !point3 || !point32 || !point33)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(point3),hm_value_stable(point32),hm_value_stable(point33)}; + return hm_value_finish(temporary,hm_geometry_apply(119,arguments,3,&temporary->stable),out); +} +hmath_status hmath_geometry_orthographic(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, const hmath_value *number5, const hmath_value *number6, hmath_value **out) { + if(!out || !number || !number2 || !number3 || !number4 || !number5 || !number6)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2),hm_value_stable(number3),hm_value_stable(number4),hm_value_stable(number5),hm_value_stable(number6)}; + return hm_value_finish(temporary,hm_geometry_apply(120,arguments,6,&temporary->stable),out); +} +hmath_status hmath_geometry_perspective(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, hmath_value **out) { + if(!out || !number || !number2 || !number3 || !number4)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2),hm_value_stable(number3),hm_value_stable(number4)}; + return hm_value_finish(temporary,hm_geometry_apply(121,arguments,4,&temporary->stable),out); +} +hmath_status hmath_geometry_constrained_delaunay(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(temporary,hm_geometry_apply(122,arguments,2,&temporary->stable),out); +} +hmath_status hmath_geometry_delaunay(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(123,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_ear_clip(hmath_context *context, const hmath_value *polygon, hmath_value **out) { + if(!out || !polygon)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(polygon)}; + return hm_value_finish(temporary,hm_geometry_apply(124,arguments,1,&temporary->stable),out); +} +hmath_status hmath_geometry_voronoi(hmath_context *context, const hmath_value *rectangle, const hmath_value *values, hmath_value **out) { + if(!out || !rectangle || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(rectangle),hm_value_stable(values)}; + return hm_value_finish(temporary,hm_geometry_apply(125,arguments,2,&temporary->stable),out); +} diff --git a/cbits/graph_bindings.c b/cbits/graph_bindings.c new file mode 100644 index 0000000..7c0fc20 --- /dev/null +++ b/cbits/graph_bindings.c @@ -0,0 +1,1595 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_graph.h" +#include "value_internal.h" +extern int hm_graph_apply(int, void *const *, size_t, hmath_graph_heuristic, void *, void **); +hmath_status hmath_graph_betweenness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(0, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bipartite_colors( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(1, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_closeness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(2, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_clustering_coefficients( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(3, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_degree_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(4, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_density( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(5, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_diameter_radius( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(6, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_eigenvector_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *graph, + hmath_value **out) { + if (!out || !iterations || !tolerance || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(tolerance), hm_value_stable(graph)}; + int code = hm_graph_apply(7, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_eulerian_path( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(8, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_exact_coloring( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out) { + if (!out || !fuel || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(fuel), hm_value_stable(graph)}; + int code = hm_graph_apply(9, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_graph_edit_distance( + hmath_context *context, + const hmath_value *budget, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + if (!out || !budget || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(budget), hm_value_stable(left), hm_value_stable(right)}; + int code = hm_graph_apply(10, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_graph_laplacian( + hmath_context *context, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out) { + if (!out || !normalized || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(normalized), hm_value_stable(graph)}; + int code = hm_graph_apply(11, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_graph_similarity( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(left), hm_value_stable(right)}; + int code = hm_graph_apply(12, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_greedy_coloring( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(13, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hamiltonian_path( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out) { + if (!out || !fuel || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(fuel), hm_value_stable(graph)}; + int code = hm_graph_apply(14, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_katz_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *alpha, + const hmath_value *beta, + const hmath_value *graph, + hmath_value **out) { + if (!out || !iterations || !tolerance || !alpha || !beta || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(tolerance), hm_value_stable(alpha), hm_value_stable(beta), hm_value_stable(graph)}; + int code = hm_graph_apply(15, arguments, 5, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_label_propagation( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + hmath_value **out) { + if (!out || !iterations || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(graph)}; + int code = hm_graph_apply(16, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_laplacian_spectrum( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out) { + if (!out || !iterations || !tolerance || !normalized || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(tolerance), hm_value_stable(normalized), hm_value_stable(graph)}; + int code = hm_graph_apply(17, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_louvain( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + hmath_value **out) { + if (!out || !budget || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(budget), hm_value_stable(graph)}; + int code = hm_graph_apply(18, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_modularity( + hmath_context *context, + const hmath_value *graph, + const hmath_value *labels, + hmath_value **out) { + if (!out || !graph || !labels) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(labels)}; + int code = hm_graph_apply(19, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_nearest_neighbor_tour( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out) { + if (!out || !graph || !start) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(start)}; + int code = hm_graph_apply(20, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_page_rank( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *damping, + const hmath_value *graph, + hmath_value **out) { + if (!out || !iterations || !tolerance || !damping || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(tolerance), hm_value_stable(damping), hm_value_stable(graph)}; + int code = hm_graph_apply(21, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_random_walk( + hmath_context *context, + const hmath_value *count, + const hmath_value *seed, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out) { + if (!out || !count || !seed || !graph || !start) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(count), hm_value_stable(seed), hm_value_stable(graph), hm_value_stable(start)}; + int code = hm_graph_apply(22, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_two_opt_tour( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + const hmath_value *tour, + hmath_value **out) { + if (!out || !iterations || !graph || !tour) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(iterations), hm_value_stable(graph), hm_value_stable(tour)}; + int code = hm_graph_apply(23, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *offsets, + const hmath_value *targets, + const hmath_value *weights, + const hmath_value *edge_ids, + const hmath_value *orientations, + hmath_value **out) { + if (!out || !directed || !vertex_count || !offsets || !targets || !weights || !edge_ids || !orientations) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(directed), hm_value_stable(vertex_count), hm_value_stable(offsets), hm_value_stable(targets), hm_value_stable(weights), hm_value_stable(edge_ids), hm_value_stable(orientations)}; + int code = hm_graph_apply(24, arguments, 7, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *weight, + hmath_value **out) { + if (!out || !edge_id || !source || !target || !weight) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge_id), hm_value_stable(source), hm_value_stable(target), hm_value_stable(weight)}; + int code = hm_graph_apply(25, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_adjacency_list( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(26, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_adjacency_matrix( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(27, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_arcs( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(28, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_articulation_points( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(29, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out) { + if (!out || !graph || !start) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(start)}; + int code = hm_graph_apply(30, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bipartite_base( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out) { + if (!out || !bipartite_graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(bipartite_graph)}; + int code = hm_graph_apply(31, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bipartite_graph( + hmath_context *context, + const hmath_value *left_vertices, + const hmath_value *right_vertices, + const hmath_value *edges, + hmath_value **out) { + if (!out || !left_vertices || !right_vertices || !edges) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(left_vertices), hm_value_stable(right_vertices), hm_value_stable(edges)}; + int code = hm_graph_apply(32, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bipartite_parts( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out) { + if (!out || !bipartite_graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(bipartite_graph)}; + int code = hm_graph_apply(33, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_boruvka( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(34, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bridges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(35, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_check_vertex( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out) { + if (!out || !graph || !vertex) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(vertex)}; + int code = hm_graph_apply(36, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_connected_components( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(37, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_directed( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(38, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_ids( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(39, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_offsets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(40, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_orientations( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(41, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_targets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(42, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_vertices( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(43, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_csr_weights( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(44, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_deserialize_bipartite_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out) { + if (!out || !text) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(text)}; + int code = hm_graph_apply(45, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_deserialize_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out) { + if (!out || !text) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(text)}; + int code = hm_graph_apply(46, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_deserialize_hypergraph( + hmath_context *context, + const hmath_value *text, + hmath_value **out) { + if (!out || !text) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(text)}; + int code = hm_graph_apply(47, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_dfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out) { + if (!out || !graph || !start) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(start)}; + int code = hm_graph_apply(48, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_directed( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(49, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge_from( + hmath_context *context, + const hmath_value *edge, + hmath_value **out) { + if (!out || !edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge)}; + int code = hm_graph_apply(50, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge_id( + hmath_context *context, + const hmath_value *edge, + hmath_value **out) { + if (!out || !edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge)}; + int code = hm_graph_apply(51, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge_to( + hmath_context *context, + const hmath_value *edge, + hmath_value **out) { + if (!out || !edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge)}; + int code = hm_graph_apply(52, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge_weight( + hmath_context *context, + const hmath_value *edge, + hmath_value **out) { + if (!out || !edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge)}; + int code = hm_graph_apply(53, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(54, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_finite( + hmath_context *context, + const hmath_value *x, + hmath_value **out) { + if (!out || !x) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(x)}; + int code = hm_graph_apply(55, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_from_adjacency_list( + hmath_context *context, + const hmath_value *directed, + const hmath_value *rows, + const hmath_value *orientations, + hmath_value **out) { + if (!out || !directed || !rows || !orientations) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(directed), hm_value_stable(rows), hm_value_stable(orientations)}; + int code = hm_graph_apply(56, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_from_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + hmath_value **out) { + if (!out || !directed || !cells) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(directed), hm_value_stable(cells)}; + int code = hm_graph_apply(57, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_from_csr( + hmath_context *context, + const hmath_value *csr, + hmath_value **out) { + if (!out || !csr) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(csr)}; + int code = hm_graph_apply(58, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_from_labeled_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + const hmath_value *orientations, + hmath_value **out) { + if (!out || !directed || !cells || !orientations) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(directed), hm_value_stable(cells), hm_value_stable(orientations)}; + int code = hm_graph_apply(59, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_graph( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out) { + if (!out || !directed || !vertex_count || !edges) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(directed), hm_value_stable(vertex_count), hm_value_stable(edges)}; + int code = hm_graph_apply(60, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_has_cycle( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(61, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hyper_vertices( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out) { + if (!out || !hypergraph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(hypergraph)}; + int code = hm_graph_apply(62, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hyperedges( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out) { + if (!out || !hypergraph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(hypergraph)}; + int code = hm_graph_apply(63, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hypergraph( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *hyperedges, + hmath_value **out) { + if (!out || !vertex_count || !hyperedges) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(vertex_count), hm_value_stable(hyperedges)}; + int code = hm_graph_apply(64, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_iterative_deepening( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out) { + if (!out || !budget || !graph || !source || !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(budget), hm_value_stable(graph), hm_value_stable(source), hm_value_stable(target)}; + int code = hm_graph_apply(65, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_kosaraju_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(66, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_kruskal( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(67, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_neighbors( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out) { + if (!out || !graph || !vertex) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(vertex)}; + int code = hm_graph_apply(68, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_prim( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(69, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_require_undirected( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(70, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_serialize_bipartite_graph( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out) { + if (!out || !bipartite) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(bipartite)}; + int code = hm_graph_apply(71, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_serialize_graph( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(72, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_serialize_hypergraph( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out) { + if (!out || !hypergraph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(hypergraph)}; + int code = hm_graph_apply(73, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_tarjan_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(74, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_to_csr( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(75, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_topological_sort( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(76, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_vertex_count( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(77, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_flow_result( + hmath_context *context, + const hmath_value *value, + const hmath_value *edge_flows, + const hmath_value *cost, + hmath_value **out) { + if (!out || !value || !edge_flows || !cost) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(edge_flows), hm_value_stable(cost)}; + int code = hm_graph_apply(78, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *capacity, + const hmath_value *cost, + hmath_value **out) { + if (!out || !edge_id || !source || !target || !capacity || !cost) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(edge_id), hm_value_stable(source), hm_value_stable(target), hm_value_stable(capacity), hm_value_stable(cost)}; + int code = hm_graph_apply(79, arguments, 5, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_dinic( + hmath_context *context, + const hmath_value *budget, + const hmath_value *network, + const hmath_value *source, + const hmath_value *target, + hmath_value **out) { + if (!out || !budget || !network || !source || !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(budget), hm_value_stable(network), hm_value_stable(source), hm_value_stable(target)}; + int code = hm_graph_apply(80, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edge_flows( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out) { + if (!out || !flow_result) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(flow_result)}; + int code = hm_graph_apply(81, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_edmonds_karp( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out) { + if (!out || !value || !network || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(network), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_graph_apply(82, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_flow_cost( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out) { + if (!out || !flow_result) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(flow_result)}; + int code = hm_graph_apply(83, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_flow_value( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out) { + if (!out || !flow_result) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(flow_result)}; + int code = hm_graph_apply(84, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_ford_fulkerson( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out) { + if (!out || !value || !network || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(network), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_graph_apply(85, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hopcroft_karp( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out) { + if (!out || !bipartite) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(bipartite)}; + int code = hm_graph_apply(86, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_hungarian( + hmath_context *context, + const hmath_value *costs, + hmath_value **out) { + if (!out || !costs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(costs)}; + int code = hm_graph_apply(87, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_minimum_cost_maximum_flow( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out) { + if (!out || !value || !network || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(network), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_graph_apply(88, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_minimum_cut( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out) { + if (!out || !value || !network || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(network), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_graph_apply(89, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out) { + if (!out || !vertex_count || !edges) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(vertex_count), hm_value_stable(edges)}; + int code = hm_graph_apply(90, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_capacity( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out) { + if (!out || !network_edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network_edge)}; + int code = hm_graph_apply(91, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_cost( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out) { + if (!out || !network_edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network_edge)}; + int code = hm_graph_apply(92, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_edge_id( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out) { + if (!out || !network_edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network_edge)}; + int code = hm_graph_apply(93, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_edges( + hmath_context *context, + const hmath_value *network, + hmath_value **out) { + if (!out || !network) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network)}; + int code = hm_graph_apply(94, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_from( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out) { + if (!out || !network_edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network_edge)}; + int code = hm_graph_apply(95, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_network_to( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out) { + if (!out || !network_edge) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(network_edge)}; + int code = hm_graph_apply(96, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_push_relabel( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out) { + if (!out || !value || !network || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(network), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_graph_apply(97, arguments, 4, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_a_star( + hmath_context *context, + const hmath_value *graph, + hmath_graph_heuristic heuristic, + void *userdata, + const hmath_value *source, + const hmath_value *target, + hmath_value **out) { + if (!out || !graph || !source || !target || !heuristic) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(source), hm_value_stable(target)}; + int code = hm_graph_apply(98, arguments, 3, heuristic, userdata, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bellman_ford( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out) { + if (!out || !graph || !source) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(source)}; + int code = hm_graph_apply(99, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_bidirectional_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out) { + if (!out || !graph || !source || !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(source), hm_value_stable(target)}; + int code = hm_graph_apply(100, arguments, 3, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out) { + if (!out || !graph || !source) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(source)}; + int code = hm_graph_apply(101, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_floyd_warshall( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(102, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_johnson( + hmath_context *context, + const hmath_value *graph, + hmath_value **out) { + if (!out || !graph) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph)}; + int code = hm_graph_apply(103, arguments, 1, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_k_shortest_paths( + hmath_context *context, + const hmath_value *budget, + const hmath_value *count, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out) { + if (!out || !budget || !count || !graph || !source || !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(budget), hm_value_stable(count), hm_value_stable(graph), hm_value_stable(source), hm_value_stable(target)}; + int code = hm_graph_apply(104, arguments, 5, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_longest_dag_paths( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out) { + if (!out || !graph || !source) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(source)}; + int code = hm_graph_apply(105, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} +hmath_status hmath_graph_multi_source_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *sources, + hmath_value **out) { + if (!out || !graph || !sources) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context, &temporary); + if (status) + return status; + void *arguments[] = {hm_value_stable(graph), hm_value_stable(sources)}; + int code = hm_graph_apply(106, arguments, 2, NULL, NULL, &temporary->stable); + return hm_value_finish(temporary, code, out); +} diff --git a/cbits/image.c b/cbits/image.c new file mode 100644 index 0000000..546e850 --- /dev/null +++ b/cbits/image.c @@ -0,0 +1,676 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_image_bindings.py. */ +#include "hmath_image.h" +#include "value_internal.h" +extern int hm_image_apply(int,void *const *,size_t,hmath_image_callback,void *,void **); +extern int hm_image_clone(void *,void **); +int hm_image_invoke(hmath_image_callback callback,void *userdata,void *stable,void **out) { + hmath_value *temporary=NULL,*input=NULL,*output=NULL; + hmath_status status=hm_value_begin(NULL,&temporary); + if(status) { extern void hm_value_free(void *);hm_value_free(stable);return status; } + temporary->stable=stable; + status=hm_value_finish(temporary,0,&input); + if(status)return status; + status=callback(input,userdata,&output); + if(!status && !output)status=hm_error(HMATH_INVALID_ARGUMENT,"NULL Image callback output"); + if(!status)status=(hmath_status)hm_image_clone(output->stable,out); + if(output)hmath_value_release(output); + hmath_value_release(input); + return status; +} +hmath_status hmath_image_image(hmath_context *context, const hmath_value *shape, const hmath_value *channels, const hmath_value *values, hmath_value **out) { + if(!out || !shape || !channels || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(shape), hm_value_stable(channels), hm_value_stable(values)}; + return hm_value_finish(temporary,hm_image_apply(0,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_from_tensor(hmath_context *context, const hmath_value *tensor, hmath_value **out) { + if(!out || !tensor)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(tensor)}; + return hm_value_finish(temporary,hm_image_apply(1,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_to_tensor(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(2,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_image_shape(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(3,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_image_channels(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(4,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_image_values(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(5,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_pixel(hmath_context *context, const hmath_value *image, const hmath_value *coordinates, hmath_value **out) { + if(!out || !image || !coordinates)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image), hm_value_stable(coordinates)}; + return hm_value_finish(temporary,hm_image_apply(6,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_channel(hmath_context *context, const hmath_value *index, const hmath_value *image, hmath_value **out) { + if(!out || !index || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(index), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(7,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_combine_channels(hmath_context *context, const hmath_value *images, hmath_value **out) { + if(!out || !images)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(images)}; + return hm_value_finish(temporary,hm_image_apply(8,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_map_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *image, hmath_value **out) { + if(!out || !function || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(9,arguments,1,function,userdata,&temporary->stable),out); +} +hmath_status hmath_image_zip_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out || !function || !a || !b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(a), hm_value_stable(b)}; + return hm_value_finish(temporary,hm_image_apply(10,arguments,2,function,userdata,&temporary->stable),out); +} +hmath_status hmath_image_normalize(hmath_context *context, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out) { + if(!out || !low || !high || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(low), hm_value_stable(high), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(11,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_brightness(hmath_context *context, const hmath_value *offset, const hmath_value *image, hmath_value **out) { + if(!out || !offset || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(offset), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(12,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_contrast(hmath_context *context, const hmath_value *factor, const hmath_value *pivot, const hmath_value *image, hmath_value **out) { + if(!out || !factor || !pivot || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(factor), hm_value_stable(pivot), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(13,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_gamma(hmath_context *context, const hmath_value *power, const hmath_value *image, hmath_value **out) { + if(!out || !power || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(power), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(14,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_constant(hmath_context *context, const hmath_value *fill, hmath_value **out) { + if(!out || !fill)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(fill)}; + return hm_value_finish(temporary,hm_image_apply(15,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_clamp(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(16,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_reflect(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(17,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_wrap(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(18,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_convolve(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !shape || !weights || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(weights), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(19,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_correlate(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !shape || !weights || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(weights), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(20,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_gaussian_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !sigma || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(sigma), hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(21,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_box_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(22,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_median_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(23,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_bilateral_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma_space, const hmath_value *sigma_range, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !sigma_space || !sigma_range || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(sigma_space), hm_value_stable(sigma_range), hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(24,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_sharpen(hmath_context *context, const hmath_value *boundary, const hmath_value *amount, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !amount || !sigma || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(amount), hm_value_stable(sigma), hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(25,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_gradient(hmath_context *context, const hmath_value *method, const hmath_value *boundary, const hmath_value *image, hmath_value **out) { + if(!out || !method || !boundary || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(boundary), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(26,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_laplacian(hmath_context *context, const hmath_value *boundary, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(27,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_canny(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !sigma || !radius || !low || !high || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(sigma), hm_value_stable(radius), hm_value_stable(low), hm_value_stable(high), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(28,arguments,6,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_morphology(hmath_context *context, const hmath_value *operation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out) { + if(!out || !operation || !boundary || !shape || !mask || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(operation), hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(mask), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(29,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_morphological_gradient(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out) { + if(!out || !boundary || !shape || !mask || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(mask), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(30,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_validate_boundary(hmath_context *context, const hmath_value *boundary, hmath_value **out) { + if(!out || !boundary)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(boundary)}; + return hm_value_finish(temporary,hm_image_apply(31,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_scalar2_d(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(32,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_window_offsets(hmath_context *context, const hmath_value *radius, const hmath_value *image, hmath_value **out) { + if(!out || !radius || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(radius), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(33,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_sobel(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(34,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_prewitt(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(35,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_scharr(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(36,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_erosion(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(37,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_dilation(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(38,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_opening(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(39,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_closing(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(40,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out) { + if(!out || !bins || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(bins), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(41,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_equalize_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out) { + if(!out || !bins || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(bins), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(42,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_clahe(hmath_context *context, const hmath_value *bins, const hmath_value *tiles, const hmath_value *clip_limit, const hmath_value *image, hmath_value **out) { + if(!out || !bins || !tiles || !clip_limit || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(bins), hm_value_stable(tiles), hm_value_stable(clip_limit), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(43,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_threshold(hmath_context *context, const hmath_value *level, const hmath_value *image, hmath_value **out) { + if(!out || !level || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(level), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(44,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_otsu(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out) { + if(!out || !bins || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(bins), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(45,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_adaptive_threshold(hmath_context *context, const hmath_value *gaussian, const hmath_value *boundary, const hmath_value *radius, const hmath_value *offset, const hmath_value *image, hmath_value **out) { + if(!out || !gaussian || !boundary || !radius || !offset || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian), hm_value_stable(boundary), hm_value_stable(radius), hm_value_stable(offset), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(46,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_template_match(hmath_context *context, const hmath_value *metric, const hmath_value *needle, const hmath_value *haystack, hmath_value **out) { + if(!out || !metric || !needle || !haystack)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(metric), hm_value_stable(needle), hm_value_stable(haystack)}; + return hm_value_finish(temporary,hm_image_apply(47,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_raw_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out) { + if(!out || !row_order || !column_order || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(row_order), hm_value_stable(column_order), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(48,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_central_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out) { + if(!out || !row_order || !column_order || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(row_order), hm_value_stable(column_order), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(49,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_image_centroid(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(50,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_integral_image(hmath_context *context, const hmath_value *image, hmath_value **out) { + if(!out || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(51,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_rectangle_sum(hmath_context *context, const hmath_value *origin, const hmath_value *extent, const hmath_value *image, hmath_value **out) { + if(!out || !origin || !extent || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(origin), hm_value_stable(extent), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(52,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_mean_squared_error(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out || !a || !b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(a), hm_value_stable(b)}; + return hm_value_finish(temporary,hm_image_apply(53,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_peak_signal_to_noise(hmath_context *context, const hmath_value *data_range, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out || !data_range || !a || !b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(data_range), hm_value_stable(a), hm_value_stable(b)}; + return hm_value_finish(temporary,hm_image_apply(54,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_structural_similarity(hmath_context *context, const hmath_value *data_range, const hmath_value *window, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out || !data_range || !window || !a || !b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(data_range), hm_value_stable(window), hm_value_stable(a), hm_value_stable(b)}; + return hm_value_finish(temporary,hm_image_apply(55,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_squared_difference(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(56,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_normalized_correlation(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(57,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_resize(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *image, hmath_value **out) { + if(!out || !interpolation || !boundary || !shape || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(interpolation), hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(58,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_warp(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *matrix, const hmath_value *image, hmath_value **out) { + if(!out || !interpolation || !boundary || !shape || !matrix || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(interpolation), hm_value_stable(boundary), hm_value_stable(shape), hm_value_stable(matrix), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(59,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_translate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *row_shift, const hmath_value *column_shift, const hmath_value *image, hmath_value **out) { + if(!out || !interpolation || !boundary || !row_shift || !column_shift || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(interpolation), hm_value_stable(boundary), hm_value_stable(row_shift), hm_value_stable(column_shift), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(60,arguments,5,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_rotate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *angle, const hmath_value *image, hmath_value **out) { + if(!out || !interpolation || !boundary || !angle || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(interpolation), hm_value_stable(boundary), hm_value_stable(angle), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(61,arguments,4,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_connected_components(hmath_context *context, const hmath_value *connectivity, const hmath_value *image, hmath_value **out) { + if(!out || !connectivity || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(connectivity), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(62,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_distance_transform(hmath_context *context, const hmath_value *spacing, const hmath_value *image, hmath_value **out) { + if(!out || !spacing || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(spacing), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(63,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_nearest(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(64,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_bilinear(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(65,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_bicubic(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(66,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_lanczos(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(67,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_axis_connected(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(68,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_fully_connected(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(69,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_convert_color(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *image, hmath_value **out) { + if(!out || !source || !destination || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(source), hm_value_stable(destination), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(70,arguments,3,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_grayscale(hmath_context *context, const hmath_value *source, const hmath_value *image, hmath_value **out) { + if(!out || !source || !image)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(source), hm_value_stable(image)}; + return hm_value_finish(temporary,hm_image_apply(71,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_srgb(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(72,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_linear_rgb(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(73,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_hsv(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(74,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_hsl(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(75,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_xyz(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(76,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_lab(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(77,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_y_cb_cr(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(temporary,hm_image_apply(78,arguments,0,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_tensor(hmath_context *context, const hmath_value *shape, const hmath_value *values, hmath_value **out) { + if(!out || !shape || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(shape), hm_value_stable(values)}; + return hm_value_finish(temporary,hm_image_apply(79,arguments,2,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_tensor_shape(hmath_context *context, const hmath_value *tensor, hmath_value **out) { + if(!out || !tensor)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(tensor)}; + return hm_value_finish(temporary,hm_image_apply(80,arguments,1,NULL,NULL,&temporary->stable),out); +} +hmath_status hmath_image_tensor_values(hmath_context *context, const hmath_value *tensor, hmath_value **out) { + if(!out || !tensor)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + void *arguments[]={hm_value_stable(tensor)}; + return hm_value_finish(temporary,hm_image_apply(81,arguments,1,NULL,NULL,&temporary->stable),out); +} diff --git a/cbits/interchange.c b/cbits/interchange.c new file mode 100644 index 0000000..d2cf6ba --- /dev/null +++ b/cbits/interchange.c @@ -0,0 +1,404 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_interchange.h" +#include "value_internal.h" +#include +extern int hm_interchange_apply(const char *,void *const *,size_t,void **); +static hmath_status invoke(hmath_context *context,const char *operation,const hmath_value *const *arguments,size_t count,hmath_value **out) { + if(!out || (count && !arguments))return hm_error(HMATH_INVALID_ARGUMENT,"NULL interchange arguments/output"); + for(size_t i=0;i(size_t)PTRDIFF_MAX/sizeof(void *))return hm_error(HMATH_OVERFLOW,"interchange argument span overflow"); + void **stable=malloc((count?count:1)*sizeof *stable); + if(!stable)return hm_error(HMATH_ALLOCATION_FAILED,"interchange arguments allocation failed"); + for(size_t i=0;istable); + free(stable); + return hm_value_finish(result,code,out); +} +hmath_status hmath_interchange_value_big_endian(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.BigEndian",arguments,0,out); +} +hmath_status hmath_interchange_value_bool8(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.Bool8",arguments,0,out); +} +hmath_status hmath_interchange_value_c128(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.C128",arguments,0,out); +} +hmath_status hmath_interchange_value_c64(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.C64",arguments,0,out); +} +hmath_status hmath_interchange_value_c_order(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.COrder",arguments,0,out); +} +hmath_status hmath_interchange_value_f32(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.F32",arguments,0,out); +} +hmath_status hmath_interchange_value_f64(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.F64",arguments,0,out); +} +hmath_status hmath_interchange_value_f_order(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.FOrder",arguments,0,out); +} +hmath_status hmath_interchange_value_i16(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.I16",arguments,0,out); +} +hmath_status hmath_interchange_value_i32(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.I32",arguments,0,out); +} +hmath_status hmath_interchange_value_i64(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.I64",arguments,0,out); +} +hmath_status hmath_interchange_value_i8(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.I8",arguments,0,out); +} +hmath_status hmath_interchange_value_interchange_io_error(hmath_context *context, const hmath_value *message, hmath_value **out) { + const hmath_value *arguments[]={message}; + return invoke(context,"HMath.Interchange.Array.InterchangeIOError",arguments,1,out); +} +hmath_status hmath_interchange_value_invalid_data(hmath_context *context, const hmath_value *message, hmath_value **out) { + const hmath_value *arguments[]={message}; + return invoke(context,"HMath.Interchange.Array.InvalidData",arguments,1,out); +} +hmath_status hmath_interchange_value_limit_exceeded(hmath_context *context, const hmath_value *message, hmath_value **out) { + const hmath_value *arguments[]={message}; + return invoke(context,"HMath.Interchange.Array.LimitExceeded",arguments,1,out); +} +hmath_status hmath_interchange_value_limits(hmath_context *context, const hmath_value *max_bytes, const hmath_value *max_elements, const hmath_value *max_rank, const hmath_value *max_metadata, const hmath_value *max_archive_entries, hmath_value **out) { + const hmath_value *arguments[]={max_bytes,max_elements,max_rank,max_metadata,max_archive_entries}; + return invoke(context,"HMath.Interchange.Array.Limits",arguments,5,out); +} +hmath_status hmath_interchange_value_little_endian(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.LittleEndian",arguments,0,out); +} +hmath_status hmath_interchange_value_u16(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.U16",arguments,0,out); +} +hmath_status hmath_interchange_value_u32(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.U32",arguments,0,out); +} +hmath_status hmath_interchange_value_u64(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.U64",arguments,0,out); +} +hmath_status hmath_interchange_value_u8(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.U8",arguments,0,out); +} +hmath_status hmath_interchange_value_unsupported(hmath_context *context, const hmath_value *message, hmath_value **out) { + const hmath_value *arguments[]={message}; + return invoke(context,"HMath.Interchange.Array.Unsupported",arguments,1,out); +} +hmath_status hmath_interchange_value_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *sh, const hmath_value *st, const hmath_value *off, const hmath_value *bs, hmath_value **out) { + const hmath_value *arguments[]={lim,dt,en,sh,st,off,bs}; + return invoke(context,"HMath.Interchange.Array.array",arguments,7,out); +} +hmath_status hmath_interchange_value_array_bytes(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayBytes",arguments,1,out); +} +hmath_status hmath_interchange_value_array_d_type(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayDType",arguments,1,out); +} +hmath_status hmath_interchange_value_array_endian(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayEndian",arguments,1,out); +} +hmath_status hmath_interchange_value_array_metadata(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayMetadata",arguments,1,out); +} +hmath_status hmath_interchange_value_array_offset(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayOffset",arguments,1,out); +} +hmath_status hmath_interchange_value_array_shape(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayShape",arguments,1,out); +} +hmath_status hmath_interchange_value_array_strides(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.arrayStrides",arguments,1,out); +} +hmath_status hmath_interchange_value_contiguous_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *order, const hmath_value *sh, const hmath_value *bs, hmath_value **out) { + const hmath_value *arguments[]={lim,dt,en,order,sh,bs}; + return invoke(context,"HMath.Interchange.Array.contiguousArray",arguments,6,out); +} +hmath_status hmath_interchange_value_default_limits(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Array.defaultLimits",arguments,0,out); +} +hmath_status hmath_interchange_value_dense_strides(hmath_context *context, const hmath_value *c_order, const hmath_value *w, const hmath_value *sh, hmath_value **out) { + const hmath_value *arguments[]={c_order,w,sh}; + return invoke(context,"HMath.Interchange.Array.denseStrides",arguments,3,out); +} +hmath_status hmath_interchange_value_element_bytes(hmath_context *context, const hmath_value *dt, hmath_value **out) { + const hmath_value *arguments[]={dt}; + return invoke(context,"HMath.Interchange.Array.elementBytes",arguments,1,out); +} +hmath_status hmath_interchange_value_element_count(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.elementCount",arguments,1,out); +} +hmath_status hmath_interchange_value_element_type(hmath_context *context, const hmath_value *prototype, hmath_value **out) { + const hmath_value *arguments[]={prototype}; + return invoke(context,"HMath.Interchange.Array.elementType",arguments,1,out); +} +hmath_status hmath_interchange_value_from_matrix(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3}; + return invoke(context,"HMath.Interchange.Array.fromMatrix",arguments,3,out); +} +hmath_status hmath_interchange_value_from_tensor(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3}; + return invoke(context,"HMath.Interchange.Array.fromTensor",arguments,3,out); +} +hmath_status hmath_interchange_value_from_values(hmath_context *context, const hmath_value *prototype, const hmath_value *limits, const hmath_value *endian, const hmath_value *shape, const hmath_value *values, hmath_value **out) { + const hmath_value *arguments[]={prototype,limits,endian,shape,values}; + return invoke(context,"HMath.Interchange.Array.fromValues",arguments,5,out); +} +hmath_status hmath_interchange_value_get_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, hmath_value **out) { + const hmath_value *arguments[]={prototype,endian}; + return invoke(context,"HMath.Interchange.Array.getElement",arguments,2,out); +} +hmath_status hmath_interchange_value_max_archive_entries(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.maxArchiveEntries",arguments,1,out); +} +hmath_status hmath_interchange_value_max_bytes(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.maxBytes",arguments,1,out); +} +hmath_status hmath_interchange_value_max_elements(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.maxElements",arguments,1,out); +} +hmath_status hmath_interchange_value_max_metadata(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.maxMetadata",arguments,1,out); +} +hmath_status hmath_interchange_value_max_rank(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Array.maxRank",arguments,1,out); +} +hmath_status hmath_interchange_value_put_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={prototype,endian,value}; + return invoke(context,"HMath.Interchange.Array.putElement",arguments,3,out); +} +hmath_status hmath_interchange_value_raw_decode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3,value4,value5,value6}; + return invoke(context,"HMath.Interchange.Array.rawDecode",arguments,6,out); +} +hmath_status hmath_interchange_value_raw_encode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3,value4}; + return invoke(context,"HMath.Interchange.Array.rawEncode",arguments,4,out); +} +hmath_status hmath_interchange_value_repack(hmath_context *context, const hmath_value *lim, const hmath_value *en, const hmath_value *order, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,en,order,a}; + return invoke(context,"HMath.Interchange.Array.repack",arguments,4,out); +} +hmath_status hmath_interchange_value_to_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out) { + const hmath_value *arguments[]={prototype,array}; + return invoke(context,"HMath.Interchange.Array.toMatrix",arguments,2,out); +} +hmath_status hmath_interchange_value_to_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out) { + const hmath_value *arguments[]={prototype,array}; + return invoke(context,"HMath.Interchange.Array.toTensor",arguments,2,out); +} +hmath_status hmath_interchange_value_to_values(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out) { + const hmath_value *arguments[]={prototype,array}; + return invoke(context,"HMath.Interchange.Array.toValues",arguments,2,out); +} +hmath_status hmath_interchange_value_validate_shape(hmath_context *context, const hmath_value *lim, const hmath_value *sh, hmath_value **out) { + const hmath_value *arguments[]={lim,sh}; + return invoke(context,"HMath.Interchange.Array.validateShape",arguments,2,out); +} +hmath_status hmath_interchange_value_with_metadata(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3}; + return invoke(context,"HMath.Interchange.Array.withMetadata",arguments,3,out); +} +hmath_status hmath_interchange_value_crc32(hmath_context *context, const hmath_value *value, hmath_value **out) { + const hmath_value *arguments[]={value}; + return invoke(context,"HMath.Interchange.Binary.crc32",arguments,1,out); +} +hmath_status hmath_interchange_value_decode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out) { + const hmath_value *arguments[]={lim,input}; + return invoke(context,"HMath.Interchange.Binary.decodeBinary",arguments,2,out); +} +hmath_status hmath_interchange_value_encode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,a}; + return invoke(context,"HMath.Interchange.Binary.encodeBinary",arguments,2,out); +} +hmath_status hmath_interchange_value_gzip(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Compression.Gzip",arguments,0,out); +} +hmath_status hmath_interchange_value_raw_deflate(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Compression.RawDeflate",arguments,0,out); +} +hmath_status hmath_interchange_value_zlib(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Compression.Zlib",arguments,0,out); +} +hmath_status hmath_interchange_value_compress(hmath_context *context, const hmath_value *lim, const hmath_value *wrapper, const hmath_value *input, hmath_value **out) { + const hmath_value *arguments[]={lim,wrapper,input}; + return invoke(context,"HMath.Interchange.Compression.compress",arguments,3,out); +} +hmath_status hmath_interchange_value_compression_available(hmath_context *context, hmath_value **out) { + const hmath_value *arguments[]={NULL}; + return invoke(context,"HMath.Interchange.Compression.compressionAvailable",arguments,0,out); +} +hmath_status hmath_interchange_value_decompress(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3,value4}; + return invoke(context,"HMath.Interchange.Compression.decompress",arguments,4,out); +} +hmath_status hmath_interchange_value_raw_spec(hmath_context *context, const hmath_value *dtype, const hmath_value *endian, const hmath_value *order, const hmath_value *shape, hmath_value **out) { + const hmath_value *arguments[]={dtype,endian,order,shape}; + return invoke(context,"HMath.Interchange.IO.RawSpec",arguments,4,out); +} +hmath_status hmath_interchange_value_mapped_read_bytes(hmath_context *context, const hmath_value *mapping, const hmath_value *offset, const hmath_value *count, hmath_value **out) { + const hmath_value *arguments[]={mapping,offset,count}; + return invoke(context,"HMath.Interchange.IO.mappedReadBytes",arguments,3,out); +} +hmath_status hmath_interchange_value_mapped_shape(hmath_context *context, const hmath_value *mapping, hmath_value **out) { + const hmath_value *arguments[]={mapping}; + return invoke(context,"HMath.Interchange.IO.mappedShape",arguments,1,out); +} +hmath_status hmath_interchange_value_mapped_value(hmath_context *context, const hmath_value *prototype, const hmath_value *mapping, const hmath_value *indices, hmath_value **out) { + const hmath_value *arguments[]={prototype,mapping,indices}; + return invoke(context,"HMath.Interchange.IO.mappedValue",arguments,3,out); +} +hmath_status hmath_interchange_value_read_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *decode, const hmath_value *path, hmath_value **out) { + const hmath_value *arguments[]={lim,decode,path}; + return invoke(context,"HMath.Interchange.IO.readArrayFile",arguments,3,out); +} +hmath_status hmath_interchange_value_read_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3,value4,value5}; + return invoke(context,"HMath.Interchange.IO.readRawChunks",arguments,5,out); +} +hmath_status hmath_interchange_value_with_mapped_array(hmath_context *context, const hmath_value *limits, const hmath_value *specification, const hmath_value *path, const hmath_value *callback, hmath_value **out) { + const hmath_value *arguments[]={limits,specification,path,callback}; + return invoke(context,"HMath.Interchange.IO.withMappedArray",arguments,4,out); +} +hmath_status hmath_interchange_value_write_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *encode, const hmath_value *path, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,encode,path,a}; + return invoke(context,"HMath.Interchange.IO.writeArrayFile",arguments,4,out); +} +hmath_status hmath_interchange_value_write_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + const hmath_value *arguments[]={value,value2,value3,value4,value5}; + return invoke(context,"HMath.Interchange.IO.writeRawChunks",arguments,5,out); +} +hmath_status hmath_interchange_value_decode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out) { + const hmath_value *arguments[]={lim,input}; + return invoke(context,"HMath.Interchange.Numpy.decodeNpy",arguments,2,out); +} +hmath_status hmath_interchange_value_decode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out) { + const hmath_value *arguments[]={lim,input}; + return invoke(context,"HMath.Interchange.Numpy.decodeNpz",arguments,2,out); +} +hmath_status hmath_interchange_value_encode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *order, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,order,a}; + return invoke(context,"HMath.Interchange.Numpy.encodeNpy",arguments,3,out); +} +hmath_status hmath_interchange_value_encode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *compressed, const hmath_value *arrays, hmath_value **out) { + const hmath_value *arguments[]={lim,compressed,arrays}; + return invoke(context,"HMath.Interchange.Numpy.encodeNpz",arguments,3,out); +} +hmath_status hmath_interchange_value_decode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *dt, const hmath_value *bs, hmath_value **out) { + const hmath_value *arguments[]={lim,separator,dt,bs}; + return invoke(context,"HMath.Interchange.Text.decodeDelimited",arguments,4,out); +} +hmath_status hmath_interchange_value_decode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out) { + const hmath_value *arguments[]={lim,bs}; + return invoke(context,"HMath.Interchange.Text.decodeMatrixMarket",arguments,2,out); +} +hmath_status hmath_interchange_value_decode_text(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out) { + const hmath_value *arguments[]={lim,bs}; + return invoke(context,"HMath.Interchange.Text.decodeText",arguments,2,out); +} +hmath_status hmath_interchange_value_encode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,separator,a}; + return invoke(context,"HMath.Interchange.Text.encodeDelimited",arguments,3,out); +} +hmath_status hmath_interchange_value_encode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,a}; + return invoke(context,"HMath.Interchange.Text.encodeMatrixMarket",arguments,2,out); +} +hmath_status hmath_interchange_value_encode_text(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={lim,a}; + return invoke(context,"HMath.Interchange.Text.encodeText",arguments,2,out); +} +hmath_status hmath_interchange_value_bounded_int(hmath_context *context, const hmath_value *name, const hmath_value *upper, const hmath_value *x, hmath_value **out) { + const hmath_value *arguments[]={name,upper,x}; + return invoke(context,"HMath.Interchange.Array.boundedInt",arguments,3,out); +} +hmath_status hmath_interchange_value_byte_offsets(hmath_context *context, const hmath_value *a, hmath_value **out) { + const hmath_value *arguments[]={a}; + return invoke(context,"HMath.Interchange.Array.byteOffsets",arguments,1,out); +} +hmath_status hmath_interchange_value_check_limits(hmath_context *context, const hmath_value *lim, hmath_value **out) { + const hmath_value *arguments[]={lim}; + return invoke(context,"HMath.Interchange.Array.checkLimits",arguments,1,out); +} +hmath_status hmath_interchange_value_guard_i(hmath_context *context, const hmath_value *p, const hmath_value *e, hmath_value **out) { + const hmath_value *arguments[]={p,e}; + return invoke(context,"HMath.Interchange.Array.guardI",arguments,2,out); +} +hmath_status hmath_interchange_value_run_decoder(hmath_context *context, const hmath_value *parser, const hmath_value *data, hmath_value **out) { + const hmath_value *arguments[]={parser,data}; + return invoke(context,"HMath.Interchange.Binary.runDecoder",arguments,2,out); +} +hmath_status hmath_interchange_value_dtype_code(hmath_context *context, const hmath_value *dtype, hmath_value **out) { + const hmath_value *arguments[]={dtype}; + return invoke(context,"__dtype_code",arguments,1,out); +} +hmath_status hmath_interchange_value_error_fields(hmath_context *context, const hmath_value *error, hmath_value **out) { + const hmath_value *arguments[]={error}; + return invoke(context,"__error_fields",arguments,1,out); +} +hmath_status hmath_interchange_value_put_bytes(hmath_context *context, const hmath_value *program, hmath_value **out) { + const hmath_value *arguments[]={program}; + return invoke(context,"__put_bytes",arguments,1,out); +} +hmath_status hmath_interchange_value_open_handle(hmath_context *context, const hmath_value *path, const hmath_value *mode, hmath_value **out) { + const hmath_value *arguments[]={path,mode}; + return invoke(context,"__open_handle",arguments,2,out); +} +hmath_status hmath_interchange_value_close_handle(hmath_context *context, const hmath_value *handle, hmath_value **out) { + const hmath_value *arguments[]={handle}; + return invoke(context,"__close_handle",arguments,1,out); +} +hmath_status hmath_interchange_value_seek_handle(hmath_context *context, const hmath_value *handle, const hmath_value *whence, const hmath_value *offset, hmath_value **out) { + const hmath_value *arguments[]={handle,whence,offset}; + return invoke(context,"__seek_handle",arguments,3,out); +} +hmath_status hmath_interchange_value_tell_handle(hmath_context *context, const hmath_value *handle, hmath_value **out) { + const hmath_value *arguments[]={handle}; + return invoke(context,"__tell_handle",arguments,1,out); +} +hmath_status hmath_interchange_value_flush_handle(hmath_context *context, const hmath_value *handle, hmath_value **out) { + const hmath_value *arguments[]={handle}; + return invoke(context,"__flush_handle",arguments,1,out); +} +hmath_status hmath_interchange_value_equal_array(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + const hmath_value *arguments[]={left,right}; + return invoke(context,"__equal_array",arguments,2,out); +} diff --git a/cbits/linear.c b/cbits/linear.c new file mode 100644 index 0000000..9868787 --- /dev/null +++ b/cbits/linear.c @@ -0,0 +1,1656 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_linear_bindings.py. */ +#include "hmath_linear.h" +#include "value_internal.h" +#include "matrix_internal.h" +#include +extern int hm_linear_apply(int opcode,void *prototype,void *const *args,size_t count,void **out); +extern int hm_linear_callback(hmath_linear_callback_fn callback,void *userdata,void **out); +extern int hm_linear_clone(void *value,void **out); +extern int hm_linear_legacy(void *value,int *kind,void **out); +extern void hm_dense_free(void *value); +hmath_status hmath_linear_vector_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out) { + if (!out || !prototype || !values1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1)}; + return hm_value_finish(result,hm_linear_apply(0,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(1,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_dimension(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(2,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_fixed_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !index1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(3,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_fixed_values(hmath_context *context, const hmath_value *prototype, const hmath_value *fixed_vector1, hmath_value **out) { + if (!out || !prototype || !fixed_vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(fixed_vector1)}; + return hm_value_finish(result,hm_linear_apply(4,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_sparse_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !index1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(5,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_sparse_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_vector1, hmath_value **out) { + if (!out || !prototype || !sparse_vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_vector1)}; + return hm_value_finish(result,hm_linear_apply(6,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_slice(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *vector3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !vector3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(vector3)}; + return hm_value_finish(result,hm_linear_apply(7,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_concat(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out) { + if (!out || !prototype || !values1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1)}; + return hm_value_finish(result,hm_linear_apply(8,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_add(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(9,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(10,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_scale(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(11,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_vector_dot(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(12,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_cross(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(13,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_outer(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(14,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_triple(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2 || !vector3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2),hm_value_stable(vector3)}; + return hm_value_finish(result,hm_linear_apply(15,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_vector_norm0(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(16,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(17,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_norm2(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(18,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(19,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_norm_p(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(20,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_normalize_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out) { + if (!out || !prototype || !vector1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1)}; + return hm_value_finish(result,hm_linear_apply(21,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_vector_project(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(22,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_reflect(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(23,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_refract(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out) { + if (!out || !prototype || !scalar1 || !vector2 || !vector3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(vector2),hm_value_stable(vector3)}; + return hm_value_finish(result,hm_linear_apply(24,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_vector_distance(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(25,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_cosine_similarity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(26,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_angle(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out) { + if (!out || !prototype || !vector1 || !vector2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(vector1),hm_value_stable(vector2)}; + return hm_value_finish(result,hm_linear_apply(27,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_vector_gram_schmidt(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(28,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_generate_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *function3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !function3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(function3)}; + return hm_value_finish(result,hm_linear_apply(29,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_triangular_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !flag1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(flag1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(30,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_symmetric_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(31,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_hermitian_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(32,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_permutation_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out) { + if (!out || !prototype || !values1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1)}; + return hm_value_finish(result,hm_linear_apply(33,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_block_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out) { + if (!out || !prototype || !values1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1)}; + return hm_value_finish(result,hm_linear_apply(34,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_banded_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(35,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_conjugate_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(36,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_zip_matrix_with(hmath_context *context, const hmath_value *prototype, const hmath_value *function1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !prototype || !function1 || !matrix2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(function1),hm_value_stable(matrix2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(37,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_batched_multiply(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !values1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(38,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(39,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_khatri_rao(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(40,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_power(hmath_context *context, const hmath_value *prototype, const hmath_value *integer1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !integer1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(integer1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(41,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_trace(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(42,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(43,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(44,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_frobenius_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(45,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_spectral_norm(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(46,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_rank(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(47,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(48,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_condition_number(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(49,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_column_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(50,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_row_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(51,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_null_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(52,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_change_coordinates(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !matrix1 || !matrix2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(53,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_exp(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(54,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_log(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(55,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_sqrt(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(56,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_polar(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(57,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_complex_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !double1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(58,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_sqrt_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !double1 || !index2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(index2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(59,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_matrix_advanced_matrix_log_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !double1 || !index2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(double1),hm_value_stable(index2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(60,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_decomposition_gaussian_elimination(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(61,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_decomposition_gauss_jordan(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(62,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_decomposition_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(63,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_ldlt(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(64,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_givens_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(65,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_bidiagonalize(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(66,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_tridiagonalize(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(67,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_power_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(68,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_decomposition_inverse_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *matrix4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !scalar3 || !matrix4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(scalar3),hm_value_stable(matrix4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(69,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_decomposition_rayleigh_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(70,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_decomposition_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(71,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_decomposition_lanczos(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(72,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_decomposition_qr_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !prototype || !scalar1 || !index2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(index2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(73,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_decomposition_jordan_chains(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !scalar1 || !matrix2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(matrix2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(74,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_decomposition_jordan_form(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out) { + if (!out || !matrix1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(75,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_decomposition_bidiagonal_u(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out) { + if (!out || !prototype || !bidiagonal1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(bidiagonal1)}; + return hm_value_finish(result,hm_linear_apply(76,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_bidiagonal_b(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out) { + if (!out || !prototype || !bidiagonal1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(bidiagonal1)}; + return hm_value_finish(result,hm_linear_apply(77,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_bidiagonal_v(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out) { + if (!out || !prototype || !bidiagonal1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(bidiagonal1)}; + return hm_value_finish(result,hm_linear_apply(78,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_new_bidiagonal(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !prototype || !matrix1 || !matrix2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(79,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_decomposition_iteration_value(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out) { + if (!out || !prototype || !iteration1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iteration1)}; + return hm_value_finish(result,hm_linear_apply(80,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_iteration_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out) { + if (!out || !prototype || !iteration1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iteration1)}; + return hm_value_finish(result,hm_linear_apply(81,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_iteration_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out) { + if (!out || !prototype || !iteration1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iteration1)}; + return hm_value_finish(result,hm_linear_apply(82,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_iteration_count(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out) { + if (!out || !prototype || !iteration1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iteration1)}; + return hm_value_finish(result,hm_linear_apply(83,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_new_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !values2 || !scalar3 || !index4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(values2),hm_value_stable(scalar3),hm_value_stable(index4)}; + return hm_value_finish(result,hm_linear_apply(84,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_decomposition_arnoldi_basis(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out) { + if (!out || !prototype || !arnoldi1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(arnoldi1)}; + return hm_value_finish(result,hm_linear_apply(85,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_arnoldi_hessenberg(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out) { + if (!out || !prototype || !arnoldi1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(arnoldi1)}; + return hm_value_finish(result,hm_linear_apply(86,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_decomposition_new_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(87,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_iterative_default_iterative_options(hmath_context *context, const hmath_value *prototype, hmath_value **out) { + if (!out || !prototype) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(88,hm_value_stable(prototype),NULL,0,&result->stable),out); +} +hmath_status hmath_linear_iterative_apply_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *preconditioner1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !preconditioner1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(preconditioner1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(89,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_iterative_identity_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, hmath_value **out) { + if (!out || !prototype || !index1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1)}; + return hm_value_finish(result,hm_linear_apply(90,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(91,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_block_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !values1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(92,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_iterative_ilu0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(93,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_ic0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(94,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_conjugate_gradient(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(95,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_preconditioned_cg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *preconditioner2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !preconditioner2 || !matrix3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(preconditioner2),hm_value_stable(matrix3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(96,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_iterative_gmres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !index2 || !matrix3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(index2),hm_value_stable(matrix3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(97,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_iterative_minres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(98,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_bicg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(99,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_bicgstab(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(100,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_lsqr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(101,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_lsmr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(102,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_jacobi_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(103,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_gauss_seidel_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(104,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_sor_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *scalar2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !scalar2 || !matrix3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(scalar2),hm_value_stable(matrix3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(105,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_iterative_iterative_refinement(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !iterative_options1 || !matrix2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1),hm_value_stable(matrix2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(106,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_iterative_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out) { + if (!out || !prototype || !iterative_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1)}; + return hm_value_finish(result,hm_linear_apply(107,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out) { + if (!out || !prototype || !iterative_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1)}; + return hm_value_finish(result,hm_linear_apply(108,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_maximum_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out) { + if (!out || !prototype || !iterative_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_options1)}; + return hm_value_finish(result,hm_linear_apply(109,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_new_iterative_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, hmath_value **out) { + if (!out || !prototype || !scalar1 || !scalar2 || !index3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(scalar2),hm_value_stable(index3)}; + return hm_value_finish(result,hm_linear_apply(110,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_iterative_iterative_solution(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out) { + if (!out || !prototype || !iterative_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_result1)}; + return hm_value_finish(result,hm_linear_apply(111,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_iterative_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out) { + if (!out || !prototype || !iterative_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_result1)}; + return hm_value_finish(result,hm_linear_apply(112,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_iterative_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out) { + if (!out || !prototype || !iterative_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_result1)}; + return hm_value_finish(result,hm_linear_apply(113,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_iterative_normal_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out) { + if (!out || !prototype || !iterative_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterative_result1)}; + return hm_value_finish(result,hm_linear_apply(114,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_iterative_new_iterative_result(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *scalar4, hmath_value **out) { + if (!out || !prototype || !values1 || !index2 || !scalar3 || !scalar4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(index2),hm_value_stable(scalar3),hm_value_stable(scalar4)}; + return hm_value_finish(result,hm_linear_apply(115,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_lapack_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(116,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_full_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(117,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_truncated_svd(hmath_context *context, const hmath_value *index1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !index1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(118,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_randomized_svd(hmath_context *context, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *integer4, const hmath_value *matrix5, hmath_value **out) { + if (!out || !index1 || !index2 || !index3 || !integer4 || !matrix5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(index3),hm_value_stable(integer4),hm_value_stable(matrix5)}; + return hm_value_finish(result,hm_linear_apply(119,NULL,args,5,&result->stable),out); +} +hmath_status hmath_linear_lapack_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(120,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(121,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_generalized_eigen(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(122,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_schur(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(123,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(124,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_hessenberg(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(125,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_balance(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(126,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_complex_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(127,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_complex_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(128,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_svd_u(hmath_context *context, const hmath_value *svd1, hmath_value **out) { + if (!out || !svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(svd1)}; + return hm_value_finish(result,hm_linear_apply(129,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_singular_values(hmath_context *context, const hmath_value *svd1, hmath_value **out) { + if (!out || !svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(svd1)}; + return hm_value_finish(result,hm_linear_apply(130,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_svd_vt(hmath_context *context, const hmath_value *svd1, hmath_value **out) { + if (!out || !svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(svd1)}; + return hm_value_finish(result,hm_linear_apply(131,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !matrix1 || !values2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(values2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(132,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_lapack_eigenvalues(hmath_context *context, const hmath_value *eigen1, hmath_value **out) { + if (!out || !eigen1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(eigen1)}; + return hm_value_finish(result,hm_linear_apply(133,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_eigenvectors(hmath_context *context, const hmath_value *eigen1, hmath_value **out) { + if (!out || !eigen1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(eigen1)}; + return hm_value_finish(result,hm_linear_apply(134,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !values1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(135,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_eigen_alpha(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out) { + if (!out || !generalized_eigen1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(generalized_eigen1)}; + return hm_value_finish(result,hm_linear_apply(136,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_eigen_beta(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out) { + if (!out || !generalized_eigen1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(generalized_eigen1)}; + return hm_value_finish(result,hm_linear_apply(137,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_generalized_eigenvectors(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out) { + if (!out || !generalized_eigen1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(generalized_eigen1)}; + return hm_value_finish(result,hm_linear_apply(138,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_generalized_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !values1 || !values2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(values2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(139,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_lapack_schur_q(hmath_context *context, const hmath_value *schur1, hmath_value **out) { + if (!out || !schur1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(schur1)}; + return hm_value_finish(result,hm_linear_apply(140,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_schur_t(hmath_context *context, const hmath_value *schur1, hmath_value **out) { + if (!out || !schur1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(schur1)}; + return hm_value_finish(result,hm_linear_apply(141,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_schur_eigenvalues(hmath_context *context, const hmath_value *schur1, hmath_value **out) { + if (!out || !schur1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(schur1)}; + return hm_value_finish(result,hm_linear_apply(142,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_schur(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out) { + if (!out || !matrix1 || !matrix2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(143,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_q(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(144,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_z(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(145,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_s(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(146,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_t(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(147,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_alpha(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(148,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_qz_beta(hmath_context *context, const hmath_value *qz1, hmath_value **out) { + if (!out || !qz1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(qz1)}; + return hm_value_finish(result,hm_linear_apply(149,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *values6, hmath_value **out) { + if (!out || !matrix1 || !matrix2 || !matrix3 || !matrix4 || !values5 || !values6) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2),hm_value_stable(matrix3),hm_value_stable(matrix4),hm_value_stable(values5),hm_value_stable(values6)}; + return hm_value_finish(result,hm_linear_apply(150,NULL,args,6,&result->stable),out); +} +hmath_status hmath_linear_lapack_hessenberg_q(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out) { + if (!out || !hessenberg1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(hessenberg1)}; + return hm_value_finish(result,hm_linear_apply(151,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_hessenberg_h(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out) { + if (!out || !hessenberg1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(hessenberg1)}; + return hm_value_finish(result,hm_linear_apply(152,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_hessenberg(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !matrix1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(153,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_balanced_matrix(hmath_context *context, const hmath_value *balance1, hmath_value **out) { + if (!out || !balance1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(balance1)}; + return hm_value_finish(result,hm_linear_apply(154,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_balance_scales(hmath_context *context, const hmath_value *balance1, hmath_value **out) { + if (!out || !balance1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(balance1)}; + return hm_value_finish(result,hm_linear_apply(155,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_balance(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out) { + if (!out || !matrix1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(156,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_lapack_complex_u(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out) { + if (!out || !complex_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(complex_svd1)}; + return hm_value_finish(result,hm_linear_apply(157,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_complex_singular_values(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out) { + if (!out || !complex_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(complex_svd1)}; + return hm_value_finish(result,hm_linear_apply(158,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_complex_vt(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out) { + if (!out || !complex_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(complex_svd1)}; + return hm_value_finish(result,hm_linear_apply(159,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_lapack_new_complex_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out) { + if (!out || !matrix1 || !values2 || !matrix3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1),hm_value_stable(values2),hm_value_stable(matrix3)}; + return hm_value_finish(result,hm_linear_apply(160,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(161,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(162,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(163,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_nonzeros(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(164,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_from_format(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_format1, hmath_value **out) { + if (!out || !prototype || !sparse_format1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_format1)}; + return hm_value_finish(result,hm_linear_apply(165,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(166,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(167,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(168,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(169,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *sparse3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !sparse3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(sparse3)}; + return hm_value_finish(result,hm_linear_apply(170,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_to_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(171,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_to_dense(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(172,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_dense_to_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out) { + if (!out || !prototype || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(173,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(174,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_add(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(175,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(176,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_spmv(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(177,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_spmm(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(178,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(179,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_triangular_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !flag1 || !sparse2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(flag1),hm_value_stable(sparse2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(180,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_diagonal_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !sparse1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(181,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_lu_lower(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out) { + if (!out || !prototype || !sparse_lu1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_lu1)}; + return hm_value_finish(result,hm_linear_apply(182,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_lu_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out) { + if (!out || !prototype || !sparse_lu1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_lu1)}; + return hm_value_finish(result,hm_linear_apply(183,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_lu_permutation(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out) { + if (!out || !prototype || !sparse_lu1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_lu1)}; + return hm_value_finish(result,hm_linear_apply(184,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !scalar1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(185,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_solve_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !sparse_lu1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_lu1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(186,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(187,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_qr_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, hmath_value **out) { + if (!out || !prototype || !sparse_qr1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_qr1)}; + return hm_value_finish(result,hm_linear_apply(188,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(189,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_qr_apply_qt(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !sparse_qr1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_qr1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(190,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_graph(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out) { + if (!out || !prototype || !sparse1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse1)}; + return hm_value_finish(result,hm_linear_apply(191,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_storage_bytes(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !prototype || !index1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(192,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !values1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(193,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_tensor_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out) { + if (!out || !prototype || !sparse_tensor1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_tensor1)}; + return hm_value_finish(result,hm_linear_apply(194,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_tensor_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out) { + if (!out || !prototype || !sparse_tensor1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_tensor1)}; + return hm_value_finish(result,hm_linear_apply(195,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_tensor_lookup(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, const hmath_value *values2, hmath_value **out) { + if (!out || !prototype || !sparse_tensor1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_tensor1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(196,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_eigen_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !integer1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(integer1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(197,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_sparse_svd_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out) { + if (!out || !integer1 || !sparse2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(integer1),hm_value_stable(sparse2)}; + return hm_value_finish(result,hm_linear_apply(198,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(199,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(200,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(201,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(202,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *values5, const hmath_value *values6, const hmath_value *values7, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !index3 || !index4 || !values5 || !values6 || !values7) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(index3),hm_value_stable(index4),hm_value_stable(values5),hm_value_stable(values6),hm_value_stable(values7)}; + return hm_value_finish(result,hm_linear_apply(203,hm_value_stable(prototype),args,7,&result->stable),out); +} +hmath_status hmath_linear_sparse_new_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !index1 || !index2 || !index3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(index1),hm_value_stable(index2),hm_value_stable(index3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(204,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_default_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, hmath_value **out) { + if (!out || !prototype) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(205,hm_value_stable(prototype),NULL,0,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_dominant_eigen(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1 || !sparse2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1),hm_value_stable(sparse2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(206,hm_value_stable(prototype),args,3,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_truncated_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *index2, const hmath_value *integer3, const hmath_value *sparse4, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1 || !index2 || !integer3 || !sparse4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1),hm_value_stable(index2),hm_value_stable(integer3),hm_value_stable(sparse4)}; + return hm_value_finish(result,hm_linear_apply(207,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1)}; + return hm_value_finish(result,hm_linear_apply(208,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1)}; + return hm_value_finish(result,hm_linear_apply(209,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_iteration_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1)}; + return hm_value_finish(result,hm_linear_apply(210,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_workspace_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out) { + if (!out || !prototype || !sparse_spectral_options1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_spectral_options1)}; + return hm_value_finish(result,hm_linear_apply(211,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_new_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, const hmath_value *integer4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !scalar2 || !index3 || !integer4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(scalar2),hm_value_stable(index3),hm_value_stable(integer4)}; + return hm_value_finish(result,hm_linear_apply(212,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_eigenvalue(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out) { + if (!out || !prototype || !sparse_eigen_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_eigen_result1)}; + return hm_value_finish(result,hm_linear_apply(213,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_eigenvector(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out) { + if (!out || !prototype || !sparse_eigen_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_eigen_result1)}; + return hm_value_finish(result,hm_linear_apply(214,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_eigen_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out) { + if (!out || !prototype || !sparse_eigen_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_eigen_result1)}; + return hm_value_finish(result,hm_linear_apply(215,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_eigen_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out) { + if (!out || !prototype || !sparse_eigen_result1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_eigen_result1)}; + return hm_value_finish(result,hm_linear_apply(216,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_new_sparse_eigen_result(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out) { + if (!out || !prototype || !scalar1 || !values2 || !scalar3 || !index4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar1),hm_value_stable(values2),hm_value_stable(scalar3),hm_value_stable(index4)}; + return hm_value_finish(result,hm_linear_apply(217,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_singular_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out) { + if (!out || !prototype || !sparse_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_svd1)}; + return hm_value_finish(result,hm_linear_apply(218,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_left_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out) { + if (!out || !prototype || !sparse_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_svd1)}; + return hm_value_finish(result,hm_linear_apply(219,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_right_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out) { + if (!out || !prototype || !sparse_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_svd1)}; + return hm_value_finish(result,hm_linear_apply(220,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_singular_residuals(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out) { + if (!out || !prototype || !sparse_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_svd1)}; + return hm_value_finish(result,hm_linear_apply(221,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_sparse_singular_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out) { + if (!out || !prototype || !sparse_svd1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(sparse_svd1)}; + return hm_value_finish(result,hm_linear_apply(222,hm_value_stable(prototype),args,1,&result->stable),out); +} +hmath_status hmath_linear_sparse_spectral_new_sparse_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out) { + if (!out || !prototype || !values1 || !values2 || !values3 || !values4 || !values5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(values1),hm_value_stable(values2),hm_value_stable(values3),hm_value_stable(values4),hm_value_stable(values5)}; + return hm_value_finish(result,hm_linear_apply(223,hm_value_stable(prototype),args,5,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_info(hmath_context *context, const hmath_value *backend1, hmath_value **out) { + if (!out || !backend1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1)}; + return hm_value_finish(result,hm_linear_apply(224,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_pure_backend(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(225,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_lapack_available(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(226,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_select_backend(hmath_context *context, const hmath_value *backend_request1, hmath_value **out) { + if (!out || !backend_request1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend_request1)}; + return hm_value_finish(result,hm_linear_apply(227,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_set_backend_threads(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, hmath_value **out) { + if (!out || !backend1 || !index2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(index2)}; + return hm_value_finish(result,hm_linear_apply(228,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_lapack_status(hmath_context *context, const hmath_value *text1, const hmath_value *index2, hmath_value **out) { + if (!out || !text1 || !index2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(text1),hm_value_stable(index2)}; + return hm_value_finish(result,hm_linear_apply(229,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_matrix_from_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, hmath_value **out) { + if (!out || !prototype || !backend_layout1 || !index2 || !index3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend_layout1),hm_value_stable(index2),hm_value_stable(index3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(230,hm_value_stable(prototype),args,4,&result->stable),out); +} +hmath_status hmath_linear_backend_matrix_to_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !prototype || !backend_layout1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend_layout1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(231,hm_value_stable(prototype),args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *double2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !backend1 || !double2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(double2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(232,NULL,args,4,&result->stable),out); +} +hmath_status hmath_linear_backend_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, const hmath_value *values3, hmath_value **out) { + if (!out || !backend1 || !values2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(values2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(233,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_backend_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out) { + if (!out || !backend1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(234,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *double3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *double6, const hmath_value *values7, hmath_value **out) { + if (!out || !backend1 || !transpose2 || !double3 || !matrix4 || !values5 || !double6 || !values7) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(transpose2),hm_value_stable(double3),hm_value_stable(matrix4),hm_value_stable(values5),hm_value_stable(double6),hm_value_stable(values7)}; + return hm_value_finish(result,hm_linear_apply(235,NULL,args,7,&result->stable),out); +} +hmath_status hmath_linear_backend_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *double7, const hmath_value *matrix8, hmath_value **out) { + if (!out || !backend1 || !transpose2 || !transpose3 || !double4 || !matrix5 || !matrix6 || !double7 || !matrix8) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(transpose2),hm_value_stable(transpose3),hm_value_stable(double4),hm_value_stable(matrix5),hm_value_stable(matrix6),hm_value_stable(double7),hm_value_stable(matrix8)}; + return hm_value_finish(result,hm_linear_apply(236,NULL,args,8,&result->stable),out); +} +hmath_status hmath_linear_backend_complex_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *complex4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *complex7, const hmath_value *matrix8, hmath_value **out) { + if (!out || !backend1 || !transpose2 || !transpose3 || !complex4 || !matrix5 || !matrix6 || !complex7 || !matrix8) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(transpose2),hm_value_stable(transpose3),hm_value_stable(complex4),hm_value_stable(matrix5),hm_value_stable(matrix6),hm_value_stable(complex7),hm_value_stable(matrix8)}; + return hm_value_finish(result,hm_linear_apply(237,NULL,args,8,&result->stable),out); +} +hmath_status hmath_linear_backend_complex_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *complex2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !backend1 || !complex2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(complex2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(238,NULL,args,4,&result->stable),out); +} +hmath_status hmath_linear_backend_complex_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *flag2, const hmath_value *values3, const hmath_value *values4, hmath_value **out) { + if (!out || !backend1 || !flag2 || !values3 || !values4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(flag2),hm_value_stable(values3),hm_value_stable(values4)}; + return hm_value_finish(result,hm_linear_apply(239,NULL,args,4,&result->stable),out); +} +hmath_status hmath_linear_backend_complex_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out) { + if (!out || !backend1 || !values2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(values2)}; + return hm_value_finish(result,hm_linear_apply(240,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_complex_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *complex3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *complex6, const hmath_value *values7, hmath_value **out) { + if (!out || !backend1 || !transpose2 || !complex3 || !matrix4 || !values5 || !complex6 || !values7) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(transpose2),hm_value_stable(complex3),hm_value_stable(matrix4),hm_value_stable(values5),hm_value_stable(complex6),hm_value_stable(values7)}; + return hm_value_finish(result,hm_linear_apply(241,NULL,args,7,&result->stable),out); +} +hmath_status hmath_linear_backend_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *double5, const hmath_value *values6, hmath_value **out) { + if (!out || !backend1 || !transpose2 || !transpose3 || !double4 || !double5 || !values6) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(transpose2),hm_value_stable(transpose3),hm_value_stable(double4),hm_value_stable(double5),hm_value_stable(values6)}; + return hm_value_finish(result,hm_linear_apply(242,NULL,args,6,&result->stable),out); +} +hmath_status hmath_linear_backend_strided_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *index5, const hmath_value *index6, const hmath_value *values7, const hmath_value *index8, const hmath_value *values9, hmath_value **out) { + if (!out || !backend1 || !index2 || !index3 || !index4 || !index5 || !index6 || !values7 || !index8 || !values9) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(index2),hm_value_stable(index3),hm_value_stable(index4),hm_value_stable(index5),hm_value_stable(index6),hm_value_stable(values7),hm_value_stable(index8),hm_value_stable(values9)}; + return hm_value_finish(result,hm_linear_apply(243,NULL,args,9,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_lu(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !backend1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(244,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_qr(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !backend1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(245,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_solve(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out) { + if (!out || !backend1 || !matrix2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(246,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_cholesky(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !backend1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(247,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_least_squares(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out) { + if (!out || !backend1 || !matrix2 || !values3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2),hm_value_stable(values3)}; + return hm_value_finish(result,hm_linear_apply(248,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_svd(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !backend1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(249,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_backend_symmetric_eigen(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out) { + if (!out || !backend1 || !matrix2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend1),hm_value_stable(matrix2)}; + return hm_value_finish(result,hm_linear_apply(250,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_pure_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(251,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_pure_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out) { + if (!out || !matrix1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix1)}; + return hm_value_finish(result,hm_linear_apply(252,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_new_pure(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(253,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_open_blas(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(254,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_blis(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(255,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_one_mkl(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(256,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_accelerate(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(257,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_lp64(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(258,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_ilp64(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(259,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_auto_backend(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(260,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_require_backend(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, const hmath_value *maybe3, hmath_value **out) { + if (!out || !provider1 || !integer_abi2 || !maybe3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(provider1),hm_value_stable(integer_abi2),hm_value_stable(maybe3)}; + return hm_value_finish(result,hm_linear_apply(261,NULL,args,3,&result->stable),out); +} +hmath_status hmath_linear_backend_selected_provider(hmath_context *context, const hmath_value *backend_info1, hmath_value **out) { + if (!out || !backend_info1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend_info1)}; + return hm_value_finish(result,hm_linear_apply(262,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_selected_integer_abi(hmath_context *context, const hmath_value *backend_info1, hmath_value **out) { + if (!out || !backend_info1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(backend_info1)}; + return hm_value_finish(result,hm_linear_apply(263,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_backend_new_backend_info(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, hmath_value **out) { + if (!out || !provider1 || !integer_abi2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(provider1),hm_value_stable(integer_abi2)}; + return hm_value_finish(result,hm_linear_apply(264,NULL,args,2,&result->stable),out); +} +hmath_status hmath_linear_backend_new_row_major(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(265,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_column_major(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(266,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_no_transpose(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(267,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_transpose(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(268,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_backend_new_conjugate_transpose(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_apply(269,NULL,NULL,0,&result->stable),out); +} +hmath_status hmath_linear_object_type(hmath_context *context,const hmath_value *value,hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear object query"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_linear_apply(-1,NULL,args,1,&result->stable),out); +} +hmath_status hmath_linear_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear object query"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_linear_apply(-2,NULL,args,1,&result->stable),out); +} + +hmath_status hmath_linear_callback(hmath_context *context,hmath_linear_callback_fn callback,void *userdata,hmath_value **out) { + if(!callback || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear callback/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_callback(callback,userdata,&result->stable),out); +} +int hm_linear_invoke_callback(hmath_linear_callback_fn callback,void *userdata,void *argument,void **out,hmath_math_error *error) { + hmath_value *input=NULL,*borrowed=NULL,*result=NULL; + hmath_status status=hm_value_begin(NULL,&input); + if(status) return status; + status=hm_value_finish(input,hm_linear_clone(argument,&input->stable),&borrowed); + if(status) return status; + status=callback(borrowed,userdata,&result,error); + if(!status) { + if(!result) { error->message="linear callback returned NULL";error->message_length=29;status=HMATH_INVALID_ARGUMENT; } + else status=(hmath_status)hm_linear_clone(hm_value_stable(result),out); + } + hmath_value_release(result);hmath_value_release(borrowed); + return status; +} +hmath_status hmath_linear_export_legacy(hmath_context *context,const hmath_value *value,void **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL legacy linear export"); + struct hmath_dense_object *result=calloc(1,sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"legacy linear handle allocation failed"); + hmath_status status=hm_enter(context);if(status) {free(result);return status;} + int kind=0;status=(hmath_status)hm_linear_legacy(hm_value_stable(value),&kind,&result->stable); + if(status) {if(result->stable)hm_dense_free(result->stable);free(result);hm_leave();return status;} + atomic_init(&result->refs,1);result->kind=(unsigned)kind;result->precision=64;*out=result; + return HMATH_OK; +} diff --git a/cbits/machinelearning.c b/cbits/machinelearning.c new file mode 100644 index 0000000..ed515a9 --- /dev/null +++ b/cbits/machinelearning.c @@ -0,0 +1,1269 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_machinelearning_bindings.py. */ +#include "hmath_machinelearning.h" +#include "value_internal.h" +extern int hm_ml_apply(int,void *const *,size_t,void *,void **); +extern int hm_ml_describe(void *,void **); +hmath_status hmath_ml_describe(hmath_context *context,const hmath_value *value,hmath_value **out) { + if(!value||!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML helper argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_ml_describe(hm_value_stable(value),&result->stable),out); +} +extern int hm_ml_parts(void *,void **); +hmath_status hmath_ml_parts(hmath_context *context,const hmath_value *value,hmath_value **out) { + if(!value||!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML helper argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_ml_parts(hm_value_stable(value),&result->stable),out); +} +hmath_status hmath_ml_average(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(0,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_complete(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(1,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_merge(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *count3, hmath_value **out) { + if(!out || !count || !count2 || !number || !count3)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(count2),hm_value_stable(number),hm_value_stable(count3)}; + return hm_value_finish(result,hm_ml_apply(2,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_single(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(3,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_ward(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(4,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_affinity_propagation(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !number || !number2 || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(number),hm_value_stable(number2),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(5,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_cluster_centers(hmath_context *context, const hmath_value *cluster_model, hmath_value **out) { + if(!out || !cluster_model)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(cluster_model)}; + return hm_value_finish(result,hm_ml_apply(6,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_cut_hierarchy(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *values, hmath_value **out) { + if(!out || !count || !count2 || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(count2),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(7,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_dbscan(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !number || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(8,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_extract_optics(hmath_context *context, const hmath_value *number, const hmath_value *values, hmath_value **out) { + if(!out || !number || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(9,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_gaussian_mixture(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(10,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_hierarchical(hmath_context *context, const hmath_value *linkage, const hmath_value *dataset, hmath_value **out) { + if(!out || !linkage || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(linkage),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(11,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(12,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_k_means_plus_plus(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(13,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_k_medoids(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(14,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_left_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out) { + if(!out || !merge)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(merge)}; + return hm_value_finish(result,hm_ml_apply(15,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_mean_shift(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(16,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_merge_distance(hmath_context *context, const hmath_value *merge, hmath_value **out) { + if(!out || !merge)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(merge)}; + return hm_value_finish(result,hm_ml_apply(17,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_merged_size(hmath_context *context, const hmath_value *merge, hmath_value **out) { + if(!out || !merge)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(merge)}; + return hm_value_finish(result,hm_ml_apply(18,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_mini_batch_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !count2 || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(count2),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(19,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_mixture_covariances(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out) { + if(!out || !gaussian_mixture)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian_mixture)}; + return hm_value_finish(result,hm_ml_apply(20,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_mixture_means(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out) { + if(!out || !gaussian_mixture)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian_mixture)}; + return hm_value_finish(result,hm_ml_apply(21,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_mixture_responsibilities(hmath_context *context, const hmath_value *gaussian_mixture, const hmath_value *dataset, hmath_value **out) { + if(!out || !gaussian_mixture || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian_mixture),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(22,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_mixture_weights(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out) { + if(!out || !gaussian_mixture)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian_mixture)}; + return hm_value_finish(result,hm_ml_apply(23,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_optics(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !number || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(24,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_clusters(hmath_context *context, const hmath_value *cluster_model, const hmath_value *dataset, hmath_value **out) { + if(!out || !cluster_model || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(cluster_model),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(25,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_right_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out) { + if(!out || !merge)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(merge)}; + return hm_value_finish(result,hm_ml_apply(26,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_spectral_clustering(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(27,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_canonical_correlations(hmath_context *context, const hmath_value *cca, hmath_value **out) { + if(!out || !cca)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(cca)}; + return hm_value_finish(result,hm_ml_apply(28,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_classical_mds(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(29,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_factor_loadings(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out) { + if(!out || !factor_analysis)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(factor_analysis)}; + return hm_value_finish(result,hm_ml_apply(30,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_factor_noise(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out) { + if(!out || !factor_analysis)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(factor_analysis)}; + return hm_value_finish(result,hm_ml_apply(31,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_finish_pca(hmath_context *context, const hmath_value *count, const hmath_value *incremental_pca, hmath_value **out) { + if(!out || !count || !incremental_pca)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(incremental_pca)}; + return hm_value_finish(result,hm_ml_apply(32,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_cca(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out) { + if(!out || !count || !number || !dataset || !dataset2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(dataset2)}; + return hm_value_finish(result,hm_ml_apply(33,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_factor_analysis(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(34,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_ica(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(35,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_kernel_pca(hmath_context *context, const hmath_value *count, const hmath_value *kernel, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !kernel || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(kernel),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(36,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_pca(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(37,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_pls(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out) { + if(!out || !ml_config || !count || !dataset || !dataset2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset),hm_value_stable(dataset2)}; + return hm_value_finish(result,hm_ml_apply(38,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_incremental_pca(hmath_context *context, const hmath_value *count, hmath_value **out) { + if(!out || !count)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count)}; + return hm_value_finish(result,hm_ml_apply(39,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_inverse_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out) { + if(!out || !pca || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pca),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(40,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_isomap(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !count2 || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(count2),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(41,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_merge_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *incremental_pca2, hmath_value **out) { + if(!out || !incremental_pca || !incremental_pca2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(incremental_pca),hm_value_stable(incremental_pca2)}; + return hm_value_finish(result,hm_ml_apply(42,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_pca_components(hmath_context *context, const hmath_value *pca, hmath_value **out) { + if(!out || !pca)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pca)}; + return hm_value_finish(result,hm_ml_apply(43,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_pca_mean(hmath_context *context, const hmath_value *pca, hmath_value **out) { + if(!out || !pca)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pca)}; + return hm_value_finish(result,hm_ml_apply(44,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_pca_variances(hmath_context *context, const hmath_value *pca, hmath_value **out) { + if(!out || !pca)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pca)}; + return hm_value_finish(result,hm_ml_apply(45,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_pls(hmath_context *context, const hmath_value *pls, const hmath_value *dataset, hmath_value **out) { + if(!out || !pls || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pls),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(46,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_random_projection(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(47,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_transform_cca(hmath_context *context, const hmath_value *cca, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out) { + if(!out || !cca || !dataset || !dataset2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(cca),hm_value_stable(dataset),hm_value_stable(dataset2)}; + return hm_value_finish(result,hm_ml_apply(48,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_transform_ica(hmath_context *context, const hmath_value *ica, const hmath_value *dataset, hmath_value **out) { + if(!out || !ica || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ica),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(49,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_transform_kernel_pca(hmath_context *context, const hmath_value *kernel_pca, const hmath_value *dataset, hmath_value **out) { + if(!out || !kernel_pca || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(kernel_pca),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(50,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_transform_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out) { + if(!out || !pca || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(pca),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(51,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_truncated_svd(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(52,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_tsne(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(53,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_umap(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !count || !count2 || !number || !number2 || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(count),hm_value_stable(count2),hm_value_stable(number),hm_value_stable(number2),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(54,arguments,6,NULL,&result->stable),out); +} +hmath_status hmath_ml_update_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *dataset, hmath_value **out) { + if(!out || !incremental_pca || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(incremental_pca),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(55,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit(hmath_context *context, const hmath_value *value, const hmath_value *count, const hmath_value *number, const hmath_value *flag, hmath_value **out) { + if(!out || !value || !count || !number || !flag)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(count),hm_value_stable(number),hm_value_stable(flag)}; + return hm_value_finish(result,hm_ml_apply(56,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_ml_config(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, const hmath_value *seed, hmath_value **out) { + if(!out || !count || !number || !number2 || !seed)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(number),hm_value_stable(number2),hm_value_stable(seed)}; + return hm_value_finish(result,hm_ml_apply(57,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_default_ml_config(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(58,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_converged(hmath_context *context, const hmath_value *fit, hmath_value **out) { + if(!out || !fit)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fit)}; + return hm_value_finish(result,hm_ml_apply(59,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_iterations(hmath_context *context, const hmath_value *fit, hmath_value **out) { + if(!out || !fit)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fit)}; + return hm_value_finish(result,hm_ml_apply(60,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_residual(hmath_context *context, const hmath_value *fit, hmath_value **out) { + if(!out || !fit)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fit)}; + return hm_value_finish(result,hm_ml_apply(61,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fitted(hmath_context *context, const hmath_value *fit, hmath_value **out) { + if(!out || !fit)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fit)}; + return hm_value_finish(result,hm_ml_apply(62,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ml_iterations(hmath_context *context, const hmath_value *ml_config, hmath_value **out) { + if(!out || !ml_config)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config)}; + return hm_value_finish(result,hm_ml_apply(63,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ml_rate(hmath_context *context, const hmath_value *ml_config, hmath_value **out) { + if(!out || !ml_config)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config)}; + return hm_value_finish(result,hm_ml_apply(64,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ml_seed(hmath_context *context, const hmath_value *ml_config, hmath_value **out) { + if(!out || !ml_config)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config)}; + return hm_value_finish(result,hm_ml_apply(65,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ml_tolerance(hmath_context *context, const hmath_value *ml_config, hmath_value **out) { + if(!out || !ml_config)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config)}; + return hm_value_finish(result,hm_ml_apply(66,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ball_tree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(67,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_kd_tree(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(68,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_neighbor_result(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out) { + if(!out || !values || !count || !flag)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(count),hm_value_stable(flag)}; + return hm_value_finish(result,hm_ml_apply(69,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_build_index(hmath_context *context, const hmath_value *index_kind, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !index_kind || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(index_kind),hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(70,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_build_lsh(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !seed || !count || !count2 || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(count),hm_value_stable(count2),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(71,arguments,5,NULL,&result->stable),out); +} +hmath_status hmath_ml_decision_one_class_svm(hmath_context *context, const hmath_value *one_class_svm, const hmath_value *dataset, hmath_value **out) { + if(!out || !one_class_svm || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(one_class_svm),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(72,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_exhaustive(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out) { + if(!out || !neighbor_result)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_result)}; + return hm_value_finish(result,hm_ml_apply(73,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_isolation_forest(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out) { + if(!out || !seed || !count || !count2 || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(count),hm_value_stable(count2),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(74,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_one_class_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, hmath_value **out) { + if(!out || !ml_config || !kernel || !number || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(kernel),hm_value_stable(number),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(75,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_knn_classify(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !spatial_index || !values || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(spatial_index),hm_value_stable(values),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(76,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_knn_regress(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !spatial_index || !values || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(spatial_index),hm_value_stable(values),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(77,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_local_outlier_factor(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out) { + if(!out || !count || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(78,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_nearest_neighbors(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *values, hmath_value **out) { + if(!out || !count || !count2 || !spatial_index || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(count2),hm_value_stable(spatial_index),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(79,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_neighbors(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out) { + if(!out || !neighbor_result)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_result)}; + return hm_value_finish(result,hm_ml_apply(80,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_query_lsh(hmath_context *context, const hmath_value *count, const hmath_value *lsh, const hmath_value *values, hmath_value **out) { + if(!out || !count || !lsh || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(lsh),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(81,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_score_isolation_forest(hmath_context *context, const hmath_value *isolation_forest, const hmath_value *dataset, hmath_value **out) { + if(!out || !isolation_forest || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(isolation_forest),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(82,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_visited_leaves(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out) { + if(!out || !neighbor_result)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(neighbor_result)}; + return hm_value_finish(result,hm_ml_apply(83,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_box_cox(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(84,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_constant_impute(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(85,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fold(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(result,hm_ml_apply(86,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_mean_impute(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(87,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_median_impute(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(88,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_min_max(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(89,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_reject_unknown(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(90,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_robust_scale(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(91,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_standardize(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(92,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_yeo_johnson(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(93,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_zero_unknown(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(94,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_encoder(hmath_context *context, const hmath_value *values, const hmath_value *prototype, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(95,arguments,1,prototype?hm_value_stable(prototype):NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_imputer(hmath_context *context, const hmath_value *imputation, const hmath_value *dataset, hmath_value **out) { + if(!out || !imputation || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(imputation),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(96,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_quantile_transformer(hmath_context *context, const hmath_value *dataset, hmath_value **out) { + if(!out || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(97,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_scaler(hmath_context *context, const hmath_value *scaling, const hmath_value *dataset, hmath_value **out) { + if(!out || !scaling || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(scaling),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(98,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_grid_search(hmath_context *context, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out) { + if(!out || !values || !values2 || !function)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values),hm_value_stable(values2),hm_value_stable(function)}; + return hm_value_finish(result,hm_ml_apply(99,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_impute(hmath_context *context, const hmath_value *imputer, const hmath_value *dataset, hmath_value **out) { + if(!out || !imputer || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(imputer),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(100,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_inverse_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out) { + if(!out || !power_transform || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(power_transform),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(101,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_inverse_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out) { + if(!out || !quantile_transformer || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(quantile_transformer),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(102,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_inverse_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out) { + if(!out || !scaler || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(scaler),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(103,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, hmath_value **out) { + if(!out || !seed || !count || !count2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(count),hm_value_stable(count2)}; + return hm_value_finish(result,hm_ml_apply(104,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_label_decode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out) { + if(!out || !encoder || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(encoder),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(105,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_label_encode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out) { + if(!out || !encoder || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(encoder),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(106,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_one_hot_encode(hmath_context *context, const hmath_value *unknown_category, const hmath_value *encoder, const hmath_value *values, hmath_value **out) { + if(!out || !unknown_category || !encoder || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(unknown_category),hm_value_stable(encoder),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(107,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out) { + if(!out || !power_transform || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(power_transform),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(108,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out) { + if(!out || !quantile_transformer || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(quantile_transformer),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(109,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_random_search(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out) { + if(!out || !seed || !count || !values || !values2 || !function)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(count),hm_value_stable(values),hm_value_stable(values2),hm_value_stable(function)}; + return hm_value_finish(result,hm_ml_apply(110,arguments,5,NULL,&result->stable),out); +} +hmath_status hmath_ml_stratified_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *prototype, hmath_value **out) { + if(!out || !seed || !count || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(count),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(111,arguments,3,prototype?hm_value_stable(prototype):NULL,&result->stable),out); +} +hmath_status hmath_ml_train_test_split(hmath_context *context, const hmath_value *seed, const hmath_value *number, const hmath_value *count, hmath_value **out) { + if(!out || !seed || !number || !count)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(seed),hm_value_stable(number),hm_value_stable(count)}; + return hm_value_finish(result,hm_ml_apply(112,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_training_indices(hmath_context *context, const hmath_value *fold, hmath_value **out) { + if(!out || !fold)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fold)}; + return hm_value_finish(result,hm_ml_apply(113,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out) { + if(!out || !scaler || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(scaler),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(114,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_validation_indices(hmath_context *context, const hmath_value *fold, hmath_value **out) { + if(!out || !fold)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(fold)}; + return hm_value_finish(result,hm_ml_apply(115,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_bernoulli_bayes(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(116,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_binomial_logit(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(117,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_elastic_net(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out) { + if(!out || !number || !number2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2)}; + return hm_value_finish(result,hm_ml_apply(118,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_gaussian_bayes(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(119,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_lasso(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(120,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_linear_kernel(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(121,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_multinomial_bayes(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(122,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_ordinary(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(123,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_poisson_log(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_ml_apply(124,arguments,0,NULL,&result->stable),out); +} +hmath_status hmath_ml_polynomial_kernel(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out) { + if(!out || !count || !number || !number2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(number),hm_value_stable(number2)}; + return hm_value_finish(result,hm_ml_apply(125,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_rbf_kernel(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(126,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_ridge(hmath_context *context, const hmath_value *number, hmath_value **out) { + if(!out || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(127,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_bayesian_covariance(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out) { + if(!out || !bayesian_linear)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(bayesian_linear)}; + return hm_value_finish(result,hm_ml_apply(128,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_bayesian_mean(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out) { + if(!out || !bayesian_linear)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(bayesian_linear)}; + return hm_value_finish(result,hm_ml_apply(129,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_coefficients(hmath_context *context, const hmath_value *linear_model, hmath_value **out) { + if(!out || !linear_model)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(linear_model)}; + return hm_value_finish(result,hm_ml_apply(130,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_decision_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out) { + if(!out || !svm || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(svm),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(131,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_bayesian(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !number || !number2 || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(number),hm_value_stable(number2),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(132,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_discriminant(hmath_context *context, const hmath_value *flag, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !flag || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(flag),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(133,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_glm(hmath_context *context, const hmath_value *ml_config, const hmath_value *glm_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !glm_family || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(glm_family),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(134,arguments,5,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_gp_classifier(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !kernel || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(kernel),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(135,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_gaussian_process(hmath_context *context, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !kernel || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(kernel),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(136,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_linear(hmath_context *context, const hmath_value *ml_config, const hmath_value *penalty, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !penalty || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(penalty),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(137,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_multinomial(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(138,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_naive_bayes(hmath_context *context, const hmath_value *bayes_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !bayes_family || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(bayes_family),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(139,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_robust(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(140,arguments,4,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out) { + if(!out || !ml_config || !kernel || !number || !dataset || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(ml_config),hm_value_stable(kernel),hm_value_stable(number),hm_value_stable(dataset),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(141,arguments,5,NULL,&result->stable),out); +} +hmath_status hmath_ml_fit_weighted(hmath_context *context, const hmath_value *dataset, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !dataset || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(dataset),hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(result,hm_ml_apply(142,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_kernel(hmath_context *context, const hmath_value *kernel, const hmath_value *values, const hmath_value *values2, hmath_value **out) { + if(!out || !kernel || !values || !values2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(kernel),hm_value_stable(values),hm_value_stable(values2)}; + return hm_value_finish(result,hm_ml_apply(143,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_polynomial_features(hmath_context *context, const hmath_value *count, const hmath_value *values, hmath_value **out) { + if(!out || !count || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(values)}; + return hm_value_finish(result,hm_ml_apply(144,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_discriminant(hmath_context *context, const hmath_value *discriminant, const hmath_value *dataset, hmath_value **out) { + if(!out || !discriminant || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(discriminant),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(145,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_glm(hmath_context *context, const hmath_value *glm, const hmath_value *dataset, hmath_value **out) { + if(!out || !glm || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(glm),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(146,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_gp_classifier(hmath_context *context, const hmath_value *gp_classifier, const hmath_value *dataset, hmath_value **out) { + if(!out || !gp_classifier || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gp_classifier),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(147,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_gaussian_process(hmath_context *context, const hmath_value *gaussian_process, const hmath_value *dataset, hmath_value **out) { + if(!out || !gaussian_process || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(gaussian_process),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(148,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_linear(hmath_context *context, const hmath_value *linear_model, const hmath_value *dataset, hmath_value **out) { + if(!out || !linear_model || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(linear_model),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(149,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_multinomial(hmath_context *context, const hmath_value *multinomial_model, const hmath_value *dataset, hmath_value **out) { + if(!out || !multinomial_model || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(multinomial_model),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(150,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_naive_bayes(hmath_context *context, const hmath_value *naive_bayes, const hmath_value *dataset, hmath_value **out) { + if(!out || !naive_bayes || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(naive_bayes),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(151,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_predict_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out) { + if(!out || !svm || !dataset)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(svm),hm_value_stable(dataset)}; + return hm_value_finish(result,hm_ml_apply(152,arguments,2,NULL,&result->stable),out); +} +hmath_status hmath_ml_recursive_coefficients(hmath_context *context, const hmath_value *recursive_ls, hmath_value **out) { + if(!out || !recursive_ls)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(recursive_ls)}; + return hm_value_finish(result,hm_ml_apply(153,arguments,1,NULL,&result->stable),out); +} +hmath_status hmath_ml_recursive_ls(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out) { + if(!out || !count || !number || !number2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(count),hm_value_stable(number),hm_value_stable(number2)}; + return hm_value_finish(result,hm_ml_apply(154,arguments,3,NULL,&result->stable),out); +} +hmath_status hmath_ml_update_recursive_ls(hmath_context *context, const hmath_value *recursive_ls, const hmath_value *values, const hmath_value *number, hmath_value **out) { + if(!out || !recursive_ls || !values || !number)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(recursive_ls),hm_value_stable(values),hm_value_stable(number)}; + return hm_value_finish(result,hm_ml_apply(155,arguments,3,NULL,&result->stable),out); +} diff --git a/cbits/matrix_bindings.c b/cbits/matrix_bindings.c new file mode 100644 index 0000000..2165d70 --- /dev/null +++ b/cbits/matrix_bindings.c @@ -0,0 +1,1468 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_bindings.py. */ +#include "hmath_matrix.h" +#include "native_internal.h" +#include +#include "matrix_internal.h" +/* kind: 1 Matrix, 2 LU, 3 QR, 4 numeric vector, 5 index list. */ +extern void hm_dense_free(void *object); +extern int hm_dense_metadata(void *object, ptrdiff_t *rows, ptrdiff_t *columns, size_t *count); +extern int hm_dense_indices_copy(void *object, ptrdiff_t *out); +extern int hm_dense_values_f32(void *object, float *out); +extern int hm_dense_values_f64(void *object, double *out); +void hmath_dense_retain(void *object) { + struct hmath_dense_object *value=object; + if(value) atomic_fetch_add_explicit(&value->refs,1,memory_order_relaxed); +} +void hmath_dense_release(void *object) { + struct hmath_dense_object *value=object; + if(value && atomic_fetch_sub_explicit(&value->refs,1,memory_order_acq_rel)==1) { + hm_dense_free(value->stable); free(value); hm_leave(); + } +} +unsigned hmath_dense_precision(const void *object) { + const struct hmath_dense_object *value=object; + return value ? value->precision : 0; +} +static int valid(const struct hmath_dense_object *object,unsigned kind,unsigned precision) { + return object && object->kind==kind && object->precision==precision; +} +hmath_status hmath_dense_shape(hmath_context *context,const hmath_dense_matrix *matrix,ptrdiff_t *rows,ptrdiff_t *columns) { + if(!matrix || matrix->kind!=1 || !rows || !columns) return hm_error(HMATH_INVALID_ARGUMENT,"invalid dense shape arguments"); + hmath_status status=hm_enter(context); if(status) return status; + size_t count; status=(hmath_status)hm_dense_metadata(matrix->stable,rows,columns,&count); hm_leave(); return status; +} +hmath_status hmath_dense_count(hmath_context *context,const void *object,size_t *count) { + const struct hmath_dense_object *value=object; + if(!value || !count || (value->kind!=1 && value->kind!=4 && value->kind!=5)) return hm_error(HMATH_INVALID_ARGUMENT,"count requires matrix or list"); + hmath_status status=hm_enter(context); if(status) return status; + ptrdiff_t rows,columns; status=(hmath_status)hm_dense_metadata(value->stable,&rows,&columns,count); hm_leave(); return status; +} +hmath_status hmath_dense_indices_copy(hmath_context *context,const hmath_dense_indices *indices,ptrdiff_t *out,size_t capacity) { + if(!indices || indices->kind!=5) return hm_error(HMATH_INVALID_ARGUMENT,"expected index list"); + size_t count; hmath_status status=hmath_dense_count(context,indices,&count); if(status) return status; + if(capacitystable,out); hm_leave(); return status; +} +hmath_status hmath_dense_values_f32(hmath_context *context,const void *object,float *out,size_t capacity) { + const struct hmath_dense_object *value=object; + if(!value || value->precision!=32 || (value->kind!=1 && value->kind!=4)) return hm_error(HMATH_INVALID_ARGUMENT,"expected matrix/vector of matching dtype"); + size_t count; hmath_status status=hmath_dense_count(context,object,&count); if(status) return status; + if(capacitystable,out); hm_leave(); return status; +} +extern int hm_dense_from_list_f32(ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2Count, void **out); +hmath_status hmath_dense_from_list_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out) { + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_from_list_f32(a0, a1, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_zero_matrix_f32(ptrdiff_t a0, ptrdiff_t a1, void **out); +hmath_status hmath_dense_zero_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_zero_matrix_f32(a0, a1, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_diagonal_f32(const float *a0, size_t a0Count, void **out); +hmath_status hmath_dense_diagonal_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out) { + if(a0_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a0_count && !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_diagonal_f32(a0, a0_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_at_f32(void *a0, ptrdiff_t a1, ptrdiff_t a2, float *out, int *found); +hmath_status hmath_dense_at_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out, int *found) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!found) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Maybe presence output"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_at_f32(a0->stable, a1, a2, out, found); + hm_leave(); return status; +} +extern int hm_dense_slice_matrix_f32(ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, void *a4, void **out); +hmath_status hmath_dense_slice_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out) { + if(!valid(a4,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a4: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_slice_matrix_f32(a0, a1, a2, a3, a4->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_reshape_f32(ptrdiff_t a0, ptrdiff_t a1, void *a2, void **out); +hmath_status hmath_dense_reshape_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a2,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_reshape_f32(a0, a1, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_add_matrix_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_add_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_add_matrix_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_subtract_matrix_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_subtract_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_subtract_matrix_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_hadamard_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_hadamard_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_hadamard_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_multiply_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_multiply_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_multiply_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_identity_f32(ptrdiff_t a0, void **out); +hmath_status hmath_dense_identity_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_identity_f32(a0, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_from_list_checked_f32(ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2Count, void **out); +hmath_status hmath_dense_from_list_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out) { + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_from_list_checked_f32(a0, a1, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_zero_matrix_checked_f32(ptrdiff_t a0, ptrdiff_t a1, void **out); +hmath_status hmath_dense_zero_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_zero_matrix_checked_f32(a0, a1, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_diagonal_checked_f32(const float *a0, size_t a0Count, void **out); +hmath_status hmath_dense_diagonal_checked_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out) { + if(a0_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a0_count && !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_diagonal_checked_f32(a0, a0_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_at_checked_f32(void *a0, ptrdiff_t a1, ptrdiff_t a2, float *out); +hmath_status hmath_dense_at_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_at_checked_f32(a0->stable, a1, a2, out); + hm_leave(); return status; +} +extern int hm_dense_slice_matrix_checked_f32(ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, void *a4, void **out); +hmath_status hmath_dense_slice_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out) { + if(!valid(a4,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a4: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_slice_matrix_checked_f32(a0, a1, a2, a3, a4->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_reshape_checked_f32(ptrdiff_t a0, ptrdiff_t a1, void *a2, void **out); +hmath_status hmath_dense_reshape_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a2,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_reshape_checked_f32(a0, a1, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_add_matrix_checked_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_add_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_add_matrix_checked_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_subtract_matrix_checked_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_subtract_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_subtract_matrix_checked_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_hadamard_checked_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_hadamard_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_hadamard_checked_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_multiply_checked_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_multiply_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_multiply_checked_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_identity_checked_f32(ptrdiff_t a0, void **out); +hmath_status hmath_dense_identity_checked_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_identity_checked_f32(a0, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_scale_matrix_f32(float a0, void *a1, void **out); +hmath_status hmath_dense_scale_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_scale_matrix_f32(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_transpose_matrix_f32(void *a0, void **out); +hmath_status hmath_dense_transpose_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_transpose_matrix_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_lu_decompose_f32(void *a0, void **out); +hmath_status hmath_dense_lu_lu_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_decompose_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=2; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_lu_decompose_with_tolerance_f32(float a0, void *a1, void **out); +hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_lu **out) { + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_decompose_with_tolerance_f32(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=2; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_lu_lower_f32(void *a0, void **out); +hmath_status hmath_dense_lu_lu_lower_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_lower_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_lu_upper_f32(void *a0, void **out); +hmath_status hmath_dense_lu_lu_upper_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_upper_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_lu_permutation_f32(void *a0, void **out); +hmath_status hmath_dense_lu_lu_permutation_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_permutation_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=5; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_solve_lu_f32(void *a0, const float *a1, size_t a1Count, void **out); +hmath_status hmath_dense_lu_solve_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const float *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_lu_f32(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_solve_matrix_lu_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_lu_solve_matrix_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_matrix_lu_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_solve_f32(void *a0, const float *a1, size_t a1Count, void **out); +hmath_status hmath_dense_lu_solve_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_f32(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_solve_matrix_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_lu_solve_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_matrix_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_lu_determinant_lu_f32(void *a0, float *out); +hmath_status hmath_dense_lu_determinant_lu_f32(hmath_context *context, const hmath_dense_lu *a0, float *out) { + if(!valid(a0,2,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_lu_determinant_lu_f32(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_lu_determinant_f32(void *a0, float *out); +hmath_status hmath_dense_lu_determinant_f32(hmath_context *context, const hmath_dense_matrix *a0, float *out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_lu_determinant_f32(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_lu_inverse_f32(void *a0, void **out); +hmath_status hmath_dense_lu_inverse_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_inverse_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_decompose_f32(void *a0, void **out); +hmath_status hmath_dense_qr_qr_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_decompose_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=3; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_decompose_with_tolerance_f32(float a0, void *a1, void **out); +hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_qr **out) { + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_decompose_with_tolerance_f32(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=3; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_q_f32(void *a0, void **out); +hmath_status hmath_dense_qr_qr_q_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_q_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_r_f32(void *a0, void **out); +hmath_status hmath_dense_qr_qr_r_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_r_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_permutation_f32(void *a0, void **out); +hmath_status hmath_dense_qr_qr_permutation_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_permutation_f32(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=5; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_qr_rank_f32(void *a0, ptrdiff_t *out); +hmath_status hmath_dense_qr_qr_rank_f32(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_qr_qr_rank_f32(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_qr_apply_q_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_apply_q_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_apply_q_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_apply_qt_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_apply_qt_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_apply_qt_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_solve_matrix_qr_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_solve_matrix_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_solve_matrix_qr_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_solve_qr_f32(void *a0, const float *a1, size_t a1Count, void **out); +hmath_status hmath_dense_qr_solve_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const float *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,3,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_solve_qr_f32(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_least_squares_f32(void *a0, const float *a1, size_t a1Count, void **out); +hmath_status hmath_dense_qr_least_squares_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_least_squares_f32(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_least_squares_matrix_f32(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_least_squares_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_least_squares_matrix_f32(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_ridge_solve_f32(float a0, void *a1, const float *a2, size_t a2Count, void **out); +hmath_status hmath_dense_qr_ridge_solve_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const float *a2, size_t a2_count, hmath_dense_vector **out) { + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(float)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_ridge_solve_f32(a0, a1->stable, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=32; *out=result; + return status; +} +extern int hm_dense_qr_ridge_solve_matrix_f32(float a0, void *a1, void *a2, void **out); +hmath_status hmath_dense_qr_ridge_solve_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a1,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!valid(a2,1,32)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_ridge_solve_matrix_f32(a0, a1->stable, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=32; *out=result; + return status; +} +hmath_status hmath_dense_values_f64(hmath_context *context,const void *object,double *out,size_t capacity) { + const struct hmath_dense_object *value=object; + if(!value || value->precision!=64 || (value->kind!=1 && value->kind!=4)) return hm_error(HMATH_INVALID_ARGUMENT,"expected matrix/vector of matching dtype"); + size_t count; hmath_status status=hmath_dense_count(context,object,&count); if(status) return status; + if(capacitystable,out); hm_leave(); return status; +} +extern int hm_dense_from_list_f64(ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2Count, void **out); +hmath_status hmath_dense_from_list_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out) { + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_from_list_f64(a0, a1, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_zero_matrix_f64(ptrdiff_t a0, ptrdiff_t a1, void **out); +hmath_status hmath_dense_zero_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_zero_matrix_f64(a0, a1, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_diagonal_f64(const double *a0, size_t a0Count, void **out); +hmath_status hmath_dense_diagonal_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out) { + if(a0_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a0_count && !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_diagonal_f64(a0, a0_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_at_f64(void *a0, ptrdiff_t a1, ptrdiff_t a2, double *out, int *found); +hmath_status hmath_dense_at_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out, int *found) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!found) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Maybe presence output"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_at_f64(a0->stable, a1, a2, out, found); + hm_leave(); return status; +} +extern int hm_dense_slice_matrix_f64(ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, void *a4, void **out); +hmath_status hmath_dense_slice_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out) { + if(!valid(a4,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a4: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_slice_matrix_f64(a0, a1, a2, a3, a4->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_reshape_f64(ptrdiff_t a0, ptrdiff_t a1, void *a2, void **out); +hmath_status hmath_dense_reshape_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a2,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_reshape_f64(a0, a1, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_add_matrix_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_add_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_add_matrix_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_subtract_matrix_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_subtract_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_subtract_matrix_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_hadamard_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_hadamard_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_hadamard_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_multiply_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_multiply_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_multiply_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_identity_f64(ptrdiff_t a0, void **out); +hmath_status hmath_dense_identity_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_identity_f64(a0, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_from_list_checked_f64(ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2Count, void **out); +hmath_status hmath_dense_from_list_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out) { + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_from_list_checked_f64(a0, a1, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_zero_matrix_checked_f64(ptrdiff_t a0, ptrdiff_t a1, void **out); +hmath_status hmath_dense_zero_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_zero_matrix_checked_f64(a0, a1, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_diagonal_checked_f64(const double *a0, size_t a0Count, void **out); +hmath_status hmath_dense_diagonal_checked_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out) { + if(a0_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a0_count && !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_diagonal_checked_f64(a0, a0_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_at_checked_f64(void *a0, ptrdiff_t a1, ptrdiff_t a2, double *out); +hmath_status hmath_dense_at_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_at_checked_f64(a0->stable, a1, a2, out); + hm_leave(); return status; +} +extern int hm_dense_slice_matrix_checked_f64(ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, void *a4, void **out); +hmath_status hmath_dense_slice_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out) { + if(!valid(a4,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a4: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_slice_matrix_checked_f64(a0, a1, a2, a3, a4->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_reshape_checked_f64(ptrdiff_t a0, ptrdiff_t a1, void *a2, void **out); +hmath_status hmath_dense_reshape_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a2,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_reshape_checked_f64(a0, a1, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_add_matrix_checked_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_add_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_add_matrix_checked_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_subtract_matrix_checked_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_subtract_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_subtract_matrix_checked_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_hadamard_checked_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_hadamard_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_hadamard_checked_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_multiply_checked_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_multiply_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_multiply_checked_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_identity_checked_f64(ptrdiff_t a0, void **out); +hmath_status hmath_dense_identity_checked_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_identity_checked_f64(a0, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_scale_matrix_f64(double a0, void *a1, void **out); +hmath_status hmath_dense_scale_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_scale_matrix_f64(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_transpose_matrix_f64(void *a0, void **out); +hmath_status hmath_dense_transpose_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_transpose_matrix_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_lu_decompose_f64(void *a0, void **out); +hmath_status hmath_dense_lu_lu_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_decompose_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=2; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_lu_decompose_with_tolerance_f64(double a0, void *a1, void **out); +hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_lu **out) { + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_decompose_with_tolerance_f64(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=2; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_lu_lower_f64(void *a0, void **out); +hmath_status hmath_dense_lu_lu_lower_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_lower_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_lu_upper_f64(void *a0, void **out); +hmath_status hmath_dense_lu_lu_upper_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_upper_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_lu_permutation_f64(void *a0, void **out); +hmath_status hmath_dense_lu_lu_permutation_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_lu_permutation_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=5; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_solve_lu_f64(void *a0, const double *a1, size_t a1Count, void **out); +hmath_status hmath_dense_lu_solve_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const double *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_lu_f64(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_solve_matrix_lu_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_lu_solve_matrix_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_matrix_lu_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_solve_f64(void *a0, const double *a1, size_t a1Count, void **out); +hmath_status hmath_dense_lu_solve_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_f64(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_solve_matrix_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_lu_solve_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_solve_matrix_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_lu_determinant_lu_f64(void *a0, double *out); +hmath_status hmath_dense_lu_determinant_lu_f64(hmath_context *context, const hmath_dense_lu *a0, double *out) { + if(!valid(a0,2,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_lu_determinant_lu_f64(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_lu_determinant_f64(void *a0, double *out); +hmath_status hmath_dense_lu_determinant_f64(hmath_context *context, const hmath_dense_matrix *a0, double *out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_lu_determinant_f64(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_lu_inverse_f64(void *a0, void **out); +hmath_status hmath_dense_lu_inverse_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_lu_inverse_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_decompose_f64(void *a0, void **out); +hmath_status hmath_dense_qr_qr_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_decompose_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=3; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_decompose_with_tolerance_f64(double a0, void *a1, void **out); +hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_qr **out) { + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_decompose_with_tolerance_f64(a0, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=3; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_q_f64(void *a0, void **out); +hmath_status hmath_dense_qr_qr_q_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_q_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_r_f64(void *a0, void **out); +hmath_status hmath_dense_qr_qr_r_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_r_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_permutation_f64(void *a0, void **out); +hmath_status hmath_dense_qr_qr_permutation_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_qr_permutation_f64(a0->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=5; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_qr_rank_f64(void *a0, ptrdiff_t *out); +hmath_status hmath_dense_qr_qr_rank_f64(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + hmath_status status=hm_enter(context); + if(status) { return status; } + status=(hmath_status)hm_dense_qr_qr_rank_f64(a0->stable, out); + hm_leave(); return status; +} +extern int hm_dense_qr_apply_q_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_apply_q_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_apply_q_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_apply_qt_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_apply_qt_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_apply_qt_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_solve_matrix_qr_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_solve_matrix_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_solve_matrix_qr_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_solve_qr_f64(void *a0, const double *a1, size_t a1Count, void **out); +hmath_status hmath_dense_qr_solve_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const double *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,3,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_solve_qr_f64(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_least_squares_f64(void *a0, const double *a1, size_t a1Count, void **out); +hmath_status hmath_dense_qr_least_squares_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(a1_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a1_count && !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_least_squares_f64(a0->stable, a1, a1_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_least_squares_matrix_f64(void *a0, void *a1, void **out); +hmath_status hmath_dense_qr_least_squares_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out) { + if(!valid(a0,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a0: object kind/precision mismatch"); + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_least_squares_matrix_f64(a0->stable, a1->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_ridge_solve_f64(double a0, void *a1, const double *a2, size_t a2Count, void **out); +hmath_status hmath_dense_qr_ridge_solve_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const double *a2, size_t a2_count, hmath_dense_vector **out) { + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(a2_count > (size_t)PTRDIFF_MAX/sizeof(double)) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t"); + if(a2_count && !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_ridge_solve_f64(a0, a1->stable, a2, a2_count, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=4; result->precision=64; *out=result; + return status; +} +extern int hm_dense_qr_ridge_solve_matrix_f64(double a0, void *a1, void *a2, void **out); +hmath_status hmath_dense_qr_ridge_solve_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out) { + if(!valid(a1,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a1: object kind/precision mismatch"); + if(!valid(a2,1,64)) return hm_error(HMATH_INVALID_ARGUMENT,"a2: object kind/precision mismatch"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output"); + struct hmath_dense_object *result=malloc(sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + result->stable=NULL; + hmath_status status=hm_enter(context); + if(status) { free(result); return status; } + status=(hmath_status)hm_dense_qr_ridge_solve_matrix_f64(a0, a1->stable, a2->stable, &result->stable); + if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=64; *out=result; + return status; +} diff --git a/cbits/matrix_internal.h b/cbits/matrix_internal.h new file mode 100644 index 0000000..59dd511 --- /dev/null +++ b/cbits/matrix_internal.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_MATRIX_INTERNAL_H +#define HMATH_MATRIX_INTERNAL_H +#include "native_internal.h" +/* Shared private layout; every stable pointer owns one runtime reservation. */ +struct hmath_dense_object { + atomic_size_t refs; + unsigned kind, precision; + void *stable; +}; +#endif diff --git a/cbits/matrix_value.c b/cbits/matrix_value.c new file mode 100644 index 0000000..8096327 --- /dev/null +++ b/cbits/matrix_value.c @@ -0,0 +1,181 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_value_bindings.py. */ +#include "hmath_matrix_value.h" +#include "matrix_internal.h" +#include "value_internal.h" +#include +extern int hm_matrix_value_apply(int opcode,void *const *args,size_t count,void **out); +extern int hm_dense_export_value(void *matrix,void **out); +extern int hm_dense_import_value(void *value,void **out); +hmath_status hmath_matrix_value_from_list(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !prototype || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(0,args,4,&result->stable),out); +} +hmath_status hmath_matrix_value_zero_matrix(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !prototype || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(1,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_diagonal(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out) { + if(!out || !prototype || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0)}; + return hm_value_finish(result,hm_matrix_value_apply(2,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_at(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(3,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_slice_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,const hmath_value *a3,const hmath_value *a4,hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3 || !a4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3),hm_value_stable(a4)}; + return hm_value_finish(result,hm_matrix_value_apply(4,args,5,&result->stable),out); +} +hmath_status hmath_matrix_value_reshape(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(5,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_add_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(6,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_subtract_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(7,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_hadamard(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(8,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_multiply(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(9,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_identity(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out) { + if(!out || !prototype || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0)}; + return hm_value_finish(result,hm_matrix_value_apply(10,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_from_list_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !prototype || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(11,args,4,&result->stable),out); +} +hmath_status hmath_matrix_value_zero_matrix_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !prototype || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(12,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_diagonal_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out) { + if(!out || !prototype || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0)}; + return hm_value_finish(result,hm_matrix_value_apply(13,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_at_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(14,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_slice_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,const hmath_value *a3,const hmath_value *a4,hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3 || !a4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3),hm_value_stable(a4)}; + return hm_value_finish(result,hm_matrix_value_apply(15,args,5,&result->stable),out); +} +hmath_status hmath_matrix_value_reshape_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_matrix_value_apply(16,args,3,&result->stable),out); +} +hmath_status hmath_matrix_value_add_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(17,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_subtract_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(18,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_hadamard_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(19,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_multiply_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(20,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_identity_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out) { + if(!out || !prototype || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(a0)}; + return hm_value_finish(result,hm_matrix_value_apply(21,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_scale_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_matrix_value_apply(22,args,2,&result->stable),out); +} +hmath_status hmath_matrix_value_transpose_matrix(hmath_context *context,const hmath_value *a0,hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_matrix_value_apply(23,args,1,&result->stable),out); +} +hmath_status hmath_matrix_value_to_list(hmath_context *context,const hmath_value *matrix,hmath_value **out) { + if(!matrix || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix)}; + return hm_value_finish(result,hm_matrix_value_apply(100,args,1,&result->stable),out); +} +hmath_status hmath_matrix_value_shape(hmath_context *context,const hmath_value *matrix,hmath_value **out) { + if(!matrix || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(matrix)}; + return hm_value_finish(result,hm_matrix_value_apply(101,args,1,&result->stable),out); +} +hmath_status hmath_dense_to_value(hmath_context *context,const hmath_dense_matrix *matrix,hmath_value **out) { + if(!matrix || matrix->kind!=1 || !out) return hm_error(HMATH_INVALID_ARGUMENT,"expected Matrix owner/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_dense_export_value(matrix->stable,&result->stable),out); +} +hmath_status hmath_dense_from_value(hmath_context *context,const hmath_value *value,hmath_dense_matrix **out) { + if(!value || value->kind!=9 || (value->dtype!=0 && value->dtype!=1) || !out) + return hm_error(HMATH_INVALID_ARGUMENT,"typed Matrix import requires Float or Double Matrix"); + struct hmath_dense_object *result=calloc(1,sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + hmath_status status=hm_enter(context); if(status) { free(result); return status; } + status=(hmath_status)hm_dense_import_value(value->stable,&result->stable); + if(status) { free(result); hm_leave(); return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=value->dtype==1 ? 32 : 64; *out=result; + return HMATH_OK; +} diff --git a/cbits/native.c b/cbits/native.c index d73930d..f4614ab 100644 --- a/cbits/native.c +++ b/cbits/native.c @@ -10,6 +10,7 @@ static _Thread_local hmath_status last_code; static _Thread_local char last_message[256]; hmath_status hm_error(hmath_status code, const char *message) { + hm_clear_math_error(); last_code = code; (void)snprintf(last_message, sizeof last_message, "%s", message ? message : ""); return code; @@ -27,13 +28,16 @@ const char *hmath_status_string(hmath_status s) { "cancelled", "bounds error", "busy", - "unsupported"}; + "unsupported", + "Haskell MathError", + "Haskell ExprError", + "Haskell InterchangeError"}; return (unsigned)s < sizeof names / sizeof names[0] ? names[s] : "unknown status"; } uint32_t hmath_abi_version(void) { return HMATH_ABI_VERSION; } const char *hmath_library_version(void) { return "1.0.2"; } const char *hmath_build_info(void) { - return "HMath ABI 1; C11; GHC threaded RTS; binary64; max-rank=8"; + return "HMath ABI 1; C11; GHC threaded RTS; scalar binary32/64; tensor binary64; max-rank=8"; } const char *hmath_backend_version(void) { return "native tensor kernels: Haskell reference binary64"; @@ -311,14 +315,22 @@ hmath_status hmath_tensor_reshape(const hmath_tensor *t, const size_t *shape, si *out = r; return hm_error(HMATH_OK, ""); } -static hmath_status gather_values(const hmath_tensor *t, double **out) { +/* Borrow contiguous storage for the whole synchronous call. Only strided + * inputs need gathered scratch; the caller owns a live tensor reference. */ +static hmath_status kernel_values(const hmath_tensor *t, const double **values, double **scratch) { if (!t) return hm_error(HMATH_INVALID_ARGUMENT, "NULL tensor"); - *out = malloc((t->count ? t->count : 1) * sizeof(double)); - if (!*out) + *scratch = NULL; + if (is_contiguous(t)) { + *values = t->storage->data; + return HMATH_OK; + } + *scratch = malloc((t->count ? t->count : 1) * sizeof(double)); + if (!*scratch) return hm_error(HMATH_ALLOCATION_FAILED, "kernel scratch allocation failed"); for (size_t i = 0; i < t->count; ++i) - (*out)[i] = t->storage->data[element_offset(t, i)]; + (*scratch)[i] = t->storage->data[element_offset(t, i)]; + *values = *scratch; return HMATH_OK; } static int same_shape(const hmath_tensor *a, const hmath_tensor *b) { @@ -361,19 +373,20 @@ static hmath_status scalar_kernel(hmath_context *context, int op, const hmath_te hmath_status s = hm_enter(context); if (s) return s; - double *xs = NULL, *ys = NULL, result; - s = gather_values(a, &xs); + const double *xs = NULL, *ys = NULL; + double *x_scratch = NULL, *y_scratch = NULL, result; + s = kernel_values(a, &xs, &x_scratch); if (!s && b) - s = gather_values(b, &ys); + s = kernel_values(b, &ys, &y_scratch); if (s) { - free(xs); - free(ys); + free(x_scratch); + free(y_scratch); hm_leave(); return s; } int code = hm_haskell_kernel(op, xs, ys, a->count, 0, 0, 0, &result); - free(xs); - free(ys); + free(x_scratch); + free(y_scratch); s = finish_kernel(context, code); if (!s) *out = result; @@ -417,29 +430,32 @@ static hmath_status tensor_kernel(hmath_context *context, int op, const hmath_te hmath_status s = hm_enter(context); if (s) return s; - double *xs = NULL, *ys = NULL, *result = NULL; - s = gather_values(a, &xs); + const double *xs = NULL, *ys = NULL; + double *x_scratch = NULL, *y_scratch = NULL, *result = NULL; + s = kernel_values(a, &xs, &x_scratch); if (!s) - s = gather_values(b, &ys); - if (!s) { - result = malloc((n ? n : 1) * sizeof(double)); - if (!result) - s = hm_error(HMATH_ALLOCATION_FAILED, "result allocation failed"); - } + s = kernel_values(b, &ys, &y_scratch); + if (!s) + s = hmath_buffer_alloc(n * sizeof(double), 64, (void **)&result); if (s) { - free(xs); - free(ys); - free(result); + free(x_scratch); + free(y_scratch); + hmath_buffer_free(result); hm_leave(); return s; } int code = hm_haskell_kernel(op, xs, ys, a->count, rows, inner, columns, result); - free(xs); - free(ys); + free(x_scratch); + free(y_scratch); s = finish_kernel(context, code); - if (!s) - s = hmath_tensor_copy(result, n, shape, rank, out); - free(result); + if (!s) { + /* The kernel already wrote the final aligned storage. Borrow takes its + * ownership only on success; no second allocation/copy is needed. */ + s = hmath_tensor_borrow(result, n, shape, NULL, rank, owned_deleter, NULL, out); + if (!s) + result = NULL; + } + hmath_buffer_free(result); return s; } hmath_status hmath_tensor_add(hmath_context *c, const hmath_tensor *a, const hmath_tensor *b, diff --git a/cbits/native_internal.h b/cbits/native_internal.h index 63f6384..d6cc503 100644 --- a/cbits/native_internal.h +++ b/cbits/native_internal.h @@ -20,6 +20,7 @@ struct hmath_tensor { hmath_storage *storage; }; hmath_status hm_error(hmath_status code, const char *message); +void hm_clear_math_error(void); hmath_status hm_enter(hmath_context *context); void hm_leave(void); int hm_cancelled(const hmath_context *context); diff --git a/cbits/numeric_generated.c b/cbits/numeric_generated.c new file mode 100644 index 0000000..bb33a6d --- /dev/null +++ b/cbits/numeric_generated.c @@ -0,0 +1,20760 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_numeric.h" +#include "numeric_internal.h" +#include +void hmath_numeric_string_free(char *value) { free(value); } +void hmath_numeric_buffer_free(void *value) { free(value); } +extern int hm_numeric_basic_factorial( + const char *n, + char **out0); +hmath_status hmath_basic_factorial( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_factorial(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_fibonacci( + const char *n, + char **out0); +hmath_status hmath_basic_fibonacci( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_fibonacci(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_is_prime( + const char *n, + int *out0); +hmath_status hmath_basic_is_prime( + hmath_context *context, + const char *n, + int *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_is_prime(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_f32( + float low, + float high, + float value, + float *out0); +hmath_status hmath_basic_clamp_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_f32(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_f64( + double low, + double high, + double value, + double *out0); +hmath_status hmath_basic_clamp_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_f64(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_rational( + const char *low_numerator, + const char *low_denominator, + const char *high_numerator, + const char *high_denominator, + const char *value_numerator, + const char *value_denominator, + char **out0, + char **out1); +hmath_status hmath_basic_clamp_rational( + hmath_context *context, + const char *low_numerator, + const char *low_denominator, + const char *high_numerator, + const char *high_denominator, + const char *value_numerator, + const char *value_denominator, + char **out0, + char **out1) { + if (!hm_decimal(low_numerator) || !hm_decimal(low_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *low_digit = low_denominator; + if (*low_digit == '-') ++low_digit; + while (*low_digit == '0') ++low_digit; + if (!*low_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(high_numerator) || !hm_decimal(high_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *high_digit = high_denominator; + if (*high_digit == '-') ++high_digit; + while (*high_digit == '0') ++high_digit; + if (!*high_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(value_numerator) || !hm_decimal(value_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *value_digit = value_denominator; + if (*value_digit == '-') ++value_digit; + while (*value_digit == '0') ++value_digit; + if (!*value_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_rational(low_numerator, low_denominator, high_numerator, high_denominator, value_numerator, value_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_integer( + const char *low, + const char *high, + const char *value, + char **out0); +hmath_status hmath_basic_clamp_integer( + hmath_context *context, + const char *low, + const char *high, + const char *value, + char **out0) { + if (!hm_decimal(low)) + return hm_error(HMATH_INVALID_ARGUMENT, "low: expected signed decimal Integer"); + if (!hm_decimal(high)) + return hm_error(HMATH_INVALID_ARGUMENT, "high: expected signed decimal Integer"); + if (!hm_decimal(value)) + return hm_error(HMATH_INVALID_ARGUMENT, "value: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_integer(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_i8( + int8_t low, + int8_t high, + int8_t value, + int8_t *out0); +hmath_status hmath_basic_clamp_i8( + hmath_context *context, + int8_t low, + int8_t high, + int8_t value, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_i8(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_i16( + int16_t low, + int16_t high, + int16_t value, + int16_t *out0); +hmath_status hmath_basic_clamp_i16( + hmath_context *context, + int16_t low, + int16_t high, + int16_t value, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_i16(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_i32( + int32_t low, + int32_t high, + int32_t value, + int32_t *out0); +hmath_status hmath_basic_clamp_i32( + hmath_context *context, + int32_t low, + int32_t high, + int32_t value, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_i32(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_i64( + int64_t low, + int64_t high, + int64_t value, + int64_t *out0); +hmath_status hmath_basic_clamp_i64( + hmath_context *context, + int64_t low, + int64_t high, + int64_t value, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_i64(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_u8( + uint8_t low, + uint8_t high, + uint8_t value, + uint8_t *out0); +hmath_status hmath_basic_clamp_u8( + hmath_context *context, + uint8_t low, + uint8_t high, + uint8_t value, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_u8(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_u16( + uint16_t low, + uint16_t high, + uint16_t value, + uint16_t *out0); +hmath_status hmath_basic_clamp_u16( + hmath_context *context, + uint16_t low, + uint16_t high, + uint16_t value, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_u16(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_u32( + uint32_t low, + uint32_t high, + uint32_t value, + uint32_t *out0); +hmath_status hmath_basic_clamp_u32( + hmath_context *context, + uint32_t low, + uint32_t high, + uint32_t value, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_u32(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_u64( + uint64_t low, + uint64_t high, + uint64_t value, + uint64_t *out0); +hmath_status hmath_basic_clamp_u64( + hmath_context *context, + uint64_t low, + uint64_t high, + uint64_t value, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_u64(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_int( + ptrdiff_t low, + ptrdiff_t high, + ptrdiff_t value, + ptrdiff_t *out0); +hmath_status hmath_basic_clamp_int( + hmath_context *context, + ptrdiff_t low, + ptrdiff_t high, + ptrdiff_t value, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_int(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_clamp_word( + size_t low, + size_t high, + size_t value, + size_t *out0); +hmath_status hmath_basic_clamp_word( + hmath_context *context, + size_t low, + size_t high, + size_t value, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_clamp_word(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_lerp_f32( + float a, + float b, + float t, + float *out0); +hmath_status hmath_basic_lerp_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_lerp_f32(a, b, t, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_lerp_f64( + double a, + double b, + double t, + double *out0); +hmath_status hmath_basic_lerp_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_lerp_f64(a, b, t, out0); + hm_leave(); + return status; +} +extern int hm_numeric_basic_lerp_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + const char *t_numerator, + const char *t_denominator, + char **out0, + char **out1); +hmath_status hmath_basic_lerp_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + const char *t_numerator, + const char *t_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(t_numerator) || !hm_decimal(t_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *t_digit = t_denominator; + if (*t_digit == '-') ++t_digit; + while (*t_digit == '0') ++t_digit; + if (!*t_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_lerp_rational(a_numerator, a_denominator, b_numerator, b_denominator, t_numerator, t_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_basic_lerp_c64( + float a_0, + float a_1, + float b_0, + float b_1, + float t_0, + float t_1, + float *out0, + float *out1); +hmath_status hmath_basic_lerp_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float t_0, + float t_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_lerp_c64(a_0, a_1, b_0, b_1, t_0, t_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_basic_lerp_c128( + double a_0, + double a_1, + double b_0, + double b_1, + double t_0, + double t_1, + double *out0, + double *out1); +hmath_status hmath_basic_lerp_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double t_0, + double t_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_basic_lerp_c128(a_0, a_1, b_0, b_1, t_0, t_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_add_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_add_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_add_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_rational(a_numerator, a_denominator, b_numerator, b_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_integer( + const char *a, + const char *b, + char **out0); +hmath_status hmath_scalar_add_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_integer(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_c64( + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +hmath_status hmath_scalar_add_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_c64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_add_c128( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_scalar_add_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_add_c128(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_subtract_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_subtract_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_subtract_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_rational(a_numerator, a_denominator, b_numerator, b_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_integer( + const char *a, + const char *b, + char **out0); +hmath_status hmath_scalar_subtract_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_integer(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_subtract_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_subtract_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_subtract_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_subtract_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_subtract_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_subtract_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_subtract_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_subtract_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_subtract_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_subtract_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_c64( + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +hmath_status hmath_scalar_subtract_scalar_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_c64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_subtract_scalar_c128( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_scalar_subtract_scalar_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_subtract_scalar_c128(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_multiply_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_rational(a_numerator, a_denominator, b_numerator, b_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_integer( + const char *a, + const char *b, + char **out0); +hmath_status hmath_scalar_multiply_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_integer(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_c64( + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +hmath_status hmath_scalar_multiply_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_c64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multiply_c128( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_scalar_multiply_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multiply_c128(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_minimum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_minimum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_minimum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_rational(a_numerator, a_denominator, b_numerator, b_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_integer( + const char *a, + const char *b, + char **out0); +hmath_status hmath_scalar_minimum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_integer(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_minimum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_minimum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_minimum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_minimum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_minimum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_minimum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_minimum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_minimum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_minimum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_minimum_scalar_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_minimum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_minimum_scalar_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_maximum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_maximum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_rational( + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_maximum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1) { + if (!hm_decimal(a_numerator) || !hm_decimal(a_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *a_digit = a_denominator; + if (*a_digit == '-') ++a_digit; + while (*a_digit == '0') ++a_digit; + if (!*a_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!hm_decimal(b_numerator) || !hm_decimal(b_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *b_digit = b_denominator; + if (*b_digit == '-') ++b_digit; + while (*b_digit == '0') ++b_digit; + if (!*b_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_rational(a_numerator, a_denominator, b_numerator, b_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_integer( + const char *a, + const char *b, + char **out0); +hmath_status hmath_scalar_maximum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_integer(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_maximum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_maximum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_maximum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_maximum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_maximum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_maximum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_maximum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_maximum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_maximum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_maximum_scalar_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_maximum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_maximum_scalar_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_f32( + float x, + float *out0); +hmath_status hmath_scalar_absolute_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_f64( + double x, + double *out0); +hmath_status hmath_scalar_absolute_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_rational( + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_absolute_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1) { + if (!hm_decimal(x_numerator) || !hm_decimal(x_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *x_digit = x_denominator; + if (*x_digit == '-') ++x_digit; + while (*x_digit == '0') ++x_digit; + if (!*x_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_rational(x_numerator, x_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_integer( + const char *x, + char **out0); +hmath_status hmath_scalar_absolute_integer( + hmath_context *context, + const char *x, + char **out0) { + if (!hm_decimal(x)) + return hm_error(HMATH_INVALID_ARGUMENT, "x: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_integer(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_i8( + int8_t x, + int8_t *out0); +hmath_status hmath_scalar_absolute_i8( + hmath_context *context, + int8_t x, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_i8(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_i16( + int16_t x, + int16_t *out0); +hmath_status hmath_scalar_absolute_i16( + hmath_context *context, + int16_t x, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_i16(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_i32( + int32_t x, + int32_t *out0); +hmath_status hmath_scalar_absolute_i32( + hmath_context *context, + int32_t x, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_i32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_i64( + int64_t x, + int64_t *out0); +hmath_status hmath_scalar_absolute_i64( + hmath_context *context, + int64_t x, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_i64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_u8( + uint8_t x, + uint8_t *out0); +hmath_status hmath_scalar_absolute_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_u8(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_u16( + uint16_t x, + uint16_t *out0); +hmath_status hmath_scalar_absolute_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_u16(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_u32( + uint32_t x, + uint32_t *out0); +hmath_status hmath_scalar_absolute_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_u32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_u64( + uint64_t x, + uint64_t *out0); +hmath_status hmath_scalar_absolute_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_u64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_int( + ptrdiff_t x, + ptrdiff_t *out0); +hmath_status hmath_scalar_absolute_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_int(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_word( + size_t x, + size_t *out0); +hmath_status hmath_scalar_absolute_word( + hmath_context *context, + size_t x, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_word(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_c64( + float x_0, + float x_1, + float *out0, + float *out1); +hmath_status hmath_scalar_absolute_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_c64(x_0, x_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_c128( + double x_0, + double x_1, + double *out0, + double *out1); +hmath_status hmath_scalar_absolute_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_c128(x_0, x_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_f32( + float x, + float *out0); +hmath_status hmath_scalar_sign_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_f64( + double x, + double *out0); +hmath_status hmath_scalar_sign_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_rational( + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +hmath_status hmath_scalar_sign_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1) { + if (!hm_decimal(x_numerator) || !hm_decimal(x_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *x_digit = x_denominator; + if (*x_digit == '-') ++x_digit; + while (*x_digit == '0') ++x_digit; + if (!*x_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_rational(x_numerator, x_denominator, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_integer( + const char *x, + char **out0); +hmath_status hmath_scalar_sign_integer( + hmath_context *context, + const char *x, + char **out0) { + if (!hm_decimal(x)) + return hm_error(HMATH_INVALID_ARGUMENT, "x: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_integer(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_i8( + int8_t x, + int8_t *out0); +hmath_status hmath_scalar_sign_i8( + hmath_context *context, + int8_t x, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_i8(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_i16( + int16_t x, + int16_t *out0); +hmath_status hmath_scalar_sign_i16( + hmath_context *context, + int16_t x, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_i16(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_i32( + int32_t x, + int32_t *out0); +hmath_status hmath_scalar_sign_i32( + hmath_context *context, + int32_t x, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_i32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_i64( + int64_t x, + int64_t *out0); +hmath_status hmath_scalar_sign_i64( + hmath_context *context, + int64_t x, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_i64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_u8( + uint8_t x, + uint8_t *out0); +hmath_status hmath_scalar_sign_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_u8(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_u16( + uint16_t x, + uint16_t *out0); +hmath_status hmath_scalar_sign_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_u16(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_u32( + uint32_t x, + uint32_t *out0); +hmath_status hmath_scalar_sign_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_u32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_u64( + uint64_t x, + uint64_t *out0); +hmath_status hmath_scalar_sign_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_u64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_int( + ptrdiff_t x, + ptrdiff_t *out0); +hmath_status hmath_scalar_sign_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_int(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_word( + size_t x, + size_t *out0); +hmath_status hmath_scalar_sign_word( + hmath_context *context, + size_t x, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_word(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_c64( + float x_0, + float x_1, + float *out0, + float *out1); +hmath_status hmath_scalar_sign_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_c64(x_0, x_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sign_c128( + double x_0, + double x_1, + double *out0, + double *out1); +hmath_status hmath_scalar_sign_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sign_c128(x_0, x_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_divide_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_divide_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_divide_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_divide_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_divide_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_divide_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_power_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_power_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_power_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_power_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_power_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_power_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_hypot_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_hypot_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_hypot_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_hypot_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_hypot_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_hypot_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_clamp_checked_f32( + float low, + float high, + float value, + float *out0); +hmath_status hmath_scalar_clamp_checked_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_clamp_checked_f32(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_clamp_checked_f64( + double low, + double high, + double value, + double *out0); +hmath_status hmath_scalar_clamp_checked_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_clamp_checked_f64(low, high, value, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_lerp_checked_f32( + float a, + float b, + float t, + float *out0); +hmath_status hmath_scalar_lerp_checked_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_lerp_checked_f32(a, b, t, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_lerp_checked_f64( + double a, + double b, + double t, + double *out0); +hmath_status hmath_scalar_lerp_checked_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_lerp_checked_f64(a, b, t, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_inverse_lerp_f32( + float a, + float b, + float x, + float *out0); +hmath_status hmath_scalar_inverse_lerp_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_inverse_lerp_f32(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_inverse_lerp_f64( + double a, + double b, + double x, + double *out0); +hmath_status hmath_scalar_inverse_lerp_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_inverse_lerp_f64(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_smoothstep_f32( + float a, + float b, + float x, + float *out0); +hmath_status hmath_scalar_smoothstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_smoothstep_f32(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_smoothstep_f64( + double a, + double b, + double x, + double *out0); +hmath_status hmath_scalar_smoothstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_smoothstep_f64(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_smootherstep_f32( + float a, + float b, + float x, + float *out0); +hmath_status hmath_scalar_smootherstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_smootherstep_f32(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_smootherstep_f64( + double a, + double b, + double x, + double *out0); +hmath_status hmath_scalar_smootherstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_smootherstep_f64(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_remap_f32( + float a, + float b, + float c, + float d, + float x, + float *out0); +hmath_status hmath_scalar_remap_f32( + hmath_context *context, + float a, + float b, + float c, + float d, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_remap_f32(a, b, c, d, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_remap_f64( + double a, + double b, + double c, + double d, + double x, + double *out0); +hmath_status hmath_scalar_remap_f64( + hmath_context *context, + double a, + double b, + double c, + double d, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_remap_f64(a, b, c, d, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_step_f32( + float edge, + float x, + float *out0); +hmath_status hmath_scalar_step_f32( + hmath_context *context, + float edge, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_step_f32(edge, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_step_f64( + double edge, + double x, + double *out0); +hmath_status hmath_scalar_step_f64( + hmath_context *context, + double edge, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_step_f64(edge, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sqrt_checked_f32( + float x, + float *out0); +hmath_status hmath_scalar_sqrt_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sqrt_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_sqrt_checked_f64( + double x, + double *out0); +hmath_status hmath_scalar_sqrt_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_sqrt_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cube_root_f32( + float x, + float *out0); +hmath_status hmath_scalar_cube_root_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cube_root_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cube_root_f64( + double x, + double *out0); +hmath_status hmath_scalar_cube_root_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cube_root_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_reciprocal_sqrt_f32( + float x, + float *out0); +hmath_status hmath_scalar_reciprocal_sqrt_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_reciprocal_sqrt_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_reciprocal_sqrt_f64( + double x, + double *out0); +hmath_status hmath_scalar_reciprocal_sqrt_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_reciprocal_sqrt_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_exp_checked_f32( + float x, + float *out0); +hmath_status hmath_scalar_exp_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_exp_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_exp_checked_f64( + double x, + double *out0); +hmath_status hmath_scalar_exp_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_exp_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_log_checked_f32( + float x, + float *out0); +hmath_status hmath_scalar_log_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_log_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_log_checked_f64( + double x, + double *out0); +hmath_status hmath_scalar_log_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_log_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_expm1_f32( + float x, + float *out0); +hmath_status hmath_scalar_expm1_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_expm1_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_expm1_f64( + double x, + double *out0); +hmath_status hmath_scalar_expm1_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_expm1_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_log1p_f32( + float x, + float *out0); +hmath_status hmath_scalar_log1p_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_log1p_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_log1p_f64( + double x, + double *out0); +hmath_status hmath_scalar_log1p_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_log1p_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_integer_power_f32( + float a, + const char *n, + float *out0); +hmath_status hmath_scalar_integer_power_f32( + hmath_context *context, + float a, + const char *n, + float *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_integer_power_f32(a, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_integer_power_f64( + double a, + const char *n, + double *out0); +hmath_status hmath_scalar_integer_power_f64( + hmath_context *context, + double a, + const char *n, + double *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_integer_power_f64(a, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_nth_root_f32( + ptrdiff_t n, + float x, + float *out0); +hmath_status hmath_scalar_nth_root_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_nth_root_f32(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_nth_root_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_scalar_nth_root_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_nth_root_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_round_digits_f32( + ptrdiff_t n, + float x, + float *out0); +hmath_status hmath_scalar_round_digits_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_round_digits_f32(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_round_digits_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_scalar_round_digits_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_round_digits_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_error_f32( + float actual, + float expected, + float *out0); +hmath_status hmath_scalar_absolute_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_error_f32(actual, expected, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_absolute_error_f64( + double actual, + double expected, + double *out0); +hmath_status hmath_scalar_absolute_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_absolute_error_f64(actual, expected, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_relative_error_f32( + float actual, + float expected, + float *out0); +hmath_status hmath_scalar_relative_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_relative_error_f32(actual, expected, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_relative_error_f64( + double actual, + double expected, + double *out0); +hmath_status hmath_scalar_relative_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_relative_error_f64(actual, expected, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_fused_multiply_add_f32( + float a, + float b, + float c, + float *out0); +hmath_status hmath_scalar_fused_multiply_add_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_fused_multiply_add_f32(a, b, c, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_fused_multiply_add_f64( + double a, + double b, + double c, + double *out0); +hmath_status hmath_scalar_fused_multiply_add_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_fused_multiply_add_f64(a, b, c, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_float_multiply_f32( + float a, + float b, + float *out0); +hmath_status hmath_scalar_checked_float_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_float_multiply_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_float_multiply_f64( + double a, + double b, + double *out0); +hmath_status hmath_scalar_checked_float_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_float_multiply_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_floor_checked_f32( + float x, + char **out0); +hmath_status hmath_scalar_floor_checked_f32( + hmath_context *context, + float x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_floor_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_floor_checked_f64( + double x, + char **out0); +hmath_status hmath_scalar_floor_checked_f64( + hmath_context *context, + double x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_floor_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_ceil_checked_f32( + float x, + char **out0); +hmath_status hmath_scalar_ceil_checked_f32( + hmath_context *context, + float x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_ceil_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_ceil_checked_f64( + double x, + char **out0); +hmath_status hmath_scalar_ceil_checked_f64( + hmath_context *context, + double x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_ceil_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_round_checked_f32( + float x, + char **out0); +hmath_status hmath_scalar_round_checked_f32( + hmath_context *context, + float x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_round_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_round_checked_f64( + double x, + char **out0); +hmath_status hmath_scalar_round_checked_f64( + hmath_context *context, + double x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_round_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_truncate_checked_f32( + float x, + char **out0); +hmath_status hmath_scalar_truncate_checked_f32( + hmath_context *context, + float x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_truncate_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_truncate_checked_f64( + double x, + char **out0); +hmath_status hmath_scalar_truncate_checked_f64( + hmath_context *context, + double x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_truncate_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_bankers_round_f32( + float x, + char **out0); +hmath_status hmath_scalar_bankers_round_f32( + hmath_context *context, + float x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_bankers_round_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_bankers_round_f64( + double x, + char **out0); +hmath_status hmath_scalar_bankers_round_f64( + hmath_context *context, + double x, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_bankers_round_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_integer_fraction_f32( + float x, + char **out0, + float *out1); +hmath_status hmath_scalar_integer_fraction_f32( + hmath_context *context, + float x, + char **out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_integer_fraction_f32(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_integer_fraction_f64( + double x, + char **out0, + double *out1); +hmath_status hmath_scalar_integer_fraction_f64( + hmath_context *context, + double x, + char **out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_integer_fraction_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_quotient_remainder( + const char *a, + const char *b, + char **out0, + char **out1); +hmath_status hmath_scalar_quotient_remainder( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_quotient_remainder(a, b, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_euclidean_division( + const char *a, + const char *b, + char **out0, + char **out1); +hmath_status hmath_scalar_euclidean_division( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_euclidean_division(a, b, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_integer( + const char *a, + const char *modulus, + char **out0); +hmath_status hmath_scalar_positive_modulo_integer( + hmath_context *context, + const char *a, + const char *modulus, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(modulus)) + return hm_error(HMATH_INVALID_ARGUMENT, "modulus: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_integer(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_i8( + int8_t a, + int8_t modulus, + int8_t *out0); +hmath_status hmath_scalar_positive_modulo_i8( + hmath_context *context, + int8_t a, + int8_t modulus, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_i8(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_i16( + int16_t a, + int16_t modulus, + int16_t *out0); +hmath_status hmath_scalar_positive_modulo_i16( + hmath_context *context, + int16_t a, + int16_t modulus, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_i16(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_i32( + int32_t a, + int32_t modulus, + int32_t *out0); +hmath_status hmath_scalar_positive_modulo_i32( + hmath_context *context, + int32_t a, + int32_t modulus, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_i32(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_i64( + int64_t a, + int64_t modulus, + int64_t *out0); +hmath_status hmath_scalar_positive_modulo_i64( + hmath_context *context, + int64_t a, + int64_t modulus, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_i64(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_u8( + uint8_t a, + uint8_t modulus, + uint8_t *out0); +hmath_status hmath_scalar_positive_modulo_u8( + hmath_context *context, + uint8_t a, + uint8_t modulus, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_u8(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_u16( + uint16_t a, + uint16_t modulus, + uint16_t *out0); +hmath_status hmath_scalar_positive_modulo_u16( + hmath_context *context, + uint16_t a, + uint16_t modulus, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_u16(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_u32( + uint32_t a, + uint32_t modulus, + uint32_t *out0); +hmath_status hmath_scalar_positive_modulo_u32( + hmath_context *context, + uint32_t a, + uint32_t modulus, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_u32(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_u64( + uint64_t a, + uint64_t modulus, + uint64_t *out0); +hmath_status hmath_scalar_positive_modulo_u64( + hmath_context *context, + uint64_t a, + uint64_t modulus, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_u64(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_int( + ptrdiff_t a, + ptrdiff_t modulus, + ptrdiff_t *out0); +hmath_status hmath_scalar_positive_modulo_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t modulus, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_int(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo_word( + size_t a, + size_t modulus, + size_t *out0); +hmath_status hmath_scalar_positive_modulo_word( + hmath_context *context, + size_t a, + size_t modulus, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo_word(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_positive_modulo( + const char *a, + const char *modulus, + char **out0); +hmath_status hmath_scalar_positive_modulo( + hmath_context *context, + const char *a, + const char *modulus, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(modulus)) + return hm_error(HMATH_INVALID_ARGUMENT, "modulus: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_positive_modulo(a, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_modular_power( + const char *a, + const char *n, + const char *modulus, + char **out0); +hmath_status hmath_scalar_modular_power( + hmath_context *context, + const char *a, + const char *n, + const char *modulus, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!hm_decimal(modulus)) + return hm_error(HMATH_INVALID_ARGUMENT, "modulus: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_modular_power(a, n, modulus, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_factorial_checked( + const char *n, + char **out0); +hmath_status hmath_scalar_factorial_checked( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_factorial_checked(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_double_factorial( + const char *n, + char **out0); +hmath_status hmath_scalar_double_factorial( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_double_factorial(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_fibonacci_checked( + const char *n, + char **out0); +hmath_status hmath_scalar_fibonacci_checked( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_fibonacci_checked(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_lucas( + const char *n, + char **out0); +hmath_status hmath_scalar_lucas( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_lucas(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_catalan( + const char *n, + char **out0); +hmath_status hmath_scalar_catalan( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_catalan(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_rising_factorial( + const char *x, + const char *n, + char **out0); +hmath_status hmath_scalar_rising_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0) { + if (!hm_decimal(x)) + return hm_error(HMATH_INVALID_ARGUMENT, "x: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_rising_factorial(x, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_falling_factorial( + const char *x, + const char *n, + char **out0); +hmath_status hmath_scalar_falling_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0) { + if (!hm_decimal(x)) + return hm_error(HMATH_INVALID_ARGUMENT, "x: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_falling_factorial(x, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_permutations( + const char *n, + const char *k, + char **out0); +hmath_status hmath_scalar_permutations( + hmath_context *context, + const char *n, + const char *k, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!hm_decimal(k)) + return hm_error(HMATH_INVALID_ARGUMENT, "k: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_permutations(n, k, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_combinations( + const char *n, + const char *k, + char **out0); +hmath_status hmath_scalar_combinations( + hmath_context *context, + const char *n, + const char *k, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!hm_decimal(k)) + return hm_error(HMATH_INVALID_ARGUMENT, "k: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_combinations(n, k, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_bernoulli( + ptrdiff_t n, + char **out0, + char **out1); +hmath_status hmath_scalar_bernoulli( + hmath_context *context, + ptrdiff_t n, + char **out0, + char **out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_bernoulli(n, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_harmonic( + const char *n, + char **out0, + char **out1); +hmath_status hmath_scalar_harmonic( + hmath_context *context, + const char *n, + char **out0, + char **out1) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_harmonic(n, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_f32( + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +hmath_status hmath_scalar_cumulative_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 0 > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 0) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 0) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_f32(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_f64( + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +hmath_status hmath_scalar_cumulative_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 0 > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 0) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 0) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_f64(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_rational( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_rational(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_integer( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (values_count && !values)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < values_count; ++i) if (!hm_decimal(values[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_integer(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_i8( + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_i8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_i16( + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_i16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_i32( + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_i32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_i64( + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_i64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_u8( + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_u8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_u16( + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_u16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_u32( + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_u32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_u64( + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_u64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_int( + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_int(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_word( + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_word(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_c64( + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_c64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_sum_c128( + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_sum_c128(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_f32( + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +hmath_status hmath_scalar_cumulative_product_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 0 > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 0) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 0) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_f32(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_f64( + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +hmath_status hmath_scalar_cumulative_product_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 0 > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 0) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 0) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_f64(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_rational( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_rational(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_integer( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (values_count && !values)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < values_count; ++i) if (!hm_decimal(values[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_integer(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_i8( + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_i8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_i16( + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_i16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_i32( + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_i32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_i64( + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_i64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_u8( + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_u8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_u16( + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_u16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_u32( + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_u32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_u64( + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_u64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_int( + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_int(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_word( + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_word(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_c64( + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_c64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_cumulative_product_c128( + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +hmath_status hmath_scalar_cumulative_product_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_cumulative_product_c128(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_f32( + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +hmath_status hmath_scalar_prefix_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 1 > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 1) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 1) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_f32(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_f64( + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +hmath_status hmath_scalar_prefix_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (values_count + 1 > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t"); + if (out_capacity < values_count + 1) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity"); + if ((values_count + 1) && !out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_f64(values, values_count, out0, out_capacity); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_rational( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_rational(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_integer( + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (values_count && !values)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < values_count; ++i) if (!hm_decimal(values[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_integer(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_i8( + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_i8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_i16( + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_i16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_i32( + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_i32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_i64( + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_i64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_u8( + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_u8(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_u16( + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_u16(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_u32( + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_u32(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_u64( + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_u64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_int( + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_int(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_word( + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_word(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_c64( + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_c64(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_prefix_sum_c128( + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +hmath_status hmath_scalar_prefix_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_prefix_sum_c128(values, values_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sin_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_sin_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sin_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sin_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_sin_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sin_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cos_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_cos_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cos_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cos_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_cos_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cos_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_tan_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_tan_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_tan_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_tan_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_tan_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_tan_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asin_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_asin_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asin_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asin_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_asin_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asin_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acos_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acos_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acos_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acos_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acos_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acos_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atan_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_atan_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atan_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atan_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_atan_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atan_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sec_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_sec_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sec_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sec_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_sec_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sec_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_csc_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_csc_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_csc_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_csc_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_csc_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_csc_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cot_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_cot_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cot_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cot_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_cot_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cot_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asec_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_asec_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asec_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asec_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_asec_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asec_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acsc_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acsc_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acsc_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acsc_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acsc_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acsc_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acot_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acot_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acot_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acot_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acot_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acot_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sinh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_sinh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sinh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sinh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_sinh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sinh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cosh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_cosh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cosh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cosh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_cosh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cosh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_tanh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_tanh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_tanh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_tanh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_tanh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_tanh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asinh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_asinh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asinh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asinh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_asinh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asinh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acosh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acosh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acosh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acosh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acosh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acosh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atanh_checked_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_atanh_checked_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atanh_checked_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atanh_checked_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_atanh_checked_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atanh_checked_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sech_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_sech_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sech_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sech_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_sech_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sech_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_csch_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_csch_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_csch_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_csch_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_csch_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_csch_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_coth_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_coth_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_coth_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_coth_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_coth_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_coth_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asech_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_asech_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asech_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_asech_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_asech_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_asech_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acsch_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acsch_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acsch_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acsch_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acsch_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acsch_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acoth_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_acoth_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acoth_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_acoth_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_acoth_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_acoth_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_normalize_angle_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_normalize_angle_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_normalize_angle_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_normalize_angle_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_normalize_angle_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_normalize_angle_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_normalize_signed_angle_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_normalize_signed_angle_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_normalize_signed_angle_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_normalize_signed_angle_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_normalize_signed_angle_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_normalize_signed_angle_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_versine_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_versine_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_versine_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_versine_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_versine_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_versine_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_haversine_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_haversine_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_haversine_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_haversine_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_haversine_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_haversine_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sinc_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_sinc_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sinc_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sinc_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_sinc_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sinc_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cosc_f32( + float x, + float *out0); +hmath_status hmath_trigonometry_cosc_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cosc_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_cosc_f64( + double x, + double *out0); +hmath_status hmath_trigonometry_cosc_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_cosc_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atan2_checked_f32( + float y, + float x, + float *out0); +hmath_status hmath_trigonometry_atan2_checked_f32( + hmath_context *context, + float y, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atan2_checked_f32(y, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_atan2_checked_f64( + double y, + double x, + double *out0); +hmath_status hmath_trigonometry_atan2_checked_f64( + hmath_context *context, + double y, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_atan2_checked_f64(y, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sincos_f32( + float x, + float *out0, + float *out1); +hmath_status hmath_trigonometry_sincos_f32( + hmath_context *context, + float x, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sincos_f32(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_sincos_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_trigonometry_sincos_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_sincos_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_wrap_f32( + float low, + float high, + float x, + float *out0); +hmath_status hmath_trigonometry_wrap_f32( + hmath_context *context, + float low, + float high, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_wrap_f32(low, high, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_wrap_f64( + double low, + double high, + double x, + double *out0); +hmath_status hmath_trigonometry_wrap_f64( + hmath_context *context, + double low, + double high, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_wrap_f64(low, high, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_angle_difference_f32( + float a, + float b, + float *out0); +hmath_status hmath_trigonometry_angle_difference_f32( + hmath_context *context, + float a, + float b, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_angle_difference_f32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_angle_difference_f64( + double a, + double b, + double *out0); +hmath_status hmath_trigonometry_angle_difference_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_angle_difference_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_great_circle_angle_f32( + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +hmath_status hmath_trigonometry_great_circle_angle_f32( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_great_circle_angle_f32(a_0, a_1, b_0, b_1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_great_circle_angle_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +hmath_status hmath_trigonometry_great_circle_angle_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_great_circle_angle_f64(a_0, a_1, b_0, b_1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_great_circle_distance_f32( + float radius, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +hmath_status hmath_trigonometry_great_circle_distance_f32( + hmath_context *context, + float radius, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_great_circle_distance_f32(radius, a_0, a_1, b_0, b_1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_great_circle_distance_f64( + double radius, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +hmath_status hmath_trigonometry_great_circle_distance_f64( + hmath_context *context, + double radius, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_great_circle_distance_f64(radius, a_0, a_1, b_0, b_1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_side_f32( + float a, + float b, + float included, + float *out0); +hmath_status hmath_trigonometry_spherical_side_f32( + hmath_context *context, + float a, + float b, + float included, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_side_f32(a, b, included, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_side_f64( + double a, + double b, + double included, + double *out0); +hmath_status hmath_trigonometry_spherical_side_f64( + hmath_context *context, + double a, + double b, + double included, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_side_f64(a, b, included, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_angles_f32( + float a, + float b, + float c, + float *out0, + float *out1, + float *out2); +hmath_status hmath_trigonometry_spherical_angles_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0, + float *out1, + float *out2) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_angles_f32(a, b, c, out0, out1, out2); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_angles_f64( + double a, + double b, + double c, + double *out0, + double *out1, + double *out2); +hmath_status hmath_trigonometry_spherical_angles_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0, + double *out1, + double *out2) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_angles_f64(a, b, c, out0, out1, out2); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_excess_f32( + float a, + float b, + float c, + float *out0); +hmath_status hmath_trigonometry_spherical_excess_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_excess_f32(a, b, c, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_spherical_excess_f64( + double a, + double b, + double c, + double *out0); +hmath_status hmath_trigonometry_spherical_excess_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_spherical_excess_f64(a, b, c, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_sin_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_sin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_sin_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_sin_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_sin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_sin_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_cos_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_cos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_cos_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_cos_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_cos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_cos_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_tan_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_tan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_tan_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_tan_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_tan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_tan_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_asin_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_asin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_asin_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_asin_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_asin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_asin_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_acos_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_acos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_acos_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_acos_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_acos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_acos_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_atan_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_atan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_atan_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_atan_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_atan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_atan_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_sinh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_sinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_sinh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_sinh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_sinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_sinh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_cosh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_cosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_cosh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_cosh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_cosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_cosh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_tanh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_tanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_tanh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_tanh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_tanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_tanh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_asinh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_asinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_asinh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_asinh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_asinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_asinh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_acosh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_acosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_acosh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_acosh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_acosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_acosh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_atanh_f32( + float z_0, + float z_1, + float *out0, + float *out1); +hmath_status hmath_trigonometry_complex_atanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_atanh_f32(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_complex_atanh_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_trigonometry_complex_atanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_complex_atanh_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_sawtooth_f32( + float period, + float x, + float *out0); +hmath_status hmath_trigonometry_periodic_sawtooth_f32( + hmath_context *context, + float period, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_sawtooth_f32(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_sawtooth_f64( + double period, + double x, + double *out0); +hmath_status hmath_trigonometry_periodic_sawtooth_f64( + hmath_context *context, + double period, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_sawtooth_f64(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_triangle_f32( + float period, + float x, + float *out0); +hmath_status hmath_trigonometry_periodic_triangle_f32( + hmath_context *context, + float period, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_triangle_f32(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_triangle_f64( + double period, + double x, + double *out0); +hmath_status hmath_trigonometry_periodic_triangle_f64( + hmath_context *context, + double period, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_triangle_f64(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_square_f32( + float period, + float x, + float *out0); +hmath_status hmath_trigonometry_periodic_square_f32( + hmath_context *context, + float period, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_square_f32(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_trigonometry_periodic_square_f64( + double period, + double x, + double *out0); +hmath_status hmath_trigonometry_periodic_square_f64( + hmath_context *context, + double period, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_trigonometry_periodic_square_f64(period, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_mean_f32( + const float *values, + size_t values_count, + float *out0); +hmath_status hmath_statistics_mean_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_mean_f32(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_mean_f64( + const double *values, + size_t values_count, + double *out0); +hmath_status hmath_statistics_mean_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_mean_f64(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_mean_rational( + const char * const *values, + size_t values_count, + char **out0, + char **out1); +hmath_status hmath_statistics_mean_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_mean_rational(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_mean_c64( + float const *values, + size_t values_count, + float *out0, + float *out1); +hmath_status hmath_statistics_mean_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_mean_c64(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_mean_c128( + double const *values, + size_t values_count, + double *out0, + double *out1); +hmath_status hmath_statistics_mean_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_mean_c128(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_variance_f32( + const float *values, + size_t values_count, + float *out0); +hmath_status hmath_statistics_variance_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_variance_f32(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_variance_f64( + const double *values, + size_t values_count, + double *out0); +hmath_status hmath_statistics_variance_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_variance_f64(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_variance_rational( + const char * const *values, + size_t values_count, + char **out0, + char **out1); +hmath_status hmath_statistics_variance_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_variance_rational(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_variance_c64( + float const *values, + size_t values_count, + float *out0, + float *out1); +hmath_status hmath_statistics_variance_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_variance_c64(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_variance_c128( + double const *values, + size_t values_count, + double *out0, + double *out1); +hmath_status hmath_statistics_variance_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_variance_c128(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_standard_deviation_f32( + const float *values, + size_t values_count, + float *out0); +hmath_status hmath_statistics_standard_deviation_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_standard_deviation_f32(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_standard_deviation_f64( + const double *values, + size_t values_count, + double *out0); +hmath_status hmath_statistics_standard_deviation_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_standard_deviation_f64(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_standard_deviation_c64( + float const *values, + size_t values_count, + float *out0, + float *out1); +hmath_status hmath_statistics_standard_deviation_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_standard_deviation_c64(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_standard_deviation_c128( + double const *values, + size_t values_count, + double *out0, + double *out1); +hmath_status hmath_statistics_standard_deviation_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_standard_deviation_c128(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_median_f32( + const float *values, + size_t values_count, + float *out0); +hmath_status hmath_statistics_median_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_median_f32(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_median_f64( + const double *values, + size_t values_count, + double *out0); +hmath_status hmath_statistics_median_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_median_f64(values, values_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_median_rational( + const char * const *values, + size_t values_count, + char **out0, + char **out1); +hmath_status hmath_statistics_median_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1) { + if (values_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * values_count; ++i) { + if (!hm_decimal(values[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = values[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_median_rational(values, values_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_constants_pi_constant_f32( + float *out0); +hmath_status hmath_constants_pi_constant_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_pi_constant_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_pi_constant_f64( + double *out0); +hmath_status hmath_constants_pi_constant_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_pi_constant_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_e_constant_f32( + float *out0); +hmath_status hmath_constants_e_constant_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_e_constant_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_e_constant_f64( + double *out0); +hmath_status hmath_constants_e_constant_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_e_constant_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_tau_f32( + float *out0); +hmath_status hmath_constants_tau_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_tau_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_tau_f64( + double *out0); +hmath_status hmath_constants_tau_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_tau_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_golden_ratio_f32( + float *out0); +hmath_status hmath_constants_golden_ratio_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_golden_ratio_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_golden_ratio_f64( + double *out0); +hmath_status hmath_constants_golden_ratio_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_golden_ratio_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_euler_mascheroni_f32( + float *out0); +hmath_status hmath_constants_euler_mascheroni_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_euler_mascheroni_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_euler_mascheroni_f64( + double *out0); +hmath_status hmath_constants_euler_mascheroni_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_euler_mascheroni_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_catalan_constant_f32( + float *out0); +hmath_status hmath_constants_catalan_constant_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_catalan_constant_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_catalan_constant_f64( + double *out0); +hmath_status hmath_constants_catalan_constant_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_catalan_constant_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_apery_constant_f32( + float *out0); +hmath_status hmath_constants_apery_constant_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_apery_constant_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_apery_constant_f64( + double *out0); +hmath_status hmath_constants_apery_constant_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_apery_constant_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_sqrt2_f32( + float *out0); +hmath_status hmath_constants_sqrt2_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_sqrt2_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_sqrt2_f64( + double *out0); +hmath_status hmath_constants_sqrt2_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_sqrt2_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_sqrt3_f32( + float *out0); +hmath_status hmath_constants_sqrt3_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_sqrt3_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_sqrt3_f64( + double *out0); +hmath_status hmath_constants_sqrt3_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_sqrt3_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_ln2_f32( + float *out0); +hmath_status hmath_constants_ln2_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_ln2_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_ln2_f64( + double *out0); +hmath_status hmath_constants_ln2_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_ln2_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_ln10_f32( + float *out0); +hmath_status hmath_constants_ln10_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_ln10_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_ln10_f64( + double *out0); +hmath_status hmath_constants_ln10_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_ln10_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_infinity_f32( + float *out0); +hmath_status hmath_constants_infinity_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_infinity_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_infinity_f64( + double *out0); +hmath_status hmath_constants_infinity_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_infinity_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_nan_f32( + float *out0); +hmath_status hmath_constants_nan_f32( + hmath_context *context, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_nan_f32(out0); + hm_leave(); + return status; +} +extern int hm_numeric_constants_nan_f64( + double *out0); +hmath_status hmath_constants_nan_f64( + hmath_context *context, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_constants_nan_f64(out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_multinomial( + const char * const *ks, + size_t ks_count, + char **out0); +hmath_status hmath_scalar_multinomial( + hmath_context *context, + const char * const *ks, + size_t ks_count, + char **out0) { + if (ks_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (ks_count && !ks)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < ks_count; ++i) if (!hm_decimal(ks[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (ks_count && !ks) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_multinomial(ks, ks_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_gcd_integer( + const char *argument1, + const char *argument2, + char **out0); +hmath_status hmath_numbertheory_gcd_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0) { + if (!hm_decimal(argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "argument1: expected signed decimal Integer"); + if (!hm_decimal(argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "argument2: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_gcd_integer(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_lcm_integer( + const char *argument1, + const char *argument2, + char **out0); +hmath_status hmath_numbertheory_lcm_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0) { + if (!hm_decimal(argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "argument1: expected signed decimal Integer"); + if (!hm_decimal(argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "argument2: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_lcm_integer(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_extended_g_c_d( + const char *a, + const char *b, + char **out0, + char **out1, + char **out2); +hmath_status hmath_numbertheory_extended_g_c_d( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1, + char **out2) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_extended_g_c_d(a, b, out0, out1, out2); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_bezout( + const char *a, + const char *b, + char **out0, + char **out1); +hmath_status hmath_numbertheory_bezout( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_bezout(a, b, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_mod_pow( + const char *a, + const char *e, + const char *m, + char **out0); +hmath_status hmath_numbertheory_mod_pow( + hmath_context *context, + const char *a, + const char *e, + const char *m, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(e)) + return hm_error(HMATH_INVALID_ARGUMENT, "e: expected signed decimal Integer"); + if (!hm_decimal(m)) + return hm_error(HMATH_INVALID_ARGUMENT, "m: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_mod_pow(a, e, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_mod_inverse( + const char *a, + const char *m, + char **out0); +hmath_status hmath_numbertheory_mod_inverse( + hmath_context *context, + const char *a, + const char *m, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(m)) + return hm_error(HMATH_INVALID_ARGUMENT, "m: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_mod_inverse(a, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_integer_square_root( + const char *n, + char **out0); +hmath_status hmath_numbertheory_integer_square_root( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_integer_square_root(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_is_prime_exact( + ptrdiff_t budget, + const char *n, + int *out0); +hmath_status hmath_numbertheory_is_prime_exact( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_is_prime_exact(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_next_prime( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_next_prime( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_next_prime(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_miller_rabin( + const char * const *bases, + size_t bases_count, + const char *n, + int *out0); +hmath_status hmath_numbertheory_miller_rabin( + hmath_context *context, + const char * const *bases, + size_t bases_count, + const char *n, + int *out0) { + if (bases_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (bases_count && !bases)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < bases_count; ++i) if (!hm_decimal(bases[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (bases_count && !bases) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_miller_rabin(bases, bases_count, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_baillie_p_s_w( + const char *n, + int *out0); +hmath_status hmath_numbertheory_baillie_p_s_w( + hmath_context *context, + const char *n, + int *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_baillie_p_s_w(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_sieve_eratosthenes( + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_sieve_eratosthenes( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_sieve_eratosthenes(bound, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_sieve_atkin( + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_sieve_atkin( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_sieve_atkin(bound, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_segmented_sieve( + const char *lo, + const char *hi, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_segmented_sieve( + hmath_context *context, + const char *lo, + const char *hi, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(lo)) + return hm_error(HMATH_INVALID_ARGUMENT, "lo: expected signed decimal Integer"); + if (!hm_decimal(hi)) + return hm_error(HMATH_INVALID_ARGUMENT, "hi: expected signed decimal Integer"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_segmented_sieve(lo, hi, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_pollard_rho( + ptrdiff_t budget, + const char *seed, + const char *n, + char **out0); +hmath_status hmath_numbertheory_pollard_rho( + hmath_context *context, + ptrdiff_t budget, + const char *seed, + const char *n, + char **out0) { + if (!hm_decimal(seed)) + return hm_error(HMATH_INVALID_ARGUMENT, "seed: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_pollard_rho(budget, seed, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_pollard_p_minus_one( + ptrdiff_t bound, + const char *base, + const char *n, + char **out0); +hmath_status hmath_numbertheory_pollard_p_minus_one( + hmath_context *context, + ptrdiff_t bound, + const char *base, + const char *n, + char **out0) { + if (!hm_decimal(base)) + return hm_error(HMATH_INVALID_ARGUMENT, "base: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_pollard_p_minus_one(bound, base, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_fermat_factor( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_fermat_factor( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_fermat_factor(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_divisors( + ptrdiff_t budget, + const char *n, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_divisors( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_divisors(budget, n, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_divisor_sum( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_divisor_sum( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_divisor_sum(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_divisor_count( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_divisor_count( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_divisor_count(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_euler_totient( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_euler_totient( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_euler_totient(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_carmichael( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_carmichael( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_carmichael(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_mobius( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_mobius( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_mobius(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_liouville( + ptrdiff_t budget, + const char *n, + char **out0); +hmath_status hmath_numbertheory_liouville( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_liouville(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_multiplicative_order( + ptrdiff_t budget, + const char *a, + const char *m, + char **out0); +hmath_status hmath_numbertheory_multiplicative_order( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *m, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(m)) + return hm_error(HMATH_INVALID_ARGUMENT, "m: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_multiplicative_order(budget, a, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_primitive_root( + ptrdiff_t budget, + const char *m, + char **out0); +hmath_status hmath_numbertheory_primitive_root( + hmath_context *context, + ptrdiff_t budget, + const char *m, + char **out0) { + if (!hm_decimal(m)) + return hm_error(HMATH_INVALID_ARGUMENT, "m: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_primitive_root(budget, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_discrete_log( + ptrdiff_t budget, + const char *a, + const char *b, + const char *m, + char **out0); +hmath_status hmath_numbertheory_discrete_log( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + const char *m, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!hm_decimal(m)) + return hm_error(HMATH_INVALID_ARGUMENT, "m: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_discrete_log(budget, a, b, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_legendre_symbol( + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +hmath_status hmath_numbertheory_legendre_symbol( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(p)) + return hm_error(HMATH_INVALID_ARGUMENT, "p: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_legendre_symbol(budget, a, p, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_jacobi_symbol( + const char *a, + const char *n, + char **out0); +hmath_status hmath_numbertheory_jacobi_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_jacobi_symbol(a, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_kronecker_symbol( + const char *a, + const char *n, + char **out0); +hmath_status hmath_numbertheory_kronecker_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_kronecker_symbol(a, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_tonelli_shanks( + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +hmath_status hmath_numbertheory_tonelli_shanks( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(p)) + return hm_error(HMATH_INVALID_ARGUMENT, "p: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_tonelli_shanks(budget, a, p, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_continued_fraction( + const char *r_numerator, + const char *r_denominator, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_continued_fraction( + hmath_context *context, + const char *r_numerator, + const char *r_denominator, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(r_numerator) || !hm_decimal(r_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *r_digit = r_denominator; + if (*r_digit == '-') ++r_digit; + while (*r_digit == '0') ++r_digit; + if (!*r_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_continued_fraction(r_numerator, r_denominator, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_from_continued_fraction( + const char * const *argument1, + size_t argument1_count, + char **out0, + char **out1); +hmath_status hmath_numbertheory_from_continued_fraction( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char **out0, + char **out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_from_continued_fraction(argument1, argument1_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_convergents( + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_convergents( + hmath_context *context, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < xs_count; ++i) if (!hm_decimal(xs[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_convergents(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_farey( + const char *n, + char * **out_data, + size_t *out_count); +hmath_status hmath_numbertheory_farey( + hmath_context *context, + const char *n, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_farey(n, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_pell_fundamental( + ptrdiff_t budget, + const char *d, + char **out0, + char **out1); +hmath_status hmath_numbertheory_pell_fundamental( + hmath_context *context, + ptrdiff_t budget, + const char *d, + char **out0, + char **out1) { + if (!hm_decimal(d)) + return hm_error(HMATH_INVALID_ARGUMENT, "d: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_pell_fundamental(budget, d, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_is_perfect_number( + ptrdiff_t budget, + const char *n, + int *out0); +hmath_status hmath_numbertheory_is_perfect_number( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_is_perfect_number(budget, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_are_amicable( + ptrdiff_t budget, + const char *a, + const char *b, + int *out0); +hmath_status hmath_numbertheory_are_amicable( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + int *out0) { + if (!hm_decimal(a)) + return hm_error(HMATH_INVALID_ARGUMENT, "a: expected signed decimal Integer"); + if (!hm_decimal(b)) + return hm_error(HMATH_INVALID_ARGUMENT, "b: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_are_amicable(budget, a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_partition_count( + ptrdiff_t n, + char **out0); +hmath_status hmath_numbertheory_partition_count( + hmath_context *context, + ptrdiff_t n, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_partition_count(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numbertheory_fibonacci_fast( + const char *n, + char **out0); +hmath_status hmath_numbertheory_fibonacci_fast( + hmath_context *context, + const char *n, + char **out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numbertheory_fibonacci_fast(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_permutations_count( + ptrdiff_t n, + ptrdiff_t k, + char **out0); +hmath_status hmath_combinatorics_permutations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_permutations_count(n, k, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_combinations_count( + ptrdiff_t n, + ptrdiff_t k, + char **out0); +hmath_status hmath_combinatorics_combinations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_combinations_count(n, k, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_multinomial( + ptrdiff_t const *argument1, + size_t argument1_count, + char **out0); +hmath_status hmath_combinatorics_multinomial( + hmath_context *context, + ptrdiff_t const *argument1, + size_t argument1_count, + char **out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_multinomial(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_rank_permutation( + ptrdiff_t const *p, + size_t p_count, + char **out0); +hmath_status hmath_combinatorics_rank_permutation( + hmath_context *context, + ptrdiff_t const *p, + size_t p_count, + char **out0) { + if (p_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (p_count && !p)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (p_count && !p) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_rank_permutation(p, p_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_unrank_permutation( + ptrdiff_t n, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_combinatorics_unrank_permutation( + hmath_context *context, + ptrdiff_t n, + const char *r, + ptrdiff_t **out_data, + size_t *out_count) { + if (!hm_decimal(r)) + return hm_error(HMATH_INVALID_ARGUMENT, "r: expected signed decimal Integer"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_unrank_permutation(n, r, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_rank_combination( + ptrdiff_t n, + ptrdiff_t const *xs, + size_t xs_count, + char **out0); +hmath_status hmath_combinatorics_rank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t const *xs, + size_t xs_count, + char **out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_rank_combination(n, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_unrank_combination( + ptrdiff_t n, + ptrdiff_t k, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_combinatorics_unrank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + const char *r, + ptrdiff_t **out_data, + size_t *out_count) { + if (!hm_decimal(r)) + return hm_error(HMATH_INVALID_ARGUMENT, "r: expected signed decimal Integer"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_unrank_combination(n, k, r, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_derangement_count( + ptrdiff_t n, + char **out0); +hmath_status hmath_combinatorics_derangement_count( + hmath_context *context, + ptrdiff_t n, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_derangement_count(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_stirling_first( + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +hmath_status hmath_combinatorics_stirling_first( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_stirling_first(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_stirling_second( + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +hmath_status hmath_combinatorics_stirling_second( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_stirling_second(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_bell_number( + ptrdiff_t n, + char **out0); +hmath_status hmath_combinatorics_bell_number( + hmath_context *context, + ptrdiff_t n, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_bell_number(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_eulerian_number( + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +hmath_status hmath_combinatorics_eulerian_number( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_eulerian_number(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_lah_number( + ptrdiff_t n, + ptrdiff_t k, + char **out0); +hmath_status hmath_combinatorics_lah_number( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_lah_number(n, k, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_catalan_number( + ptrdiff_t argument1, + char **out0); +hmath_status hmath_combinatorics_catalan_number( + hmath_context *context, + ptrdiff_t argument1, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_catalan_number(argument1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_fibonacci( + ptrdiff_t n, + char **out0); +hmath_status hmath_combinatorics_fibonacci( + hmath_context *context, + ptrdiff_t n, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_fibonacci(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_lucas( + ptrdiff_t n, + char **out0); +hmath_status hmath_combinatorics_lucas( + hmath_context *context, + ptrdiff_t n, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_lucas(n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_inclusion_exclusion( + ptrdiff_t n, + const char * const *sizes, + size_t sizes_count, + char **out0); +hmath_status hmath_combinatorics_inclusion_exclusion( + hmath_context *context, + ptrdiff_t n, + const char * const *sizes, + size_t sizes_count, + char **out0) { + if (sizes_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (sizes_count && !sizes)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < sizes_count; ++i) if (!hm_decimal(sizes[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (sizes_count && !sizes) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_inclusion_exclusion(n, sizes, sizes_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_multiset_count_f32( + const float *argument1, + size_t argument1_count, + char **out0); +hmath_status hmath_combinatorics_multiset_count_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + char **out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_multiset_count_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_multiset_count_f64( + const double *argument1, + size_t argument1_count, + char **out0); +hmath_status hmath_combinatorics_multiset_count_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + char **out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_multiset_count_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_linear_recurrence( + ptrdiff_t n, + const char * const *cs, + size_t cs_count, + const char * const *initial, + size_t initial_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_combinatorics_linear_recurrence( + hmath_context *context, + ptrdiff_t n, + const char * const *cs, + size_t cs_count, + const char * const *initial, + size_t initial_count, + char * **out_data, + size_t *out_count) { + if (cs_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (cs_count && !cs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < cs_count; ++i) if (!hm_decimal(cs[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (cs_count && !cs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (initial_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (initial_count && !initial)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < initial_count; ++i) if (!hm_decimal(initial[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (initial_count && !initial) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_linear_recurrence(n, cs, cs_count, initial, initial_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_convolve_series( + ptrdiff_t n, + const char * const *a, + size_t a_count, + const char * const *b, + size_t b_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_combinatorics_convolve_series( + hmath_context *context, + ptrdiff_t n, + const char * const *a, + size_t a_count, + const char * const *b, + size_t b_count, + char * **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (a_count && !a)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < a_count; ++i) if (!hm_decimal(a[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (b_count && !b)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < b_count; ++i) if (!hm_decimal(b[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_convolve_series(n, a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_finite_sum_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_combinatorics_finite_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_finite_sum_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_combinatorics_finite_sum_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_combinatorics_finite_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_combinatorics_finite_sum_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +hmath_status hmath_linear_dot_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_f32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +hmath_status hmath_linear_dot_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_f64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_rational( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +hmath_status hmath_linear_dot_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument1_count; ++i) { + if (!hm_decimal(argument1[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument1[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_rational(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_integer( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +hmath_status hmath_linear_dot_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_integer(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_i8( + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +hmath_status hmath_linear_dot_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_i8(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_i16( + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +hmath_status hmath_linear_dot_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_i16(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_i32( + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +hmath_status hmath_linear_dot_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_i32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_i64( + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +hmath_status hmath_linear_dot_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_i64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_u8( + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +hmath_status hmath_linear_dot_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_u8(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_u16( + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +hmath_status hmath_linear_dot_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_u16(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_u32( + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +hmath_status hmath_linear_dot_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_u32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_u64( + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +hmath_status hmath_linear_dot_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_u64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_int( + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +hmath_status hmath_linear_dot_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_int(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_word( + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +hmath_status hmath_linear_dot_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_word(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_c64( + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +hmath_status hmath_linear_dot_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_c64(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_c128( + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +hmath_status hmath_linear_dot_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_c128(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +hmath_status hmath_linear_dot_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_f32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +hmath_status hmath_linear_dot_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_f64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_rational( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +hmath_status hmath_linear_dot_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument1_count; ++i) { + if (!hm_decimal(argument1[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument1[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_rational(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_integer( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +hmath_status hmath_linear_dot_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_integer(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_i8( + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +hmath_status hmath_linear_dot_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_i8(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_i16( + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +hmath_status hmath_linear_dot_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_i16(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_i32( + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +hmath_status hmath_linear_dot_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_i32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_i64( + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +hmath_status hmath_linear_dot_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_i64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_u8( + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +hmath_status hmath_linear_dot_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_u8(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_u16( + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +hmath_status hmath_linear_dot_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_u16(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_u32( + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +hmath_status hmath_linear_dot_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_u32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_u64( + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +hmath_status hmath_linear_dot_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_u64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_int( + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +hmath_status hmath_linear_dot_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_int(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_word( + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +hmath_status hmath_linear_dot_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_word(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_c64( + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +hmath_status hmath_linear_dot_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_c64(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_dot_checked_c128( + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +hmath_status hmath_linear_dot_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_dot_checked_c128(argument1, argument1_count, argument2, argument2_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_magnitude_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_linear_magnitude_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_magnitude_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_magnitude_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_linear_magnitude_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_magnitude_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_linear_magnitude_c64( + float const *argument1, + size_t argument1_count, + float *out0, + float *out1); +hmath_status hmath_linear_magnitude_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float *out0, + float *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_magnitude_c64(argument1, argument1_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_magnitude_c128( + double const *argument1, + size_t argument1_count, + double *out0, + double *out1); +hmath_status hmath_linear_magnitude_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double *out0, + double *out1) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_magnitude_c128(argument1, argument1_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_linear_normalize_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_normalize_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_normalize_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_normalize_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_normalize_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_normalize_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_normalize_c64( + float const *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_normalize_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_normalize_c64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_normalize_c128( + double const *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_normalize_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_normalize_c128(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_add_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_f32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_f64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_rational( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_add_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument1_count; ++i) { + if (!hm_decimal(argument1[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument1[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_rational(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_integer( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_add_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_integer(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_i8( + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_i8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_i16( + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_i16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_i32( + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_i32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_i64( + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_i64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_u8( + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_u8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_u16( + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_u16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_u32( + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_u32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_u64( + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_u64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_int( + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_int(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_word( + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_word(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_c64( + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_add_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_c64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_c128( + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_add_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_c128(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_f32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_f64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_rational( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument1_count; ++i) { + if (!hm_decimal(argument1[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument1[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_rational(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_integer( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_integer(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_i8( + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_i8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_i16( + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_i16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_i32( + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_i32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_i64( + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_i64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_u8( + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_u8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_u16( + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_u16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_u32( + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_u32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_u64( + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_u64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_int( + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_int(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_word( + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_word(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_c64( + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_c64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_add_checked_c128( + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_add_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_add_checked_c128(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_f32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_f64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_rational( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument1_count; ++i) { + if (!hm_decimal(argument1[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument1[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_rational(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_integer( + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_integer(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_i8( + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_i8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_i16( + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_i16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_i32( + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_i32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_i64( + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_i64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_u8( + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_u8(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_u16( + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_u16(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_u32( + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_u32(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_u64( + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_u64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_int( + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_int(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_word( + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_word(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_c64( + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_c64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_subtract_checked_c128( + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_subtract_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_subtract_checked_c128(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_f32( + float argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_f32( + hmath_context *context, + float argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_f32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_f64( + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_rational( + const char *argument1_numerator, + const char *argument1_denominator, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_rational( + hmath_context *context, + const char *argument1_numerator, + const char *argument1_denominator, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(argument1_numerator) || !hm_decimal(argument1_denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components"); + const char *argument1_digit = argument1_denominator; + if (*argument1_digit == '-') ++argument1_digit; + while (*argument1_digit == '0') ++argument1_digit; + if (!*argument1_digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational denominator"); + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(const char *))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + for (size_t i = 0; i < 2 * argument2_count; ++i) { + if (!hm_decimal(argument2[i])) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational list component"); + if (i % 2) { + const char *digit = argument2[i]; + if (*digit == '-') ++digit; + while (*digit == '0') ++digit; + if (!*digit) + return hm_error(HMATH_INVALID_ARGUMENT, "zero Rational list denominator"); + } + } + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_rational(argument1_numerator, argument1_denominator, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_integer( + const char *argument1, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_integer( + hmath_context *context, + const char *argument1, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "argument1: expected signed decimal Integer"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument2_count && !argument2)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument2_count; ++i) if (!hm_decimal(argument2[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_integer(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_i8( + int8_t argument1, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_i8( + hmath_context *context, + int8_t argument1, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_i8(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_i16( + int16_t argument1, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_i16( + hmath_context *context, + int16_t argument1, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_i16(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_i32( + int32_t argument1, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_i32( + hmath_context *context, + int32_t argument1, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_i32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_i64( + int64_t argument1, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_i64( + hmath_context *context, + int64_t argument1, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(int64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_i64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_u8( + uint8_t argument1, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_u8( + hmath_context *context, + uint8_t argument1, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint8_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_u8(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_u16( + uint16_t argument1, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_u16( + hmath_context *context, + uint16_t argument1, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint16_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_u16(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_u32( + uint32_t argument1, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_u32( + hmath_context *context, + uint32_t argument1, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_u32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_u64( + uint64_t argument1, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_u64( + hmath_context *context, + uint64_t argument1, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(uint64_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_u64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_int( + ptrdiff_t argument1, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_int( + hmath_context *context, + ptrdiff_t argument1, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_int(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_word( + size_t argument1, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_word( + hmath_context *context, + size_t argument1, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(size_t)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_word(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_c64( + float argument1_0, + float argument1_1, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_c64( + hmath_context *context, + float argument1_0, + float argument1_1, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(float))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_c64(argument1_0, argument1_1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_linear_scale_c128( + double argument1_0, + double argument1_1, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_linear_scale_c128( + hmath_context *context, + double argument1_0, + double argument1_1, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / (2 * sizeof(double))) + return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_linear_scale_c128(argument1_0, argument1_1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_special_gamma_f64( + double x, + double *out0); +hmath_status hmath_special_gamma_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_gamma_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_log_gamma_f64( + double x, + double *out0); +hmath_status hmath_special_log_gamma_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_log_gamma_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_log_beta_f64( + double a, + double b, + double *out0); +hmath_status hmath_special_log_beta_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_log_beta_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_beta_f64( + double a, + double b, + double *out0); +hmath_status hmath_special_beta_f64( + hmath_context *context, + double a, + double b, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_beta_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_gamma_p_f64( + double a, + double x, + double *out0); +hmath_status hmath_special_gamma_p_f64( + hmath_context *context, + double a, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_gamma_p_f64(a, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_gamma_q_f64( + double a, + double x, + double *out0); +hmath_status hmath_special_gamma_q_f64( + hmath_context *context, + double a, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_gamma_q_f64(a, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_incomplete_gamma_f64( + double a, + double x, + double *out0); +hmath_status hmath_special_incomplete_gamma_f64( + hmath_context *context, + double a, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_incomplete_gamma_f64(a, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_beta_i_f64( + double a, + double b, + double x, + double *out0); +hmath_status hmath_special_beta_i_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_beta_i_f64(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_incomplete_beta_f64( + double a, + double b, + double x, + double *out0); +hmath_status hmath_special_incomplete_beta_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_incomplete_beta_f64(a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_digamma_f64( + double x, + double *out0); +hmath_status hmath_special_digamma_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_digamma_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_trigamma_f64( + double argument1, + double *out0); +hmath_status hmath_special_trigamma_f64( + hmath_context *context, + double argument1, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_trigamma_f64(argument1, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_polygamma_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_polygamma_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_polygamma_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_erf_f64( + double x, + double *out0); +hmath_status hmath_special_erf_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_erf_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_erfc_f64( + double x, + double *out0); +hmath_status hmath_special_erfc_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_erfc_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_erfcx_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_erfcx_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_erfcx_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_normal_c_d_f_f64( + double x, + double *out0); +hmath_status hmath_special_normal_c_d_f_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_normal_c_d_f_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_normal_quantile_f64( + double p, + double *out0); +hmath_status hmath_special_normal_quantile_f64( + hmath_context *context, + double p, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_normal_quantile_f64(p, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_inverse_erf_f64( + double x, + double *out0); +hmath_status hmath_special_inverse_erf_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_inverse_erf_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_dawson_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_dawson_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_dawson_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_exponential_integral_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_exponential_integral_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_exponential_integral_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_logarithmic_integral_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_logarithmic_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_logarithmic_integral_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_sine_integral_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_sine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_sine_integral_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_cosine_integral_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_cosine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_cosine_integral_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_fresnel_f64( + double x, + double *out0, + double *out1, + double *out2, + double *out3); +hmath_status hmath_special_fresnel_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_fresnel_f64(x, out0, out1, out2, out3); + hm_leave(); + return status; +} +extern int hm_numeric_special_elliptic_f_f64( + double phi, + double m, + double *out0, + double *out1); +hmath_status hmath_special_elliptic_f_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_elliptic_f_f64(phi, m, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_elliptic_e_f64( + double phi, + double m, + double *out0, + double *out1); +hmath_status hmath_special_elliptic_e_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_elliptic_e_f64(phi, m, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_elliptic_pi_f64( + double n, + double phi, + double m, + double *out0, + double *out1); +hmath_status hmath_special_elliptic_pi_f64( + hmath_context *context, + double n, + double phi, + double m, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_elliptic_pi_f64(n, phi, m, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_jacobi_elliptic_f64( + double u, + double m, + double *out0, + double *out1, + double *out2); +hmath_status hmath_special_jacobi_elliptic_f64( + hmath_context *context, + double u, + double m, + double *out0, + double *out1, + double *out2) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_jacobi_elliptic_f64(u, m, out0, out1, out2); + hm_leave(); + return status; +} +extern int hm_numeric_special_bessel_j_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bessel_j_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_bessel_y_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bessel_y_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_bessel_i_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bessel_i_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_scaled_bessel_i_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_scaled_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_scaled_bessel_i_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_bessel_k_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bessel_k_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_scaled_bessel_k_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_scaled_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_scaled_bessel_k_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_spherical_bessel_j_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_spherical_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_spherical_bessel_j_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_spherical_bessel_y_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_spherical_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_spherical_bessel_y_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_airy_f64( + double x, + double *out0, + double *out1, + double *out2, + double *out3, + double *out4, + double *out5, + double *out6, + double *out7); +hmath_status hmath_special_airy_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3, + double *out4, + double *out5, + double *out6, + double *out7) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out4) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out5) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out6) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out7) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_airy_f64(x, out0, out1, out2, out3, out4, out5, out6, out7); + hm_leave(); + return status; +} +extern int hm_numeric_special_struve_f64( + double nu, + double x, + double *out0, + double *out1); +hmath_status hmath_special_struve_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_struve_f64(nu, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_hypergeometric_f64( + const double *as, + size_t as_count, + const double *bs, + size_t bs_count, + double z, + double *out0, + double *out1); +hmath_status hmath_special_hypergeometric_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *bs, + size_t bs_count, + double z, + double *out0, + double *out1) { + if (as_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (as_count && !as) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (bs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (bs_count && !bs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_hypergeometric_f64(as, as_count, bs, bs_count, z, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_hypergeometric1_f1_f64( + double a, + double b, + double z, + double *out0, + double *out1); +hmath_status hmath_special_hypergeometric1_f1_f64( + hmath_context *context, + double a, + double b, + double z, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_hypergeometric1_f1_f64(a, b, z, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_hypergeometric2_f1_f64( + double a, + double b, + double c, + double z, + double *out0, + double *out1); +hmath_status hmath_special_hypergeometric2_f1_f64( + hmath_context *context, + double a, + double b, + double c, + double z, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_hypergeometric2_f1_f64(a, b, c, z, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_legendre_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_legendre_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_legendre_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_associated_legendre_f64( + ptrdiff_t l, + ptrdiff_t m, + double x, + double *out0); +hmath_status hmath_special_associated_legendre_f64( + hmath_context *context, + ptrdiff_t l, + ptrdiff_t m, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_associated_legendre_f64(l, m, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_hurwitz_zeta_f64( + double s, + double q, + double *out0, + double *out1); +hmath_status hmath_special_hurwitz_zeta_f64( + hmath_context *context, + double s, + double q, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_hurwitz_zeta_f64(s, q, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_riemann_zeta_f64( + double s, + double *out0, + double *out1); +hmath_status hmath_special_riemann_zeta_f64( + hmath_context *context, + double s, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_riemann_zeta_f64(s, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_polylogarithm_f64( + double s, + double z, + double *out0, + double *out1); +hmath_status hmath_special_polylogarithm_f64( + hmath_context *context, + double s, + double z, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_polylogarithm_f64(s, z, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_dilogarithm_f64( + double x, + double *out0, + double *out1); +hmath_status hmath_special_dilogarithm_f64( + hmath_context *context, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_dilogarithm_f64(x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_lambert_w_f64( + ptrdiff_t branch, + double x, + double *out0, + double *out1); +hmath_status hmath_special_lambert_w_f64( + hmath_context *context, + ptrdiff_t branch, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_lambert_w_f64(branch, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_debye_f64( + ptrdiff_t n, + double x, + double *out0, + double *out1); +hmath_status hmath_special_debye_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_debye_f64(n, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_clausen_f64( + double theta, + double *out0, + double *out1); +hmath_status hmath_special_clausen_f64( + hmath_context *context, + double theta, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_clausen_f64(theta, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_fermi_dirac_f64( + double order, + double eta, + double *out0, + double *out1); +hmath_status hmath_special_fermi_dirac_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_fermi_dirac_f64(order, eta, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_bose_einstein_f64( + double order, + double eta, + double *out0, + double *out1); +hmath_status hmath_special_bose_einstein_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bose_einstein_f64(order, eta, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_coulomb_wave_f64( + ptrdiff_t l, + double eta, + double rho, + double *out0, + double *out1, + double *out2, + double *out3); +hmath_status hmath_special_coulomb_wave_f64( + hmath_context *context, + ptrdiff_t l, + double eta, + double rho, + double *out0, + double *out1, + double *out2, + double *out3) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out3) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_coulomb_wave_f64(l, eta, rho, out0, out1, out2, out3); + hm_leave(); + return status; +} +extern int hm_numeric_special_gegenbauer_f64( + ptrdiff_t n, + double a, + double x, + double *out0); +hmath_status hmath_special_gegenbauer_f64( + hmath_context *context, + ptrdiff_t n, + double a, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_gegenbauer_f64(n, a, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_parabolic_cylinder_f64( + double nu, + double x, + double *out0, + double *out1); +hmath_status hmath_special_parabolic_cylinder_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_parabolic_cylinder_f64(nu, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_mathieu_f64( + int evenMode, + ptrdiff_t n, + double q, + double x, + double *out0, + double *out1, + double *out2); +hmath_status hmath_special_mathieu_f64( + hmath_context *context, + int evenMode, + ptrdiff_t n, + double q, + double x, + double *out0, + double *out1, + double *out2) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_mathieu_f64(evenMode, n, q, x, out0, out1, out2); + hm_leave(); + return status; +} +extern int hm_numeric_special_bernoulli_polynomial_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_bernoulli_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_bernoulli_polynomial_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_euler_polynomial_f64( + ptrdiff_t n, + double x, + double *out0); +hmath_status hmath_special_euler_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_euler_polynomial_f64(n, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_wigner3j_f64( + ptrdiff_t j1, + ptrdiff_t j2, + ptrdiff_t j3, + ptrdiff_t m1, + ptrdiff_t m2, + ptrdiff_t m3, + double *out0); +hmath_status hmath_special_wigner3j_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t j2, + ptrdiff_t j3, + ptrdiff_t m1, + ptrdiff_t m2, + ptrdiff_t m3, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_wigner3j_f64(j1, j2, j3, m1, m2, m3, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_wigner6j_f64( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t c, + ptrdiff_t d, + ptrdiff_t e, + ptrdiff_t f, + double *out0); +hmath_status hmath_special_wigner6j_f64( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t c, + ptrdiff_t d, + ptrdiff_t e, + ptrdiff_t f, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_wigner6j_f64(a, b, c, d, e, f, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_wigner9j_f64( + ptrdiff_t const *js, + size_t js_count, + double *out0); +hmath_status hmath_special_wigner9j_f64( + hmath_context *context, + ptrdiff_t const *js, + size_t js_count, + double *out0) { + if (js_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (js_count && !js)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (js_count && !js) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_wigner9j_f64(js, js_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_special_clebsch_gordan_f64( + ptrdiff_t j1, + ptrdiff_t m1, + ptrdiff_t j2, + ptrdiff_t m2, + ptrdiff_t j, + ptrdiff_t m, + double *out0); +hmath_status hmath_special_clebsch_gordan_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t m1, + ptrdiff_t j2, + ptrdiff_t m2, + ptrdiff_t j, + ptrdiff_t m, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_clebsch_gordan_f64(j1, m1, j2, m2, j, m, out0); + hm_leave(); + return status; +} +extern int hm_numeric_complex_to_polar_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_complex_to_polar_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_to_polar_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_probability_gamma_poisson_update_f64( + double shapePrior, + double ratePrior, + ptrdiff_t const *xs, + size_t xs_count, + double *out0, + double *out1); +hmath_status hmath_probability_gamma_poisson_update_f64( + hmath_context *context, + double shapePrior, + double ratePrior, + ptrdiff_t const *xs, + size_t xs_count, + double *out0, + double *out1) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_gamma_poisson_update_f64(shapePrior, ratePrior, xs, xs_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_probability_normal_normal_update_f64( + double mu, + double priorVariance, + double observationVariance, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +hmath_status hmath_probability_normal_normal_update_f64( + hmath_context *context, + double mu, + double priorVariance, + double observationVariance, + const double *xs, + size_t xs_count, + double *out0, + double *out1) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_normal_normal_update_f64(mu, priorVariance, observationVariance, xs, xs_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_probability_conditional_probability_f64( + double joint, + double given, + double *out0); +hmath_status hmath_probability_conditional_probability_f64( + hmath_context *context, + double joint, + double given, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_conditional_probability_f64(joint, given, out0); + hm_leave(); + return status; +} +extern int hm_numeric_probability_bayes_f64( + const double *priors, + size_t priors_count, + const double *likelihoods, + size_t likelihoods_count, + double **out_data, + size_t *out_count); +hmath_status hmath_probability_bayes_f64( + hmath_context *context, + const double *priors, + size_t priors_count, + const double *likelihoods, + size_t likelihoods_count, + double **out_data, + size_t *out_count) { + if (priors_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (priors_count && !priors) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (likelihoods_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (likelihoods_count && !likelihoods) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_bayes_f64(priors, priors_count, likelihoods, likelihoods_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_probability_multinomial_p_m_f_f64( + const double *ps, + size_t ps_count, + ptrdiff_t const *counts, + size_t counts_count, + double *out0); +hmath_status hmath_probability_multinomial_p_m_f_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + ptrdiff_t const *counts, + size_t counts_count, + double *out0) { + if (ps_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ps_count && !ps) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (counts_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (counts_count && !counts)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (counts_count && !counts) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_multinomial_p_m_f_f64(ps, ps_count, counts, counts_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_probability_dirichlet_density_f64( + const double *as, + size_t as_count, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_probability_dirichlet_density_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *xs, + size_t xs_count, + double *out0) { + if (as_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (as_count && !as) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_probability_dirichlet_density_f64(as, as_count, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_complex_complex_f64( + double real, + double imaginary, + double *out0, + double *out1); +hmath_status hmath_complex_complex_f64( + hmath_context *context, + double real, + double imaginary, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_complex_f64(real, imaginary, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_reciprocal_f64( + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_complex_reciprocal_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_reciprocal_f64(z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_add_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_complex_add_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_add_f64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_subtract_complex_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_complex_subtract_complex_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_subtract_complex_f64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_multiply_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_complex_multiply_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_multiply_f64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_divide_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_complex_divide_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_divide_f64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_power_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +hmath_status hmath_complex_power_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_power_f64(a_0, a_1, b_0, b_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_from_polar_f64( + double radius, + double angle, + double *out0, + double *out1); +hmath_status hmath_complex_from_polar_f64( + hmath_context *context, + double radius, + double angle, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_from_polar_f64(radius, angle, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_complex_rotate_f64( + double angle, + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_complex_rotate_f64( + hmath_context *context, + double angle, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_complex_rotate_f64(angle, z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_hankel_f64( + ptrdiff_t kind, + ptrdiff_t order, + double x, + double *out0, + double *out1); +hmath_status hmath_special_hankel_f64( + hmath_context *context, + ptrdiff_t kind, + ptrdiff_t order, + double x, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_hankel_f64(kind, order, x, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_spherical_harmonic_f64( + ptrdiff_t degree, + ptrdiff_t order, + double theta, + double phi, + double *out0, + double *out1); +hmath_status hmath_special_spherical_harmonic_f64( + hmath_context *context, + ptrdiff_t degree, + ptrdiff_t order, + double theta, + double phi, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_spherical_harmonic_f64(degree, order, theta, phi, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_special_complex1_f1_f64( + double a_0, + double a_1, + double b_0, + double b_1, + double z_0, + double z_1, + double *out0, + double *out1); +hmath_status hmath_special_complex1_f1_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double z_0, + double z_1, + double *out0, + double *out1) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_special_complex1_f1_f64(a_0, a_1, b_0, b_1, z_0, z_1, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_api_algebra_inner_product_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +hmath_status hmath_api_algebra_inner_product_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_api_algebra_inner_product_f32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_api_algebra_inner_product_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +hmath_status hmath_api_algebra_inner_product_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_api_algebra_inner_product_f64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_lower_bound_f32( + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +hmath_status hmath_algorithms_lower_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_lower_bound_f32(x, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_lower_bound_f64( + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +hmath_status hmath_algorithms_lower_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_lower_bound_f64(x, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_upper_bound_f32( + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +hmath_status hmath_algorithms_upper_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_upper_bound_f32(x, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_upper_bound_f64( + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +hmath_status hmath_algorithms_upper_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_upper_bound_f64(x, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_quickselect_f32( + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +hmath_status hmath_algorithms_quickselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_quickselect_f32(k, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_quickselect_f64( + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_algorithms_quickselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_quickselect_f64(k, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_introselect_f32( + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +hmath_status hmath_algorithms_introselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_introselect_f32(k, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_introselect_f64( + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_algorithms_introselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_introselect_f64(k, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_partial_sort_f32( + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_partial_sort_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_partial_sort_f32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_partial_sort_f64( + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_partial_sort_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_partial_sort_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_merge_sort_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_merge_sort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_merge_sort_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_merge_sort_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_merge_sort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_merge_sort_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_quicksort_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_quicksort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_quicksort_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_quicksort_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_quicksort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_quicksort_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_heapsort_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_heapsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_heapsort_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_heapsort_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_heapsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_heapsort_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_introsort_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_introsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_introsort_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_introsort_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_introsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_introsort_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_counting_sort( + ptrdiff_t budget, + ptrdiff_t const *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_algorithms_counting_sort( + hmath_context *context, + ptrdiff_t budget, + ptrdiff_t const *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_counting_sort(budget, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_radix_sort( + const char * const *argument1, + size_t argument1_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_algorithms_radix_sort( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char * **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (argument1_count && !argument1)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < argument1_count; ++i) if (!hm_decimal(argument1[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_radix_sort(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_bucket_sort_f64( + ptrdiff_t buckets, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_bucket_sort_f64( + hmath_context *context, + ptrdiff_t buckets, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_bucket_sort_f64(buckets, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_argsort_f32( + const float *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_algorithms_argsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_argsort_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_argsort_f64( + const double *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_algorithms_argsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_argsort_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_top_k_f32( + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_top_k_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_top_k_f32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_top_k_f64( + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_top_k_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_top_k_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_quantile_select_f64( + double q, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_algorithms_quantile_select_f64( + hmath_context *context, + double q, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_quantile_select_f64(q, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_deduplicate_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_deduplicate_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_deduplicate_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_deduplicate_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_deduplicate_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_deduplicate_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_prefix_sums_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_prefix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_prefix_sums_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_prefix_sums_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_prefix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_prefix_sums_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_suffix_sums_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_suffix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_suffix_sums_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_suffix_sums_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_suffix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_suffix_sums_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_difference_array_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_difference_array_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_difference_array_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_difference_array_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_difference_array_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_difference_array_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_apply_differences_f32( + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +hmath_status hmath_algorithms_apply_differences_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_apply_differences_f32(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_apply_differences_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_algorithms_apply_differences_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_apply_differences_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_binary_lift( + ptrdiff_t const *next, + size_t next_count, + const char *steps, + ptrdiff_t start, + ptrdiff_t *out0); +hmath_status hmath_algorithms_binary_lift( + hmath_context *context, + ptrdiff_t const *next, + size_t next_count, + const char *steps, + ptrdiff_t start, + ptrdiff_t *out0) { + if (next_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (next_count && !next)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (next_count && !next) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!hm_decimal(steps)) + return hm_error(HMATH_INVALID_ARGUMENT, "steps: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_binary_lift(next, next_count, steps, start, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_polynomial_hash( + const char *base, + const char *modulus, + const char * const *xs, + size_t xs_count, + char **out0); +hmath_status hmath_algorithms_polynomial_hash( + hmath_context *context, + const char *base, + const char *modulus, + const char * const *xs, + size_t xs_count, + char **out0) { + if (!hm_decimal(base)) + return hm_error(HMATH_INVALID_ARGUMENT, "base: expected signed decimal Integer"); + if (!hm_decimal(modulus)) + return hm_error(HMATH_INVALID_ARGUMENT, "modulus: expected signed decimal Integer"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < xs_count; ++i) if (!hm_decimal(xs[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_polynomial_hash(base, modulus, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_algorithms_rolling_hashes( + const char *base, + const char *modulus, + ptrdiff_t width, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +hmath_status hmath_algorithms_rolling_hashes( + hmath_context *context, + const char *base, + const char *modulus, + ptrdiff_t width, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count) { + if (!hm_decimal(base)) + return hm_error(HMATH_INVALID_ARGUMENT, "base: expected signed decimal Integer"); + if (!hm_decimal(modulus)) + return hm_error(HMATH_INVALID_ARGUMENT, "modulus: expected signed decimal Integer"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(const char *) || (xs_count && !xs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + for (size_t i = 0; i < xs_count; ++i) if (!hm_decimal(xs[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_algorithms_rolling_hashes(base, modulus, width, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_datastructure_monotonic_minima_f32( + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +hmath_status hmath_datastructure_monotonic_minima_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_datastructure_monotonic_minima_f32(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_datastructure_monotonic_minima_f64( + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_datastructure_monotonic_minima_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_datastructure_monotonic_minima_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_log_softmax_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_deeplearning_core_log_softmax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_log_softmax_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_softmax_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_deeplearning_core_softmax_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_softmax_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_sparsemax_f64( + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +hmath_status hmath_deeplearning_core_sparsemax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_sparsemax_f64(argument1, argument1_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_gated_linear_unit_f64( + const double *values, + size_t values_count, + const double *gate, + size_t gate_count, + double **out_data, + size_t *out_count); +hmath_status hmath_deeplearning_core_gated_linear_unit_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *gate, + size_t gate_count, + double **out_data, + size_t *out_count) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (gate_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (gate_count && !gate) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_gated_linear_unit_f64(values, values_count, gate, gate_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_categorical_cross_entropy_logits_f64( + const double *target, + size_t target_count, + const double *logits, + size_t logits_count, + double *out0); +hmath_status hmath_deeplearning_core_categorical_cross_entropy_logits_f64( + hmath_context *context, + const double *target, + size_t target_count, + const double *logits, + size_t logits_count, + double *out0) { + if (target_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (target_count && !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (logits_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (logits_count && !logits) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_categorical_cross_entropy_logits_f64(target, target_count, logits, logits_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_regularization_f64( + double l1, + double l2, + const double *weights, + size_t weights_count, + double *out0); +hmath_status hmath_deeplearning_core_regularization_f64( + hmath_context *context, + double l1, + double l2, + const double *weights, + size_t weights_count, + double *out0) { + if (weights_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (weights_count && !weights) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_regularization_f64(l1, l2, weights, weights_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_contrastive_loss_f64( + double margin, + int similar, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +hmath_status hmath_deeplearning_core_contrastive_loss_f64( + hmath_context *context, + double margin, + int similar, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_contrastive_loss_f64(margin, similar, a, a_count, b, b_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_triplet_loss_f64( + double margin, + const double *anchor, + size_t anchor_count, + const double *positive, + size_t positive_count, + const double *negative, + size_t negative_count, + double *out0); +hmath_status hmath_deeplearning_core_triplet_loss_f64( + hmath_context *context, + double margin, + const double *anchor, + size_t anchor_count, + const double *positive, + size_t positive_count, + const double *negative, + size_t negative_count, + double *out0) { + if (anchor_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (anchor_count && !anchor) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (positive_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (positive_count && !positive) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (negative_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (negative_count && !negative) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_triplet_loss_f64(margin, anchor, anchor_count, positive, positive_count, negative, negative_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_focal_loss_f64( + double alpha, + double gamma, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +hmath_status hmath_deeplearning_core_focal_loss_f64( + hmath_context *context, + double alpha, + double gamma, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0) { + if (target_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (target_count && !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (prediction_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (prediction_count && !prediction) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_focal_loss_f64(alpha, gamma, target, target_count, prediction, prediction_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_dice_loss_f64( + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +hmath_status hmath_deeplearning_core_dice_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0) { + if (target_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (target_count && !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (prediction_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (prediction_count && !prediction) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_dice_loss_f64(smooth, target, target_count, prediction, prediction_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_core_iou_loss_f64( + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +hmath_status hmath_deeplearning_core_iou_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0) { + if (target_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (target_count && !target) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (prediction_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (prediction_count && !prediction) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_core_iou_loss_f64(smooth, target, target_count, prediction, prediction_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_metrics_perplexity_f64( + const double *logs, + size_t logs_count, + double *out0); +hmath_status hmath_deeplearning_metrics_perplexity_f64( + hmath_context *context, + const double *logs, + size_t logs_count, + double *out0) { + if (logs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (logs_count && !logs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_metrics_perplexity_f64(logs, logs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_metrics_margin_ranking_loss_f64( + double margin, + const double *labels, + size_t labels_count, + const double *left, + size_t left_count, + const double *right, + size_t right_count, + double *out0); +hmath_status hmath_deeplearning_metrics_margin_ranking_loss_f64( + hmath_context *context, + double margin, + const double *labels, + size_t labels_count, + const double *left, + size_t left_count, + const double *right, + size_t right_count, + double *out0) { + if (labels_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (labels_count && !labels) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (left_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (left_count && !left) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (right_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (right_count && !right) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_metrics_margin_ranking_loss_f64(margin, labels, labels_count, left, left_count, right, right_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_precision_gradient_norm_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_deeplearning_precision_gradient_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_precision_gradient_norm_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_deeplearning_precision_clip_gradients_f64( + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_deeplearning_precision_clip_gradients_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_deeplearning_precision_clip_gradients_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_union_f32( + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_union_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_union_f32(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_union_f64( + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_union_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_union_f64(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_intersection_f32( + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_intersection_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_intersection_f32(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_intersection_f64( + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_intersection_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_intersection_f64(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_difference_f32( + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_difference_f32(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_set_difference_f64( + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +hmath_status hmath_discrete_set_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_set_difference_f64(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_symmetric_difference_f32( + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +hmath_status hmath_discrete_symmetric_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_symmetric_difference_f32(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_discrete_symmetric_difference_f64( + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +hmath_status hmath_discrete_symmetric_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_discrete_symmetric_difference_f64(a, a_count, b, b_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_frequencies_f64( + ptrdiff_t n, + double spacing, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_frequencies_f64( + hmath_context *context, + ptrdiff_t n, + double spacing, + double **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_frequencies_f64(n, spacing, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_fft_shift_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_fft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_fft_shift_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_ifft_shift_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_ifft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_ifft_shift_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_hartley_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_hartley_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_hartley_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_periodogram_f64( + double rate, + const double *window, + size_t window_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_periodogram_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (window_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (window_count && !window) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_periodogram_f64(rate, window, window_count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_welch_f64( + double rate, + const double *window, + size_t window_count, + ptrdiff_t hop, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_welch_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + ptrdiff_t hop, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (window_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (window_count && !window) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_welch_f64(rate, window, window_count, hop, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_cepstrum_f64( + double floorValue, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_cepstrum_f64( + hmath_context *context, + double floorValue, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_cepstrum_f64(floorValue, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_fourier_hilbert_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_fourier_hilbert_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_fourier_hilbert_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_geometry_primitives_hamming_distance_f32( + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + ptrdiff_t *out0); +hmath_status hmath_geometry_primitives_hamming_distance_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + ptrdiff_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_geometry_primitives_hamming_distance_f32(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_geometry_primitives_hamming_distance_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + ptrdiff_t *out0); +hmath_status hmath_geometry_primitives_hamming_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + ptrdiff_t *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_geometry_primitives_hamming_distance_f64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_geometry_primitives_jaccard_distance_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +hmath_status hmath_geometry_primitives_jaccard_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_geometry_primitives_jaccard_distance_f64(argument1, argument1_count, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_graph_core_finite_f64( + double x, + int *out0); +hmath_status hmath_graph_core_finite_f64( + hmath_context *context, + double x, + int *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_graph_core_finite_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_image_color_srgb_to_linear_f64( + double x, + double *out0); +hmath_status hmath_image_color_srgb_to_linear_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_image_color_srgb_to_linear_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_image_color_linear_to_srgb_f64( + double x, + double *out0); +hmath_status hmath_image_color_linear_to_srgb_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_image_color_linear_to_srgb_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_interpolation_evaluate_chebyshev_f64( + const double *cs, + size_t cs_count, + double a, + double b, + double x, + double *out0); +hmath_status hmath_interpolation_evaluate_chebyshev_f64( + hmath_context *context, + const double *cs, + size_t cs_count, + double a, + double b, + double x, + double *out0) { + if (cs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (cs_count && !cs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_interpolation_evaluate_chebyshev_f64(cs, cs_count, a, b, x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_next_after_f32( + float argument1, + float argument2, + float *out0); +hmath_status hmath_numeric_next_after_f32( + hmath_context *context, + float argument1, + float argument2, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_next_after_f32(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_next_after_f64( + double argument1, + double argument2, + double *out0); +hmath_status hmath_numeric_next_after_f64( + hmath_context *context, + double argument1, + double argument2, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_next_after_f64(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_ldexp_f32( + float argument1, + ptrdiff_t argument2, + float *out0); +hmath_status hmath_numeric_ldexp_f32( + hmath_context *context, + float argument1, + ptrdiff_t argument2, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_ldexp_f32(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_ldexp_f64( + double argument1, + ptrdiff_t argument2, + double *out0); +hmath_status hmath_numeric_ldexp_f64( + hmath_context *context, + double argument1, + ptrdiff_t argument2, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_ldexp_f64(argument1, argument2, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_ulp_distance_f64( + double a, + double b, + char **out0); +hmath_status hmath_numeric_ulp_distance_f64( + hmath_context *context, + double a, + double b, + char **out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_ulp_distance_f64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_within_u_l_ps_f64( + const char *n, + double a, + double b, + int *out0); +hmath_status hmath_numeric_within_u_l_ps_f64( + hmath_context *context, + const char *n, + double a, + double b, + int *out0) { + if (!hm_decimal(n)) + return hm_error(HMATH_INVALID_ARGUMENT, "n: expected signed decimal Integer"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_within_u_l_ps_f64(n, a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_kahan_sum_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_numeric_kahan_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_kahan_sum_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_kahan_sum_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_numeric_kahan_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_kahan_sum_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_neumaier_sum_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_numeric_neumaier_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_neumaier_sum_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_neumaier_sum_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_numeric_neumaier_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_neumaier_sum_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_pairwise_sum_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_numeric_pairwise_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_pairwise_sum_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_pairwise_sum_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_numeric_pairwise_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_pairwise_sum_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_logsumexp_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_numeric_logsumexp_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_logsumexp_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_logsumexp_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_numeric_logsumexp_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_logsumexp_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_sum_error_bound_f32( + const float *argument1, + size_t argument1_count, + float *out0); +hmath_status hmath_numeric_sum_error_bound_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(float)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_sum_error_bound_f32(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_numeric_sum_error_bound_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_numeric_sum_error_bound_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_numeric_sum_error_bound_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_optimization_common_dot_f64( + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +hmath_status hmath_optimization_common_dot_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0) { + if (a_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (a_count && !a) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (b_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (b_count && !b) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_optimization_common_dot_f64(a, a_count, b, b_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_optimization_common_norm_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_optimization_common_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_optimization_common_norm_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_optimization_common_add_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_optimization_common_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_optimization_common_add_f64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_optimization_common_sub_f64( + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_optimization_common_sub_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_optimization_common_sub_f64(argument1, argument1_count, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_optimization_common_scale_f64( + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_optimization_common_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_optimization_common_scale_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_random_importance_f64( + const double *values, + size_t values_count, + const double *weights, + size_t weights_count, + double *out0); +hmath_status hmath_random_importance_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *weights, + size_t weights_count, + double *out0) { + if (values_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (values_count && !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (weights_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (weights_count && !weights) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_random_importance_f64(values, values_count, weights, weights_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_random_halton_f64( + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +hmath_status hmath_random_halton_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_random_halton_f64(dimension, index, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_random_sobol_f64( + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +hmath_status hmath_random_sobol_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_random_sobol_f64(dimension, index, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_random_faure_f64( + ptrdiff_t d, + ptrdiff_t ix, + double **out_data, + size_t *out_count); +hmath_status hmath_random_faure_f64( + hmath_context *context, + ptrdiff_t d, + ptrdiff_t ix, + double **out_data, + size_t *out_count) { + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_random_faure_f64(d, ix, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_convolution_f64( + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_convolution_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_convolution_f64(xs, xs_count, ys, ys_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_circular_convolution_f64( + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_circular_convolution_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count) { + if (x_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (x_count && !x) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (y_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (y_count && !y) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_circular_convolution_f64(x, x_count, y, y_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_correlation_f64( + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_correlation_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count) { + if (x_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (x_count && !x) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (y_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (y_count && !y) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_correlation_f64(x, x_count, y, y_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_autocorrelation_f64( + const double *x, + size_t x_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_autocorrelation_f64( + hmath_context *context, + const double *x, + size_t x_count, + double **out_data, + size_t *out_count) { + if (x_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (x_count && !x) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_autocorrelation_f64(x, x_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_overlap_add_f64( + ptrdiff_t block, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_overlap_add_f64( + hmath_context *context, + ptrdiff_t block, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (kernel_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (kernel_count && !kernel) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_overlap_add_f64(block, kernel, kernel_count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_overlap_save_f64( + ptrdiff_t fftLength, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_overlap_save_f64( + hmath_context *context, + ptrdiff_t fftLength, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (kernel_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (kernel_count && !kernel) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_overlap_save_f64(fftLength, kernel, kernel_count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_moving_average_f64( + ptrdiff_t count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_moving_average_f64( + hmath_context *context, + ptrdiff_t count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_moving_average_f64(count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_median_filter_f64( + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_median_filter_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_median_filter_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_gaussian_filter_f64( + ptrdiff_t width, + double sigma, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_gaussian_filter_f64( + hmath_context *context, + ptrdiff_t width, + double sigma, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_gaussian_filter_f64(width, sigma, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_savitzky_golay_f64( + ptrdiff_t width, + ptrdiff_t degree, + ptrdiff_t derivative, + double spacing, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_savitzky_golay_f64( + hmath_context *context, + ptrdiff_t width, + ptrdiff_t degree, + ptrdiff_t derivative, + double spacing, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_savitzky_golay_f64(width, degree, derivative, spacing, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_downsample_f64( + ptrdiff_t factor, + ptrdiff_t offset, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_downsample_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t offset, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_downsample_f64(factor, offset, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_upsample_f64( + ptrdiff_t factor, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_upsample_f64( + hmath_context *context, + ptrdiff_t factor, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_upsample_f64(factor, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_resample_polyphase_f64( + ptrdiff_t up, + ptrdiff_t down, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_resample_polyphase_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (kernel_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (kernel_count && !kernel) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_resample_polyphase_f64(up, down, kernel, kernel_count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_resample_f64( + ptrdiff_t up, + ptrdiff_t down, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_resample_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_resample_f64(up, down, taps, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_anti_alias_f64( + ptrdiff_t factor, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_anti_alias_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_anti_alias_f64(factor, taps, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_zero_crossings_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_zero_crossings_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_zero_crossings_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_envelope_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_envelope_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_envelope_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_unwrap_phase_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_unwrap_phase_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_unwrap_phase_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_detrend_f64( + int linear, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_detrend_f64( + hmath_context *context, + int linear, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_detrend_f64(linear, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_normalize_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_normalize_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_normalize_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_smooth_f64( + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +hmath_status hmath_signal_smooth_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_smooth_f64(argument1, argument2, argument2_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_signal_noise_estimate_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_signal_noise_estimate_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_noise_estimate_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_signal_signal_to_noise_f64( + const double *signal, + size_t signal_count, + const double *noise, + size_t noise_count, + double *out0); +hmath_status hmath_signal_signal_to_noise_f64( + hmath_context *context, + const double *signal, + size_t signal_count, + const double *noise, + size_t noise_count, + double *out0) { + if (signal_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (signal_count && !signal) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (noise_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (noise_count && !noise) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_signal_to_noise_f64(signal, signal_count, noise, noise_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_signal_rms_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_signal_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_signal_rms_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_arithmetic_mean_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_arithmetic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_arithmetic_mean_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_weighted_mean_f64( + const double *xs, + size_t xs_count, + const double *ws, + size_t ws_count, + double *out0); +hmath_status hmath_statistics_advanced_weighted_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ws, + size_t ws_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ws_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ws_count && !ws) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_weighted_mean_f64(xs, xs_count, ws, ws_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_geometric_mean_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_geometric_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_geometric_mean_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_harmonic_mean_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_harmonic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_harmonic_mean_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_rms_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_rms_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_trimmed_mean_f64( + double fraction, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_trimmed_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_trimmed_mean_f64(fraction, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_winsorized_mean_f64( + double fraction, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_winsorized_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_winsorized_mean_f64(fraction, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_quantile_f64( + double p, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_quantile_f64( + hmath_context *context, + double p, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_quantile_f64(p, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_median_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_statistics_advanced_median_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_median_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_percentile_f64( + double argument1, + const double *argument2, + size_t argument2_count, + double *out0); +hmath_status hmath_statistics_advanced_percentile_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double *out0) { + if (argument2_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument2_count && !argument2) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_percentile_f64(argument1, argument2, argument2_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_modes_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_modes_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_modes_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_interquartile_range_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_interquartile_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_interquartile_range_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_median_absolute_deviation_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_median_absolute_deviation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_median_absolute_deviation_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_data_range_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_data_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_data_range_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_central_moment_f64( + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_central_moment_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_central_moment_f64(k, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_population_variance_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_statistics_advanced_population_variance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_population_variance_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_sample_variance_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_sample_variance_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_sample_variance_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_population_s_d_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_statistics_advanced_population_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_population_s_d_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_sample_s_d_f64( + const double *argument1, + size_t argument1_count, + double *out0); +hmath_status hmath_statistics_advanced_sample_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0) { + if (argument1_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (argument1_count && !argument1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_sample_s_d_f64(argument1, argument1_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_coefficient_of_variation_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_coefficient_of_variation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_coefficient_of_variation_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_skewness_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_skewness_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_skewness_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_kurtosis_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_kurtosis_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_kurtosis_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_covariance_f64( + int sampleCorrection, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_covariance_f64( + hmath_context *context, + int sampleCorrection, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_covariance_f64(sampleCorrection, xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_correlation_f64( + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_correlation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_correlation_f64(xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_spearman_f64( + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_spearman_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_spearman_f64(xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_kendall_f64( + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_kendall_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_kendall_f64(xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_autocorrelation_f64( + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_autocorrelation_f64(lag, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_cross_correlation_f64( + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_cross_correlation_f64(lag, xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_moving_average_f64( + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_moving_average_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_moving_average_f64(window, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_moving_variance_f64( + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_moving_variance_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_moving_variance_f64(window, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_exponential_moving_average_f64( + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_exponential_moving_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_exponential_moving_average_f64(alpha, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_entropy_f64( + const double *ps, + size_t ps_count, + double *out0); +hmath_status hmath_statistics_advanced_entropy_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double *out0) { + if (ps_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ps_count && !ps) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_entropy_f64(ps, ps_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_kl_divergence_f64( + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +hmath_status hmath_statistics_advanced_kl_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0) { + if (p_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (p_count && !p) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (q_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (q_count && !q) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_kl_divergence_f64(p, p_count, q, q_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_js_divergence_f64( + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +hmath_status hmath_statistics_advanced_js_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0) { + if (p_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (p_count && !p) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (q_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (q_count && !q) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_js_divergence_f64(p, p_count, q, q_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_z_scores_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_z_scores_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_z_scores_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_standard_error_f64( + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_standard_error_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_standard_error_f64(xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_confidence_interval_f64( + double level, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +hmath_status hmath_statistics_advanced_confidence_interval_f64( + hmath_context *context, + double level, + const double *xs, + size_t xs_count, + double *out0, + double *out1) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + if (!out1) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_confidence_interval_f64(level, xs, xs_count, out0, out1); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_bonferroni_f64( + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_bonferroni_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count) { + if (ps_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ps_count && !ps) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_bonferroni_f64(ps, ps_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_benjamini_hochberg_f64( + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_benjamini_hochberg_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count) { + if (ps_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ps_count && !ps) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_benjamini_hochberg_f64(ps, ps_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_cohens_d_f64( + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_statistics_advanced_cohens_d_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_cohens_d_f64(xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_normal_test_power_f64( + double alpha, + double standardizedEffect, + ptrdiff_t n, + double *out0); +hmath_status hmath_statistics_advanced_normal_test_power_f64( + hmath_context *context, + double alpha, + double standardizedEffect, + ptrdiff_t n, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_normal_test_power_f64(alpha, standardizedEffect, n, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_normal_sample_size_f64( + double alpha, + double power, + double effect, + ptrdiff_t *out0); +hmath_status hmath_statistics_advanced_normal_sample_size_f64( + hmath_context *context, + double alpha, + double power, + double effect, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_normal_sample_size_f64(alpha, power, effect, out0); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_tukey_outliers_f64( + double multiplier, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_statistics_advanced_tukey_outliers_f64( + hmath_context *context, + double multiplier, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_tukey_outliers_f64(multiplier, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_statistics_advanced_huber_location_f64( + double tuning, + const double *xs, + size_t xs_count, + double *out0); +hmath_status hmath_statistics_advanced_huber_location_f64( + hmath_context *context, + double tuning, + const double *xs, + size_t xs_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_statistics_advanced_huber_location_f64(tuning, xs, xs_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_tensor_shape_size( + ptrdiff_t const *dims, + size_t dims_count, + ptrdiff_t *out0); +hmath_status hmath_tensor_shape_size( + hmath_context *context, + ptrdiff_t const *dims, + size_t dims_count, + ptrdiff_t *out0) { + if (dims_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (dims_count && !dims)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (dims_count && !dims) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_tensor_shape_size(dims, dims_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_tensor_infer_broadcast( + ptrdiff_t const *as, + size_t as_count, + ptrdiff_t const *bs, + size_t bs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_tensor_infer_broadcast( + hmath_context *context, + ptrdiff_t const *as, + size_t as_count, + ptrdiff_t const *bs, + size_t bs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (as_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (as_count && !as)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (as_count && !as) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (bs_count > (size_t)PTRDIFF_MAX / sizeof(ptrdiff_t) || (bs_count && !bs)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span"); + if (bs_count && !bs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_tensor_infer_broadcast(as, as_count, bs, bs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_exponential_average_f64( + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_exponential_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_exponential_average_f64(alpha, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_weighted_average_f64( + const double *ws, + size_t ws_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_weighted_average_f64( + hmath_context *context, + const double *ws, + size_t ws_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (ws_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ws_count && !ws) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_weighted_average_f64(ws, ws_count, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_cumulative_returns_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_cumulative_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_cumulative_returns_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_logarithmic_returns_f64( + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_logarithmic_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_logarithmic_returns_f64(xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_difference_f64( + ptrdiff_t order, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_difference_f64( + hmath_context *context, + ptrdiff_t order, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_difference_f64(order, lag, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_autocorrelation_f64( + ptrdiff_t lags, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lags, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_autocorrelation_f64(lags, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_cross_correlation_f64( + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +hmath_status hmath_timeseries_core_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (ys_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (ys_count && !ys) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_cross_correlation_f64(lag, xs, xs_count, ys, ys_count, out0); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_core_partial_autocorrelation_f64( + ptrdiff_t order, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +hmath_status hmath_timeseries_core_partial_autocorrelation_f64( + hmath_context *context, + ptrdiff_t order, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_core_partial_autocorrelation_f64(order, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_diagnostics_change_points_f64( + double penalty, + ptrdiff_t minSegment, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_timeseries_diagnostics_change_points_f64( + hmath_context *context, + double penalty, + ptrdiff_t minSegment, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_diagnostics_change_points_f64(penalty, minSegment, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_diagnostics_cusum_f64( + double mean, + double sd, + double drift, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_timeseries_diagnostics_cusum_f64( + hmath_context *context, + double mean, + double sd, + double drift, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_diagnostics_cusum_f64(mean, sd, drift, threshold, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_timeseries_diagnostics_anomalies_f64( + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +hmath_status hmath_timeseries_diagnostics_anomalies_f64( + hmath_context *context, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count) { + if (xs_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t"); + if (xs_count && !xs) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input"); + if (!out_data || !out_count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_timeseries_diagnostics_anomalies_f64(threshold, xs, xs_count, out_data, out_count); + hm_leave(); + return status; +} +extern int hm_numeric_units_radians_to_degrees_f32( + float x, + float *out0); +hmath_status hmath_units_radians_to_degrees_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_radians_to_degrees_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_radians_to_degrees_f64( + double x, + double *out0); +hmath_status hmath_units_radians_to_degrees_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_radians_to_degrees_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_degrees_to_radians_f32( + float x, + float *out0); +hmath_status hmath_units_degrees_to_radians_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_degrees_to_radians_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_degrees_to_radians_f64( + double x, + double *out0); +hmath_status hmath_units_degrees_to_radians_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_degrees_to_radians_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_radians_to_gradians_f32( + float x, + float *out0); +hmath_status hmath_units_radians_to_gradians_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_radians_to_gradians_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_radians_to_gradians_f64( + double x, + double *out0); +hmath_status hmath_units_radians_to_gradians_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_radians_to_gradians_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_gradians_to_radians_f32( + float x, + float *out0); +hmath_status hmath_units_gradians_to_radians_f32( + hmath_context *context, + float x, + float *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_gradians_to_radians_f32(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_units_gradians_to_radians_f64( + double x, + double *out0); +hmath_status hmath_units_gradians_to_radians_f64( + hmath_context *context, + double x, + double *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_units_gradians_to_radians_f64(x, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_saturating_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_saturating_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_saturating_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_saturating_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_saturating_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_saturating_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_saturating_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_saturating_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_saturating_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_add_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_saturating_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_add_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_saturating_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_saturating_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_saturating_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_saturating_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_saturating_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_saturating_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_saturating_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_saturating_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_saturating_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_subtract_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_saturating_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_subtract_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_saturating_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_saturating_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_saturating_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_saturating_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_saturating_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_saturating_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_saturating_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_saturating_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_saturating_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_saturating_multiply_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_saturating_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_saturating_multiply_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_checked_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_checked_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_checked_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_checked_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_checked_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_checked_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_checked_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_checked_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_checked_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_add_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_checked_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_add_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_checked_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_checked_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_checked_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_checked_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_checked_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_checked_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_checked_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_checked_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_checked_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_subtract_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_checked_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_subtract_word(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_i8( + int8_t a, + int8_t b, + int8_t *out0); +hmath_status hmath_scalar_checked_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_i8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_i16( + int16_t a, + int16_t b, + int16_t *out0); +hmath_status hmath_scalar_checked_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_i16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_i32( + int32_t a, + int32_t b, + int32_t *out0); +hmath_status hmath_scalar_checked_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_i32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_i64( + int64_t a, + int64_t b, + int64_t *out0); +hmath_status hmath_scalar_checked_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_i64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_u8( + uint8_t a, + uint8_t b, + uint8_t *out0); +hmath_status hmath_scalar_checked_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_u8(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_u16( + uint16_t a, + uint16_t b, + uint16_t *out0); +hmath_status hmath_scalar_checked_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_u16(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_u32( + uint32_t a, + uint32_t b, + uint32_t *out0); +hmath_status hmath_scalar_checked_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_u32(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_u64( + uint64_t a, + uint64_t b, + uint64_t *out0); +hmath_status hmath_scalar_checked_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_u64(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_int( + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +hmath_status hmath_scalar_checked_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_int(a, b, out0); + hm_leave(); + return status; +} +extern int hm_numeric_scalar_checked_multiply_word( + size_t a, + size_t b, + size_t *out0); +hmath_status hmath_scalar_checked_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0) { + if (!out0) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL output"); + hmath_status status = hm_enter(context); + if (status) + return status; + status = (hmath_status)hm_numeric_scalar_checked_multiply_word(a, b, out0); + hm_leave(); + return status; +} diff --git a/cbits/numeric_internal.h b/cbits/numeric_internal.h new file mode 100644 index 0000000..0ecd1b5 --- /dev/null +++ b/cbits/numeric_internal.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_NUMERIC_INTERNAL_H +#define HMATH_NUMERIC_INTERNAL_H +#include "native_internal.h" +#include + +/* Decimal transport for arbitrary-precision Integer, not an arithmetic limit. */ +static inline int hm_decimal(const char *value) { + if (!value) + return 0; + if (*value == '-') + ++value; + if (!*value) + return 0; + for (; *value; ++value) + if (*value < '0' || *value > '9') + return 0; + return 1; +} +#endif diff --git a/cbits/numeric_objects.c b/cbits/numeric_objects.c new file mode 100644 index 0000000..9d0472e --- /dev/null +++ b/cbits/numeric_objects.c @@ -0,0 +1,269 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_numeric_objects.py. */ +#include "hmath_numeric_objects.h" +#include "value_internal.h" +extern int hm_numeric_objects_apply(int,void *,void *const *,size_t,void **); +hmath_status hmath_basic_clamp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *low, const hmath_value *high, const hmath_value *value, hmath_value **out) { + if(!out||!prototype||!low||!high||!value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(low),hm_value_stable(high),hm_value_stable(value)}; + return hm_value_finish(result,hm_numeric_objects_apply(0,hm_value_stable(prototype),arguments,3,&result->stable),out); +} +hmath_status hmath_basic_lerp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, const hmath_value *t, hmath_value **out) { + if(!out||!prototype||!a||!b||!t)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b),hm_value_stable(t)}; + return hm_value_finish(result,hm_numeric_objects_apply(1,hm_value_stable(prototype),arguments,3,&result->stable),out); +} +hmath_status hmath_scalar_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(2,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_subtract_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(3,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(4,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_minimum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(5,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_maximum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(6,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_absolute_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out) { + if(!out||!prototype||!x)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(x)}; + return hm_value_finish(result,hm_numeric_objects_apply(7,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_scalar_sign_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out) { + if(!out||!prototype||!x)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(x)}; + return hm_value_finish(result,hm_numeric_objects_apply(8,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_scalar_positive_modulo_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *modulus, hmath_value **out) { + if(!out||!prototype||!a||!modulus)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(modulus)}; + return hm_value_finish(result,hm_numeric_objects_apply(9,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_cumulative_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(10,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_scalar_cumulative_product_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(11,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_scalar_prefix_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(12,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_statistics_mean_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(13,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_statistics_variance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(14,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_statistics_standard_deviation_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(15,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_statistics_median_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out) { + if(!out||!prototype||!values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_numeric_objects_apply(16,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_linear_dot_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(17,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_linear_dot_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(18,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_linear_magnitude_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out) { + if(!out||!prototype||!argument1)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1)}; + return hm_value_finish(result,hm_numeric_objects_apply(19,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_linear_normalize_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out) { + if(!out||!prototype||!argument1)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1)}; + return hm_value_finish(result,hm_numeric_objects_apply(20,hm_value_stable(prototype),arguments,1,&result->stable),out); +} +hmath_status hmath_linear_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(21,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_linear_add_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(22,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_linear_subtract_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(23,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_linear_scale_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(24,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_saturating_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(25,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_saturating_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(26,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_saturating_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(27,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_checked_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(28,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_checked_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(29,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_scalar_checked_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out||!prototype||!a||!b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_numeric_objects_apply(30,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_geometry_primitives_hamming_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(31,hm_value_stable(prototype),arguments,2,&result->stable),out); +} +hmath_status hmath_geometry_primitives_jaccard_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out) { + if(!out||!prototype||!argument1||!argument2)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(argument1),hm_value_stable(argument2)}; + return hm_value_finish(result,hm_numeric_objects_apply(32,hm_value_stable(prototype),arguments,2,&result->stable),out); +} diff --git a/cbits/numeric_types.c b/cbits/numeric_types.c new file mode 100644 index 0000000..284a5f5 --- /dev/null +++ b/cbits/numeric_types.c @@ -0,0 +1,1030 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_numeric_types.h" +#include "numeric_internal.h" +#include "value_internal.h" +#include +extern int hm_numeric_types_clone(void *stable,void **out); +void hmath_numeric_types_retain(hmath_numeric_value *value) { hmath_value_retain(value); } +void hmath_numeric_types_release(hmath_numeric_value *value) { hmath_value_release(value); } +void hmath_numeric_types_buffer_free(void *value) { free(value); } +int hmath_numeric_types_kind(const hmath_numeric_value *value) { return value ? value->kind : 0; } +int hm_numeric_types_invoke(hmath_numeric_callback callback,void *userdata,void *input_stable,void **out) { + hmath_numeric_value *temporary=NULL,*input=NULL,*output=NULL; + hmath_status status=hm_value_begin(NULL,&temporary); + if(status) { extern void hm_value_free(void *);hm_value_free(input_stable);return status; } + temporary->stable=input_stable; + status=hm_value_finish(temporary,0,&input); + if(status) return status; + status=callback(input,userdata,&output); + if(!status && !output) status=hm_error(HMATH_INVALID_ARGUMENT,"callback returned NULL value"); + if(!status) status=(hmath_status)hm_numeric_types_clone(output->stable,out); + if(output) hmath_value_release(output); + hmath_value_release(input); + return status; +} +extern int hm_numeric_types_type_name(void *value, void **out); +hmath_status hmath_numeric_types_type_name(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_type_name(value->stable, &result->stable), out); +} +extern int hm_numeric_types_binary(int operation, void *a, void *b, void **out); +hmath_status hmath_numeric_types_binary(hmath_context *context, int operation, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_binary(operation, a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_unary(int operation, void *value, void **out); +hmath_status hmath_numeric_types_unary(hmath_context *context, int operation, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_unary(operation, value->stable, &result->stable), out); +} +extern int hm_numeric_types_literal_integer(void *like, const char *value, void **out); +hmath_status hmath_numeric_types_literal_integer(hmath_context *context, const hmath_numeric_value *like, const char *value, hmath_numeric_value **out) { + if(!like) return hm_error(HMATH_INVALID_ARGUMENT,"NULL like"); + if(!hm_decimal(value)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_literal_integer(like->stable, value, &result->stable), out); +} +extern int hm_numeric_types_literal_rational(void *like, const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_literal_rational(hmath_context *context, const hmath_numeric_value *like, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!like) return hm_error(HMATH_INVALID_ARGUMENT,"NULL like"); + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_literal_rational(like->stable, value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_integer_power(void *value, const char *power, void **out); +hmath_status hmath_numeric_types_integer_power(hmath_context *context, const hmath_numeric_value *value, const char *power, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!hm_decimal(power)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_integer_power(value->stable, power, &result->stable), out); +} +extern int hm_numeric_types_equal(void *a, void *b, void **out); +hmath_status hmath_numeric_types_equal(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_equal(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_sequence_get(void *value, ptrdiff_t index, void **out); +hmath_status hmath_numeric_types_sequence_get(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_sequence_get(value->stable, index, &result->stable), out); +} +extern int hm_numeric_types_round_rational(int mode, const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_round_rational(hmath_context *context, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_round_rational(mode, value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_classify(void *value, void **out); +hmath_status hmath_numeric_types_classify(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_classify(value->stable, &result->stable), out); +} +extern int hm_numeric_types_frexp(void *value, void **out); +hmath_status hmath_numeric_types_frexp(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_frexp(value->stable, &result->stable), out); +} +extern int hm_numeric_types_numeric_limits(void *value, void **out); +hmath_status hmath_numeric_types_numeric_limits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_numeric_limits(value->stable, &result->stable), out); +} +extern int hm_numeric_types_integer_limits(void *value, void **out); +hmath_status hmath_numeric_types_integer_limits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_integer_limits(value->stable, &result->stable), out); +} +extern int hm_numeric_types_float16_limits(void **out); +hmath_status hmath_numeric_types_float16_limits(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_float16_limits(&result->stable), out); +} +extern int hm_numeric_types_bfloat16_limits(void **out); +hmath_status hmath_numeric_types_bfloat16_limits(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_bfloat16_limits(&result->stable), out); +} +extern int hm_numeric_types_numeric_limits_record(void *normal, void *subnormal, void *maximum_value, void *epsilon, ptrdiff_t digits, ptrdiff_t low, ptrdiff_t high, void **out); +hmath_status hmath_numeric_types_numeric_limits_record(hmath_context *context, const hmath_numeric_value *normal, const hmath_numeric_value *subnormal, const hmath_numeric_value *maximum_value, const hmath_numeric_value *epsilon, ptrdiff_t digits, ptrdiff_t low, ptrdiff_t high, hmath_numeric_value **out) { + if(!normal) return hm_error(HMATH_INVALID_ARGUMENT,"NULL normal"); + if(!subnormal) return hm_error(HMATH_INVALID_ARGUMENT,"NULL subnormal"); + if(!maximum_value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL maximum_value"); + if(!epsilon) return hm_error(HMATH_INVALID_ARGUMENT,"NULL epsilon"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_numeric_limits_record(normal->stable, subnormal->stable, maximum_value->stable, epsilon->stable, digits, low, high, &result->stable), out); +} +extern int hm_numeric_types_minimum_normal(void *value, void **out); +hmath_status hmath_numeric_types_minimum_normal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_minimum_normal(value->stable, &result->stable), out); +} +extern int hm_numeric_types_minimum_subnormal(void *value, void **out); +hmath_status hmath_numeric_types_minimum_subnormal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_minimum_subnormal(value->stable, &result->stable), out); +} +extern int hm_numeric_types_maximum_finite(void *value, void **out); +hmath_status hmath_numeric_types_maximum_finite(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_maximum_finite(value->stable, &result->stable), out); +} +extern int hm_numeric_types_machine_epsilon(void *value, void **out); +hmath_status hmath_numeric_types_machine_epsilon(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_machine_epsilon(value->stable, &result->stable), out); +} +extern int hm_numeric_types_significand_digits(void *value, void **out); +hmath_status hmath_numeric_types_significand_digits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_significand_digits(value->stable, &result->stable), out); +} +extern int hm_numeric_types_minimum_exponent(void *value, void **out); +hmath_status hmath_numeric_types_minimum_exponent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_minimum_exponent(value->stable, &result->stable), out); +} +extern int hm_numeric_types_maximum_exponent(void *value, void **out); +hmath_status hmath_numeric_types_maximum_exponent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_maximum_exponent(value->stable, &result->stable), out); +} +extern int hm_numeric_types_safe_integral_cast(void *value, int dtype, void **out); +hmath_status hmath_numeric_types_safe_integral_cast(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_safe_integral_cast(value->stable, dtype, &result->stable), out); +} +extern int hm_numeric_types_saturating_cast(void *value, int dtype, void **out); +hmath_status hmath_numeric_types_saturating_cast(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_saturating_cast(value->stable, dtype, &result->stable), out); +} +extern int hm_numeric_types_real_to_integral(int mode, void *value, int dtype, void **out); +hmath_status hmath_numeric_types_real_to_integral(hmath_context *context, int mode, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_real_to_integral(mode, value->stable, dtype, &result->stable), out); +} +extern int hm_numeric_types_narrow_float(void *value, int dtype, void **out); +hmath_status hmath_numeric_types_narrow_float(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_narrow_float(value->stable, dtype, &result->stable), out); +} +extern int hm_numeric_types_float16(int mode, double value, void **out); +hmath_status hmath_numeric_types_float16(hmath_context *context, int mode, double value, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_float16(mode, value, &result->stable), out); +} +extern int hm_numeric_types_bfloat16(int mode, double value, void **out); +hmath_status hmath_numeric_types_bfloat16(hmath_context *context, int mode, double value, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_bfloat16(mode, value, &result->stable), out); +} +extern int hm_numeric_types_float16_from_bits(uint16_t bits, void **out); +hmath_status hmath_numeric_types_float16_from_bits(hmath_context *context, uint16_t bits, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_float16_from_bits(bits, &result->stable), out); +} +extern int hm_numeric_types_bfloat16_from_bits(uint16_t bits, void **out); +hmath_status hmath_numeric_types_bfloat16_from_bits(hmath_context *context, uint16_t bits, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_bfloat16_from_bits(bits, &result->stable), out); +} +extern int hm_numeric_types_float16_bits(void *value, void **out); +hmath_status hmath_numeric_types_float16_bits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_float16_bits(value->stable, &result->stable), out); +} +extern int hm_numeric_types_bfloat16_bits(void *value, void **out); +hmath_status hmath_numeric_types_bfloat16_bits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_bfloat16_bits(value->stable, &result->stable), out); +} +extern int hm_numeric_types_from_float16(void *value, void **out); +hmath_status hmath_numeric_types_from_float16(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_from_float16(value->stable, &result->stable), out); +} +extern int hm_numeric_types_from_bfloat16(void *value, void **out); +hmath_status hmath_numeric_types_from_bfloat16(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_from_bfloat16(value->stable, &result->stable), out); +} +extern int hm_numeric_types_rounded(void *value, const int *flags, size_t flags_count, void **out); +hmath_status hmath_numeric_types_rounded(hmath_context *context, const hmath_numeric_value *value, const int *flags, size_t flags_count, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(flags_count>(size_t)PTRDIFF_MAX/sizeof(int) || (flags_count && !flags)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid array span"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_rounded(value->stable, flags, flags_count, &result->stable), out); +} +extern int hm_numeric_types_rounded_value(void *value, void **out); +hmath_status hmath_numeric_types_rounded_value(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_rounded_value(value->stable, &result->stable), out); +} +extern int hm_numeric_types_numerical_exceptions(void *value, void **out); +hmath_status hmath_numeric_types_numerical_exceptions(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_numerical_exceptions(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_float(ptrdiff_t precision, int mode, const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_big_float(hmath_context *context, ptrdiff_t precision, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_float(precision, mode, value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_extended(const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_extended(hmath_context *context, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_extended(value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_big_precision(void *value, void **out); +hmath_status hmath_numeric_types_big_precision(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_precision(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_rational(void *value, void **out); +hmath_status hmath_numeric_types_big_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_rational(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_to_double(void *value, void **out); +hmath_status hmath_numeric_types_big_to_double(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_to_double(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_add(void *a, void *b, void **out); +hmath_status hmath_numeric_types_big_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_add(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_big_subtract(void *a, void *b, void **out); +hmath_status hmath_numeric_types_big_subtract(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_subtract(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_big_multiply(void *a, void *b, void **out); +hmath_status hmath_numeric_types_big_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_multiply(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_big_divide(void *a, void *b, void **out); +hmath_status hmath_numeric_types_big_divide(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_divide(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_big_sqrt(void *value, void **out); +hmath_status hmath_numeric_types_big_sqrt(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_sqrt(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_exp(void *value, void **out); +hmath_status hmath_numeric_types_big_exp(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_exp(value->stable, &result->stable), out); +} +extern int hm_numeric_types_big_log(void *value, void **out); +hmath_status hmath_numeric_types_big_log(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_big_log(value->stable, &result->stable), out); +} +extern int hm_numeric_types_mixed_add(void *a, double b, void **out); +hmath_status hmath_numeric_types_mixed_add(hmath_context *context, const hmath_numeric_value *a, double b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_mixed_add(a->stable, b, &result->stable), out); +} +extern int hm_numeric_types_mixed_multiply(void *a, double b, void **out); +hmath_status hmath_numeric_types_mixed_multiply(hmath_context *context, const hmath_numeric_value *a, double b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_mixed_multiply(a->stable, b, &result->stable), out); +} +extern int hm_numeric_types_fixed(ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_fixed(hmath_context *context, ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed(scale, mode, value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_fixed_rational(void *value, void **out); +hmath_status hmath_numeric_types_fixed_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_rational(value->stable, &result->stable), out); +} +extern int hm_numeric_types_fixed_add(void *a, void *b, void **out); +hmath_status hmath_numeric_types_fixed_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_add(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_fixed_multiply(int mode, void *a, void *b, void **out); +hmath_status hmath_numeric_types_fixed_multiply(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_multiply(mode, a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_fixed_divide(int mode, void *a, void *b, void **out); +hmath_status hmath_numeric_types_fixed_divide(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_divide(mode, a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_decimal(ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, void **out); +hmath_status hmath_numeric_types_decimal(hmath_context *context, ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out) { + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_decimal(scale, mode, value_numerator, value_denominator, &result->stable), out); +} +extern int hm_numeric_types_decimal_rational(void *value, void **out); +hmath_status hmath_numeric_types_decimal_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_decimal_rational(value->stable, &result->stable), out); +} +extern int hm_numeric_types_decimal_add(void *a, void *b, void **out); +hmath_status hmath_numeric_types_decimal_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_decimal_add(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_decimal_multiply(int mode, void *a, void *b, void **out); +hmath_status hmath_numeric_types_decimal_multiply(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_decimal_multiply(mode, a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_decimal_divide(int mode, void *a, void *b, void **out); +hmath_status hmath_numeric_types_decimal_divide(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_decimal_divide(mode, a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_fixed_scale(void *value, void **out); +hmath_status hmath_numeric_types_fixed_scale(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_scale(value->stable, &result->stable), out); +} +extern int hm_numeric_types_fixed_coefficient(void *value, void **out); +hmath_status hmath_numeric_types_fixed_coefficient(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_fixed_coefficient(value->stable, &result->stable), out); +} +extern int hm_numeric_types_interval(double low, double high, void **out); +hmath_status hmath_numeric_types_interval(hmath_context *context, double low, double high, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval(low, high, &result->stable), out); +} +extern int hm_numeric_types_interval_bounds(void *value, void **out); +hmath_status hmath_numeric_types_interval_bounds(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_bounds(value->stable, &result->stable), out); +} +extern int hm_numeric_types_interval_contains(void *value, double point, void **out); +hmath_status hmath_numeric_types_interval_contains(hmath_context *context, const hmath_numeric_value *value, double point, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_contains(value->stable, point, &result->stable), out); +} +extern int hm_numeric_types_interval_add(void *a, void *b, void **out); +hmath_status hmath_numeric_types_interval_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_add(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_interval_subtract(void *a, void *b, void **out); +hmath_status hmath_numeric_types_interval_subtract(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_subtract(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_interval_multiply(void *a, void *b, void **out); +hmath_status hmath_numeric_types_interval_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_multiply(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_interval_divide(void *a, void *b, void **out); +hmath_status hmath_numeric_types_interval_divide(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_interval_divide(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_dual(void *primal_value, void *tangent_value, void **out); +hmath_status hmath_numeric_types_dual(hmath_context *context, const hmath_numeric_value *primal_value, const hmath_numeric_value *tangent_value, hmath_numeric_value **out) { + if(!primal_value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL primal_value"); + if(!tangent_value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL tangent_value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_dual(primal_value->stable, tangent_value->stable, &result->stable), out); +} +extern int hm_numeric_types_primal(void *value, void **out); +hmath_status hmath_numeric_types_primal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_primal(value->stable, &result->stable), out); +} +extern int hm_numeric_types_tangent(void *value, void **out); +hmath_status hmath_numeric_types_tangent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_tangent(value->stable, &result->stable), out); +} +extern int hm_numeric_types_derivative(hmath_numeric_callback function, void *function_userdata, void *value, void **out); +hmath_status hmath_numeric_types_derivative(hmath_context *context, hmath_numeric_callback function, void *function_userdata, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!function) return hm_error(HMATH_INVALID_ARGUMENT,"NULL callback"); + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_derivative(function, function_userdata, value->stable, &result->stable), out); +} +extern int hm_numeric_types_quaternion(void *real, void *i, void *j, void *k, void **out); +hmath_status hmath_numeric_types_quaternion(hmath_context *context, const hmath_numeric_value *real, const hmath_numeric_value *i, const hmath_numeric_value *j, const hmath_numeric_value *k, hmath_numeric_value **out) { + if(!real) return hm_error(HMATH_INVALID_ARGUMENT,"NULL real"); + if(!i) return hm_error(HMATH_INVALID_ARGUMENT,"NULL i"); + if(!j) return hm_error(HMATH_INVALID_ARGUMENT,"NULL j"); + if(!k) return hm_error(HMATH_INVALID_ARGUMENT,"NULL k"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_quaternion(real->stable, i->stable, j->stable, k->stable, &result->stable), out); +} +extern int hm_numeric_types_quaternion_conjugate(void *value, void **out); +hmath_status hmath_numeric_types_quaternion_conjugate(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_quaternion_conjugate(value->stable, &result->stable), out); +} +extern int hm_numeric_types_quaternion_norm(void *value, void **out); +hmath_status hmath_numeric_types_quaternion_norm(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_quaternion_norm(value->stable, &result->stable), out); +} +extern int hm_numeric_types_quaternion_inverse(void *value, void **out); +hmath_status hmath_numeric_types_quaternion_inverse(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_quaternion_inverse(value->stable, &result->stable), out); +} +extern int hm_numeric_types_quaternion_component(void *value, ptrdiff_t index, void **out); +hmath_status hmath_numeric_types_quaternion_component(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_quaternion_component(value->stable, index, &result->stable), out); +} +extern int hm_numeric_types_dual_quaternion(void *real, void *dual, void **out); +hmath_status hmath_numeric_types_dual_quaternion(hmath_context *context, const hmath_numeric_value *real, const hmath_numeric_value *dual, hmath_numeric_value **out) { + if(!real) return hm_error(HMATH_INVALID_ARGUMENT,"NULL real"); + if(!dual) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dual"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_dual_quaternion(real->stable, dual->stable, &result->stable), out); +} +extern int hm_numeric_types_dual_quaternion_component(void *value, ptrdiff_t index, void **out); +hmath_status hmath_numeric_types_dual_quaternion_component(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_dual_quaternion_component(value->stable, index, &result->stable), out); +} +extern int hm_numeric_types_dual_quaternion_multiply(void *a, void *b, void **out); +hmath_status hmath_numeric_types_dual_quaternion_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out) { + if(!a) return hm_error(HMATH_INVALID_ARGUMENT,"NULL a"); + if(!b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL b"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_dual_quaternion_multiply(a->stable, b->stable, &result->stable), out); +} +extern int hm_numeric_types_dual_quaternion_inverse(void *value, void **out); +hmath_status hmath_numeric_types_dual_quaternion_inverse(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_dual_quaternion_inverse(value->stable, &result->stable), out); +} +extern int hm_numeric_types_rotate_vector(void *value, void *x, void *y, void *z, void **out); +hmath_status hmath_numeric_types_rotate_vector(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL x"); + if(!y) return hm_error(HMATH_INVALID_ARGUMENT,"NULL y"); + if(!z) return hm_error(HMATH_INVALID_ARGUMENT,"NULL z"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_rotate_vector(value->stable, x->stable, y->stable, z->stable, &result->stable), out); +} +extern int hm_numeric_types_rigid_transform(void *value, void *x, void *y, void *z, void **out); +hmath_status hmath_numeric_types_rigid_transform(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL x"); + if(!y) return hm_error(HMATH_INVALID_ARGUMENT,"NULL y"); + if(!z) return hm_error(HMATH_INVALID_ARGUMENT,"NULL z"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_rigid_transform(value->stable, x->stable, y->stable, z->stable, &result->stable), out); +} +extern int hm_numeric_types_transform_point(void *value, void *x, void *y, void *z, void **out); +hmath_status hmath_numeric_types_transform_point(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL x"); + if(!y) return hm_error(HMATH_INVALID_ARGUMENT,"NULL y"); + if(!z) return hm_error(HMATH_INVALID_ARGUMENT,"NULL z"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_transform_point(value->stable, x->stable, y->stable, z->stable, &result->stable), out); +} +extern int hm_numeric_types_constant(const uint32_t *name, size_t name_count, const char *value_numerator, const char *value_denominator, const char *uncertainty_numerator, const char *uncertainty_denominator, const char *approximation_numerator, const char *approximation_denominator, const uint32_t *unit, size_t unit_count, const uint32_t *source, size_t source_count, void **out); +hmath_status hmath_numeric_types_constant(hmath_context *context, const uint32_t *name, size_t name_count, const char *value_numerator, const char *value_denominator, const char *uncertainty_numerator, const char *uncertainty_denominator, const char *approximation_numerator, const char *approximation_denominator, const uint32_t *unit, size_t unit_count, const uint32_t *source, size_t source_count, hmath_numeric_value **out) { + if(name_count>(size_t)PTRDIFF_MAX/sizeof(uint32_t) || (name_count && !name)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid array span"); + for(size_t i=0;i0x10ffffu) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Char code point"); + if(!hm_decimal(value_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(value_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *valueDigit=value_denominator; if(*valueDigit=='-') ++valueDigit; while(*valueDigit=='0') ++valueDigit; if(!*valueDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!hm_decimal(uncertainty_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(uncertainty_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *uncertaintyDigit=uncertainty_denominator; if(*uncertaintyDigit=='-') ++uncertaintyDigit; while(*uncertaintyDigit=='0') ++uncertaintyDigit; if(!*uncertaintyDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(!hm_decimal(approximation_numerator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + if(!hm_decimal(approximation_denominator)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal"); + const char *approximationDigit=approximation_denominator; if(*approximationDigit=='-') ++approximationDigit; while(*approximationDigit=='0') ++approximationDigit; if(!*approximationDigit) return hm_error(HMATH_INVALID_ARGUMENT,"zero Rational denominator"); + if(unit_count>(size_t)PTRDIFF_MAX/sizeof(uint32_t) || (unit_count && !unit)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid array span"); + for(size_t i=0;i0x10ffffu) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Char code point"); + if(source_count>(size_t)PTRDIFF_MAX/sizeof(uint32_t) || (source_count && !source)) return hm_error(HMATH_INVALID_ARGUMENT,"invalid array span"); + for(size_t i=0;i0x10ffffu) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Char code point"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant(name, name_count, value_numerator, value_denominator, uncertainty_numerator, uncertainty_denominator, approximation_numerator, approximation_denominator, unit, unit_count, source, source_count, &result->stable), out); +} +extern int hm_numeric_types_constant_name(void *value, void **out); +hmath_status hmath_numeric_types_constant_name(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_name(value->stable, &result->stable), out); +} +extern int hm_numeric_types_constant_value(void *value, void **out); +hmath_status hmath_numeric_types_constant_value(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_value(value->stable, &result->stable), out); +} +extern int hm_numeric_types_standard_uncertainty(void *value, void **out); +hmath_status hmath_numeric_types_standard_uncertainty(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_standard_uncertainty(value->stable, &result->stable), out); +} +extern int hm_numeric_types_approximation_bound(void *value, void **out); +hmath_status hmath_numeric_types_approximation_bound(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_approximation_bound(value->stable, &result->stable), out); +} +extern int hm_numeric_types_constant_unit(void *value, void **out); +hmath_status hmath_numeric_types_constant_unit(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_unit(value->stable, &result->stable), out); +} +extern int hm_numeric_types_constant_source(void *value, void **out); +hmath_status hmath_numeric_types_constant_source(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_source(value->stable, &result->stable), out); +} +extern int hm_numeric_types_constant_as(void *value, int dtype, void **out); +hmath_status hmath_numeric_types_constant_as(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_as(value->stable, dtype, &result->stable), out); +} +extern int hm_numeric_types_constant_as_like(void *value, void *prototype, void **out); +hmath_status hmath_numeric_types_constant_as_like(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *prototype, hmath_numeric_value **out) { + if(!value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value"); + if(!prototype) return hm_error(HMATH_INVALID_ARGUMENT,"NULL prototype"); + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_constant_as_like(value->stable, prototype->stable, &result->stable), out); +} +extern int hm_numeric_types_mathematical_constants(void **out); +hmath_status hmath_numeric_types_mathematical_constants(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_mathematical_constants(&result->stable), out); +} +extern int hm_numeric_types_physical_constants(void **out); +hmath_status hmath_numeric_types_physical_constants(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_physical_constants(&result->stable), out); +} +extern int hm_numeric_types_speed_of_light(void **out); +hmath_status hmath_numeric_types_speed_of_light(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_speed_of_light(&result->stable), out); +} +extern int hm_numeric_types_planck_constant(void **out); +hmath_status hmath_numeric_types_planck_constant(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_planck_constant(&result->stable), out); +} +extern int hm_numeric_types_elementary_charge(void **out); +hmath_status hmath_numeric_types_elementary_charge(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_elementary_charge(&result->stable), out); +} +extern int hm_numeric_types_boltzmann_constant(void **out); +hmath_status hmath_numeric_types_boltzmann_constant(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_boltzmann_constant(&result->stable), out); +} +extern int hm_numeric_types_avogadro_constant(void **out); +hmath_status hmath_numeric_types_avogadro_constant(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_avogadro_constant(&result->stable), out); +} +extern int hm_numeric_types_gravitational_constant(void **out); +hmath_status hmath_numeric_types_gravitational_constant(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_gravitational_constant(&result->stable), out); +} +extern int hm_numeric_types_electron_mass(void **out); +hmath_status hmath_numeric_types_electron_mass(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_electron_mass(&result->stable), out); +} +extern int hm_numeric_types_astronomical_unit(void **out); +hmath_status hmath_numeric_types_astronomical_unit(hmath_context *context, hmath_numeric_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output"); + hmath_numeric_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result, hm_numeric_types_astronomical_unit(&result->stable), out); +} +extern int hm_numeric_types_enum_value(void *stable,int *out); +hmath_status hmath_numeric_types_enum_value(hmath_context *context,const hmath_numeric_value *value,int *out) { if(!value||!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL enum argument"); hmath_status status=hm_enter(context);if(status)return status;status=(hmath_status)hm_numeric_types_enum_value(value->stable,out);hm_leave();return status;} diff --git a/cbits/numerical.c b/cbits/numerical.c new file mode 100644 index 0000000..2968630 --- /dev/null +++ b/cbits/numerical.c @@ -0,0 +1,1670 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_numerical.h" +#include "value_internal.h" +extern int hm_numerical_apply(int,void *const *,size_t,void **); +hmath_status hmath_calculus_estimate(hmath_context *context, const hmath_value *value, const hmath_value *error, const hmath_value *evaluations, hmath_value **out) { + if (!out || !value || !error || !evaluations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(error), hm_value_stable(evaluations)}; + int code=hm_numerical_apply(0,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_estimate_value(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(1,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_estimate_error(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(2,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(3,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_tolerance(hmath_context *context, const hmath_value *absolute_tolerance, const hmath_value *relative_tolerance, const hmath_value *maximum_evaluations, hmath_value **out) { + if (!out || !absolute_tolerance || !relative_tolerance || !maximum_evaluations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(absolute_tolerance), hm_value_stable(relative_tolerance), hm_value_stable(maximum_evaluations)}; + int code=hm_numerical_apply(4,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(5,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(6,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_maximum_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(7,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_default_tolerance(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(8,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_forward(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(9,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_backward(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(10,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_central(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(11,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_trapezoidal(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(12,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_simpson(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(13,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_three_eighths(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(14,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_derivative(hmath_context *context, const hmath_value *method, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !method || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(15,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_derivative_n(hmath_context *context, const hmath_value *order, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !order || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(order), hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(16,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_complex_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(17,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_richardson(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !tol || !initial || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(initial), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(18,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_ridders(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !tol || !initial || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(initial), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(19,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_limit(hmath_context *context, const hmath_value *side, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !side || !tol || !initial || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(side), hm_value_stable(tol), hm_value_stable(initial), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(20,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_partial_derivative(hmath_context *context, const hmath_value *i, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out) { + if (!out || !i || !h || !f || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(i), hm_value_stable(h), hm_value_stable(f), hm_value_stable(xs)}; + int code=hm_numerical_apply(21,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gradient(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out) { + if (!out || !h || !f || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(xs)}; + int code=hm_numerical_apply(22,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_jacobian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out) { + if (!out || !h || !f || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(xs)}; + int code=hm_numerical_apply(23,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_hessian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out) { + if (!out || !h || !f || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(xs)}; + int code=hm_numerical_apply(24,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_directional_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out) { + if (!out || !h || !f || !x || !v) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x), hm_value_stable(v)}; + int code=hm_numerical_apply(25,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_jvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out) { + if (!out || !h || !f || !x || !v) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x), hm_value_stable(v)}; + int code=hm_numerical_apply(26,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_vjp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out) { + if (!out || !h || !f || !x || !v) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x), hm_value_stable(v)}; + int code=hm_numerical_apply(27,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_hvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out) { + if (!out || !h || !f || !x || !v) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x), hm_value_stable(v)}; + int code=hm_numerical_apply(28,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_divergence(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(29,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_curl(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(30,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_laplacian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out) { + if (!out || !h || !f || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(h), hm_value_stable(f), hm_value_stable(x)}; + int code=hm_numerical_apply(31,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_integrate_composite(hmath_context *context, const hmath_value *method, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !method || !n || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(n), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(32,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_romberg(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(33,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gauss_legendre(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !n || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(n), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(34,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gauss_hermite(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(35,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gauss_laguerre(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(36,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gauss_chebyshev(hmath_context *context, const hmath_value *n, const hmath_value *f, hmath_value **out) { + if (!out || !n || !f) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(n), hm_value_stable(f)}; + int code=hm_numerical_apply(37,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_gauss_kronrod(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(38,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_adaptive_integrate(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(39,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_clenshaw_curtis(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !n || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(n), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(40,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_tanh_sinh(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(41,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_integrate_infinite(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(42,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_integrate_oscillatory(hmath_context *context, const hmath_value *sine, const hmath_value *omega, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !sine || !omega || !tol || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(sine), hm_value_stable(omega), hm_value_stable(tol), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(43,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_integrate_nd(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out) { + if (!out || !panels || !budget || !f || !bounds) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(panels), hm_value_stable(budget), hm_value_stable(f), hm_value_stable(bounds)}; + int code=hm_numerical_apply(44,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_monte_carlo(hmath_context *context, const hmath_value *seed, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out) { + if (!out || !seed || !n || !f || !bounds) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(seed), hm_value_stable(n), hm_value_stable(f), hm_value_stable(bounds)}; + int code=hm_numerical_apply(45,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_quasi_monte_carlo(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out) { + if (!out || !n || !f || !bounds) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(n), hm_value_stable(f), hm_value_stable(bounds)}; + int code=hm_numerical_apply(46,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_cumulative_integral(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(47,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_path_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !curve || !tangent || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(curve), hm_value_stable(tangent), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(48,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_line_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *field, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tol || !curve || !tangent || !field || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tol), hm_value_stable(curve), hm_value_stable(tangent), hm_value_stable(field), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(49,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_surface_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *surface, const hmath_value *du, const hmath_value *dv, const hmath_value *f, const hmath_value *bounds, hmath_value **out) { + if (!out || !panels || !budget || !surface || !du || !dv || !f || !bounds) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(panels), hm_value_stable(budget), hm_value_stable(surface), hm_value_stable(du), hm_value_stable(dv), hm_value_stable(f), hm_value_stable(bounds)}; + int code=hm_numerical_apply(50,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_calculus_volume_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out) { + if (!out || !panels || !budget || !f || !bounds) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(panels), hm_value_stable(budget), hm_value_stable(f), hm_value_stable(bounds)}; + int code=hm_numerical_apply(51,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_options(hmath_context *context, const hmath_value *root_max_iterations, const hmath_value *root_max_evaluations, const hmath_value *root_tolerance, const hmath_value *root_step_tolerance, hmath_value **out) { + if (!out || !root_max_iterations || !root_max_evaluations || !root_tolerance || !root_step_tolerance) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(root_max_iterations), hm_value_stable(root_max_evaluations), hm_value_stable(root_tolerance), hm_value_stable(root_step_tolerance)}; + int code=hm_numerical_apply(52,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_max_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(53,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_max_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(54,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(55,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_step_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(56,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_default_root_options(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(57,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_result(hmath_context *context, const hmath_value *root_value, const hmath_value *root_residual, const hmath_value *root_error_bound, const hmath_value *root_iterations, const hmath_value *root_evaluations, hmath_value **out) { + if (!out || !root_value || !root_residual || !root_error_bound || !root_iterations || !root_evaluations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(root_value), hm_value_stable(root_residual), hm_value_stable(root_error_bound), hm_value_stable(root_iterations), hm_value_stable(root_evaluations)}; + int code=hm_numerical_apply(58,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_value(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(59,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_residual(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(60,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_error_bound(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(61,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(62,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_root_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(63,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_bisection(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(64,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_regula_falsi(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(65,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_illinois(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(66,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_brent(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(67,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_ridder(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(68,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_newton(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(69,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_halley(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(70,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_householder3(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(71,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_picard(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(72,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_aitken(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(73,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_steffensen_fixed(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(74,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_multivariate_newton(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(75,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_newton_trust_region(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(76,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_broyden(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(77,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_system_root_result(hmath_context *context, const hmath_value *system_root, const hmath_value *system_residual, const hmath_value *system_iterations, const hmath_value *system_evaluations, hmath_value **out) { + if (!out || !system_root || !system_residual || !system_iterations || !system_evaluations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(system_root), hm_value_stable(system_residual), hm_value_stable(system_iterations), hm_value_stable(system_evaluations)}; + int code=hm_numerical_apply(78,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_system_root(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(79,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_system_residual(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(80,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_system_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(81,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_system_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(82,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_bracket(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(83,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_solve_bracket(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4)}; + int code=hm_numerical_apply(84,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_bracket_scan(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out) { + if (!out || !o || !f || !a || !b || !cells) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(o), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b), hm_value_stable(cells)}; + int code=hm_numerical_apply(85,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_isolate_intervals(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out) { + if (!out || !o || !f || !a || !b || !cells) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(o), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b), hm_value_stable(cells)}; + int code=hm_numerical_apply(86,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_solve_derivative(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *derivatives, const hmath_value *x0, hmath_value **out) { + if (!out || !method || !o || !f || !derivatives || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(o), hm_value_stable(f), hm_value_stable(derivatives), hm_value_stable(x0)}; + int code=hm_numerical_apply(87,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_secant(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !o || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(o), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_numerical_apply(88,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_steffensen(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *x0, hmath_value **out) { + if (!out || !o || !f || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(o), hm_value_stable(f), hm_value_stable(x0)}; + int code=hm_numerical_apply(89,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_fixed_point(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out) { + if (!out || !method || !o || !g || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(o), hm_value_stable(g), hm_value_stable(x0)}; + int code=hm_numerical_apply(90,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_anderson(hmath_context *context, const hmath_value *depth, const hmath_value *regularization, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out) { + if (!out || !depth || !regularization || !o || !g || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(depth), hm_value_stable(regularization), hm_value_stable(o), hm_value_stable(g), hm_value_stable(x0)}; + int code=hm_numerical_apply(91,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_solve_system(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *jac, const hmath_value *x0, hmath_value **out) { + if (!out || !method || !o || !f || !jac || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(o), hm_value_stable(f), hm_value_stable(jac), hm_value_stable(x0)}; + int code=hm_numerical_apply(92,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_polynomial_roots(hmath_context *context, const hmath_value *o, const hmath_value *p, hmath_value **out) { + if (!out || !o || !p) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(o), hm_value_stable(p)}; + int code=hm_numerical_apply(93,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_root_real_polynomial_roots(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *p, hmath_value **out) { + if (!out || !budget || !tolerance || !p) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(budget), hm_value_stable(tolerance), hm_value_stable(p)}; + int code=hm_numerical_apply(94,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_euler(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(95,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_heun(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(96,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_midpoint(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(97,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rk2(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(98,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rk4(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(99,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rk23(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(100,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rk45(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(101,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_dormand_prince(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(102,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_dop853(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(103,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_adams_bashforth(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(104,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_adams_moulton(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(105,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_predictor_corrector(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(106,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_backward_euler(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(107,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_bdf(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(108,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_radau(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(109,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rosenbrock(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(110,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_ode_options(hmath_context *context, const hmath_value *ode_absolute_tolerance, const hmath_value *ode_relative_tolerance, const hmath_value *initial_step, const hmath_value *minimum_step, const hmath_value *maximum_step, const hmath_value *maximum_steps, const hmath_value *newton_iterations, hmath_value **out) { + if (!out || !ode_absolute_tolerance || !ode_relative_tolerance || !initial_step || !minimum_step || !maximum_step || !maximum_steps || !newton_iterations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(ode_absolute_tolerance), hm_value_stable(ode_relative_tolerance), hm_value_stable(initial_step), hm_value_stable(minimum_step), hm_value_stable(maximum_step), hm_value_stable(maximum_steps), hm_value_stable(newton_iterations)}; + int code=hm_numerical_apply(111,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_ode_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(112,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_ode_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(113,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_initial_step(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(114,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_minimum_step(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(115,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_maximum_step(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(116,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_maximum_steps(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(117,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_newton_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(118,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_default_ode_options(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(119,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_trajectory(hmath_context *context, const hmath_value *trajectory_times, const hmath_value *trajectory_states, const hmath_value *trajectory_derivatives, hmath_value **out) { + if (!out || !trajectory_times || !trajectory_states || !trajectory_derivatives) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(trajectory_times), hm_value_stable(trajectory_states), hm_value_stable(trajectory_derivatives)}; + int code=hm_numerical_apply(120,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_trajectory_times(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(121,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_trajectory_states(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(122,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_trajectory_derivatives(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(123,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_ivp(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out) { + if (!out || !method || !options || !panels || !f || !start || !end || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(options), hm_value_stable(panels), hm_value_stable(f), hm_value_stable(start), hm_value_stable(end), hm_value_stable(initial)}; + int code=hm_numerical_apply(124,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_adaptive(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out) { + if (!out || !method || !options || !f || !start || !end || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(options), hm_value_stable(f), hm_value_stable(start), hm_value_stable(end), hm_value_stable(initial)}; + int code=hm_numerical_apply(125,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_interpolate_trajectory(hmath_context *context, const hmath_value *trajectory, const hmath_value *t, hmath_value **out) { + if (!out || !trajectory || !t) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(trajectory), hm_value_stable(t)}; + int code=hm_numerical_apply(126,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_any_direction(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(127,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_rising(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(128,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_falling(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(129,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_event(hmath_context *context, const hmath_value *event_time, const hmath_value *event_state, hmath_value **out) { + if (!out || !event_time || !event_state) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(event_time), hm_value_stable(event_state)}; + int code=hm_numerical_apply(130,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_event_time(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(131,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_event_state(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(132,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_locate_events(hmath_context *context, const hmath_value *direction, const hmath_value *tolerance, const hmath_value *function, const hmath_value *trajectory, hmath_value **out) { + if (!out || !direction || !tolerance || !function || !trajectory) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(direction), hm_value_stable(tolerance), hm_value_stable(function), hm_value_stable(trajectory)}; + int code=hm_numerical_apply(133,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_boundary(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *boundary, const hmath_value *start, const hmath_value *end, const hmath_value *guess, hmath_value **out) { + if (!out || !method || !options || !panels || !f || !boundary || !start || !end || !guess) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(options), hm_value_stable(panels), hm_value_stable(f), hm_value_stable(boundary), hm_value_stable(start), hm_value_stable(end), hm_value_stable(guess)}; + int code=hm_numerical_apply(134,arguments,8,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_dae(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *residual, const hmath_value *start, const hmath_value *end, const hmath_value *initial, const hmath_value *initial_derivative, hmath_value **out) { + if (!out || !options || !panels || !residual || !start || !end || !initial || !initial_derivative) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(options), hm_value_stable(panels), hm_value_stable(residual), hm_value_stable(start), hm_value_stable(end), hm_value_stable(initial), hm_value_stable(initial_derivative)}; + int code=hm_numerical_apply(135,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_symplectic_euler(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(136,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_verlet(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(137,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_leapfrog(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(138,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_hamiltonian(hmath_context *context, const hmath_value *method, const hmath_value *panels, const hmath_value *velocity, const hmath_value *force, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *p0, hmath_value **out) { + if (!out || !method || !panels || !velocity || !force || !start || !end || !q0 || !p0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(panels), hm_value_stable(velocity), hm_value_stable(force), hm_value_stable(start), hm_value_stable(end), hm_value_stable(q0), hm_value_stable(p0)}; + int code=hm_numerical_apply(139,arguments,8,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_solve_nystrom(hmath_context *context, const hmath_value *panels, const hmath_value *acceleration, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *v0, hmath_value **out) { + if (!out || !panels || !acceleration || !start || !end || !q0 || !v0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(panels), hm_value_stable(acceleration), hm_value_stable(start), hm_value_stable(end), hm_value_stable(q0), hm_value_stable(v0)}; + int code=hm_numerical_apply(140,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_sensitivities(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *h, const hmath_value *family, const hmath_value *parameters, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out) { + if (!out || !method || !options || !panels || !h || !family || !parameters || !start || !end || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(options), hm_value_stable(panels), hm_value_stable(h), hm_value_stable(family), hm_value_stable(parameters), hm_value_stable(start), hm_value_stable(end), hm_value_stable(initial)}; + int code=hm_numerical_apply(141,arguments,9,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_equilibrium(hmath_context *context, const hmath_value *options, const hmath_value *field, const hmath_value *guess, hmath_value **out) { + if (!out || !options || !field || !guess) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(options), hm_value_stable(field), hm_value_stable(guess)}; + int code=hm_numerical_apply(142,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_phase_trajectories(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, const hmath_value *value7, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5 || !value6 || !value7) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5), hm_value_stable(value6), hm_value_stable(value7)}; + int code=hm_numerical_apply(143,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_ode_lyapunov_exponents(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *difference_step, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out) { + if (!out || !options || !panels || !difference_step || !f || !start || !end || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(options), hm_value_stable(panels), hm_value_stable(difference_step), hm_value_stable(f), hm_value_stable(start), hm_value_stable(end), hm_value_stable(initial)}; + int code=hm_numerical_apply(144,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_dirichlet(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(145,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_neumann(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(146,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_robin(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code=hm_numerical_apply(147,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_periodic(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(148,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_finite_difference(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(149,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_finite_volume(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(150,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_finite_element(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_numerical_apply(151,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_result(hmath_context *context, const hmath_value *pde_values, const hmath_value *pde_residual, const hmath_value *pde_error_estimate, hmath_value **out) { + if (!out || !pde_values || !pde_residual || !pde_error_estimate) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(pde_values), hm_value_stable(pde_residual), hm_value_stable(pde_error_estimate)}; + int code=hm_numerical_apply(152,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_values(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(153,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_residual(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(154,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_error_estimate(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(155,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_grid(hmath_context *context, const hmath_value *dims, const hmath_value *bounds, const hmath_value *periodic, hmath_value **out) { + if (!out || !dims || !bounds || !periodic) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(dims), hm_value_stable(bounds), hm_value_stable(periodic)}; + int code=hm_numerical_apply(156,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_grid_shape(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(157,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_grid_spacing(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(158,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_flatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(159,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_unflatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(160,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_grid_coordinates(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(161,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_assemble_pde(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code=hm_numerical_apply(162,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_stiffness(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(163,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_mass(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(164,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pde_boundary_load(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_numerical_apply(165,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_solve_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(166,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_poisson(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *forcing, hmath_value **out) { + if (!out || !method || !g || !bc || !forcing) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(g), hm_value_stable(bc), hm_value_stable(forcing)}; + int code=hm_numerical_apply(167,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_laplace(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, hmath_value **out) { + if (!out || !method || !g || !bc) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(g), hm_value_stable(bc)}; + int code=hm_numerical_apply(168,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_helmholtz(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *k, const hmath_value *forcing, hmath_value **out) { + if (!out || !method || !g || !bc || !k || !forcing) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(g), hm_value_stable(bc), hm_value_stable(k), hm_value_stable(forcing)}; + int code=hm_numerical_apply(169,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_spatial_gradient(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_numerical_apply(170,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_laplacian_stencil(hmath_context *context, const hmath_value *g, const hmath_value *bc, const hmath_value *values, hmath_value **out) { + if (!out || !g || !bc || !values) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(bc), hm_value_stable(values)}; + int code=hm_numerical_apply(171,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_spectral_derivative(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4)}; + int code=hm_numerical_apply(172,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_spectral_laplacian(hmath_context *context, const hmath_value *g, const hmath_value *values, hmath_value **out) { + if (!out || !g || !values) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(values)}; + int code=hm_numerical_apply(173,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_spectral_poisson(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code=hm_numerical_apply(174,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_pseudo_spectral_diffusion(hmath_context *context, const hmath_value *g, const hmath_value *kappas, const hmath_value *values, hmath_value **out) { + if (!out || !g || !kappas || !values) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(kappas), hm_value_stable(values)}; + int code=hm_numerical_apply(175,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_method_of_lines(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code=hm_numerical_apply(176,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_heat(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code=hm_numerical_apply(177,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_diffusion(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *kappas, const hmath_value *times, const hmath_value *initial, hmath_value **out) { + if (!out || !method || !g || !bc || !kappas || !times || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(g), hm_value_stable(bc), hm_value_stable(kappas), hm_value_stable(times), hm_value_stable(initial)}; + int code=hm_numerical_apply(178,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_wave(hmath_context *context, const hmath_value *g, const hmath_value *speed, const hmath_value *times, const hmath_value *initial, const hmath_value *velocity, hmath_value **out) { + if (!out || !g || !speed || !times || !initial || !velocity) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(speed), hm_value_stable(times), hm_value_stable(initial), hm_value_stable(velocity)}; + int code=hm_numerical_apply(179,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_advection(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4)}; + int code=hm_numerical_apply(180,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_advection_diffusion(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code=hm_numerical_apply(181,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_stability_limit(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, hmath_value **out) { + if (!out || !g || !diffusivity || !velocity) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(diffusivity), hm_value_stable(velocity)}; + int code=hm_numerical_apply(182,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_cfl_number(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, const hmath_value *dt, hmath_value **out) { + if (!out || !g || !diffusivity || !velocity || !dt) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(diffusivity), hm_value_stable(velocity), hm_value_stable(dt)}; + int code=hm_numerical_apply(183,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_pde_manufactured_error(hmath_context *context, const hmath_value *g, const hmath_value *exact, const hmath_value *values, hmath_value **out) { + if (!out || !g || !exact || !values) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(g), hm_value_stable(exact), hm_value_stable(values)}; + int code=hm_numerical_apply(184,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} diff --git a/cbits/optimization.c b/cbits/optimization.c new file mode 100644 index 0000000..2b6370d --- /dev/null +++ b/cbits/optimization.c @@ -0,0 +1,125 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_optimization.h" +#include "native_internal.h" +#include "value_internal.h" +#include + +struct hmath_optimizer_state { + atomic_size_t refs; + void *stable; +}; + +extern int hm_optimizer_initialize(ptrdiff_t dimension, void **out); +extern void hm_optimizer_free(void *state); +extern int hm_optimizer_step(int method, double rate, void *state, const double *parameters, + size_t parameter_count, const double *gradient, size_t gradient_count, + double *out_parameters, void **out_state); + +hmath_status hmath_initialize_optimizer(hmath_context *context, ptrdiff_t dimension, + hmath_optimizer_state **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL optimizer output"); + hmath_optimizer_state *state = malloc(sizeof *state); + if (!state) + return hm_error(HMATH_ALLOCATION_FAILED, "optimizer handle allocation failed"); + hmath_status status = hm_enter(context); + if (status) { + free(state); + return status; + } + status = (hmath_status)hm_optimizer_initialize(dimension, &state->stable); + if (status) { + free(state); + hm_leave(); + return status; + } + atomic_init(&state->refs, 1); + *out = state; + /* Keep the reservation for this stable pointer's whole lifetime. */ + return HMATH_OK; +} + +void hmath_optimizer_state_retain(hmath_optimizer_state *state) { + if (state) + atomic_fetch_add_explicit(&state->refs, 1, memory_order_relaxed); +} + +void hmath_optimizer_state_release(hmath_optimizer_state *state) { + if (state && atomic_fetch_sub_explicit(&state->refs, 1, memory_order_acq_rel) == 1) { + hm_optimizer_free(state->stable); + free(state); + hm_leave(); + } +} + +hmath_status hmath_optimizer_step(hmath_context *context, hmath_gradient_method method, double rate, + const hmath_optimizer_state *state, const double *parameters, + size_t parameter_count, const double *gradient, + size_t gradient_count, double *out_parameters, + size_t out_capacity, hmath_optimizer_state **out_state) { + if (!state || !out_state || (parameter_count && (!parameters || !out_parameters)) || + (gradient_count && !gradient)) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL optimizer argument"); + if ((unsigned)method > HMATH_RADAM) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid GradientMethod constructor"); + if (parameter_count > (size_t)PTRDIFF_MAX / sizeof(double) || + gradient_count > (size_t)PTRDIFF_MAX / sizeof(double)) + return hm_error(HMATH_OVERFLOW, "optimizer byte span exceeds ptrdiff_t"); + if (out_capacity < parameter_count) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient optimizer output capacity"); + hmath_optimizer_state *next = malloc(sizeof *next); + if (!next) + return hm_error(HMATH_ALLOCATION_FAILED, "optimizer handle allocation failed"); + hmath_status status = hm_enter(context); + if (status) { + free(next); + return status; + } + status = + (hmath_status)hm_optimizer_step(method, rate, state->stable, parameters, parameter_count, + gradient, gradient_count, out_parameters, &next->stable); + if (status) { + free(next); + hm_leave(); + return status; + } + atomic_init(&next->refs, 1); + *out_state = next; + return HMATH_OK; +} + +extern int hm_opt_import_state(void *state, void **out); +extern int hm_opt_export_state(void *value, void **out); +hmath_status hmath_optimization_state_import(hmath_context *context, + const hmath_optimizer_state *state, + hmath_value **out) { + if (!state || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL optimizer state import"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_opt_import_state(state->stable, &result->stable), out); +} +hmath_status hmath_optimization_state_export(hmath_context *context, const hmath_value *value, + hmath_optimizer_state **out) { + if (!value || !out || value->kind != 34) + return hm_error(HMATH_INVALID_ARGUMENT, "expected optimizer state value"); + hmath_optimizer_state *state = malloc(sizeof *state); + if (!state) + return hm_error(HMATH_ALLOCATION_FAILED, "optimizer state owner allocation failed"); + hmath_status status = hm_enter(context); + if (status) { + free(state); + return status; + } + status = (hmath_status)hm_opt_export_state(hm_value_stable(value), &state->stable); + if (status) { + free(state); + hm_leave(); + return status; + } + atomic_init(&state->refs, 1); + *out = state; + return HMATH_OK; +} diff --git a/cbits/optimization_all.c b/cbits/optimization_all.c new file mode 100644 index 0000000..73616d3 --- /dev/null +++ b/cbits/optimization_all.c @@ -0,0 +1,667 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_optimization_all.h" +#include "value_internal.h" +#include +#include +extern int hm_opt_invoke(const char *name, void *const *arguments, size_t count, void **out); +extern int hm_opt_callback(int role, hmath_optimization_callback_fn function, void *userdata, + void **out); +extern int hm_opt_clone(void *value, void **out); + +static hmath_status invoke(hmath_context *context, const char *name, + const hmath_value *const *arguments, size_t count, hmath_value **out) { + if (!out || (count && !arguments)) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL optimization argument/output"); + if (count > (size_t)PTRDIFF_MAX / sizeof(void *)) + return hm_error(HMATH_OVERFLOW, "optimization argument span overflow"); + for (size_t i = 0; i < count; ++i) + if (!arguments[i]) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL optimization value"); + void **stable = malloc((count ? count : 1) * sizeof *stable); + if (!stable) + return hm_error(HMATH_ALLOCATION_FAILED, "optimization argument allocation failed"); + for (size_t i = 0; i < count; ++i) + stable[i] = hm_value_stable(arguments[i]); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) { + free(stable); + return status; + } + int code = hm_opt_invoke(name, stable, count, &result->stable); + free(stable); + return hm_value_finish(result, code, out); +} +hmath_status hmath_optimization_callback(hmath_context *context, int role, + hmath_optimization_callback_fn function, void *userdata, + hmath_value **out) { + if (!function || !out || (unsigned)role > 4) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid optimization callback"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + return hm_value_finish(result, hm_opt_callback(role, function, userdata, &result->stable), out); +} +/* Called safely from Haskell. Callback input is borrowed; callback output + * transfers an owned reference. The helper clones both independent roots. */ +int hm_opt_invoke_callback(hmath_optimization_callback_fn function, void *userdata, void *argument, + void **out, hmath_math_error *error) { + hmath_value *input; + hmath_status status = hm_value_begin(NULL, &input); + if (status) { + error->message = "optimization callback input allocation failed"; + error->message_length = strlen(error->message); + return status; + } + hmath_value *published = NULL; + status = hm_value_finish(input, hm_opt_clone(argument, &input->stable), &published); + if (status) { + error->message = "optimization callback input clone failed"; + error->message_length = strlen(error->message); + return status; + } + hmath_value *result = NULL; + status = function(published, userdata, &result, error); + if (!status) { + if (!result) { + status = HMATH_INVALID_ARGUMENT; + error->message = "callback returned a NULL value"; + error->message_length = strlen(error->message); + } else + status = (hmath_status)hm_opt_clone(hm_value_stable(result), out); + } + hmath_value_release(result); + hmath_value_release(published); + return status; +} +hmath_status hmath_optimization_function_apply(hmath_context *context, const hmath_value *function, + const hmath_value *const *arguments, size_t count, + hmath_value **out) { + if (!function || (count && !arguments) || count >= (size_t)PTRDIFF_MAX / sizeof(void *)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid optimization function arguments"); + const hmath_value **all = malloc((count + 1) * sizeof *all); + if (!all) + return hm_error(HMATH_ALLOCATION_FAILED, "function argument allocation failed"); + all[0] = function; + for (size_t i = 0; i < count; ++i) + all[i + 1] = arguments[i]; + hmath_status status = invoke(context, "__apply", all, count + 1, out); + free(all); + return status; +} +hmath_status hmath_optimization_optimize_options_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "OptimizeOptions", arguments, 4, out); +} +hmath_status hmath_optimization_default_optimize_options(hmath_context *context, + hmath_value **out) { + return invoke(context, "defaultOptimizeOptions", NULL, 0, out); +} +hmath_status hmath_optimization_optimize_result_create(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + const hmath_value *a2, const hmath_value *a3, + const hmath_value *a4, const hmath_value *a5, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "OptimizeResult", arguments, 6, out); +} +hmath_status hmath_optimization_early_stopping_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2}; + return invoke(context, "EarlyStopping", arguments, 3, out); +} +hmath_status hmath_optimization_constant_rate_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "ConstantRate", arguments, 1, out); +} +hmath_status hmath_optimization_step_decay_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2}; + return invoke(context, "StepDecay", arguments, 3, out); +} +hmath_status hmath_optimization_exponential_decay_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "ExponentialDecay", arguments, 2, out); +} +hmath_status hmath_optimization_cosine_annealing_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2}; + return invoke(context, "CosineAnnealing", arguments, 3, out); +} +hmath_status hmath_optimization_warmup_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "Warmup", arguments, 2, out); +} +hmath_status hmath_optimization_armijo_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Armijo", NULL, 0, out); +} +hmath_status hmath_optimization_strong_wolfe_create(hmath_context *context, hmath_value **out) { + return invoke(context, "StrongWolfe", NULL, 0, out); +} +hmath_status hmath_optimization_checked_options(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "checkedOptions", arguments, 1, out); +} +hmath_status hmath_optimization_checked_point(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "checkedPoint", arguments, 1, out); +} +hmath_status hmath_optimization_checked_value(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "checkedValue", arguments, 2, out); +} +hmath_status hmath_optimization_checked_gradient(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "checkedGradient", arguments, 2, out); +} +hmath_status hmath_optimization_check_budget(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "checkBudget", arguments, 2, out); +} +hmath_status hmath_optimization_dot(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "dot", arguments, 2, out); +} +hmath_status hmath_optimization_add(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "add", arguments, 2, out); +} +hmath_status hmath_optimization_sub(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "sub", arguments, 2, out); +} +hmath_status hmath_optimization_outer(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "outer", arguments, 2, out); +} +hmath_status hmath_optimization_norm(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "norm", arguments, 1, out); +} +hmath_status hmath_optimization_scale(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "scale", arguments, 2, out); +} +hmath_status hmath_optimization_identity(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "identity", arguments, 1, out); +} +hmath_status hmath_optimization_mat_vec(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "matVec", arguments, 2, out); +} +hmath_status hmath_optimization_mat_mul(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "matMul", arguments, 2, out); +} +hmath_status hmath_optimization_transpose(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "transpose", arguments, 1, out); +} +hmath_status hmath_optimization_solve_dense(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "solveDense", arguments, 2, out); +} +hmath_status hmath_optimization_result(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "result", arguments, 6, out); +} +hmath_status hmath_optimization_learning_rate(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "learningRate", arguments, 2, out); +} +hmath_status hmath_optimization_early_stopping(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "earlyStopping", arguments, 4, out); +} +hmath_status hmath_optimization_line_search(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, const hmath_value *a6, + const hmath_value *a7, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5, a6, a7}; + return invoke(context, "lineSearch", arguments, 8, out); +} +hmath_status hmath_optimization_opt_max_iterations(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optMaxIterations", arguments, 1, out); +} +hmath_status hmath_optimization_opt_max_evaluations(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optMaxEvaluations", arguments, 1, out); +} +hmath_status hmath_optimization_opt_tolerance(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optTolerance", arguments, 1, out); +} +hmath_status hmath_optimization_opt_learning_rate(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optLearningRate", arguments, 1, out); +} +hmath_status hmath_optimization_opt_point(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optPoint", arguments, 1, out); +} +hmath_status hmath_optimization_opt_value(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optValue", arguments, 1, out); +} +hmath_status hmath_optimization_opt_gradient_norm(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optGradientNorm", arguments, 1, out); +} +hmath_status hmath_optimization_opt_iterations(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optIterations", arguments, 1, out); +} +hmath_status hmath_optimization_opt_evaluations(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optEvaluations", arguments, 1, out); +} +hmath_status hmath_optimization_opt_converged(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "optConverged", arguments, 1, out); +} +hmath_status hmath_optimization_best_score(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "bestScore", arguments, 1, out); +} +hmath_status hmath_optimization_stale_steps(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "staleSteps", arguments, 1, out); +} +hmath_status hmath_optimization_stopped(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "stopped", arguments, 1, out); +} +hmath_status hmath_optimization_gradient_descent_create(hmath_context *context, hmath_value **out) { + return invoke(context, "GradientDescent", NULL, 0, out); +} +hmath_status hmath_optimization_momentum_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Momentum", NULL, 0, out); +} +hmath_status hmath_optimization_nesterov_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Nesterov", NULL, 0, out); +} +hmath_status hmath_optimization_ada_grad_create(hmath_context *context, hmath_value **out) { + return invoke(context, "AdaGrad", NULL, 0, out); +} +hmath_status hmath_optimization_rms_prop_create(hmath_context *context, hmath_value **out) { + return invoke(context, "RMSProp", NULL, 0, out); +} +hmath_status hmath_optimization_ada_delta_create(hmath_context *context, hmath_value **out) { + return invoke(context, "AdaDelta", NULL, 0, out); +} +hmath_status hmath_optimization_adam_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Adam", NULL, 0, out); +} +hmath_status hmath_optimization_adam_w_create(hmath_context *context, hmath_value **out) { + return invoke(context, "AdamW", NULL, 0, out); +} +hmath_status hmath_optimization_ams_grad_create(hmath_context *context, hmath_value **out) { + return invoke(context, "AMSGrad", NULL, 0, out); +} +hmath_status hmath_optimization_ada_max_create(hmath_context *context, hmath_value **out) { + return invoke(context, "AdaMax", NULL, 0, out); +} +hmath_status hmath_optimization_nadam_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Nadam", NULL, 0, out); +} +hmath_status hmath_optimization_r_adam_create(hmath_context *context, hmath_value **out) { + return invoke(context, "RAdam", NULL, 0, out); +} +hmath_status hmath_optimization_initialize_optimizer(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "initializeOptimizer", arguments, 1, out); +} +hmath_status hmath_optimization_optimizer_step(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "optimizerStep", arguments, 5, out); +} +hmath_status hmath_optimization_minimize_gradient(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "minimizeGradient", arguments, 5, out); +} +hmath_status hmath_optimization_minimize_gradient_with_callback( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "minimizeGradientWithCallback", arguments, 6, out); +} +hmath_status hmath_optimization_stochastic_gradient(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "stochasticGradient", arguments, 4, out); +} +hmath_status hmath_optimization_mini_batch_gradient(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "miniBatchGradient", arguments, 1, out); +} +hmath_status hmath_optimization_projected_gradient(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "projectedGradient", arguments, 5, out); +} +hmath_status hmath_optimization_proximal_gradient(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "proximalGradient", arguments, 5, out); +} +hmath_status hmath_optimization_fista(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "fista", arguments, 5, out); +} +hmath_status hmath_optimization_coordinate_descent(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "coordinateDescent", arguments, 5, out); +} +hmath_status hmath_optimization_golden_section_create(hmath_context *context, hmath_value **out) { + return invoke(context, "GoldenSection", NULL, 0, out); +} +hmath_status hmath_optimization_ternary_search_create(hmath_context *context, hmath_value **out) { + return invoke(context, "TernarySearch", NULL, 0, out); +} +hmath_status hmath_optimization_brent_search_create(hmath_context *context, hmath_value **out) { + return invoke(context, "BrentSearch", NULL, 0, out); +} +hmath_status hmath_optimization_minimize_scalar(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "minimizeScalar", arguments, 5, out); +} +hmath_status hmath_optimization_bfgs_create(hmath_context *context, hmath_value **out) { + return invoke(context, "BFGS", NULL, 0, out); +} +hmath_status hmath_optimization_dfp_create(hmath_context *context, hmath_value **out) { + return invoke(context, "DFP", NULL, 0, out); +} +hmath_status hmath_optimization_sr1_create(hmath_context *context, hmath_value **out) { + return invoke(context, "SR1", NULL, 0, out); +} +hmath_status hmath_optimization_lbfgs_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "LBFGS", arguments, 1, out); +} +hmath_status hmath_optimization_minimize_quasi_newton(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "minimizeQuasiNewton", arguments, 5, out); +} +hmath_status hmath_optimization_newton_create(hmath_context *context, hmath_value **out) { + return invoke(context, "Newton", NULL, 0, out); +} +hmath_status hmath_optimization_newton_cg_create(hmath_context *context, hmath_value **out) { + return invoke(context, "NewtonCG", NULL, 0, out); +} +hmath_status hmath_optimization_trust_region_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "TrustRegion", arguments, 1, out); +} +hmath_status hmath_optimization_dogleg_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "Dogleg", arguments, 1, out); +} +hmath_status hmath_optimization_minimize_newton(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "minimizeNewton", arguments, 6, out); +} +hmath_status hmath_optimization_nonlinear_cg(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "nonlinearCG", arguments, 4, out); +} +hmath_status hmath_optimization_squared_loss_create(hmath_context *context, hmath_value **out) { + return invoke(context, "SquaredLoss", NULL, 0, out); +} +hmath_status hmath_optimization_huber_loss_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "HuberLoss", arguments, 1, out); +} +hmath_status hmath_optimization_cauchy_loss_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "CauchyLoss", arguments, 1, out); +} +hmath_status hmath_optimization_soft_l1_create(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "SoftL1", arguments, 1, out); +} +hmath_status hmath_optimization_least_squares(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "leastSquares", arguments, 6, out); +} +hmath_status hmath_optimization_nelder_mead(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2}; + return invoke(context, "nelderMead", arguments, 3, out); +} +hmath_status hmath_optimization_powell(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "powell", arguments, 4, out); +} +hmath_status hmath_optimization_equality_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "Equality", arguments, 2, out); +} +hmath_status hmath_optimization_less_equal_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "LessEqual", arguments, 2, out); +} +hmath_status hmath_optimization_feasibility(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "feasibility", arguments, 2, out); +} +hmath_status hmath_optimization_quadratic_penalty_create(hmath_context *context, + hmath_value **out) { + return invoke(context, "QuadraticPenalty", NULL, 0, out); +} +hmath_status hmath_optimization_log_barrier_create(hmath_context *context, hmath_value **out) { + return invoke(context, "LogBarrier", NULL, 0, out); +} +hmath_status hmath_optimization_interior_point_create(hmath_context *context, hmath_value **out) { + return invoke(context, "InteriorPoint", NULL, 0, out); +} +hmath_status hmath_optimization_augmented_lagrangian_create(hmath_context *context, + hmath_value **out) { + return invoke(context, "AugmentedLagrangian", NULL, 0, out); +} +hmath_status hmath_optimization_constrained_minimize(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "constrainedMinimize", arguments, 6, out); +} +hmath_status hmath_optimization_lp_result_create(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3}; + return invoke(context, "LPResult", arguments, 4, out); +} +hmath_status hmath_optimization_linear_programming(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "linearProgramming", arguments, 5, out); +} +hmath_status hmath_optimization_revised_simplex(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "revisedSimplex", arguments, 6, out); +} +hmath_status hmath_optimization_quadratic_programming(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "quadraticProgramming", arguments, 6, out); +} +hmath_status hmath_optimization_slsqp(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "slsqp", arguments, 6, out); +} +hmath_status hmath_optimization_cobyla(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4}; + return invoke(context, "cobyla", arguments, 5, out); +} +hmath_status hmath_optimization_weighted_objective(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1}; + return invoke(context, "weightedObjective", arguments, 2, out); +} +hmath_status hmath_optimization_pareto_front(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "paretoFront", arguments, 1, out); +} +hmath_status hmath_optimization_lp_point(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "lpPoint", arguments, 1, out); +} +hmath_status hmath_optimization_lp_value(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "lpValue", arguments, 1, out); +} +hmath_status hmath_optimization_lp_basis(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "lpBasis", arguments, 1, out); +} +hmath_status hmath_optimization_lp_iterations(hmath_context *context, const hmath_value *a0, + hmath_value **out) { + const hmath_value *arguments[] = {a0}; + return invoke(context, "lpIterations", arguments, 1, out); +} +hmath_status hmath_optimization_simulated_annealing_create(hmath_context *context, + hmath_value **out) { + return invoke(context, "SimulatedAnnealing", NULL, 0, out); +} +hmath_status hmath_optimization_differential_evolution_create(hmath_context *context, + hmath_value **out) { + return invoke(context, "DifferentialEvolution", NULL, 0, out); +} +hmath_status hmath_optimization_genetic_algorithm_create(hmath_context *context, + hmath_value **out) { + return invoke(context, "GeneticAlgorithm", NULL, 0, out); +} +hmath_status hmath_optimization_particle_swarm_create(hmath_context *context, hmath_value **out) { + return invoke(context, "ParticleSwarm", NULL, 0, out); +} +hmath_status hmath_optimization_cmaes_create(hmath_context *context, hmath_value **out) { + return invoke(context, "CMAES", NULL, 0, out); +} +hmath_status hmath_optimization_global_minimize(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5}; + return invoke(context, "globalMinimize", arguments, 6, out); +} +hmath_status hmath_optimization_basin_hopping(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, const hmath_value *a6, + hmath_value **out) { + const hmath_value *arguments[] = {a0, a1, a2, a3, a4, a5, a6}; + return invoke(context, "basinHopping", arguments, 7, out); +} diff --git a/cbits/polynomial.c b/cbits/polynomial.c new file mode 100644 index 0000000..5fdacea --- /dev/null +++ b/cbits/polynomial.c @@ -0,0 +1,323 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_polynomial_bindings.py. */ +#include "hmath_polynomial.h" +#include "value_internal.h" +extern int hm_polynomial_apply(int opcode,void *const *args,size_t count,void **out); +hmath_status hmath_polynomial_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out) { + if(!out || !prototype || !coefficients) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(coefficients)}; + return hm_value_finish(result,hm_polynomial_apply(0,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_coefficients(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(1,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_polynomial_degree(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(2,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_evaluate_polynomial(hmath_context *context, const hmath_value *polynomial, const hmath_value *x, hmath_value **out) { + if(!out || !polynomial || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial),hm_value_stable(x)}; + return hm_value_finish(result,hm_polynomial_apply(3,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_add_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(4,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_subtract_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(5,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_scale_polynomial(hmath_context *context, const hmath_value *scalar, const hmath_value *polynomial, hmath_value **out) { + if(!out || !scalar || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(scalar),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(6,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_multiply_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(7,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_compose_polynomial(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out) { + if(!out || !outer || !inner) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(outer),hm_value_stable(inner)}; + return hm_value_finish(result,hm_polynomial_apply(8,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_divide_polynomial(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if(!out || !numerator || !denominator) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(numerator),hm_value_stable(denominator)}; + return hm_value_finish(result,hm_polynomial_apply(9,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_monic_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(10,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_gcd_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(11,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_differentiate_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(12,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_integrate_polynomial(hmath_context *context, const hmath_value *constant, const hmath_value *polynomial, hmath_value **out) { + if(!out || !constant || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(constant),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(13,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_square_free_factors(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(14,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_rational_roots(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out) { + if(!out || !budget || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(budget),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(15,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_factor_rational_polynomial(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out) { + if(!out || !budget || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(budget),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(16,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_sturm_sequence(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(17,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_count_real_roots(hmath_context *context, const hmath_value *polynomial, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !polynomial || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial),hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(18,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_isolate_real_roots(hmath_context *context, const hmath_value *depth, const hmath_value *width, const hmath_value *polynomial, hmath_value **out) { + if(!out || !depth || !width || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(depth),hm_value_stable(width),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(19,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_durand_kerner(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out) { + if(!out || !iterations || !tolerance || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterations),hm_value_stable(tolerance),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(20,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_aberth_ehrlich(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out) { + if(!out || !iterations || !tolerance || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(iterations),hm_value_stable(tolerance),hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(21,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_companion_matrix(hmath_context *context, const hmath_value *polynomial, hmath_value **out) { + if(!out || !polynomial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(polynomial)}; + return hm_value_finish(result,hm_polynomial_apply(22,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_lagrange_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out) { + if(!out || !prototype || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(points)}; + return hm_value_finish(result,hm_polynomial_apply(23,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_newton_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out) { + if(!out || !prototype || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(points)}; + return hm_value_finish(result,hm_polynomial_apply(24,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_chebyshev_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out) { + if(!out || !prototype || !degree) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree)}; + return hm_value_finish(result,hm_polynomial_apply(25,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_legendre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out) { + if(!out || !prototype || !degree) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree)}; + return hm_value_finish(result,hm_polynomial_apply(26,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_hermite_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out) { + if(!out || !prototype || !degree) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree)}; + return hm_value_finish(result,hm_polynomial_apply(27,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_laguerre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out) { + if(!out || !prototype || !degree) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree)}; + return hm_value_finish(result,hm_polynomial_apply(28,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_bernstein_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *index, hmath_value **out) { + if(!out || !prototype || !degree || !index) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree),hm_value_stable(index)}; + return hm_value_finish(result,hm_polynomial_apply(29,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_polynomial_regression(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *points, hmath_value **out) { + if(!out || !prototype || !degree || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(degree),hm_value_stable(points)}; + return hm_value_finish(result,hm_polynomial_apply(30,args,3,&result->stable),out); +} +hmath_status hmath_polynomial_power_series(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out) { + if(!out || !prototype || !coefficients) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(prototype),hm_value_stable(coefficients)}; + return hm_value_finish(result,hm_polynomial_apply(31,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_series_coefficients(hmath_context *context, const hmath_value *series, hmath_value **out) { + if(!out || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(32,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_add_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(33,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_multiply_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(34,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_reciprocal_series(hmath_context *context, const hmath_value *series, hmath_value **out) { + if(!out || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(35,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_divide_series(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if(!out || !numerator || !denominator) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(numerator),hm_value_stable(denominator)}; + return hm_value_finish(result,hm_polynomial_apply(36,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_compose_series(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out) { + if(!out || !outer || !inner) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(outer),hm_value_stable(inner)}; + return hm_value_finish(result,hm_polynomial_apply(37,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_differentiate_series(hmath_context *context, const hmath_value *series, hmath_value **out) { + if(!out || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(38,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_integrate_series(hmath_context *context, const hmath_value *constant, const hmath_value *series, hmath_value **out) { + if(!out || !constant || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(constant),hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(39,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_exp_series(hmath_context *context, const hmath_value *series, hmath_value **out) { + if(!out || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(40,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_log_series(hmath_context *context, const hmath_value *series, hmath_value **out) { + if(!out || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(series)}; + return hm_value_finish(result,hm_polynomial_apply(41,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_rational_function(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if(!out || !numerator || !denominator) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(numerator),hm_value_stable(denominator)}; + return hm_value_finish(result,hm_polynomial_apply(42,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_rational_numerator(hmath_context *context, const hmath_value *function, hmath_value **out) { + if(!out || !function) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(function)}; + return hm_value_finish(result,hm_polynomial_apply(43,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_rational_denominator(hmath_context *context, const hmath_value *function, hmath_value **out) { + if(!out || !function) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(function)}; + return hm_value_finish(result,hm_polynomial_apply(44,args,1,&result->stable),out); +} +hmath_status hmath_polynomial_evaluate_rational_function(hmath_context *context, const hmath_value *function, const hmath_value *x, hmath_value **out) { + if(!out || !function || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(function),hm_value_stable(x)}; + return hm_value_finish(result,hm_polynomial_apply(45,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_add_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(46,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_multiply_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(47,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_partial_fractions(hmath_context *context, const hmath_value *budget, const hmath_value *function, hmath_value **out) { + if(!out || !budget || !function) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(budget),hm_value_stable(function)}; + return hm_value_finish(result,hm_polynomial_apply(48,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_polynomial_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(49,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_series_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(50,args,2,&result->stable),out); +} +hmath_status hmath_polynomial_rational_function_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right) return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_polynomial_apply(51,args,2,&result->stable),out); +} +extern int hm_polynomial_chebyshev_approximation(ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,void **out); +hmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context,ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,hmath_value **out) { + if(!callback || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL approximation callback/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_polynomial_chebyshev_approximation(degree,callback,userdata,&result->stable),out); +} diff --git a/cbits/rotations.c b/cbits/rotations.c new file mode 100644 index 0000000..73c6f7c --- /dev/null +++ b/cbits/rotations.c @@ -0,0 +1,396 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_rotation_bindings.py. */ +#include "hmath_rotations.h" +#include "value_internal.h" +extern int hm_quaternion_quaternion(void *w, void *x, void *y, void *z, void **out); +hmath_status hmath_quaternion_quaternion(hmath_context *context, const hmath_value *w, const hmath_value *x, const hmath_value *y, const hmath_value *z, hmath_value **out) { + if(!w || !x || !y || !z || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_quaternion(w->stable, x->stable, y->stable, z->stable, &result->stable),out); +} +extern int hm_quaternion_components(void *value, void **out); +hmath_status hmath_quaternion_components(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_components(value->stable, &result->stable),out); +} +extern int hm_quaternion_norm(void *value, void **out); +hmath_status hmath_quaternion_norm(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_norm(value->stable, &result->stable),out); +} +extern int hm_quaternion_normalize(void *value, void **out); +hmath_status hmath_quaternion_normalize(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_normalize(value->stable, &result->stable),out); +} +extern int hm_quaternion_inverse(void *value, void **out); +hmath_status hmath_quaternion_inverse(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_inverse(value->stable, &result->stable),out); +} +extern int hm_quaternion_conjugate(void *value, void **out); +hmath_status hmath_quaternion_conjugate(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_conjugate(value->stable, &result->stable),out); +} +extern int hm_quaternion_multiply(void *a, void *b, void **out); +hmath_status hmath_quaternion_multiply(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_multiply(a->stable, b->stable, &result->stable),out); +} +extern int hm_quaternion_add(void *a, void *b, void **out); +hmath_status hmath_quaternion_add(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_add(a->stable, b->stable, &result->stable),out); +} +extern int hm_quaternion_scale(void *factor, void *value, void **out); +hmath_status hmath_quaternion_scale(hmath_context *context, const hmath_value *factor, const hmath_value *value, hmath_value **out) { + if(!factor || !value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_scale(factor->stable, value->stable, &result->stable),out); +} +extern int hm_quaternion_rotate_vector(void *value, void *vector, void **out); +hmath_status hmath_quaternion_rotate_vector(hmath_context *context, const hmath_value *value, const hmath_value *vector, hmath_value **out) { + if(!value || !vector || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_rotate_vector(value->stable, vector->stable, &result->stable),out); +} +extern int hm_quaternion_axis_angle(void *axis, void *angle, void **out); +hmath_status hmath_quaternion_axis_angle(hmath_context *context, const hmath_value *axis, const hmath_value *angle, hmath_value **out) { + if(!axis || !angle || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_axis_angle(axis->stable, angle->stable, &result->stable),out); +} +extern int hm_quaternion_to_axis_angle(void *value, void **out); +hmath_status hmath_quaternion_to_axis_angle(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_to_axis_angle(value->stable, &result->stable),out); +} +extern int hm_quaternion_from_euler(void *roll, void *pitch, void *yaw, void **out); +hmath_status hmath_quaternion_from_euler(hmath_context *context, const hmath_value *roll, const hmath_value *pitch, const hmath_value *yaw, hmath_value **out) { + if(!roll || !pitch || !yaw || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_from_euler(roll->stable, pitch->stable, yaw->stable, &result->stable),out); +} +extern int hm_quaternion_to_euler(void *value, void **out); +hmath_status hmath_quaternion_to_euler(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_to_euler(value->stable, &result->stable),out); +} +extern int hm_quaternion_to_matrix(void *value, void **out); +hmath_status hmath_quaternion_to_matrix(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_to_matrix(value->stable, &result->stable),out); +} +extern int hm_quaternion_from_matrix(void *matrix, void **out); +hmath_status hmath_quaternion_from_matrix(hmath_context *context, const hmath_value *matrix, hmath_value **out) { + if(!matrix || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_from_matrix(matrix->stable, &result->stable),out); +} +extern int hm_quaternion_nlerp(void *fraction, void *a, void *b, void **out); +hmath_status hmath_quaternion_nlerp(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!fraction || !a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_nlerp(fraction->stable, a->stable, b->stable, &result->stable),out); +} +extern int hm_quaternion_slerp(void *fraction, void *a, void *b, void **out); +hmath_status hmath_quaternion_slerp(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!fraction || !a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_slerp(fraction->stable, a->stable, b->stable, &result->stable),out); +} +extern int hm_quaternion_squad(void *fraction, void *q0, void *q1, void *q2, void *q3, void **out); +hmath_status hmath_quaternion_squad(hmath_context *context, const hmath_value *fraction, const hmath_value *q0, const hmath_value *q1, const hmath_value *q2, const hmath_value *q3, hmath_value **out) { + if(!fraction || !q0 || !q1 || !q2 || !q3 || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_squad(fraction->stable, q0->stable, q1->stable, q2->stable, q3->stable, &result->stable),out); +} +extern int hm_quaternion_exponential(void *value, void **out); +hmath_status hmath_quaternion_exponential(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_exponential(value->stable, &result->stable),out); +} +extern int hm_quaternion_logarithm(void *value, void **out); +hmath_status hmath_quaternion_logarithm(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_logarithm(value->stable, &result->stable),out); +} +extern int hm_quaternion_swing_twist(void *axis, void *value, void **out); +hmath_status hmath_quaternion_swing_twist(hmath_context *context, const hmath_value *axis, const hmath_value *value, hmath_value **out) { + if(!axis || !value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_quaternion_swing_twist(axis->stable, value->stable, &result->stable),out); +} +extern int hm_rotation_so3(void *value, void **out); +hmath_status hmath_rotation_so3(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_so3(value->stable, &result->stable),out); +} +extern int hm_rotation_rotation_quaternion(void *value, void **out); +hmath_status hmath_rotation_rotation_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_rotation_quaternion(value->stable, &result->stable),out); +} +extern int hm_rotation_identity_rotation(void **out); +hmath_status hmath_rotation_identity_rotation(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_identity_rotation(&result->stable),out); +} +extern int hm_rotation_compose_rotation(void *a, void *b, void **out); +hmath_status hmath_rotation_compose_rotation(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_compose_rotation(a->stable, b->stable, &result->stable),out); +} +extern int hm_rotation_inverse_rotation(void *value, void **out); +hmath_status hmath_rotation_inverse_rotation(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_inverse_rotation(value->stable, &result->stable),out); +} +extern int hm_rotation_rotate(void *value, void *vector, void **out); +hmath_status hmath_rotation_rotate(hmath_context *context, const hmath_value *value, const hmath_value *vector, hmath_value **out) { + if(!value || !vector || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_rotate(value->stable, vector->stable, &result->stable),out); +} +extern int hm_rotation_exp_so3(void *omega, void **out); +hmath_status hmath_rotation_exp_so3(hmath_context *context, const hmath_value *omega, hmath_value **out) { + if(!omega || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_exp_so3(omega->stable, &result->stable),out); +} +extern int hm_rotation_log_so3(void *value, void **out); +hmath_status hmath_rotation_log_so3(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_log_so3(value->stable, &result->stable),out); +} +extern int hm_rotation_se3(void *rotation, void *translation, void **out); +hmath_status hmath_rotation_se3(hmath_context *context, const hmath_value *rotation, const hmath_value *translation, hmath_value **out) { + if(!rotation || !translation || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_se3(rotation->stable, translation->stable, &result->stable),out); +} +extern int hm_rotation_rotation_part(void *value, void **out); +hmath_status hmath_rotation_rotation_part(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_rotation_part(value->stable, &result->stable),out); +} +extern int hm_rotation_translation_part(void *value, void **out); +hmath_status hmath_rotation_translation_part(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_translation_part(value->stable, &result->stable),out); +} +extern int hm_rotation_identity_transform(void **out); +hmath_status hmath_rotation_identity_transform(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_identity_transform(&result->stable),out); +} +extern int hm_rotation_compose(void *a, void *b, void **out); +hmath_status hmath_rotation_compose(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_compose(a->stable, b->stable, &result->stable),out); +} +extern int hm_rotation_inverse(void *value, void **out); +hmath_status hmath_rotation_inverse(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_inverse(value->stable, &result->stable),out); +} +extern int hm_rotation_transform_point(void *value, void *point, void **out); +hmath_status hmath_rotation_transform_point(hmath_context *context, const hmath_value *value, const hmath_value *point, hmath_value **out) { + if(!value || !point || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_transform_point(value->stable, point->stable, &result->stable),out); +} +extern int hm_rotation_exp_se3(void *twist, void **out); +hmath_status hmath_rotation_exp_se3(hmath_context *context, const hmath_value *twist, hmath_value **out) { + if(!twist || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_exp_se3(twist->stable, &result->stable),out); +} +extern int hm_rotation_log_se3(void *value, void **out); +hmath_status hmath_rotation_log_se3(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_log_se3(value->stable, &result->stable),out); +} +extern int hm_rotation_to_homogeneous(void *value, void **out); +hmath_status hmath_rotation_to_homogeneous(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_to_homogeneous(value->stable, &result->stable),out); +} +extern int hm_rotation_from_homogeneous(void *matrix, void **out); +hmath_status hmath_rotation_from_homogeneous(hmath_context *context, const hmath_value *matrix, hmath_value **out) { + if(!matrix || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_from_homogeneous(matrix->stable, &result->stable),out); +} +extern int hm_rotation_dual_quaternion(void *real, void *dual, void **out); +hmath_status hmath_rotation_dual_quaternion(hmath_context *context, const hmath_value *real, const hmath_value *dual, hmath_value **out) { + if(!real || !dual || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_dual_quaternion(real->stable, dual->stable, &result->stable),out); +} +extern int hm_rotation_dual_parts(void *value, void **out); +hmath_status hmath_rotation_dual_parts(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_dual_parts(value->stable, &result->stable),out); +} +extern int hm_rotation_to_dual_quaternion(void *value, void **out); +hmath_status hmath_rotation_to_dual_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_to_dual_quaternion(value->stable, &result->stable),out); +} +extern int hm_rotation_from_dual_quaternion(void *value, void **out); +hmath_status hmath_rotation_from_dual_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_from_dual_quaternion(value->stable, &result->stable),out); +} +extern int hm_rotation_multiply_dual(void *a, void *b, void **out); +hmath_status hmath_rotation_multiply_dual(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_multiply_dual(a->stable, b->stable, &result->stable),out); +} +extern int hm_rotation_inverse_dual(void *value, void **out); +hmath_status hmath_rotation_inverse_dual(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_inverse_dual(value->stable, &result->stable),out); +} +extern int hm_rotation_interpolate_dual(void *fraction, void *a, void *b, void **out); +hmath_status hmath_rotation_interpolate_dual(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!fraction || !a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotation_interpolate_dual(fraction->stable, a->stable, b->stable, &result->stable),out); +} +extern int hm_rotations_equal(void *a, void *b, void **out); +hmath_status hmath_rotations_equal(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!a || !b || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_rotations_equal(a->stable, b->stable, &result->stable),out); +} diff --git a/cbits/runtime.c b/cbits/runtime.c index b240b87..9899d5d 100644 --- a/cbits/runtime.c +++ b/cbits/runtime.c @@ -54,7 +54,7 @@ hmath_status hmath_runtime_shutdown(void) { lock(); if (active_calls) { unlock(); - return hm_error(HMATH_BUSY, "numerical calls are active; join workers before shutdown"); + return hm_error(HMATH_BUSY, "calls or Haskell-backed states remain; join workers and release states"); } if (runtime_state == RUNNING) { hs_exit(); diff --git a/cbits/scalar_extras.c b/cbits/scalar_extras.c new file mode 100644 index 0000000..16fa551 --- /dev/null +++ b/cbits/scalar_extras.c @@ -0,0 +1,405 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_scalar_extras.py. */ +#include "hmath_scalar_extras.h" +#include "value_internal.h" +extern int hm_scalar_extras_apply(int,void *const *,size_t,void **); +hmath_status hmath_complex_exp(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(0,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_log(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(1,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_sqrt(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(2,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_sin(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(3,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_cos(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(4,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_tan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(5,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_sinh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(6,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_cosh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(7,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_tanh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(8,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_asin(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(9,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_acos(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(10,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_atan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(11,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_asinh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(12,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_acosh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(13,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_atanh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(14,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_sin(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(15,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_cos(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(16,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_tan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(17,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_asin(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(18,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_acos(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(19,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_atan(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(20,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_sinh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(21,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_cosh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(22,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_tanh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(23,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_asinh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(24,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_acosh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(25,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_atanh(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(26,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_sec(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(27,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_csc(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(28,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_cot(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(29,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_sech(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(30,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_csch(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(31,arguments,0,&result->stable),out); +} +hmath_status hmath_trigonometry_c_coth(hmath_context *context, hmath_value **out) { + if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={NULL}; + return hm_value_finish(result,hm_scalar_extras_apply(32,arguments,0,&result->stable),out); +} +hmath_status hmath_complex_elementary(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out) { + if(!out || !operation || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(operation),hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(33,arguments,2,&result->stable),out); +} +hmath_status hmath_complex_complex_matrix(hmath_context *context, const hmath_value *rows, const hmath_value *columns, const hmath_value *values, hmath_value **out) { + if(!out || !rows || !columns || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(rows),hm_value_stable(columns),hm_value_stable(values)}; + return hm_value_finish(result,hm_scalar_extras_apply(34,arguments,3,&result->stable),out); +} +hmath_status hmath_complex_multiply_matrices(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if(!out || !a || !b)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b)}; + return hm_value_finish(result,hm_scalar_extras_apply(35,arguments,2,&result->stable),out); +} +hmath_status hmath_complex_conjugate_transpose(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(36,arguments,1,&result->stable),out); +} +hmath_status hmath_complex_complex_fft(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_scalar_extras_apply(37,arguments,1,&result->stable),out); +} +hmath_status hmath_complex_complex_ifft(hmath_context *context, const hmath_value *values, hmath_value **out) { + if(!out || !values)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(values)}; + return hm_value_finish(result,hm_scalar_extras_apply(38,arguments,1,&result->stable),out); +} +hmath_status hmath_trigonometry_complex_function(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out) { + if(!out || !operation || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(operation),hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(39,arguments,2,&result->stable),out); +} +hmath_status hmath_numbertheory_chinese_remainder(hmath_context *context, const hmath_value *congruences, hmath_value **out) { + if(!out || !congruences)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(congruences)}; + return hm_value_finish(result,hm_scalar_extras_apply(40,arguments,1,&result->stable),out); +} +hmath_status hmath_numbertheory_linear_diophantine(hmath_context *context, const hmath_value *a, const hmath_value *b, const hmath_value *c, hmath_value **out) { + if(!out || !a || !b || !c)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(a),hm_value_stable(b),hm_value_stable(c)}; + return hm_value_finish(result,hm_scalar_extras_apply(41,arguments,3,&result->stable),out); +} +hmath_status hmath_numbertheory_perfect_power(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(42,arguments,1,&result->stable),out); +} +hmath_status hmath_numbertheory_prime_factorization(hmath_context *context, const hmath_value *budget, const hmath_value *value, hmath_value **out) { + if(!out || !budget || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(budget),hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(43,arguments,2,&result->stable),out); +} +hmath_status hmath_numbertheory_partitions(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(44,arguments,1,&result->stable),out); +} +hmath_status hmath_special_sf_result(hmath_context *context, const hmath_value *value, const hmath_value *error, hmath_value **out) { + if(!out || !value || !error)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value),hm_value_stable(error)}; + return hm_value_finish(result,hm_scalar_extras_apply(45,arguments,2,&result->stable),out); +} +hmath_status hmath_special_sf_value(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(46,arguments,1,&result->stable),out); +} +hmath_status hmath_special_sf_error(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + void *arguments[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_scalar_extras_apply(47,arguments,1,&result->stable),out); +} +extern int hm_scalar_selector_name(void *,void **); +hmath_status hmath_scalar_selector_name(hmath_context *context,const hmath_value *value0,hmath_value **out) { + if(!out || !value0)return hm_error(HMATH_INVALID_ARGUMENT,"NULL selector argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_scalar_selector_name(hm_value_stable(value0),&result->stable),out); +} +extern int hm_scalar_selector_equal(void *,void *,void **); +hmath_status hmath_scalar_selector_equal(hmath_context *context,const hmath_value *value0,const hmath_value *value1,hmath_value **out) { + if(!out || !value0 || !value1)return hm_error(HMATH_INVALID_ARGUMENT,"NULL selector argument"); + hmath_value *result=NULL; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_scalar_selector_equal(hm_value_stable(value0),hm_value_stable(value1),&result->stable),out); +} diff --git a/cbits/shape.c b/cbits/shape.c new file mode 100644 index 0000000..51cc443 --- /dev/null +++ b/cbits/shape.c @@ -0,0 +1,182 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_shape.h" +#include "value_internal.h" +extern int hm_shape_apply(int, void *const *, size_t, void **); +hmath_status hmath_shape_shape_dimensions(hmath_context *context, const hmath_value *shape, + hmath_value **out) { + if (!out || !shape) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(shape)}; + return hm_value_finish(result, hm_shape_apply(0, args, 1, &result->stable), out); +} +hmath_status hmath_shape_shape_elements(hmath_context *context, const hmath_value *shape, + hmath_value **out) { + if (!out || !shape) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(shape)}; + return hm_value_finish(result, hm_shape_apply(1, args, 1, &result->stable), out); +} +hmath_status hmath_shape_make_shape(hmath_context *context, const hmath_value *dimensions, + hmath_value **out) { + if (!out || !dimensions) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(dimensions)}; + return hm_value_finish(result, hm_shape_apply(2, args, 1, &result->stable), out); +} +hmath_status hmath_shape_scalar_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out) { + if (!out || !shape) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(shape)}; + return hm_value_finish(result, hm_shape_apply(3, args, 1, &result->stable), out); +} +hmath_status hmath_shape_vector_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out) { + if (!out || !shape) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(shape)}; + return hm_value_finish(result, hm_shape_apply(4, args, 1, &result->stable), out); +} +hmath_status hmath_shape_matrix_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out) { + if (!out || !shape) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(shape)}; + return hm_value_finish(result, hm_shape_apply(5, args, 1, &result->stable), out); +} +hmath_status hmath_shape_static_matrix(hmath_context *context, const hmath_value *rows, + const hmath_value *columns, const hmath_value *matrix, + hmath_value **out) { + if (!out || !rows || !columns || !matrix) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(rows), hm_value_stable(columns), hm_value_stable(matrix)}; + return hm_value_finish(result, hm_shape_apply(6, args, 3, &result->stable), out); +} +hmath_status hmath_shape_dynamic_matrix(hmath_context *context, const hmath_value *matrix, + hmath_value **out) { + if (!out || !matrix) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(matrix)}; + return hm_value_finish(result, hm_shape_apply(7, args, 1, &result->stable), out); +} +hmath_status hmath_shape_static_multiply(hmath_context *context, const hmath_value *left, + const hmath_value *right, hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(left), hm_value_stable(right)}; + return hm_value_finish(result, hm_shape_apply(8, args, 2, &result->stable), out); +} +hmath_status hmath_shape_static_transpose(hmath_context *context, const hmath_value *matrix, + hmath_value **out) { + if (!out || !matrix) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(matrix)}; + return hm_value_finish(result, hm_shape_apply(9, args, 1, &result->stable), out); +} +hmath_status hmath_shape_reflected_shape(hmath_context *context, const hmath_value *dimensions, + hmath_value **out) { + if (!out || !dimensions) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(dimensions)}; + return hm_value_finish(result, hm_shape_apply(10, args, 1, &result->stable), out); +} +hmath_status hmath_shape_static_tensor(hmath_context *context, const hmath_value *dimensions, + const hmath_value *tensor, hmath_value **out) { + if (!out || !dimensions || !tensor) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(dimensions), hm_value_stable(tensor)}; + return hm_value_finish(result, hm_shape_apply(11, args, 2, &result->stable), out); +} +hmath_status hmath_shape_dynamic_tensor(hmath_context *context, const hmath_value *tensor, + hmath_value **out) { + if (!out || !tensor) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(tensor)}; + return hm_value_finish(result, hm_shape_apply(12, args, 1, &result->stable), out); +} +hmath_status hmath_shape_coordinates(hmath_context *context, const hmath_value *prototype, + const hmath_value *count, const hmath_value *values, + hmath_value **out) { + if (!out || !prototype || !count || !values) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(prototype), hm_value_stable(count), hm_value_stable(values)}; + return hm_value_finish(result, hm_shape_apply(13, args, 3, &result->stable), out); +} +hmath_status hmath_shape_coordinate_values(hmath_context *context, const hmath_value *coordinates, + hmath_value **out) { + if (!out || !coordinates) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(coordinates)}; + return hm_value_finish(result, hm_shape_apply(14, args, 1, &result->stable), out); +} +hmath_status hmath_shape_coordinates_to_vector(hmath_context *context, + const hmath_value *coordinates, hmath_value **out) { + if (!out || !coordinates) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL shape argument"); + hmath_value *result; + hmath_status status = hm_value_begin(context, &result); + if (status) + return status; + void *args[] = {hm_value_stable(coordinates)}; + return hm_value_finish(result, hm_shape_apply(15, args, 1, &result->stable), out); +} diff --git a/cbits/spectral.c b/cbits/spectral.c new file mode 100644 index 0000000..58248bd --- /dev/null +++ b/cbits/spectral.c @@ -0,0 +1,1410 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_spectral.h" +#include "value_internal.h" +extern int hm_spectral_apply(int,void *const *,size_t,void **); +hmath_status hmath_signal_value_iir(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if (!out || !numerator || !denominator) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(numerator), hm_value_stable(denominator)}; + int code=hm_spectral_apply(0,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_fir(hmath_context *context, const hmath_value *b, hmath_value **out) { + if (!out || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(b)}; + int code=hm_spectral_apply(1,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_filter_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(2,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_filter_state(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(3,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_reset_filter(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(4,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_filter_signal(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(5,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_frequency_response(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(6,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_butterworth(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(7,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_chebyshev_i(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(8,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_chebyshev_ii(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(9,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(10,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_bessel(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(11,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_lowpass(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(12,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_highpass(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(13,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_bandpass(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(14,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_bandstop(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(15,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_design_iir(hmath_context *context, const hmath_value *family, const hmath_value *band, const hmath_value *order, const hmath_value *rate, hmath_value **out) { + if (!out || !family || !band || !order || !rate) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(family), hm_value_stable(band), hm_value_stable(order), hm_value_stable(rate)}; + int code=hm_spectral_apply(16,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_notch(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out) { + if (!out || !omega || !quality) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(omega), hm_value_stable(quality)}; + int code=hm_spectral_apply(17,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_all_pass(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out) { + if (!out || !omega || !quality) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(omega), hm_value_stable(quality)}; + int code=hm_spectral_apply(18,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_wiener(hmath_context *context, const hmath_value *width, const hmath_value *noise, const hmath_value *xs, hmath_value **out) { + if (!out || !width || !noise || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(width), hm_value_stable(noise), hm_value_stable(xs)}; + int code=hm_spectral_apply(19,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_hann(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(20,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_hamming(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(21,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_blackman(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(22,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_bartlett(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(23,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_kaiser(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(24,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(25,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_tukey(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(26,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_flat_top(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(27,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_dolph_chebyshev(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(28,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_window(hmath_context *context, const hmath_value *kind, const hmath_value *n, hmath_value **out) { + if (!out || !kind || !n) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(kind), hm_value_stable(n)}; + int code=hm_spectral_apply(29,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_windowed_sinc(hmath_context *context, const hmath_value *kind, const hmath_value *taps, const hmath_value *cutoff, const hmath_value *rate, hmath_value **out) { + if (!out || !kind || !taps || !cutoff || !rate) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(kind), hm_value_stable(taps), hm_value_stable(cutoff), hm_value_stable(rate)}; + int code=hm_spectral_apply(30,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peak(hmath_context *context, const hmath_value *peak_index, const hmath_value *peak_height, const hmath_value *peak_prominence, const hmath_value *peak_width, hmath_value **out) { + if (!out || !peak_index || !peak_height || !peak_prominence || !peak_width) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(peak_index), hm_value_stable(peak_height), hm_value_stable(peak_prominence), hm_value_stable(peak_width)}; + int code=hm_spectral_apply(31,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peak_index(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(32,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peak_height(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(33,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peak_prominence(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(34,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peak_width(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(35,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_peaks(hmath_context *context, const hmath_value *minimum_prominence, const hmath_value *minimum_distance, const hmath_value *xs, hmath_value **out) { + if (!out || !minimum_prominence || !minimum_distance || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(minimum_prominence), hm_value_stable(minimum_distance), hm_value_stable(xs)}; + int code=hm_spectral_apply(36,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5 || !value6) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5), hm_value_stable(value6)}; + int code=hm_spectral_apply(37,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_extended_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5 || !value6) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5), hm_value_stable(value6)}; + int code=hm_spectral_apply(38,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_unscented_kalman(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, const hmath_value *kappa, const hmath_value *transition, const hmath_value *measurement, const hmath_value *q, const hmath_value *r, const hmath_value *measured, const hmath_value *state, hmath_value **out) { + if (!out || !alpha || !beta || !kappa || !transition || !measurement || !q || !r || !measured || !state) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(alpha), hm_value_stable(beta), hm_value_stable(kappa), hm_value_stable(transition), hm_value_stable(measurement), hm_value_stable(q), hm_value_stable(r), hm_value_stable(measured), hm_value_stable(state)}; + int code=hm_spectral_apply(39,arguments,9,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_haar(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(40,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_daubechies2(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(41,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_daubechies4(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(42,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_biorthogonal53(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(43,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_wavelet_approximation(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(44,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_wavelet_details(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(45,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_dwt(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out) { + if (!out || !family || !levels || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(family), hm_value_stable(levels), hm_value_stable(xs)}; + int code=hm_spectral_apply(46,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_idwt(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(47,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_morlet(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(48,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_mexican_hat(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(49,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_gaussian_derivative(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(50,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_cwt(hmath_context *context, const hmath_value *mother, const hmath_value *spacing, const hmath_value *scales, const hmath_value *xs, hmath_value **out) { + if (!out || !mother || !spacing || !scales || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(mother), hm_value_stable(spacing), hm_value_stable(scales), hm_value_stable(xs)}; + int code=hm_spectral_apply(51,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_wavelet_packets(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out) { + if (!out || !family || !levels || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(family), hm_value_stable(levels), hm_value_stable(xs)}; + int code=hm_spectral_apply(52,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_inverse_wavelet_packets(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(53,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_packet_bands(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(54,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_signal_value_wavelet_denoise(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *threshold, const hmath_value *xs, hmath_value **out) { + if (!out || !family || !levels || !threshold || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(family), hm_value_stable(levels), hm_value_stable(threshold), hm_value_stable(xs)}; + int code=hm_spectral_apply(55,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_reject(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(56,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_clamp(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(57,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_extrapolate(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(58,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_nearest(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(59,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_linear(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(60,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_lagrange(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(61,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_newton(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(62,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_barycentric(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(63,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_natural(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(64,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_clamped(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(65,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_periodic(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(66,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(67,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(68,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_inverse_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(69,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_thin_plate(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(70,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_cubic(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(71,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_approximation(hmath_context *context, const hmath_value *approximation_coefficients, const hmath_value *approximation_error, const hmath_value *approximation_iterations, hmath_value **out) { + if (!out || !approximation_coefficients || !approximation_error || !approximation_iterations) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(approximation_coefficients), hm_value_stable(approximation_error), hm_value_stable(approximation_iterations)}; + int code=hm_spectral_apply(72,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_approximation_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(73,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_approximation_error(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(74,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_approximation_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(75,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *points, const hmath_value *x0, hmath_value **out) { + if (!out || !method || !policy || !points || !x0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(policy), hm_value_stable(points), hm_value_stable(x0)}; + int code=hm_spectral_apply(76,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_hermite(hmath_context *context, const hmath_value *triples, const hmath_value *x, hmath_value **out) { + if (!out || !triples || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(triples), hm_value_stable(x)}; + int code=hm_spectral_apply(77,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_piecewise_polynomial(hmath_context *context, const hmath_value *knots, const hmath_value *coefficients, hmath_value **out) { + if (!out || !knots || !coefficients) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(knots), hm_value_stable(coefficients)}; + int code=hm_spectral_apply(78,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_piecewise_knots(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(79,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_evaluate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code=hm_spectral_apply(80,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_differentiate_piecewise(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(81,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_integrate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code=hm_spectral_apply(82,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_cubic_hermite(hmath_context *context, const hmath_value *triples, hmath_value **out) { + if (!out || !triples) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(triples)}; + int code=hm_spectral_apply(83,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_cubic_spline(hmath_context *context, const hmath_value *boundary, const hmath_value *points, hmath_value **out) { + if (!out || !boundary || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(boundary), hm_value_stable(points)}; + int code=hm_spectral_apply(84,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_pchip(hmath_context *context, const hmath_value *points, hmath_value **out) { + if (!out || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(points)}; + int code=hm_spectral_apply(85,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_akima(hmath_context *context, const hmath_value *points, hmath_value **out) { + if (!out || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(points)}; + int code=hm_spectral_apply(86,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_smoothing_spline(hmath_context *context, const hmath_value *lambda_, const hmath_value *points, hmath_value **out) { + if (!out || !lambda_ || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(lambda_), hm_value_stable(points)}; + int code=hm_spectral_apply(87,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_b_spline(hmath_context *context, const hmath_value *degree, const hmath_value *knots, const hmath_value *controls, const hmath_value *weights, hmath_value **out) { + if (!out || !degree || !knots || !controls || !weights) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(degree), hm_value_stable(knots), hm_value_stable(controls), hm_value_stable(weights)}; + int code=hm_spectral_apply(88,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_evaluate_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out) { + if (!out || !s || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(s), hm_value_stable(x)}; + int code=hm_spectral_apply(89,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_derivative_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out) { + if (!out || !s || !x) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(s), hm_value_stable(x)}; + int code=hm_spectral_apply(90,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_insert_knot(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(91,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_rational_bezier(hmath_context *context, const hmath_value *controls, const hmath_value *ws, const hmath_value *t, hmath_value **out) { + if (!out || !controls || !ws || !t) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(controls), hm_value_stable(ws), hm_value_stable(t)}; + int code=hm_spectral_apply(92,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_bezier(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(93,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_kochanek_bartels(hmath_context *context, const hmath_value *tension, const hmath_value *continuity, const hmath_value *bias, const hmath_value *points, hmath_value **out) { + if (!out || !tension || !continuity || !bias || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tension), hm_value_stable(continuity), hm_value_stable(bias), hm_value_stable(points)}; + int code=hm_spectral_apply(94,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_cardinal_spline(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(95,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_catmull_rom(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(96,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_curve_integral(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4)}; + int code=hm_spectral_apply(97,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_arc_length(hmath_context *context, const hmath_value *tolerance, const hmath_value *spline, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !tolerance || !spline || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tolerance), hm_value_stable(spline), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_spectral_apply(98,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_grid_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *axes, const hmath_value *values, const hmath_value *point, hmath_value **out) { + if (!out || !method || !policy || !axes || !values || !point) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(policy), hm_value_stable(axes), hm_value_stable(values), hm_value_stable(point)}; + int code=hm_spectral_apply(99,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_fit_rbf(hmath_context *context, const hmath_value *method, const hmath_value *smoothing, const hmath_value *nodes, const hmath_value *ys, hmath_value **out) { + if (!out || !method || !smoothing || !nodes || !ys) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(method), hm_value_stable(smoothing), hm_value_stable(nodes), hm_value_stable(ys)}; + int code=hm_spectral_apply(100,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_evaluate_rbf(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(101,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_inverse_distance(hmath_context *context, const hmath_value *power, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out) { + if (!out || !power || !nodes || !ys || !point) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(power), hm_value_stable(nodes), hm_value_stable(ys), hm_value_stable(point)}; + int code=hm_spectral_apply(102,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_shepard(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code=hm_spectral_apply(103,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_kriging(hmath_context *context, const hmath_value *range, const hmath_value *nugget, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out) { + if (!out || !range || !nugget || !nodes || !ys || !point) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(range), hm_value_stable(nugget), hm_value_stable(nodes), hm_value_stable(ys), hm_value_stable(point)}; + int code=hm_spectral_apply(104,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_polynomial_fit(hmath_context *context, const hmath_value *degree, const hmath_value *points, hmath_value **out) { + if (!out || !degree || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(degree), hm_value_stable(points)}; + int code=hm_spectral_apply(105,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_chebyshev_approximate(hmath_context *context, const hmath_value *degree, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !degree || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(degree), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_spectral_apply(106,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_pade(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *series, hmath_value **out) { + if (!out || !m || !n || !series) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(m), hm_value_stable(n), hm_value_stable(series)}; + int code=hm_spectral_apply(107,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_rational_fit(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *points, hmath_value **out) { + if (!out || !m || !n || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(m), hm_value_stable(n), hm_value_stable(points)}; + int code=hm_spectral_apply(108,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_remez(hmath_context *context, const hmath_value *degree, const hmath_value *grid_count, const hmath_value *tolerance, const hmath_value *budget, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !degree || !grid_count || !tolerance || !budget || !f || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(degree), hm_value_stable(grid_count), hm_value_stable(tolerance), hm_value_stable(budget), hm_value_stable(f), hm_value_stable(a), hm_value_stable(b)}; + int code=hm_spectral_apply(109,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_nonlinear_fit(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *model, const hmath_value *points, const hmath_value *initial, hmath_value **out) { + if (!out || !budget || !tolerance || !model || !points || !initial) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(budget), hm_value_stable(tolerance), hm_value_stable(model), hm_value_stable(points), hm_value_stable(initial)}; + int code=hm_spectral_apply(110,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_interpolation_value_interpolation_error(hmath_context *context, const hmath_value *f, const hmath_value *points, hmath_value **out) { + if (!out || !f || !points) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(f), hm_value_stable(points)}; + int code=hm_spectral_apply(111,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_forward(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(112,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_inverse(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(113,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_automatic(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(114,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_direct(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(115,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_radix2(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(116,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_radix4(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(117,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_mixed_radix(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(118,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_split_radix(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(119,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_bluestein(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(120,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_rader(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(121,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_type_i(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(122,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_type_ii(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(123,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_type_iii(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(124,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_type_iv(hmath_context *context, hmath_value **out) { + if (!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={NULL}; + int code=hm_spectral_apply(125,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_plan_fft(hmath_context *context, const hmath_value *direction, const hmath_value *method, const hmath_value *n, hmath_value **out) { + if (!out || !direction || !method || !n) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(direction), hm_value_stable(method), hm_value_stable(n)}; + int code=hm_spectral_apply(126,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_execute_fft(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(127,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(128,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_ifft(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(129,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_dft(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(130,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_real_fft(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(131,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_inverse_real_fft(hmath_context *context, const hmath_value *tolerance, const hmath_value *xs, hmath_value **out) { + if (!out || !tolerance || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(tolerance), hm_value_stable(xs)}; + int code=hm_spectral_apply(132,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft_batch(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(133,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft_nd(hmath_context *context, const hmath_value *direction, const hmath_value *dims, const hmath_value *xs, hmath_value **out) { + if (!out || !direction || !dims || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(direction), hm_value_stable(dims), hm_value_stable(xs)}; + int code=hm_spectral_apply(134,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_dct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(135,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_idct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(136,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_dst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(137,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_idst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value), hm_value_stable(value2)}; + int code=hm_spectral_apply(138,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_stft_frames(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(139,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_stft(hmath_context *context, const hmath_value *window, const hmath_value *hop, const hmath_value *xs, hmath_value **out) { + if (!out || !window || !hop || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(window), hm_value_stable(hop), hm_value_stable(xs)}; + int code=hm_spectral_apply(140,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_istft(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(141,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_magnitude_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(142,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_phase_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(143,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_power_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(value)}; + int code=hm_spectral_apply(144,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_cross_spectrum(hmath_context *context, const hmath_value *rate, const hmath_value *window, const hmath_value *x, const hmath_value *y, hmath_value **out) { + if (!out || !rate || !window || !x || !y) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(rate), hm_value_stable(window), hm_value_stable(x), hm_value_stable(y)}; + int code=hm_spectral_apply(145,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_spectrogram(hmath_context *context, const hmath_value *w, const hmath_value *h, const hmath_value *xs, hmath_value **out) { + if (!out || !w || !h || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(w), hm_value_stable(h), hm_value_stable(xs)}; + int code=hm_spectral_apply(146,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_analytic_signal(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(147,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_chirp_z(hmath_context *context, const hmath_value *count, const hmath_value *a, const hmath_value *w, const hmath_value *xs, hmath_value **out) { + if (!out || !count || !a || !w || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(count), hm_value_stable(a), hm_value_stable(w), hm_value_stable(xs)}; + int code=hm_spectral_apply(148,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_goertzel(hmath_context *context, const hmath_value *omega, const hmath_value *xs, hmath_value **out) { + if (!out || !omega || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(omega), hm_value_stable(xs)}; + int code=hm_spectral_apply(149,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft_convolve(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(a), hm_value_stable(b)}; + int code=hm_spectral_apply(150,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft_correlate(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out) { + if (!out || !a || !b) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(a), hm_value_stable(b)}; + int code=hm_spectral_apply(151,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_fft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(152,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_fourier_value_ifft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[]={hm_value_stable(xs)}; + int code=hm_spectral_apply(153,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} + +extern int hm_spectral_fft_in_place(void *,void *,ptrdiff_t); +hmath_status hmath_fourier_value_fft_in_place(hmath_context *context,const hmath_value *plan,double *interleaved,ptrdiff_t count) { + if (!plan) return hm_error(HMATH_INVALID_ARGUMENT,"NULL FFT plan"); + hmath_status status=hm_enter(context); + if(status)return status; + int code=hm_spectral_fft_in_place(hm_value_stable(plan),interleaved,count); + hm_leave(); + return (hmath_status)code; +} + +extern int hm_spectral_describe(void *,void **); +hmath_status hmath_spectral_describe(hmath_context *context,const hmath_value *value,hmath_value **out) { + if (!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL spectral description argument"); + hmath_value *temporary=NULL; + hmath_status status=hm_value_begin(context,&temporary); + if(status)return status; + return hm_value_finish(temporary,hm_spectral_describe(hm_value_stable(value),&temporary->stable),out); +} diff --git a/cbits/stochastic.c b/cbits/stochastic.c new file mode 100644 index 0000000..1dba61d --- /dev/null +++ b/cbits/stochastic.c @@ -0,0 +1,878 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_stochastic_bindings.py. */ +#include "hmath_stochastic.h" +#include "value_internal.h" +extern int hm_stochastic_apply(int opcode,void *const *args,size_t count,void **out); +hmath_status hmath_stochastic_random_clone_rng(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(0,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_seed_rng(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(1,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_next_word64(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(2,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_split_rng(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(3,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_serialize_rng(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(4,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_restore_rng(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(5,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_uniform(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(6,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_uniform_open(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(7,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_uniform_int(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(8,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_sample_n(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(9,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_box_muller(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(10,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_marsaglia_normal(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(11,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_ziggurat_normal(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(12,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(13,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_exponential(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(14,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_gamma(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(15,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_beta(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(16,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_poisson(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(17,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(18,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_weighted(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(19,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_alias_table(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(20,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_random_alias_sample(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(21,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_shuffle(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(22,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_with_replacement(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(23,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_without_replacement(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(24,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_reservoir(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(25,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_stratified(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(26,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_rejection(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(27,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_random_inverse_transform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(28,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_metropolis_hastings(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3 || !a4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3),hm_value_stable(a4)}; + return hm_value_finish(result,hm_stochastic_apply(29,args,5,&result->stable),out); +} +hmath_status hmath_stochastic_random_gibbs(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(30,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_random_hamiltonian_monte_carlo(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, const hmath_value *a6, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3 || !a4 || !a5 || !a6) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3),hm_value_stable(a4),hm_value_stable(a5),hm_value_stable(a6)}; + return hm_value_finish(result,hm_stochastic_apply(31,args,7,&result->stable),out); +} +hmath_status hmath_stochastic_random_monte_carlo(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(32,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_latin_hypercube(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(33,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_random_random_quality(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(34,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_random_entropy_seed(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(35,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_pcg32(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(36,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_xoshiro256_star_star(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(37,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_xoroshiro128_plus(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(38,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_mt19937(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(39,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_philox4x32(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(40,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_threefry2x64(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(41,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_random_new_cha_cha20(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(42,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_probability_validate_distribution(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(43,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(44,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(45,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_cdf(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(46,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_survival(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(47,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_quantile(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(48,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_hazard(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(49,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_log_likelihood(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(50,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_moments(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(51,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_entropy(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(52,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_expectation(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(53,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_sample(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(54,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_fit_normal(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(55,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_fit_exponential(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(56,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_fit_bernoulli(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(57,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_fit_mle_grid(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(58,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_fit_map_grid(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(59,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_beta_bernoulli_update(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(60,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_goodness_of_fit(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(61,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_gaussian_kde(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(62,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_multivariate_normal_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(63,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_sample_multivariate_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(64,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_wishart_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(65,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_sample_wishart(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(66,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_markov(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(67,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_transition(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(68,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_stationary(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(69,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_hmm(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(70,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_forward(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(71,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_backward(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(72,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_posterior_states(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(73,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_viterbi(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(74,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_baum_welch(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(75,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_bernoulli(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(76,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(77,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_negative_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(78,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_geometric(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(79,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_hypergeometric(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(80,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_poisson(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(81,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_categorical(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(82,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_discrete_uniform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(83,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_uniform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(84,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(85,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_log_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(86,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_exponential(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(87,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_gamma(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(88,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_beta(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(89,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_chi_square(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(90,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_student_t(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(91,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_fisher_f(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(92,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_cauchy(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(93,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_laplace(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(94,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_logistic(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(95,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_weibull(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(96,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_pareto(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(97,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_rayleigh(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(98,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_maxwell(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(99,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_gumbel(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(100,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_generalized_extreme_value(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(101,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_beta_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(102,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_skellam(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(103,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_von_mises(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(104,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_triangular(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(105,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_truncated_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(106,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_mixture(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(107,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_empirical(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(108,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_probability_new_gaussian_kde(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(109,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_covariance_matrix(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(110,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_partial_correlation(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(111,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_empty_streaming(hmath_context *context, hmath_value **out) { + if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + return hm_value_finish(result,hm_stochastic_apply(112,NULL,0,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_update_streaming(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(113,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_combine_streaming(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(114,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_streaming_result(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(115,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_histogram_nd(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(116,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_mutual_information(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(117,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_bootstrap(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(118,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_jackknife(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(119,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_one_sample_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(120,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_two_sample_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(121,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_paired_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(122,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_z_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(123,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_chi_square_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(124,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_variance_f_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(125,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_anova(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(126,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_welch_anova(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(127,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_kruskal_wallis(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(128,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_mann_whitney(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(129,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_wilcoxon(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(130,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_kolmogorov_smirnov(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(131,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_shapiro_wilk(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(132,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_anderson_darling(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(133,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_levene(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(134,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_bartlett(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(135,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_fisher_exact(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3)}; + return hm_value_finish(result,hm_stochastic_apply(136,args,4,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_permutation_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, hmath_value **out) { + if(!out || !a0 || !a1 || !a2 || !a3 || !a4) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2),hm_value_stable(a3),hm_value_stable(a4)}; + return hm_value_finish(result,hm_stochastic_apply(137,args,5,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_eta_squared(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(138,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_grubbs(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(139,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_masked(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out) { + if(!out || !a0 || !a1) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1)}; + return hm_value_finish(result,hm_stochastic_apply(140,args,2,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_test_statistic(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(141,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_p_value(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(142,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_degrees_of_freedom(hmath_context *context, const hmath_value *a0, hmath_value **out) { + if(!out || !a0) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0)}; + return hm_value_finish(result,hm_stochastic_apply(143,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_statistics_advanced_new_test_result(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out) { + if(!out || !a0 || !a1 || !a2) return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(a0),hm_value_stable(a1),hm_value_stable(a2)}; + return hm_value_finish(result,hm_stochastic_apply(144,args,3,&result->stable),out); +} +hmath_status hmath_stochastic_object_parts(hmath_context *context, const hmath_value *value, hmath_value **out) { + if(!out || !value)return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic query argument"); + hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(value)}; + return hm_value_finish(result,hm_stochastic_apply(-1,args,1,&result->stable),out); +} +hmath_status hmath_stochastic_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if(!out || !left || !right)return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic query argument"); + hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_stochastic_apply(-2,args,2,&result->stable),out); +} diff --git a/cbits/tensor_bindings.c b/cbits/tensor_bindings.c new file mode 100644 index 0000000..8dad297 --- /dev/null +++ b/cbits/tensor_bindings.c @@ -0,0 +1,1021 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_tensor_bindings.h" +#include "value_internal.h" +#include +#include +extern int hm_tensor_apply(const char *,void *const *,size_t,void **); +extern int hm_tensor_callback(int,void (*)(void),void *,void **); +extern int hm_tensor_clone(void *,void **); +static hmath_status invoke(hmath_context *context,const char *name,const hmath_value *const *arguments,size_t count,hmath_value **out) { + if(!out || (count && !arguments))return hm_error(HMATH_INVALID_ARGUMENT,"NULL Tensor argument/output"); + if(count>(size_t)PTRDIFF_MAX/sizeof(void *))return hm_error(HMATH_OVERFLOW,"Tensor argument span overflow"); + for(size_t i=0;istable); + free(stable); + return hm_value_finish(result,code,out); +} +static hmath_status make_callback(hmath_context *context,int role,void (*function)(void),void *userdata,hmath_value **out) { + if(!function || !out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL Tensor callback/output"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status)return status; + return hm_value_finish(result,hm_tensor_callback(role,function,userdata,&result->stable),out); +} +hmath_status hmath_tensor_object_callback(hmath_context *context,hmath_tensor_scalar_callback_fn function,void *userdata,hmath_value **out) { + return make_callback(context,0,(void (*)(void))function,userdata,out); +} +hmath_status hmath_tensor_object_buffer_callback(hmath_context *context,hmath_tensor_buffer_callback_fn function,void *userdata,hmath_value **out) { + return make_callback(context,1,(void (*)(void))function,userdata,out); +} +static int callback_input(void *stable,hmath_value **out,hmath_math_error *error) { + hmath_value *input; + hmath_status status=hm_value_begin(NULL,&input); + if(!status)status=hm_value_finish(input,hm_tensor_clone(stable,&input->stable),out); + if(status){error->message="Tensor callback input allocation failed";error->message_length=strlen(error->message);} + return status; +} +static int callback_result(int status,hmath_value *result,void **out,hmath_math_error *error) { + if(!status){ + if(!result){status=HMATH_INVALID_ARGUMENT;error->message="Tensor callback returned NULL";error->message_length=strlen(error->message);} + else status=hm_tensor_clone(hm_value_stable(result),out); + } + hmath_value_release(result); + return status; +} +int hm_tensor_invoke_callback(hmath_tensor_scalar_callback_fn function,void *userdata,void *argument,void **out,hmath_math_error *error) { + hmath_value *input=NULL,*result=NULL; + int status=callback_input(argument,&input,error); + if(!status){ + status=function(input,userdata,&result,error); + status=callback_result(status,result,out,error); + } + hmath_value_release(input); + return status; +} +int hm_tensor_invoke_buffer(hmath_tensor_buffer_callback_fn function,void *userdata,void *pointer,void *argument,void **out,hmath_math_error *error) { + hmath_value *input=NULL,*result=NULL; + int status=callback_input(argument,&input,error); + if(!status){ + status=function(pointer,input,userdata,&result,error); + status=callback_result(status,result,out,error); + } + hmath_value_release(input); + return status; +} +hmath_status hmath_tensor_object_prototype(hmath_context *ctx,const hmath_value *value,hmath_value **out){const hmath_value *args[]={value};return invoke(ctx,"__prototype",args,1,out);} +hmath_status hmath_tensor_object_graph_prototype(hmath_context *ctx,const hmath_value *value,hmath_value **out){const hmath_value *args[]={value};return invoke(ctx,"__graph_prototype",args,1,out);} +hmath_status hmath_tensor_object_mutable_prototype(hmath_context *ctx,const hmath_value *value,hmath_value **out){const hmath_value *args[]={value};return invoke(ctx,"__mutable_prototype",args,1,out);} +hmath_status hmath_tensor_object_equal_instance(hmath_context *ctx,const hmath_value *a,const hmath_value *b,hmath_value **out){const hmath_value *args[]={a,b};return invoke(ctx,"__equal",args,2,out);} +hmath_status hmath_tensor_object_full_typed(hmath_context *ctx,const hmath_value *type,const hmath_value *shape,const hmath_value *fill,hmath_value **out){const hmath_value *args[]={type,shape,fill};return invoke(ctx,"__full_typed",args,3,out);} +/* BEGIN GENERATED */ +hmath_status hmath_tensor_object_row_major_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "RowMajor", NULL, 0, out); +} + +hmath_status hmath_tensor_object_column_major_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "ColumnMajor", NULL, 0, out); +} + +hmath_status hmath_tensor_object_strided_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "Strided", NULL, 0, out); +} + +hmath_status hmath_tensor_object_cpu_create( + hmath_context *context, + hmath_value **out) { + return invoke(context, "CPU", NULL, 0, out); +} + +hmath_status hmath_tensor_object_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + const hmath_value *xs, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, shape, xs}; + return invoke(context, "tensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_tensor_column_major( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + const hmath_value *xs, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, shape, xs}; + return invoke(context, "tensorColumnMajor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_tensor_full( + hmath_context *context, + const hmath_value *shape, + const hmath_value *fill_value, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape, fill_value}; + return invoke(context, "tensorFull", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_zeros( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, shape}; + return invoke(context, "tensorZeros", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_ones( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, shape}; + return invoke(context, "tensorOnes", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_arange( + hmath_context *context, + const hmath_value *start, + const hmath_value *end, + const hmath_value *step, + hmath_value **out) { + const hmath_value *hm_arguments[] = {start, end, step}; + return invoke(context, "tensorArange", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_tensor_linspace( + hmath_context *context, + const hmath_value *start, + const hmath_value *end, + const hmath_value *count, + hmath_value **out) { + const hmath_value *hm_arguments[] = {start, end, count}; + return invoke(context, "tensorLinspace", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_tensor_logspace( + hmath_context *context, + const hmath_value *base, + const hmath_value *start, + const hmath_value *end, + const hmath_value *count, + hmath_value **out) { + const hmath_value *hm_arguments[] = {base, start, end, count}; + return invoke(context, "tensorLogspace", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_tensor_random( + hmath_context *context, + const hmath_value *seed, + const hmath_value *shape, + hmath_value **out) { + const hmath_value *hm_arguments[] = {seed, shape}; + return invoke(context, "tensorRandom", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_values( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorValues", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_shape( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorShape", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_strides( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorStrides", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_offset( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorOffset", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_d_type( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorDType", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_device( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorDevice", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_tensor_layout( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorLayout", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_numel( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "numel", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_is_contiguous( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "isContiguous", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_shape_size( + hmath_context *context, + const hmath_value *shape, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape}; + return invoke(context, "shapeSize", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_infer_broadcast( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[] = {left, right}; + return invoke(context, "inferBroadcast", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_contiguous( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "contiguous", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_index_tensor( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor, index}; + return invoke(context, "indexTensor", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_slice_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *start, + const hmath_value *count, + const hmath_value *step, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, start, count, step, input_tensor}; + return invoke(context, "sliceTensor", hm_arguments, 5, out); +} + +hmath_status hmath_tensor_object_fancy_index( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, indices, input_tensor}; + return invoke(context, "fancyIndex", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_gather( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, indices, input_tensor}; + return invoke(context, "gather", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_boolean_index( + hmath_context *context, + const hmath_value *mask, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {mask, input_tensor}; + return invoke(context, "booleanIndex", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_scatter( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *updates, + const hmath_value *target, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, indices, updates, target}; + return invoke(context, "scatter", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_scatter_add( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *updates, + const hmath_value *target, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, indices, updates, target}; + return invoke(context, "scatterAdd", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_reshape_tensor( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape, input_tensor}; + return invoke(context, "reshapeTensor", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_flatten_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "flattenTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_squeeze( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "squeeze", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_unsqueeze( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, input_tensor}; + return invoke(context, "unsqueeze", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_expand( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape, input_tensor}; + return invoke(context, "expand", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_permute( + hmath_context *context, + const hmath_value *axes, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, input_tensor}; + return invoke(context, "permute", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_transpose_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "transposeTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_move_axis( + hmath_context *context, + const hmath_value *from_axis, + const hmath_value *to_axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {from_axis, to_axis, input_tensor}; + return invoke(context, "moveAxis", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_swap_axes( + hmath_context *context, + const hmath_value *from_axis, + const hmath_value *to_axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {from_axis, to_axis, input_tensor}; + return invoke(context, "swapAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_broadcast_to( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape, input_tensor}; + return invoke(context, "broadcastTo", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_repeat_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, count, input_tensor}; + return invoke(context, "repeatTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_tile( + hmath_context *context, + const hmath_value *counts, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {counts, input_tensor}; + return invoke(context, "tile", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_concatenate( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *axis, + const hmath_value *inputs, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, axis, inputs}; + return invoke(context, "concatenate", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_stack( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *axis, + const hmath_value *inputs, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, axis, inputs}; + return invoke(context, "stack", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_split_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *segments, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, segments, input_tensor}; + return invoke(context, "splitTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_chunk_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, count, input_tensor}; + return invoke(context, "chunkTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_pad_tensor( + hmath_context *context, + const hmath_value *padding, + const hmath_value *fill_value, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {padding, fill_value, input_tensor}; + return invoke(context, "padTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_roll( + hmath_context *context, + const hmath_value *axis, + const hmath_value *shift, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, shift, input_tensor}; + return invoke(context, "roll", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_flip_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, input_tensor}; + return invoke(context, "flipTensor", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_rotate( + hmath_context *context, + const hmath_value *first, + const hmath_value *second, + const hmath_value *turns, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {first, second, turns, input_tensor}; + return invoke(context, "rotate", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_sort_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "sortTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_unique( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "unique", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_argsort( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "argsort", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_topk( + hmath_context *context, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {count, input_tensor}; + return invoke(context, "topk", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_nonzero( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "nonzero", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_where_tensor( + hmath_context *context, + const hmath_value *mask, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[] = {mask, left, right}; + return invoke(context, "whereTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_masked_fill( + hmath_context *context, + const hmath_value *mask, + const hmath_value *fill_value, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {mask, fill_value, input_tensor}; + return invoke(context, "maskedFill", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_masked_select( + hmath_context *context, + const hmath_value *mask, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {mask, input_tensor}; + return invoke(context, "maskedSelect", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_map_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, cb, input_tensor}; + return invoke(context, "mapTensor", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_zip_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, cb, left, right}; + return invoke(context, "zipTensor", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_tensor_add( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorAdd", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_subtract( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorSubtract", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_multiply( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorMultiply", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_divide( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorDivide", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_equal( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorEqual", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_less( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorLess", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_and( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorAnd", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_or( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorOr", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_not( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "tensorNot", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_promote_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, input_tensor}; + return invoke(context, "promoteTensor", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_sum_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "sumAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_product_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "productAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_mean_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "meanAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_variance_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "varianceAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_norm_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "normAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_min_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "minAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_max_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axes, keep_dimensions, input_tensor}; + return invoke(context, "maxAxes", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_argmin( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "argmin", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_argmax( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "argmax", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_cumulative_sum( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, input_tensor}; + return invoke(context, "cumulativeSum", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_cumulative_product( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, input_tensor}; + return invoke(context, "cumulativeProduct", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensordot( + hmath_context *context, + const hmath_value *left_axes, + const hmath_value *right_axes, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[] = {left_axes, right_axes, left, right}; + return invoke(context, "tensordot", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_einsum( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *labels, + const hmath_value *output_labels, + const hmath_value *inputs, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, labels, output_labels, inputs}; + return invoke(context, "einsum", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_batched_matmul( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "batchedMatmul", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_tensor_kronecker( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out) { + const hmath_value *hm_arguments[] = {a, b}; + return invoke(context, "tensorKronecker", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_serialize_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "serializeTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_deserialize_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *text, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, text}; + return invoke(context, "deserializeTensor", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_input_graph( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "inputGraph", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_map_graph( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, cb, input_tensor}; + return invoke(context, "mapGraph", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_zip_graph( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *left, + const hmath_value *right, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type, cb, left, right}; + return invoke(context, "zipGraph", hm_arguments, 4, out); +} + +hmath_status hmath_tensor_object_evaluate_graph( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "evaluateGraph", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_new_mutable( + hmath_context *context, + const hmath_value *shape, + const hmath_value *fill_value, + hmath_value **out) { + const hmath_value *hm_arguments[] = {shape, fill_value}; + return invoke(context, "newMutable", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_thaw_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "thawTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_freeze_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "freezeTensor", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_mutable_shape( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "mutableShape", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_read_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor, index}; + return invoke(context, "readMutable", hm_arguments, 2, out); +} + +hmath_status hmath_tensor_object_write_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + const hmath_value *fill_value, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor, index, fill_value}; + return invoke(context, "writeMutable", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_modify_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + const hmath_value *cb, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor, index, cb}; + return invoke(context, "modifyMutable", hm_arguments, 3, out); +} + +hmath_status hmath_tensor_object_slice_mutable( + hmath_context *context, + const hmath_value *axis, + const hmath_value *start, + const hmath_value *count, + const hmath_value *step, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {axis, start, count, step, input_tensor}; + return invoke(context, "sliceMutable", hm_arguments, 5, out); +} + +hmath_status hmath_tensor_object_transpose_mutable( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor}; + return invoke(context, "transposeMutable", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_mutable_alignment( + hmath_context *context, + const hmath_value *element_type, + hmath_value **out) { + const hmath_value *hm_arguments[] = {element_type}; + return invoke(context, "mutableAlignment", hm_arguments, 1, out); +} + +hmath_status hmath_tensor_object_with_mutable_buffer( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *cb, + hmath_value **out) { + const hmath_value *hm_arguments[] = {input_tensor, cb}; + return invoke(context, "withMutableBuffer", hm_arguments, 2, out); +} +/* END GENERATED */ diff --git a/cbits/timeseries.c b/cbits/timeseries.c new file mode 100644 index 0000000..b9e43f4 --- /dev/null +++ b/cbits/timeseries.c @@ -0,0 +1,1024 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated; do not edit. */ +#include "hmath_timeseries.h" +#include "value_internal.h" +extern int hm_timeseries_apply(int, void *const *, size_t, void **); +extern int hm_timeseries_describe(void *,void **); +hmath_status hmath_timeseries_describe(hmath_context *context,const hmath_value *value,hmath_value **out) { + if (!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series description argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + int code = hm_timeseries_describe(hm_value_stable(value),&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_backward_fill(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(0,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_bin_last(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(1,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_bin_mean(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(2,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_forward_fill(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(3,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_inner(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(4,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_left_aligned(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(5,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_linear_fill(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(6,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_linear_samples(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(7,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_moving_maximum(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(8,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_moving_mean(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(9,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_moving_minimum(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(10,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_moving_sd(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(11,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_moving_variance(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(12,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_outer(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(13,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_align(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code = hm_timeseries_apply(14,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_autocorrelation(hmath_context *context, const hmath_value *lags, const hmath_value *xs, hmath_value **out) { + if (!out || !lags || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(lags), hm_value_stable(xs)}; + int code = hm_timeseries_apply(15,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_cross_correlation(hmath_context *context, const hmath_value *lag, const hmath_value *xs, const hmath_value *ys, hmath_value **out) { + if (!out || !lag || !xs || !ys) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(lag), hm_value_stable(xs), hm_value_stable(ys)}; + int code = hm_timeseries_apply(16,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_cumulative_returns(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(xs)}; + int code = hm_timeseries_apply(17,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_difference(hmath_context *context, const hmath_value *order, const hmath_value *lag, const hmath_value *xs, hmath_value **out) { + if (!out || !order || !lag || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(order), hm_value_stable(lag), hm_value_stable(xs)}; + int code = hm_timeseries_apply(18,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_durbin_levinson(hmath_context *context, const hmath_value *covariance, hmath_value **out) { + if (!out || !covariance) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(covariance)}; + int code = hm_timeseries_apply(19,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_exponential_average(hmath_context *context, const hmath_value *alpha, const hmath_value *xs, hmath_value **out) { + if (!out || !alpha || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(alpha), hm_value_stable(xs)}; + int code = hm_timeseries_apply(20,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fill_missing(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2)}; + int code = hm_timeseries_apply(21,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_is_regular(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2)}; + int code = hm_timeseries_apply(22,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_logarithmic_returns(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(xs)}; + int code = hm_timeseries_apply(23,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_observations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(24,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_partial_autocorrelation(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out) { + if (!out || !order || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(order), hm_value_stable(xs)}; + int code = hm_timeseries_apply(25,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_regular_series(hmath_context *context, const hmath_value *start, const hmath_value *step, const hmath_value *xs, hmath_value **out) { + if (!out || !start || !step || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(start), hm_value_stable(step), hm_value_stable(xs)}; + int code = hm_timeseries_apply(26,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_resample(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code = hm_timeseries_apply(27,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_rolling(hmath_context *context, const hmath_value *method, const hmath_value *width, const hmath_value *xs, hmath_value **out) { + if (!out || !method || !width || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(method), hm_value_stable(width), hm_value_stable(xs)}; + int code = hm_timeseries_apply(28,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_series(hmath_context *context, const hmath_value *xs, hmath_value **out) { + if (!out || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(xs)}; + int code = hm_timeseries_apply(29,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_series_values(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(30,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_weighted_average(hmath_context *context, const hmath_value *ws, const hmath_value *xs, hmath_value **out) { + if (!out || !ws || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(ws), hm_value_stable(xs)}; + int code = hm_timeseries_apply(31,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_yule_walker(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out) { + if (!out || !order || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(order), hm_value_stable(xs)}; + int code = hm_timeseries_apply(32,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_dtw_result(hmath_context *context, const hmath_value *distance, const hmath_value *path, hmath_value **out) { + if (!out || !distance || !path) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(distance), hm_value_stable(path)}; + int code = hm_timeseries_apply(33,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_level(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(34,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_linear_trend(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(35,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_mae(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(36,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_mape(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(37,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_mase(hmath_context *context, const hmath_value *period, const hmath_value *training, hmath_value **out) { + if (!out || !period || !training) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(period), hm_value_stable(training)}; + int code = hm_timeseries_apply(38,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_mse(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(39,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_rmse(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(40,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_smape(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {NULL}; + int code = hm_timeseries_apply(41,arguments,0,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stationarity(hmath_context *context, const hmath_value *statistic, const hmath_value *critical_values, const hmath_value *observations, const hmath_value *null_hypothesis, hmath_value **out) { + if (!out || !statistic || !critical_values || !observations || !null_hypothesis) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(statistic), hm_value_stable(critical_values), hm_value_stable(observations), hm_value_stable(null_hypothesis)}; + int code = hm_timeseries_apply(42,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_anomalies(hmath_context *context, const hmath_value *threshold, const hmath_value *xs, hmath_value **out) { + if (!out || !threshold || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(threshold), hm_value_stable(xs)}; + int code = hm_timeseries_apply(43,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_augmented_dickey_fuller(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out) { + if (!out || !deterministic || !lags || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(deterministic), hm_value_stable(lags), hm_value_stable(xs)}; + int code = hm_timeseries_apply(44,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_change_points(hmath_context *context, const hmath_value *penalty, const hmath_value *min_segment, const hmath_value *xs, hmath_value **out) { + if (!out || !penalty || !min_segment || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(penalty), hm_value_stable(min_segment), hm_value_stable(xs)}; + int code = hm_timeseries_apply(45,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_cusum(hmath_context *context, const hmath_value *mean, const hmath_value *sd, const hmath_value *drift, const hmath_value *threshold, const hmath_value *xs, hmath_value **out) { + if (!out || !mean || !sd || !drift || !threshold || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(mean), hm_value_stable(sd), hm_value_stable(drift), hm_value_stable(threshold), hm_value_stable(xs)}; + int code = hm_timeseries_apply(46,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_dtw_distance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(47,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_dtw_path(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(48,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_dynamic_time_warping(hmath_context *context, const hmath_value *radius, const hmath_value *xs, const hmath_value *ys, hmath_value **out) { + if (!out || !radius || !xs || !ys) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(radius), hm_value_stable(xs), hm_value_stable(ys)}; + int code = hm_timeseries_apply(49,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_forecast_error(hmath_context *context, const hmath_value *metric, const hmath_value *actual, const hmath_value *predicted, hmath_value **out) { + if (!out || !metric || !actual || !predicted) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(metric), hm_value_stable(actual), hm_value_stable(predicted)}; + int code = hm_timeseries_apply(50,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_kpss(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out) { + if (!out || !deterministic || !lags || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(deterministic), hm_value_stable(lags), hm_value_stable(xs)}; + int code = hm_timeseries_apply(51,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_spectrum(hmath_context *context, const hmath_value *sample_rate, const hmath_value *xs, hmath_value **out) { + if (!out || !sample_rate || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(sample_rate), hm_value_stable(xs)}; + int code = hm_timeseries_apply(52,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stationarity_critical_values(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(53,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stationarity_null(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(54,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stationarity_observations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(55,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stationarity_statistic(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(56,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_decomposition(hmath_context *context, const hmath_value *trend, const hmath_value *seasonal, const hmath_value *remainder, hmath_value **out) { + if (!out || !trend || !seasonal || !remainder) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(trend), hm_value_stable(seasonal), hm_value_stable(remainder)}; + int code = hm_timeseries_apply(57,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_holt(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, hmath_value **out) { + if (!out || !alpha || !beta) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(alpha), hm_value_stable(beta)}; + int code = hm_timeseries_apply(58,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_holt_winters(hmath_context *context, const hmath_value *period, const hmath_value *alpha, const hmath_value *beta, const hmath_value *gamma, hmath_value **out) { + if (!out || !period || !alpha || !beta || !gamma) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(period), hm_value_stable(alpha), hm_value_stable(beta), hm_value_stable(gamma)}; + int code = hm_timeseries_apply(59,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_sarima_order(hmath_context *context, const hmath_value *ar, const hmath_value *difference, const hmath_value *ma, const hmath_value *seasonal_ar, const hmath_value *seasonal_difference, const hmath_value *seasonal_ma, const hmath_value *period, hmath_value **out) { + if (!out || !ar || !difference || !ma || !seasonal_ar || !seasonal_difference || !seasonal_ma || !period) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(ar), hm_value_stable(difference), hm_value_stable(ma), hm_value_stable(seasonal_ar), hm_value_stable(seasonal_difference), hm_value_stable(seasonal_ma), hm_value_stable(period)}; + int code = hm_timeseries_apply(60,arguments,7,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_config(hmath_context *context, const hmath_value *period, const hmath_value *seasonal_window, const hmath_value *trend_window, const hmath_value *low_pass_window, const hmath_value *inner_iterations, const hmath_value *robust_iterations, hmath_value **out) { + if (!out || !period || !seasonal_window || !trend_window || !low_pass_window || !inner_iterations || !robust_iterations) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(period), hm_value_stable(seasonal_window), hm_value_stable(trend_window), hm_value_stable(low_pass_window), hm_value_stable(inner_iterations), hm_value_stable(robust_iterations)}; + int code = hm_timeseries_apply(61,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_simple(hmath_context *context, const hmath_value *alpha, hmath_value **out) { + if (!out || !alpha) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(alpha)}; + int code = hm_timeseries_apply(62,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_ar_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(63,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(64,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_arima_innovation_variance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(65,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_arima_parameters(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(66,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_arima_residuals(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(67,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_decompose(hmath_context *context, const hmath_value *period, const hmath_value *xs, hmath_value **out) { + if (!out || !period || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(period), hm_value_stable(xs)}; + int code = hm_timeseries_apply(68,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_default_stl_config(hmath_context *context, const hmath_value *period, hmath_value **out) { + if (!out || !period) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(period)}; + int code = hm_timeseries_apply(69,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(70,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_ar(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out) { + if (!out || !order || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(order), hm_value_stable(xs)}; + int code = hm_timeseries_apply(71,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4 || !value5) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4), hm_value_stable(value5)}; + int code = hm_timeseries_apply(72,arguments,5,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_arma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out) { + if (!out || !value || !value2 || !value3 || !value4) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3), hm_value_stable(value4)}; + int code = hm_timeseries_apply(73,arguments,4,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_ma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out) { + if (!out || !value || !value2 || !value3) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2), hm_value_stable(value3)}; + int code = hm_timeseries_apply(74,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_sarima(hmath_context *context, const hmath_value *options, const hmath_value *order, const hmath_value *xs, hmath_value **out) { + if (!out || !options || !order || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(options), hm_value_stable(order), hm_value_stable(xs)}; + int code = hm_timeseries_apply(75,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_fit_var(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out) { + if (!out || !order || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(order), hm_value_stable(xs)}; + int code = hm_timeseries_apply(76,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_forecast_ar(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2)}; + int code = hm_timeseries_apply(77,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_forecast_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2)}; + int code = hm_timeseries_apply(78,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_forecast_var(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out) { + if (!out || !value || !value2) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value), hm_value_stable(value2)}; + int code = hm_timeseries_apply(79,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_kalman_series(hmath_context *context, const hmath_value *transition, const hmath_value *observation, const hmath_value *q, const hmath_value *r, const hmath_value *initial, const hmath_value *measured, hmath_value **out) { + if (!out || !transition || !observation || !q || !r || !initial || !measured) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(transition), hm_value_stable(observation), hm_value_stable(q), hm_value_stable(r), hm_value_stable(initial), hm_value_stable(measured)}; + int code = hm_timeseries_apply(80,arguments,6,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(81,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_remainder_component(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(82,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_seasonal_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(83,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_seasonal_component(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(84,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_seasonal_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(85,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_seasonal_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(86,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_seasonal_period(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(87,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_smooth_forecast(hmath_context *context, const hmath_value *method, const hmath_value *horizon, const hmath_value *xs, hmath_value **out) { + if (!out || !method || !horizon || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(method), hm_value_stable(horizon), hm_value_stable(xs)}; + int code = hm_timeseries_apply(88,arguments,3,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl(hmath_context *context, const hmath_value *config, const hmath_value *xs, hmath_value **out) { + if (!out || !config || !xs) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(config), hm_value_stable(xs)}; + int code = hm_timeseries_apply(89,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_inner_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(90,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_low_pass_window(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(91,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_period(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(92,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_robust_iterations(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(93,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_seasonal_window(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(94,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_stl_trend_window(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(95,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_trend_component(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(96,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_var_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(97,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_gaussian_state(hmath_context *context, const hmath_value *mean, const hmath_value *covariance, hmath_value **out) { + if (!out || !mean || !covariance) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(mean), hm_value_stable(covariance)}; + int code = hm_timeseries_apply(98,arguments,2,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_state_mean(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(99,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} +hmath_status hmath_timeseries_state_covariance(hmath_context *context, const hmath_value *value, hmath_value **out) { + if (!out || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument"); + hmath_value *temporary = NULL; + hmath_status status = hm_value_begin(context,&temporary); + if (status) return status; + void *arguments[] = {hm_value_stable(value)}; + int code = hm_timeseries_apply(100,arguments,1,&temporary->stable); + return hm_value_finish(temporary,code,out); +} diff --git a/cbits/units.c b/cbits/units.c new file mode 100644 index 0000000..5f1ceeb --- /dev/null +++ b/cbits/units.c @@ -0,0 +1,652 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_units_bindings.py. */ +#include "hmath_units.h" +#include "value_internal.h" +extern int hm_units_apply(int opcode,void *const *args,size_t count,void **out); +hmath_status hmath_units_value_dimension(hmath_context *context, const hmath_value *exponents, hmath_value **out) { + if (!out || !exponents) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(exponents)}; + return hm_value_finish(result,hm_units_apply(0,args,1,&result->stable),out); +} +hmath_status hmath_units_value_dimension_exponents(hmath_context *context, const hmath_value *dimension, hmath_value **out) { + if (!out || !dimension) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(dimension)}; + return hm_value_finish(result,hm_units_apply(1,args,1,&result->stable),out); +} +hmath_status hmath_units_value_dimensionless(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(2,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_length_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(3,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_mass_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(4,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_time_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(5,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_temperature_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(6,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_angle_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(7,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_data_dimension(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(8,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_unit(hmath_context *context, const hmath_value *name, const hmath_value *dimension, const hmath_value *scale, const hmath_value *offset, hmath_value **out) { + if (!out || !name || !dimension || !scale || !offset) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(name),hm_value_stable(dimension),hm_value_stable(scale),hm_value_stable(offset)}; + return hm_value_finish(result,hm_units_apply(9,args,4,&result->stable),out); +} +hmath_status hmath_units_value_unit_name(hmath_context *context, const hmath_value *unit, hmath_value **out) { + if (!out || !unit) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit)}; + return hm_value_finish(result,hm_units_apply(10,args,1,&result->stable),out); +} +hmath_status hmath_units_value_unit_dimension(hmath_context *context, const hmath_value *unit, hmath_value **out) { + if (!out || !unit) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit)}; + return hm_value_finish(result,hm_units_apply(11,args,1,&result->stable),out); +} +hmath_status hmath_units_value_unit_scale(hmath_context *context, const hmath_value *unit, hmath_value **out) { + if (!out || !unit) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit)}; + return hm_value_finish(result,hm_units_apply(12,args,1,&result->stable),out); +} +hmath_status hmath_units_value_unit_offset(hmath_context *context, const hmath_value *unit, hmath_value **out) { + if (!out || !unit) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit)}; + return hm_value_finish(result,hm_units_apply(13,args,1,&result->stable),out); +} +hmath_status hmath_units_value_unit_product(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(14,args,2,&result->stable),out); +} +hmath_status hmath_units_value_unit_quotient(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if (!out || !numerator || !denominator) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(numerator),hm_value_stable(denominator)}; + return hm_value_finish(result,hm_units_apply(15,args,2,&result->stable),out); +} +hmath_status hmath_units_value_unit_power(hmath_context *context, const hmath_value *unit, const hmath_value *exponent, hmath_value **out) { + if (!out || !unit || !exponent) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit),hm_value_stable(exponent)}; + return hm_value_finish(result,hm_units_apply(16,args,2,&result->stable),out); +} +hmath_status hmath_units_value_quantity(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out) { + if (!out || !unit || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit),hm_value_stable(value)}; + return hm_value_finish(result,hm_units_apply(17,args,2,&result->stable),out); +} +hmath_status hmath_units_value_temperature_difference(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out) { + if (!out || !unit || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit),hm_value_stable(value)}; + return hm_value_finish(result,hm_units_apply(18,args,2,&result->stable),out); +} +hmath_status hmath_units_value_quantity_dimension(hmath_context *context, const hmath_value *quantity, hmath_value **out) { + if (!out || !quantity) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(quantity)}; + return hm_value_finish(result,hm_units_apply(19,args,1,&result->stable),out); +} +hmath_status hmath_units_value_si_value(hmath_context *context, const hmath_value *quantity, hmath_value **out) { + if (!out || !quantity) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(quantity)}; + return hm_value_finish(result,hm_units_apply(20,args,1,&result->stable),out); +} +hmath_status hmath_units_value_in_unit(hmath_context *context, const hmath_value *unit, const hmath_value *quantity, hmath_value **out) { + if (!out || !unit || !quantity) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(unit),hm_value_stable(quantity)}; + return hm_value_finish(result,hm_units_apply(21,args,2,&result->stable),out); +} +hmath_status hmath_units_value_convert(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *value, hmath_value **out) { + if (!out || !source || !destination || !value) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(source),hm_value_stable(destination),hm_value_stable(value)}; + return hm_value_finish(result,hm_units_apply(22,args,3,&result->stable),out); +} +hmath_status hmath_units_value_add_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(23,args,2,&result->stable),out); +} +hmath_status hmath_units_value_subtract_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(24,args,2,&result->stable),out); +} +hmath_status hmath_units_value_multiply_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out) { + if (!out || !left || !right) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(25,args,2,&result->stable),out); +} +hmath_status hmath_units_value_divide_quantity(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out) { + if (!out || !numerator || !denominator) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(numerator),hm_value_stable(denominator)}; + return hm_value_finish(result,hm_units_apply(26,args,2,&result->stable),out); +} +hmath_status hmath_units_value_si_prefix(hmath_context *context, const hmath_value *name, const hmath_value *symbol, const hmath_value *exponent, hmath_value **out) { + if (!out || !name || !symbol || !exponent) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(name),hm_value_stable(symbol),hm_value_stable(exponent)}; + return hm_value_finish(result,hm_units_apply(27,args,3,&result->stable),out); +} +hmath_status hmath_units_value_si_prefixes(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(28,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_prefixed(hmath_context *context, const hmath_value *prefix, const hmath_value *unit, hmath_value **out) { + if (!out || !prefix || !unit) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(prefix),hm_value_stable(unit)}; + return hm_value_finish(result,hm_units_apply(29,args,2,&result->stable),out); +} +hmath_status hmath_units_value_metre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(30,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_kilometre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(31,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_centimetre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(32,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_millimetre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(33,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_inch(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(34,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_foot(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(35,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_yard(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(36,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_mile(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(37,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_nautical_mile(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(38,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_square_metre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(39,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_hectare(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(40,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_cubic_metre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(41,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_litre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(42,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_millilitre(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(43,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_kilogram(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(44,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_gram(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(45,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_tonne(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(46,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_pound(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(47,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_second(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(48,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_minute(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(49,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_hour(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(50,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_day(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(51,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_metres_per_second(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(52,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_kilometres_per_hour(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(53,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_miles_per_hour(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(54,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_metres_per_second_squared(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(55,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_newton(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(56,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_joule(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(57,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_watt(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(58,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_pascal(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(59,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_bar(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(60,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_atmosphere(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(61,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_kelvin(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(62,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_celsius(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(63,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_fahrenheit(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(64,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_hertz(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(65,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_bit(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(66,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_byte(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(67,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_kibibyte(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(68,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_mebibyte(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(69,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_gigabyte(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(70,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_radian(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(71,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_degree(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(72,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_gradian(hmath_context *context, hmath_value **out) { + if (!out) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + return hm_value_finish(result,hm_units_apply(73,NULL,0,&result->stable),out); +} +hmath_status hmath_units_value_prefix_name(hmath_context *context, const hmath_value *prefix, hmath_value **out) { + if (!out || !prefix) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(prefix)}; + return hm_value_finish(result,hm_units_apply(74,args,1,&result->stable),out); +} +hmath_status hmath_units_value_prefix_symbol(hmath_context *context, const hmath_value *prefix, hmath_value **out) { + if (!out || !prefix) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(prefix)}; + return hm_value_finish(result,hm_units_apply(75,args,1,&result->stable),out); +} +hmath_status hmath_units_value_prefix_exponent(hmath_context *context, const hmath_value *prefix, hmath_value **out) { + if (!out || !prefix) + return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument"); + hmath_value *result; + hmath_status status=hm_value_begin(context,&result); + if(status) return status; + void *args[]={hm_value_stable(prefix)}; + return hm_value_finish(result,hm_units_apply(76,args,1,&result->stable),out); +} +hmath_status hmath_units_value_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out) { + if(!left || !right || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units equality argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(100,args,2,&result->stable),out); +} diff --git a/cbits/value.c b/cbits/value.c new file mode 100644 index 0000000..f9f93fc --- /dev/null +++ b/cbits/value.c @@ -0,0 +1,231 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "numeric_internal.h" +#include "value_internal.h" +#include +extern void hm_value_free(void *stable); +extern int hm_value_info(void *stable, int *kind, int *dtype, size_t *count); +extern int hm_value_real_f32(float real, float imaginary, int complex, void **out); +extern int hm_value_real_f64(double real, double imaginary, int complex, void **out); +extern int hm_value_exact(int dtype, const char *numerator, const char *denominator, void **out); +extern int hm_value_index(ptrdiff_t value, void **out); +extern int hm_value_boolean(int value, void **out); +extern int hm_value_none(void **out); +extern int hm_value_sequence(int tuple, void *const *items, size_t count, void **out); +extern int hm_value_item(void *value, size_t index, void **out); +extern int hm_value_get_real_f32(void *value, float *real, float *imaginary); +extern int hm_value_get_real_f64(void *value, double *real, double *imaginary); +extern int hm_value_get_exact(void *value, char **numerator, char **denominator); +extern int hm_value_get_index(void *value, ptrdiff_t *out); +extern int hm_value_get_boolean(void *value, int *out); + +extern int hm_value_text(const uint32_t *input, size_t count, void **out); +extern int hm_value_get_text(void *value, uint32_t *out); +hmath_status hm_value_begin(hmath_context *context, hmath_value **temporary) { + hmath_value *value = calloc(1, sizeof *value); + if (!value) + return hm_error(HMATH_ALLOCATION_FAILED, "value owner allocation failed"); + hmath_status status = hm_enter(context); + if (status) { + free(value); + return status; + } + atomic_init(&value->refs, 1); + *temporary = value; + return HMATH_OK; +} +hmath_status hm_value_finish(hmath_value *temporary, int code, hmath_value **out) { + if (!code && !temporary->stable) + code = hm_error(HMATH_RUNTIME_ERROR, "missing Haskell value result"); + if (!code) + code = hm_value_info(temporary->stable, &temporary->kind, &temporary->dtype, + &temporary->count); + if (!code && temporary->count > (size_t)PTRDIFF_MAX) + code = hm_error(HMATH_OVERFLOW, "value metadata length exceeds Haskell Int"); + if (code) { + if (temporary->stable) + hm_value_free(temporary->stable); + free(temporary); + hm_leave(); + return (hmath_status)code; + } + *out = temporary; + return HMATH_OK; +} +void *hm_value_stable(const hmath_value *value) { return value ? value->stable : NULL; } +void hmath_value_retain(hmath_value *value) { + if (value) + atomic_fetch_add_explicit(&value->refs, 1, memory_order_relaxed); +} +void hmath_value_release(hmath_value *value) { + if (value && atomic_fetch_sub_explicit(&value->refs, 1, memory_order_acq_rel) == 1) { + hm_value_free(value->stable); + free(value); + hm_leave(); + } +} +hmath_status hmath_value_info(const hmath_value *value, int *kind, int *dtype, size_t *count) { + if (!value || !kind || !dtype || !count) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL value metadata argument"); + *kind = value->kind; + *dtype = value->dtype; + *count = value->count; + return HMATH_OK; +} +void hmath_value_string_free(char *value) { free(value); } +#define BEGIN_VALUE() \ + if (!out) \ + return hm_error(HMATH_INVALID_ARGUMENT, "NULL value output"); \ + hmath_value *result; \ + hmath_status status = hm_value_begin(context, &result); \ + if (status) \ + return status +hmath_status hmath_value_f32(hmath_context *context, float value, hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_real_f32(value, 0, 0, &result->stable), out); +} +hmath_status hmath_value_f64(hmath_context *context, double value, hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_real_f64(value, 0, 0, &result->stable), out); +} +hmath_status hmath_value_complex_f32(hmath_context *context, float real, float imaginary, + hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_real_f32(real, imaginary, 1, &result->stable), out); +} +hmath_status hmath_value_complex_f64(hmath_context *context, double real, double imaginary, + hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_real_f64(real, imaginary, 1, &result->stable), out); +} +hmath_status hmath_value_integral(hmath_context *context, hmath_coefficient_type dtype, + const char *decimal, hmath_value **out) { + if (!hm_decimal(decimal) || (dtype != 2 && (dtype < 6 || dtype > 15))) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid integral type/decimal representation"); + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_exact(dtype, decimal, "1", &result->stable), out); +} +hmath_status hmath_value_integer(hmath_context *context, const char *decimal, hmath_value **out) { + return hmath_value_integral(context, HMATH_COEFFICIENT_INTEGER, decimal, out); +} +hmath_status hmath_value_rational(hmath_context *context, const char *numerator, + const char *denominator, hmath_value **out) { + if (!hm_decimal(numerator) || !hm_decimal(denominator)) + return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal representation"); + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_exact(3, numerator, denominator, &result->stable), out); +} +hmath_status hmath_value_index(hmath_context *context, ptrdiff_t value, hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_index(value, &result->stable), out); +} +hmath_status hmath_value_boolean(hmath_context *context, int value, hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_boolean(value, &result->stable), out); +} +hmath_status hmath_value_none(hmath_context *context, hmath_value **out) { + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_none(&result->stable), out); +} +static hmath_status sequence(hmath_context *context, int tuple, const hmath_value *const *items, + size_t count, hmath_value **out) { + if (count && !items) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL value sequence storage"); + if (count > (size_t)PTRDIFF_MAX / sizeof(void *)) + return hm_error(HMATH_OVERFLOW, "value sequence span exceeds ptrdiff_t"); + for (size_t i = 0; i < count; ++i) + if (!items[i]) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL sequence item"); + BEGIN_VALUE(); + void **stable = count ? malloc(count * sizeof *stable) : NULL; + if (count && !stable) + return hm_value_finish( + result, hm_error(HMATH_ALLOCATION_FAILED, "value sequence scratch allocation failed"), + out); + for (size_t i = 0; i < count; ++i) + stable[i] = items[i]->stable; + int code = hm_value_sequence(tuple, stable, count, &result->stable); + free(stable); + return hm_value_finish(result, code, out); +} +hmath_status hmath_value_list(hmath_context *context, const hmath_value *const *items, size_t count, + hmath_value **out) { + return sequence(context, 0, items, count, out); +} +hmath_status hmath_value_tuple(hmath_context *context, const hmath_value *const *items, + size_t count, hmath_value **out) { + return sequence(context, 1, items, count, out); +} +hmath_status hmath_value_item(hmath_context *context, const hmath_value *sequence, ptrdiff_t index, + hmath_value **out) { + if (!sequence || (sequence->kind != 4 && sequence->kind != 5)) + return hm_error(HMATH_INVALID_ARGUMENT, "value is not a list/tuple"); + if (index < 0 || (size_t)index >= sequence->count) + return hm_error(HMATH_BOUNDS_ERROR, "value item index out of range"); + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_item(sequence->stable, (size_t)index, &result->stable), + out); +} +#define SCALAR_ACCESSOR(name, valid_types, ctype, call) \ + hmath_status name(const hmath_value *value, ctype *a, ctype *b) { \ + if (!value || value->kind != 1 || !(valid_types) || !a || !b || a == b) \ + return hm_error(HMATH_INVALID_ARGUMENT, "value scalar type/output mismatch"); \ + hmath_status status = hm_enter(NULL); \ + if (status) \ + return status; \ + int code = call(value->stable, a, b); \ + hm_leave(); \ + return (hmath_status)code; \ + } +SCALAR_ACCESSOR(hmath_value_get_f32, value->dtype == 1 || value->dtype == 5, float, + hm_value_get_real_f32) +SCALAR_ACCESSOR(hmath_value_get_f64, value->dtype == 0 || value->dtype == 4, double, + hm_value_get_real_f64) +SCALAR_ACCESSOR(hmath_value_get_exact, + value->dtype == 2 || value->dtype == 3 || (value->dtype >= 6 && value->dtype <= 15), + char *, hm_value_get_exact) +#undef SCALAR_ACCESSOR +hmath_status hmath_value_get_index(const hmath_value *value, ptrdiff_t *out) { + if (!value || value->kind != 2 || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "expected index and output"); + hmath_status status = hm_enter(NULL); + if (status) + return status; + int code = hm_value_get_index(value->stable, out); + hm_leave(); + return (hmath_status)code; +} +hmath_status hmath_value_get_boolean(const hmath_value *value, int *out) { + if (!value || value->kind != 3 || !out) + return hm_error(HMATH_INVALID_ARGUMENT, "expected Boolean and output"); + hmath_status status = hm_enter(NULL); + if (status) + return status; + int code = hm_value_get_boolean(value->stable, out); + hm_leave(); + return (hmath_status)code; +} + +hmath_status hmath_value_text(hmath_context *context, const uint32_t *codepoints, size_t count, + hmath_value **out) { + if (count && !codepoints) + return hm_error(HMATH_INVALID_ARGUMENT, "NULL String codepoint storage"); + if (count > (size_t)PTRDIFF_MAX / sizeof(uint32_t)) + return hm_error(HMATH_OVERFLOW, "String codepoint span exceeds ptrdiff_t"); + for (size_t i = 0; i < count; ++i) + if (codepoints[i] > 0x10ffffu) + return hm_error(HMATH_INVALID_ARGUMENT, "codepoint exceeds Haskell Char range"); + BEGIN_VALUE(); + return hm_value_finish(result, hm_value_text(codepoints, count, &result->stable), out); +} +hmath_status hmath_value_get_text(const hmath_value *value, uint32_t *out, size_t capacity) { + if (!value || value->kind != 10 || (value->count && !out)) + return hm_error(HMATH_INVALID_ARGUMENT, "expected String value and output"); + if (capacity < value->count) + return hm_error(HMATH_BOUNDS_ERROR, "insufficient String codepoint output capacity"); + hmath_status status = hm_enter(NULL); + if (status) + return status; + int code = hm_value_get_text(value->stable, out); + hm_leave(); + return (hmath_status)code; +} diff --git a/cbits/value_internal.h b/cbits/value_internal.h new file mode 100644 index 0000000..748eca1 --- /dev/null +++ b/cbits/value_internal.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_VALUE_INTERNAL_H +#define HMATH_VALUE_INTERNAL_H +#include "hmath_value.h" +#include "native_internal.h" +struct hmath_value { + atomic_size_t refs; + void *stable; + int kind, dtype; + size_t count; +}; +/* begin reserves the runtime and allocates a private output owner. finish + * transfers this reservation on success, or frees every temporary on error. + * A successful domain Haskell call must write an owned StablePtr Value. */ +hmath_status hm_value_begin(hmath_context *context, hmath_value **temporary); +hmath_status hm_value_finish(hmath_value *temporary, int status, hmath_value **out); +void *hm_value_stable(const hmath_value *value); +#endif diff --git a/docs/getting-started/choose-an-operation.md b/docs/getting-started/choose-an-operation.md index a11d672..bc14e69 100644 --- a/docs/getting-started/choose-an-operation.md +++ b/docs/getting-started/choose-an-operation.md @@ -1,8 +1,9 @@ # Choose an operation Start with the problem you want to solve, then select an available interface. -The Python wheel provides the native scalar/tensor interface. The Haskell -library additionally supplies the broader numerical algorithms below. +The Python wheel includes the native library. Domain namespaces expose the +original Haskell algorithms through Python and C; the tables below point to +function-level contracts. ## Python, C, and Wave @@ -27,6 +28,25 @@ Read the [Python](../reference/python.md), [C](../reference/c.md), or [matrix calculation guide](../guides/matrix-calculation.md) demonstrates the three operations on the same inputs. +## Domain algorithms in Python and C + +| Task | Python namespace | C reference | +| --- | --- | --- | +| Factor matrices, solve systems and compute eigenpairs | `matrix`, `decomposition`, `iterative`, `sparse` | [Linear algebra](../reference/linear-bindings.md) | +| Differentiate, integrate and solve ODE/PDE systems | `calculus`, `root`, `ode`, `pde` | [Numerical solvers](../reference/numerical-solvers.md) | +| Build expressions and compute gradients | `expression`, `symbolic`, `autodiff` | [Expressions](../reference/expression-bindings.md), [autodiff](../reference/autodiff-bindings.md) | +| Optimize objectives or update parameters | `optimization` | [Optimizers](../reference/optimization-bindings.md) | +| Process tensors and neural layers | `tensor`, `deeplearning_core`, `deeplearning_layers` | [Tensors](../reference/tensor-bindings.md), [deep learning](../reference/deeplearning-bindings.md) | +| Fit models and preprocess datasets | `machinelearning` | [Machine learning](../reference/machinelearning-bindings.md) | +| Work with distributions, generators and forecasts | `probability`, `random`, `timeseries` | [Probability/random](../reference/stochastic.md), [time series](../reference/timeseries-bindings.md) | +| Transform and filter signals | `fourier`, `signal`, `interpolation` | [Spectral functions](../reference/spectral-bindings.md) | +| Exchange arrays and stream files | `interchange` | [Interchange](../reference/interchange-bindings.md) | + +See the [Python namespace index](../reference/python.md#domain-namespaces) for +other domains and [structured values](../reference/values.md) for shared C +ownership and callback rules. Wave can call the public C ABI; its convenience +wrapper retains the smaller tensor interface listed above. + ## Haskell numerical algorithms | Task | Start with | Guide / reference | diff --git a/docs/guides/releasing.md b/docs/guides/releasing.md new file mode 100644 index 0000000..5477ee5 --- /dev/null +++ b/docs/guides/releasing.md @@ -0,0 +1,63 @@ +# Prepare and publish a release + +Release preparation uses one source commit for the C SDK, Python wheel/source +distribution, and Haskell Cabal source package. The version is read from +`pyproject.toml` and checked against Cabal, Meson, and the native version query; +the workflow does not ask for a second version value. + +## Preparation + +Run **Prepare HMath release** from GitHub Actions. This workflow publishes no +packages. It requires the public Haskell API inventory to have no pending +bindings, then runs the full compatibility checks and builds all distributions. +An inventory match is a necessary check; review the documented concrete type +specializations and numerical contracts as well. Arbitrary user-defined Haskell +typeclass instances are not implied by a concrete C/Python binding. + +The `release-candidate` artifact contains: + +| Artifact | Purpose | +| --- | --- | +| `hmath_python-VERSION-*.whl` | Self-contained Python installation | +| `hmath_python-VERSION.tar.gz` | Python source distribution | +| `hmath-VERSION-linux-x86_64.tar.gz` | Relocatable C/C++ SDK with headers, shared library, bundled runtime dependencies, CMake and pkg-config metadata | +| `hmath-VERSION.tar.gz` | Cabal source package for Haskell | +| `release.json` | Exact source commit, version and artifact checksums | +| `SHA256SUMS` | Download integrity checks | + +The C SDK is built from the repaired wheel's exact native library, rather than +another compilation. CI relocates the SDK and compiles C/C++ consumers without +a system GHC installation. The Haskell check extracts and builds the actual +Cabal source archive. Python checks install the actual wheel on each supported +Python version. + +## Publishing configuration + +Keep PyPI Trusted Publishing configured for the repository's existing `pypi` +environment and publish workflow. Configure TestPyPI separately for the +`testpypi` environment if using that index. + +For Haskell, create an individual Hackage account with upload permission and an +API token, then store the token as `HACKAGE_TOKEN` in the GitHub `pypi` +environment. Do not commit credentials. The account must be a maintainer of an +existing `hmath` package, or have permission to create the new package. +See [Hackage uploading and maintainer rules](https://hackage.haskell.org/upload). + +## Publication + +After reviewing the prepared changes, run **Publish HMath release** on upstream +`master`. Publication consumes an existing successful preparation, without rebuilding. +Leave the optional candidate run ID blank to resume the staged candidate or select +the most recent successful preparation for this exact commit. Select `testpypi` to publish only the Python test package, or `pypi` +for Hackage, PyPI, and the GitHub release containing all language artifacts. +Production publication first checks existing version hashes and Hackage +configuration before writing package indexes. Hackage publication precedes +PyPI so an unavailable Hackage account does not leave only Python published. + +If a publication step fails, use **Re-run failed jobs** or dispatch publication +again. The staged release records its original candidate run ID, so publication +reuses those exact artifacts. Do not rebuild packages to resume an upload. Existing package files are accepted +only when their hashes match the prepared artifacts; different bytes require a +new version. GitHub asset uploads resume through a draft release, verify existing +assets, and publish the release after all uploads finish. Separate package +indexes cannot be updated as one atomic transaction. diff --git a/docs/reference/algebra-values.md b/docs/reference/algebra-values.md new file mode 100644 index 0000000..dcc8983 --- /dev/null +++ b/docs/reference/algebra-values.md @@ -0,0 +1,406 @@ +# Original algebra interfaces + +The two source modules define different classes and instances. Their functions remain separate. Prototypes select the actual original type, without adding arithmetic instances or converting through Double. `Exact` wraps Rational and deliberately has no Num instance. Old Algebra supports Integer/Rational/Polynomial rings, Rational fields, Additive groups and Integer/Rational list modules. API.Algebra supports Integer/Rational/Float/Double/Complex Double/Exact; Field excludes Integer and FloatingPoint is Float/Double/Complex Double. Source errors, modular ring identity, finite-field proof budgets and checked inversion are unchanged. Values own references and support close/context management. + +## `algebra.linear_combination` + +Checked linear combination. Supply the zero vector explicitly so the empty combination retains its dimension. + +Original signature: `v -> [(s, v)] -> Either MathError v`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.semiring_laws` + +Exhaustive semiring identities on the supplied finite sample. This is a test utility, not a proof for types with an infinite carrier. + +Original signature: `[a] -> [(String, Bool)]`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.ring_laws` + +Semiring laws plus additive inverses on a finite sample. + +Original signature: `[a] -> [(String, Bool)]`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_laws` + +Ring laws, commutative multiplication and nonzero inverses. + +Original signature: `[a] -> [(String, Bool)]`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.group_laws` + +Group identities on a finite sample. + +Original signature: `[a] -> [(String, Bool)]`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.module_laws` + +Check module scalar identity, composition, and both distributive laws. Vectors in the sample must belong to the same runtime space. + +Original signature: `[s] -> [v] -> [(String, Bool)]`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.modular` + +Construct a residue, requiring m>1; arbitrary signed values are reduced. + +Original signature: `Integer -> Integer -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.modular_value` + +Canonical value in [0,m). + +Original signature: `Modular -> Integer`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.modular_modulus` + +Modulus greater than one. + +Original signature: `Modular -> Integer`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.add_modular` + +Checked residue addition. + +Original signature: `Modular -> Modular -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.subtract_modular` + +Checked residue subtraction. + +Original signature: `Modular -> Modular -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.multiply_modular` + +Checked residue multiplication. + +Original signature: `Modular -> Modular -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.inverse_modular` + +Invert a unit; zero and nonunits are domain errors. + +Original signature: `Modular -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.power_modular` + +Integer power, with negative powers supported for units. + +Original signature: `Modular -> Integer -> Either MathError Modular`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.finite_field` + +Construct GF(p^n) from an irreducible polynomial of positive degree. Primality is proven by trial division. Irreducibility uses successive Frobenius powers and polynomial gcds; n must not exceed the proof budget. + +Original signature: `Int -> Integer -> [Integer] -> Either MathError FiniteField`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.prime_field` + +Prime field GF(p), represented as F_p[x]/(x). + +Original signature: `Int -> Integer -> Either MathError FiniteField`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_characteristic` + +Prime characteristic p. + +Original signature: `FiniteField -> Integer`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_degree` + +Extension degree n. + +Original signature: `FiniteField -> Int`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_cardinality` + +Exact carrier size p^n. + +Original signature: `FiniteField -> Integer`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_modulus` + +Ascending coefficients of the monic irreducible defining polynomial. + +Original signature: `FiniteField -> [Integer]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_element` + +Reduce an arbitrary integer polynomial into a finite field. + +Original signature: `FiniteField -> [Integer] -> FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_element_coefficients` + +Canonical ascending residue coefficients (trailing zeros removed). + +Original signature: `FieldElement -> [Integer]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.field_elements` + +Enumerate the complete carrier, rejecting sizes above an explicit storage budget. Enumeration is coefficient-lexicographic and deterministic. + +Original signature: `Int -> FiniteField -> Either MathError [FieldElement]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.add_field` + +Addition; different defining fields are rejected even if isomorphic. + +Original signature: `FieldElement -> FieldElement -> Either MathError FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.negate_field` + +Additive inverse in the same field. + +Original signature: `FieldElement -> FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.subtract_field` + +Checked field subtraction. + +Original signature: `FieldElement -> FieldElement -> Either MathError FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.multiply_field` + +Checked field multiplication, reduced modulo the defining polynomial. + +Original signature: `FieldElement -> FieldElement -> Either MathError FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.inverse_field_element` + +Nonzero inverse via the finite-field identity a^(q-2). + +Original signature: `FieldElement -> Either MathError FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.power_field` + +Binary exponentiation, with inverses for negative exponents. + +Original signature: `FieldElement -> Integer -> Either MathError FieldElement`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.finite_field_laws` + +Exhaustive carrier checks for small fields, including distributivity, associativity, identities and every nonzero inverse. Budget bounds enumeration; the cubic law checks are intended for small validation fields. + +Original signature: `Int -> FiniteField -> Either MathError [(String, Bool)]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.get_additive` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Additive -> field`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.Additive` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.horner` + +Coefficients are highest degree first; an empty polynomial is zero. + +Original signature: `[a] -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.inner_product` + +Return sum(conjugate a[i] * b[i]) using the Scalar and Ring operations. Equal list lengths are required; mismatch returns VectorLengthMismatch. Empty lists give the ring zero; instance arithmetic controls precision/overflow. + +Original signature: `[a] -> [a] -> Either MathError a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.get_exact` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Exact -> field`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.Exact` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.zero` + +Additive identity. + +Original signature: `a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.one` + +Multiplicative identity. + +Original signature: `a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.plus` + +Semiring addition. + +Original signature: `a -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.times` + +Semiring multiplication. + +Original signature: `a -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.negate_ring` + +Additive inverse. + +Original signature: `a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.inverse_field` + +Multiplicative inverse; zero returns a domain error. + +Original signature: `a -> Either MathError a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.group_identity` + +Group identity. + +Original signature: `a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.group_combine` + +Group operation, not necessarily commutative. + +Original signature: `a -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.group_inverse` + +Two-sided inverse. + +Original signature: `a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.module_scale` + +Scalar action. + +Original signature: `scalar -> vector -> vector`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra.module_add` + +Addition, rejecting incompatible runtime shapes. + +Original signature: `vector -> vector -> Either MathError vector`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.zero` + +Additive identity of this ring. + +Original signature: `a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.one` + +Multiplicative identity of this ring. + +Original signature: `a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.plus` + +Add two ring elements; exact instances obey ring laws and IEEE instances retain host rounding. + +Original signature: `a -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.times` + +Multiply two ring elements using the instance arithmetic. + +Original signature: `a -> a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.negative` + +Return the additive inverse of a ring element. + +Original signature: `a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.integer` + +Embed an unbounded Integer into the domain; instance representation/rounding rules apply. + +Original signature: `Integer -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.invert` + +Return multiplicative inverse of a nonzero domain element, or Left MathError for zero/invalid/nonrepresentable inverse. + +Original signature: `a -> Either MathError a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.conjugate_scalar` + +Return scalar conjugate; real/exact instances use identity and complex instances conjugate imaginary components. + +Original signature: `a -> a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.machine_epsilon` + +Given a type proxy, return floating precision epsilon as Double (2^-52 for Double,2^-23 for Float). + +Original signature: `proxy a -> Double`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.finite_scalar` + +Test whether all real/complex components are finite for this instance. + +Original signature: `a -> Bool`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.rational` + +Convert exact Rational into the domain, returning Left MathError if it cannot be represented under the instance contract. + +Original signature: `Rational -> Either MathError a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.matrix_dimensions` + +Return logical (rows,columns) of a matrix-like container. + +Original signature: `m a -> (Int, Int)`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.matrix_elements` + +Return matrix elements in logical row-major order. + +Original signature: `m a -> [a]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.matrix_construct` + +Given rows,columns,flat row-major elements, construct a matrix-like value or return checked shape/count failure. + +Original signature: `Int -> Int -> [a] -> Either MathError (m a)`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.tensor_dimensions` + +Return tensor-like dimensions in axis order; [] denotes scalar. + +Original signature: `t a -> [Int]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.tensor_elements` + +Return tensor-like elements in logical row-major coordinate order. + +Original signature: `t a -> [a]`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.tensor_construct` + +Given dimensions then flat values, construct a tensor-like value or return shape/count failure. + +Original signature: `[Int] -> [a] -> Either MathError (t a)`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.vector_plus` + +Add identically shaped vector-space values, returning checked dimension errors on mismatch. + +Original signature: `(Num a) => v a -> v a -> Either MathError (v a)`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.vector_scale` + +Given scalar then vector-space value, return its coordinatewise scalar multiple. + +Original signature: `(Num a) => a -> v a -> v a`. The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + +## `algebra_api.differential` + +Extract associated differential; the Dual instance returns its tangent component. + +Original signature: `a -> Differential a`. Borrowed source-order arguments; owned successful output; failure leaves the output untouched. + diff --git a/docs/reference/autodiff-bindings.md b/docs/reference/autodiff-bindings.md new file mode 100644 index 0000000..a2c722a --- /dev/null +++ b/docs/reference/autodiff-bindings.md @@ -0,0 +1,320 @@ +# Automatic differentiation bindings + +These C and Python interfaces call `HMath.Autodiff`. They retain its checked +input domains, graph node budget, accumulation rules and derivative conventions. +Scalar expressions, compiled graphs, gradient states and symbolic tensors are +immutable Haskell values with independently owned references. + +Include `hmath_autodiff.h` in C or C++; use `from hmath import autodiff as ad` in +Python. Numerical reverse-graph evaluation uses the original binary64 implementation. +`Dual`, `primal`, `tangent` and `forward` support arbitrary nesting over `Double`, +`Float`, `Integer` and `Rational` leaves. Float arithmetic stays Float; exact +leaves never pass through floating-point intermediates. Other generic leaf +instances remain pending and are not claimed by this page. + +## Ownership and errors + +Each returned C handle owns one reference. `hmath_ad_retain(value)` adds a +reference; `hmath_ad_release(value)` removes one. Both accept `NULL`. The caller +holds an input reference throughout a call, and never races final release with +use. Every live handle reserves the Haskell runtime: final shutdown returns +`HMATH_BUSY` until those references are released. Expressions/graphs retain their +Haskell dependencies independently; releasing a source expression does not +invalidate a compiled graph or derivative. + +Python objects provide idempotent `close()` and `with` blocks. Their destructor +is a fallback. A closed object rejects use with `ValueError`. Operations pin +input references during calls, including reentrant callbacks. Sharing immutable +objects across threads is supported; caller output buffers must be independent. + +C arrays are borrowed for the call. Outputs must not overlap inputs or each +other. Output capacity is measured in elements, not bytes. Insufficient capacity +returns `HMATH_BOUNDS_ERROR`; outputs remain untouched on failure. A `NULL` +context disables cancellation; otherwise cancellation is checked before entry. +An in-flight Haskell operation is not asynchronously interrupted. + +Original `Left MathError` values become `HMATH_MATH_ERROR` in C and `HMathError` +with `status == 11` in Python. The error message retains the original constructor +and payload. Pure Haskell exceptions become status 6. Invalid native pointers, +wrong handle kinds, buffer capacities and allocation failures are binding errors. +No extra finite check is added to unchecked Dual arithmetic or the raw +`GradientState` constructor. + +## Scalar expressions and graphs + +| Python | C | Contract | +| --- | --- | --- | +| `variable(index)` | `hmath_ad_variable` | Declare a zero-based graph input. The original `compileGraph` checks index validity, including negative indices. | +| `constant(value)` | `hmath_ad_constant` | Embed a `Double`; non-finite literals are rejected during graph compilation, not construction. | +| `compile_graph(input_count, expression)` | `hmath_ad_compile_graph` | Compile a reusable graph with exactly that many inputs. The C parameter named `index` is this input count. Original maximum is one million scalar nodes. | +| `evaluate_graph(graph, values)` / `graph.evaluate(values)` | `hmath_ad_evaluate_graph` | Re-evaluate with exactly the declared number of finite inputs. | +| `differentiate(index, expression)` | `hmath_ad_differentiate` | Construct a symbolic derivative. Opaque custom rules retain their original higher-order rejection. | +| `detach(expression)` | `hmath_ad_unary` with `HMATH_AD_DETACH` | Preserve the primal while dropping reverse edges. | +| `stop_gradient(expression)` | `hmath_ad_unary` with `HMATH_AD_STOP_GRADIENT` | Original `stopGradient` alias. | + +Python `Expr` implements `+`, `-`, `*`, `/`, `**`, unary `-` and `abs` through +original Haskell instances. Scalar literals are converted to native constants. +C uses `hmath_ad_binary` and `hmath_ad_unary` with the enums in the header. +Python unary helpers are `negate`, `absolute`, `sign`, `reciprocal`, `exp`, `log`, +`sqrt`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, +`asinh`, `acosh` and `atanh`. These also operate on `Dual` values where the +corresponding Haskell instance exists. Dual comparisons use the original Eq/Ord +instances: equality includes both fields, while ordering compares primal fields +only, recursively. This intentionally preserves their distinction when two +Dual values have equal primals but different tangents. + +```python +from hmath import autodiff as ad + +with ad.variable(0) as x: + with ad.compile_graph(1, x * x + 1) as graph: + assert graph.evaluate([3]) == 10 + assert graph.evaluate([4]) == 17 +``` + +See the [original expression and compilation contracts](haskell/HMath-Autodiff.md#v:compileGraph). + +## Reverse derivatives and products + +Python builders are pure functions receiving a list of `Expr` inputs. They return +one expression for scalar objectives or a sequence for vector objectives. An +existing expression, or sequence of expressions, may be passed instead of a +builder. The C interface receives those explicit expression handles. A builder's +external Python side effects and evaluation count are not part of its mathematical +contract; build expressions only from the supplied inputs and deterministic rules. + +| Python signature | C function | Returned result / C flat output layout | +| --- | --- | --- | +| `value_and_gradient(function, values)` | `hmath_ad_value_and_gradient` | `(value, gradient)` / `[value, gradient...]`, capacity `n+1`. Repeated input leaves accumulate. | +| `gradient(function, values)` | `hmath_ad_gradient` | Fresh length-`n` list; no ambient accumulation. | +| `hessian(function, values)` | `hmath_ad_hessian` | `n` rows of `n` symbolic second derivatives / row-major `n*n`. | +| `jacobian(function, values)` | `hmath_ad_jacobian` | `m` output-by-input rows / row-major `m*n`; empty outputs preserve shape. | +| `jvp(function, values, direction)` | `hmath_ad_jvp` | Jacobian times input direction, length `m`; original direction length/finite checks. | +| `vjp(function, values, direction)` | `hmath_ad_vjp` | Output cotangent times Jacobian, length `n`; direction length is `m`. | +| `hvp(function, values, direction)` | `hmath_ad_hvp` | Hessian times input direction, length `n`. | +| `gradient_check(step, function, values)` | `hmath_ad_gradient_check` | Maximum absolute discrepancy from central finite differences; positive finite `step` is required. | +| `complex_gradient(function, value)` | `hmath_ad_complex_gradient` | Complex Wirtinger derivative; the builder receives `[real, imaginary]`. C input/output are two real coordinates. The original convention divides real-coordinate derivatives by two. | +| `differentiable_step(rate, function, expressions)` | `hmath_ad_differentiable_step` | Updated symbolic expressions preserving outer derivatives. C returns a rank-one ADTensor; retrieve its owned expression references. | + +Here `n` is input count and `m` is output expression count. Native result products +are checked for representable sizes before allocating/writing memory. The original +`MathError` values cover invalid lengths, non-finite values, invalid tolerances, +invalid graph indices and graph-budget exhaustion. + +```python +from hmath import autodiff as ad + +def objective(xs): + x, y = xs + return x * x + x * y + +assert ad.value_and_gradient(objective, [3, 4]) == (21, [10, 3]) +assert ad.hessian(objective, [3, 4]) == [[2, 1], [1, 0]] +assert ad.hvp(objective, [3, 4], [2, -1]) == [3, 2] +``` + +See [reverse differentiation](haskell/HMath-Autodiff.md#v:valueAndGradient), +[Jacobian](haskell/HMath-Autodiff.md#v:jacobian), +[Hessian](haskell/HMath-Autodiff.md#v:hessian), +and [differentiable steps](haskell/HMath-Autodiff.md#v:differentiableStep). + +## Dual forward mode + +`Dual(value, tangent, dtype=None)` uses the original `Dual` numeric instances. +The default leaf type is `Double`; nested values inherit the component type. +Supported explicit choices are: + +| Python dtype | Original Haskell leaf | C constructor | Available classes | +| --- | --- | --- | --- | +| `"float64"` | `Double` | `hmath_ad_dual_create` | Num, Fractional, Floating, Eq, Ord | +| `"float32"` | `Float` | `hmath_ad_dual_create_f32` | Num, Fractional, Floating, Eq, Ord | +| `"integer"` | `Integer` | `hmath_ad_dual_create_integer` | Num, Eq, Ord | +| `"rational"` | `Rational` | `hmath_ad_dual_create_rational` | Num, Fractional, Eq, Ord | +| `"complex64"`, `"complex128"` | `Complex Float`, `Complex Double` | shared Value export + `hmath_ad_dual_nested` | Num, Fractional, Floating, Eq | +| `"int8"` … `"int64"`, `"intp"` | Signed bounded integers / native Int | shared Value export + `hmath_ad_dual_nested` | Num, Eq, Ord | +| `"uint8"` … `"uint64"`, `"uintp"` | Unsigned bounded integers / native Word | shared Value export + `hmath_ad_dual_nested` | Num, Eq, Ord | +| Typed NumericValue prototype | Original Numeric.Dual towers or Quaternion Float/Double | shared Value export + `hmath_ad_dual_nested` | Original leaf dictionaries only | + +Unsupported class operations reject the request, such as Integer division or +Rational exp; they never silently convert to Double. `dual.dtype` reports the +leaf type and `dual.depth` reports nesting depth. Components may themselves be +Dual values of the same scalar type/depth. +Numeric literals are embedded at that depth/type with zero tangents, following the +original Num instance. Mixing already constructed incompatible depths is a +`TypeError`, corresponding to incompatible Haskell types. +`primal(dual)` / `dual.primal` and `tangent(dual)` / `dual.tangent` extract their +respective components. C constructs a dual with `hmath_ad_dual_create` and copies +`[primal, tangent]` through `hmath_ad_values_copy` for flat Dual values. For +nested values, `hmath_ad_dual_nested` constructs the next level and +`hmath_ad_dual_parts` returns two independently owned component handles. +`hmath_ad_dual_depth` reports nesting depth; scalar component handles have depth +zero. Flat Double/Float leaves support their compatible floating copy view. +Python unwraps standard scalar leaves to floats, complex values, exact integers +or fractions +and returns Dual objects for nested components. Integer/Rational constructors use +signed decimal strings, with separate rational numerator/denominator strings. +The compatible Integer/Rational component accessor is `hmath_ad_scalar_text`; +free both returned +strings with `hmath_ad_string_free`. Python exposes those leaves as arbitrary +precision `int` and `fractions.Fraction`, including beyond Python's decimal +conversion digit cap. Integer/Rational and other typed coefficient handles have +no implicit Double copy view. For every coefficient type, +`hmath_ad_value_import` converts a depth-zero component handle to a shared typed +Value; query/extract it with the shared Value API. Conversely, create a typed +shared coefficient Value, export it with `hmath_ad_value_export`, then pass +matching component handles to `hmath_ad_dual_nested`. Both conversions preserve +original scalar types and exact payloads. + +A boxed `hmath.numeric_types.NumericValue` can select the complete original +coefficient type, including nested Numeric.Dual and Quaternion components. +`Dual.element_type` returns an independently owned scalar prototype; it retains +the entire coefficient witness. `dtype` reports primitive names or +`"numeric.dual"` / `"numeric.quaternion"` for those structured leaves. The +prototype, rather than that diagnostic string, selects a structured type. +Original Numeric.Dual has no Ord dictionary; Quaternion has Num but no +Fractional/Floating dictionary. The binding rejects those unavailable operations +without assigning new instances. AD.Dual may be nested over any supported leaf; +its Eq and available Ord continue to use the original instances. Bounded +arithmetic wraps according to the original Haskell type; constructor input +conversion rejects out-of-range Python integers. + +`forward(function, value, dtype=None)` seeds a native dual with tangent one, applies the +builder using original Dual arithmetic, and returns `(primal, derivative)`. +C callers compose the same sequence using the dual constructor, native operators +and component extraction. Unchecked non-finite behavior is retained. + +`forward_jvp(function, values, direction)` returns `(primals, tangents)` using the +original checked vector API. Input length and finite checks precede builder +execution. C callers can first invoke `hmath_ad_forward_jvp_result` with zero +outputs to perform those checks, then build their dual outputs with the input +values/direction, and invoke it again to extract checked output components. +The C result layout is `[primals..., tangents...]` with capacity `2*m`. + +```python +from hmath import autodiff as ad + +assert ad.forward(lambda x: x * x * x, 3) == (27, 27) +assert ad.forward(lambda x: x+1, 16777216, dtype="float32") == (16777216, 1) +assert ad.forward(lambda x: x*x, 10**100, dtype="integer") == (10**200, 2*10**100) +with ad.Dual(3, 1) as seed: + value, derivative = ad.forward(lambda x: x*x*x, seed) + with value, derivative: + assert (derivative.primal, derivative.tangent) == (27, 18) +assert ad.forward_jvp(lambda xs: [xs[0] * xs[1]], [2, 3], [1, 2]) == ([6], [7]) +``` + +See [forward mode](haskell/HMath-Autodiff.md#v:forward). + +## Explicit gradient state + +| Python | C | Meaning | +| --- | --- | --- | +| `GradientState(values)` | `hmath_ad_gradient_state_create` | Original raw constructor; stores the supplied list without extra validation. | +| `zero_gradients(count)` | `hmath_ad_zero_gradients` | Create zeros; negative count retains the original `InvalidArgument`. | +| `state.accumulated_gradient` | `hmath_ad_values_copy` | Copy the retained gradient list. | +| `accumulate_gradients(state, values)` | `hmath_ad_accumulate_gradients` | Return a new state with a checked, same-length finite sum. Original state is unchanged. | +| `reset_gradients(state)` | `hmath_ad_reset_gradients` | New zeros of the original length. | +| `gradient_hook(function, state)` | `hmath_ad_gradient_hook_result` | Apply a checked transformation; changed length and non-finite output are rejected. In C retrieve state values, apply the caller's hook, then pass the transformed values to the result adapter. | +| `clip_gradient(limit, values)` | `hmath_ad_clip_gradient` | Clip Euclidean norm without overflowing the norm calculation. C returns a gradient-list handle to copy/release. Positive finite limit is required. | + +See [gradient accumulation](haskell/HMath-Autodiff.md#v:GradientState). + +## Symbolic tensors + +`ADTensor(shape, values)` / `ad_tensor(shape, values)` call the original checked +`adTensor`; values are expressions in logical row-major order. C uses +`hmath_ad_tensor_create`. Shape product must match expression count, with original +negative-dimension, broadcast and contraction failures preserved. + +| Python | C | Meaning | +| --- | --- | --- | +| `ad_shape(tensor)` / `tensor.shape` | `hmath_ad_shape_copy` | Dimensions; Python returns a tuple, C uses `ptrdiff_t` array. | +| `ad_values(tensor)` / `tensor.values` | `hmath_ad_tensor_values` | Logical expression list. Every returned C expression reference is owned. | +| `ad_broadcast(shape, tensor)` | `hmath_ad_broadcast` | Original checked broadcasting; reverse contributions sum over repeats. | +| `ad_add(left, right)` / `left + right` | `hmath_ad_tensor_add` | Broadcasted symbolic addition. | +| `ad_multiply(left, right)` / `left * right` | `hmath_ad_tensor_multiply` | Broadcasted symbolic elementwise product. | +| `ad_matmul(left, right)` / `left @ right` | `hmath_ad_matmul` | Original symbolic batched matrix multiplication. | +| `ad_contract(left_axes, right_axes, left, right)` | `hmath_ad_contract` | Contraction preserving uncontracted axis order. | +| `ad_sum(tensor)` | `hmath_ad_sum` | Symbolic scalar sum. | + +`hmath_ad_metadata` reports value count and rank before allocating getter buffers. +These tensors retain the original scalar-expression expansion; this binding does +not claim a new tensor-kernel AD engine or change the existing graph budget. +See [original tensor rules](haskell/HMath-Autodiff.md#t:ADTensor). + +## Custom rules and checkpoints + +`custom_operation(rule, expressions)` calls original `customOperation`. The rule +receives numerical values and returns `(value, partial_derivatives)`. The original +reverse evaluator checks derivative arity and finite values. Value-only compiled +graph evaluation retains its original behavior, including not validating unused +partial-derivative arity. Python materializes the returned derivative sequence +when invoking the foreign callback. + +`custom_unary(function, derivative, expression)` calls original `customUnary` +with separate native callbacks. Evaluating only the graph value does not call the +derivative. Custom rules retain their first-order limitation: symbolic higher +orders return the original `InvalidArgument`. + +`checkpoint(builder, expressions)` stores the original graph-building recipe. +The recipe is replayed by Haskell during evaluation/backpropagation. Its inputs +are local symbolic expressions, not concrete floating-point values. Builder +results may contain nested custom rules or checkpoints. + +Python keeps callbacks and their referenced data alive transitively through +arithmetic, tensor, derivative and compiled-graph handles, including expressions +created by checkpoint replay. Python exceptions are caught at the callback +boundary and rethrown after native cleanup. An existing `HMathError` retains its +status and message. Callback-created expressions are retained conservatively +until all owning checkpoint/derived handles are released. + +The additive C entries `hmath_ad_custom_operation_checked`, +`hmath_ad_custom_unary_checked` and `hmath_ad_checkpoint_checked` use the +`hmath_callback_error` wire from `hmath_callback.h`. This preserves all 21 +original MathError constructors and complete message payloads, including NUL, +Unicode and long strings. Returning status11 from a custom rule supplies an +actual `Left MathError` to the original evaluator. Positioned expression errors +(status12) and interchange errors (status13) retain their structured fields. +Python selects these entries when available; raise `hmath.errors.MathError`, +`hmath.expression.ExprError` or an interchange error from a callback to preserve +that domain value. Unexpected Python exceptions rethrow after native cleanup. + +C callback function pointers, userdata and error payload storage must remain +live until all derived handles are released. Callbacks are synchronous and may +reenter HMath; return an error status rather than throwing across C. Error +payload memory must remain valid until the invoking native call returns. The +legacy string-only callback entries remain ABI compatible; use the checked +entries for lossless structured failures. Every callback-created Expr returned +from checkpoint replay is independently retained for its derived graph's life. + +C custom-rule callbacks receive writable partial capacity equal to argument +count and separately report actual partial count. Never write beyond capacity. +A checkpoint builder receives borrowed expression handles and returns one owned +expression reference; retain an input before returning that same input. The +header contains the complete callback signatures. + +```python +from hmath import autodiff as ad + +assert ad.value_and_gradient( + lambda xs: ad.custom_unary(lambda x: x**3, lambda x: 3*x*x, xs[0]), + [2], +) == (8, [12]) +assert ad.value_and_gradient( + lambda xs: ad.checkpoint(lambda ys: ys[0]*ys[0], xs), + [2], +) == (4, [4]) +``` + +See [custom rules](haskell/HMath-Autodiff.md#v:customOperation) and +[checkpoints](haskell/HMath-Autodiff.md#v:checkpoint). + +## Shared object interchange + +`hmath_ad_value_import` converts an owned legacy Expr/ADTensor/Dual handle into +an independently owned shared Value, and `hmath_ad_value_export` converts back. +No expression is reparsed or reconstructed mathematically. Python performs this +conversion automatically for neural and generic APIs, retaining callback owners +through the converted value and every derived result. Value287 is original Expr, +288 is original ADTensor and289 is original Autodiff.Dual. Numeric.Dual remains +a distinct original type; these owners are never silently exchanged. diff --git a/docs/reference/buffer-bindings.md b/docs/reference/buffer-bindings.md new file mode 100644 index 0000000..4ec617c --- /dev/null +++ b/docs/reference/buffer-bindings.md @@ -0,0 +1,365 @@ +# Buffer API + +`from hmath import buffer` exposes the actual `HMath.API.Buffer` containers and operations. C includes `hmath_buffer.h`; all objects use the shared [Value ownership contract](values.md). Outputs own one reference and remain untouched on failure. Release every owner with `close()`/`hmath_value_release`. + +Boxed elements remain exact generic values. The distinction between original lazy and WHNF-strict constructors is preserved; foreign values themselves are already materialized, so these constructors do not synthesize Haskell bottoms. Unboxed storage is Double, with no added NaN/Inf checks. Every freeze/thaw conversion copies. + +## Mutable scopes and storage + +`run_st_buffer(boxed, callback)` lends an actual STBuffer to a synchronous callback. Use `thaw_st_buffer(region, boxed)` to select that same ST state region explicitly. Scoped handles cannot execute on another thread or after the callback; immutable frozen values and ordinary callback results remain owned. + +`IOBuffer(n, initial, dtype=...)` / `new_io_buffer` allocate original pinned, synchronized IO storage. Standard Float/Double, Complex Float/Double, signed/unsigned bounded and native integers, Bool and Char have original Storable instances. Exact Integer/Rational and Dual do not. Python integer initial values default to native `intp`; use explicit dtype to select width. Boxed constructors accept dtype to preserve that element witness, and `thaw_io_buffer(boxed, dtype=...)` performs the explicit marshal conversion before the original copying thaw. Empty storage requires dtype or a typed prototype. + +`with_io_buffer(io, callback)` lends `(BorrowedPointer, count)` while holding the original lock and ForeignPtr. `pointer.read/write`, `.layout` and `.address` are valid only in that callback and thread. Never retain the raw address or reenter locking operations on the same IOBuffer; same-thread reentry returns BUSY. Other threads use the original synchronized operations. Callback errors release the pointer borrow and lock before propagating the original exception. Bool/Char layouts are queried from their actual Storable instance, not assumed to match C bool/char. `.layout` is `(dtype, size, alignment, length)`; Bool uses dtype16 and Char17. + +```python +from hmath import buffer + +with buffer.Boxed([1, 2, 3]) as source: + def change(region): + region.write(1, 8) + return region.freeze() + with buffer.run_st_buffer(source, change) as frozen: + assert frozen.values == [1, 8, 3] + +with buffer.IOBuffer(3, 0.0, dtype="float32") as storage: + storage.with_pointer(lambda pointer, count: pointer.write(count - 1, 2.0)) + assert storage.read(2) == 2.0 +``` + +## `buffer.lazy_boxed` + +Finite lists only. The list spine is consumed; elements remain lazy. + +```haskell +[a] -> Boxed a +``` + +```text +lazy_boxed(values, *, dtype=None) +``` + +```c +hmath_status hmath_buffer_lazy_boxed(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `buffer.strict_boxed` + + Construct a boxed container from a finite list, forcing every element to weak head normal form (not deep normal form). Preserve order; element evaluation exceptions propagate. + +```haskell +[a] -> Boxed a +``` + +```text +strict_boxed(values, *, dtype=None) +``` + +```c +hmath_status hmath_buffer_strict_boxed(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `buffer.boxed_values` + + Return boxed elements in zero-based array order as a list. Elements retain the laziness/strictness chosen at construction. + +```haskell +Boxed a -> [a] +``` + +```text +boxed_values(value) +``` + +```c +hmath_status hmath_buffer_boxed_values(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.boxed_length` + +Return the number of elements in a boxed container; empty storage has length zero. + +```haskell +Boxed a -> Int +``` + +```text +boxed_length(value) +``` + +```c +hmath_status hmath_buffer_boxed_length(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.map_strict` + + Given element transformation then boxed input, return a boxed result with every mapped element forced to WHNF. Preserve length/order; evaluation exceptions propagate. + +```haskell +(a -> b) -> Boxed a -> Boxed b +``` + +```text +map_strict(function, value) +``` + +```c +hmath_status hmath_buffer_map_strict(hmath_context *context, const hmath_value *function, const hmath_value *value, hmath_value **out); +``` + +## `buffer.unboxed_double` + + Copy a finite Double list into an immutable unboxed array in list order. Values are evaluated by unboxing; no finiteness validation is added. + +```haskell +[Double] -> UnboxedDouble +``` + +```text +unboxed_double(values) +``` + +```c +hmath_status hmath_buffer_unboxed_double(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `buffer.unboxed_values` + +Copy/expand unboxed Doubles into a list in array order, preserving length. + +```haskell +UnboxedDouble -> [Double] +``` + +```text +unboxed_values(value) +``` + +```c +hmath_status hmath_buffer_unboxed_values(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.run_st_buffer` + +The rank-2 state parameter prevents a mutable region from escaping. + +```haskell +Boxed a -> (forall s. STBuffer s a -> ST s b) -> b +``` + +```text +run_st_buffer(value, callback) +``` + +```c +hmath_status hmath_buffer_run_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out); +``` + +## `buffer.thaw_st_buffer` + + Copy immutable boxed values into new mutable storage in the current ST region. The input remains unchanged; storage cannot escape the region. + +```haskell +Boxed a -> ST s (STBuffer s a) +``` + +```text +thaw_st_buffer(region, value) +``` + +```c +hmath_status hmath_buffer_thaw_st_buffer(hmath_context *context, const hmath_value *region, const hmath_value *value, hmath_value **out); +``` + +## `buffer.freeze_st_buffer` + + Copy current mutable ST values into an immutable boxed container; later writes do not modify the frozen result. + +```haskell +STBuffer s a -> ST s (Boxed a) +``` + +```text +freeze_st_buffer(value) +``` + +```c +hmath_status hmath_buffer_freeze_st_buffer(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.read_st_buffer` + + Given ST buffer then zero-based index, read the element. Negative/out-of-range indices return Left InvalidArgument within ST, rather than indexing the array. + +```haskell +STBuffer s a -> Int -> ST s (Either MathError a) +``` + +```text +read_st_buffer(value, index) +``` + +```c +hmath_status hmath_buffer_read_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out); +``` + +## `buffer.write_st_buffer` + + Given ST buffer, zero-based index, then value, update one element and return Right (). Invalid index returns Left InvalidArgument without writing. + +```haskell +STBuffer s a -> Int -> a -> ST s (Either MathError ()) +``` + +```text +write_st_buffer(value, index, element) +``` + +```c +hmath_status hmath_buffer_write_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out); +``` + +## `buffer.new_io_buffer` + + Allocation overflow is checked before allocation. Allocation/OS exceptions remain IO exceptions; MathError describes input and numeric contract failures. + +```haskell +Storable a => Int -> a -> IO (Either MathError (IOBuffer a)) +``` + +```text +new_io_buffer(count, initial, *, dtype=None) +``` + +```c +hmath_status hmath_buffer_new_io_buffer(hmath_context *context, const hmath_value *count, const hmath_value *initial, hmath_value **out); +``` + +## `buffer.thaw_io_buffer` + + Copy boxed Storable values into new pinned IO storage. Return Left InvalidArgument for byte-size overflow; allocation/OS/evaluation failures remain IO exceptions. + +```haskell +Storable a => Boxed a -> IO (Either MathError (IOBuffer a)) +``` + +```text +thaw_io_buffer(value, *, dtype=None, prototype=None) +``` + +```c +hmath_status hmath_buffer_thaw_io_buffer(hmath_context *context, const hmath_value *prototype, const hmath_value *value, hmath_value **out); +``` + +## `buffer.freeze_io_buffer` + + Lock and copy pinned IO values to a strict immutable boxed container. The result is independent of later buffer writes; allocation/IO exceptions propagate. + +```haskell +Storable a => IOBuffer a -> IO (Boxed a) +``` + +```text +freeze_io_buffer(value) +``` + +```c +hmath_status hmath_buffer_freeze_io_buffer(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.io_buffer_length` + + Return the immutable element count of a pinned IO buffer. This query neither borrows its pointer nor takes ownership. + +```haskell +IOBuffer a -> Int +``` + +```text +io_buffer_length(value) +``` + +```c +hmath_status hmath_buffer_io_buffer_length(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.read_io_buffer` + + Given IO buffer then zero-based index, read under the buffer lock. Invalid index returns Left InvalidArgument; IO exceptions propagate. + +```haskell +Storable a => IOBuffer a -> Int -> IO (Either MathError a) +``` + +```text +read_io_buffer(value, index) +``` + +```c +hmath_status hmath_buffer_read_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out); +``` + +## `buffer.write_io_buffer` + + Given IO buffer, zero-based index, then value, write under its lock and return Right (). Invalid index returns Left InvalidArgument without modification. + +```haskell +Storable a => IOBuffer a -> Int -> a -> IO (Either MathError ()) +``` + +```text +write_io_buffer(value, index, element) +``` + +```c +hmath_status hmath_buffer_write_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out); +``` + +## `buffer.with_io_buffer` + + Given IO buffer then callback, hold its lock and lend a Ptr plus element count for the callback duration. Do not retain the pointer or reenter locking operations on this same buffer. Callback exceptions propagate while releasing the lock. + +```haskell +Storable a => IOBuffer a -> (Ptr a -> Int -> IO b) -> IO b +``` + +```text +with_io_buffer(value, callback) +``` + +```c +hmath_status hmath_buffer_with_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out); +``` + +## `buffer.unboxed_to_boxed` + + Convert unboxed Double storage to a new strict boxed container, preserving order and values. + +```haskell +UnboxedDouble -> Boxed Double +``` + +```text +unboxed_to_boxed(value) +``` + +```c +hmath_status hmath_buffer_unboxed_to_boxed(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `buffer.boxed_to_unboxed` + + Convert boxed Double values to a new unboxed array, forcing values during copying. Preserve order and length. + +```haskell +Boxed Double -> UnboxedDouble +``` + +```text +boxed_to_unboxed(value) +``` + +```c +hmath_status hmath_buffer_boxed_to_unboxed(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + diff --git a/docs/reference/c.md b/docs/reference/c.md index d258564..f51a785 100644 --- a/docs/reference/c.md +++ b/docs/reference/c.md @@ -96,8 +96,11 @@ interrupt a running Haskell kernel. | 6 | `HMATH_HASKELL_EXCEPTION` | Contained Haskell exception | | 7 | `HMATH_CANCELLED` | Cooperative cancellation | | 8 | `HMATH_BOUNDS_ERROR` | Buffer or metadata bounds error | -| 9 | `HMATH_BUSY` | Active work prevents shutdown | +| 9 | `HMATH_BUSY` | Active work or Haskell-backed states prevent shutdown | | 10 | `HMATH_UNSUPPORTED` | Unsupported operation | +| 11 | `HMATH_MATH_ERROR` | Original Haskell `MathError`; use `hmath_last_math_error` for its constructor and complete payload. | +| 12 | `HMATH_EXPRESSION_ERROR` | Original expression `ExprError`; use `hmath_last_expression_error` for its kind, position and complete message. | +| 13 | `HMATH_INTERCHANGE_ERROR` | Original `InterchangeError`; use `hmath_last_interchange_error` for its kind and complete message. | ## Version and diagnostics @@ -279,8 +282,8 @@ None. #### Returns `HMATH_OK` after final shutdown or `HMATH_BUSY` -while a checked/legacy call or callback is active. Join workers, then retry a -busy result. Successful shutdown is irreversible; only the process owner +while a checked/legacy call or callback is active, or an optimizer state is alive. +Join workers and release optimizer states, then retry a busy result. Successful shutdown is irreversible; only the process owner should invoke it. Release owned resources before shutdown. #### See also diff --git a/docs/reference/deeplearning-bindings.md b/docs/reference/deeplearning-bindings.md new file mode 100644 index 0000000..58c67bf --- /dev/null +++ b/docs/reference/deeplearning-bindings.md @@ -0,0 +1,614 @@ +# Neural numerical primitives + +The `deeplearning_core`, `deeplearning_layers`, `deeplearning_precision` and +`deeplearning_metrics` namespaces call the original Haskell APIs. C/C++ include +`hmath_deeplearning.h` and pass owned shared Values. Selectors, parameters, +training state, random continuations, AD graphs, exact INT8 accumulation and +result diagnostics retain original behavior. + +```python +from hmath import deeplearning_core as core +from hmath import deeplearning_layers as layers +from hmath import tensor + +with tensor.tensor([1, 2], [1, 2]) as inputs: + with tensor.tensor([1, 2], [3, 4]) as weights: + with layers.dense(inputs, weights, [1]) as output: + assert output.values == [12.0] + +assert core.activation(core.Sigmoid, 0.0) == 0.5 +``` + +## Types, layouts and state + +The original neural functions use **Double**; their Tensor parameters require +actual `tensor.TensorDouble` objects (Value161). Typed Float tensors are rejected +rather than silently widened. Use explicit tensor promotion when converting a +source type. Reduced precision and INT8 are selected through the original +precision APIs described below. + +Dense inputs use trailing feature dimensions; weights use `[output,input]`. +Convolution/pooling input layout is `[N,C,spatial...]`, with one to three spatial +axes. Convolution weights use `[Cout,Cin/groups,kernel...]`; transpose convolution +uses `[Cin,Cout/groups,kernel...]`. Padding is symmetric zero padding. Attention +uses `[sequence,feature]`; `True` in a mask permits a key. Original fully masked +attention rows produce exact zero output and weights. + +Training mode is explicit: `Training.TRAINING` or `Training.INFERENCE` (also +`Inference`). Functions do not consult ambient model state. Dropout returns +`(output, mask, next_rng)`. Its input/output RNG is the complete original +`hmath.random.RNG` continuation, retaining the selected generator and pending +state. Inference dropout consumes no random values. + +```python +from hmath import random + +with random.pcg32() as generator: + with random.seed_rng(generator, 42) as rng: + with tensor.tensor([1, 2], [1, 2]) as inputs: + output, mask, advanced = layers.dropout( + layers.Training.TRAINING, 0.5, rng, inputs + ) + try: + print(output.values, mask.values) + finally: + output.close() + mask.close() + advanced.close() +``` + +## Selectors and records + +Activation selectors are `Sigmoid`, `Tanh`, `ReLU`, `LeakyReLU(parameter)`, +`PReLU(parameter)`, `ELU(parameter)`, `SELU`, `GELU`, `SiLU`, `Mish`, `Softplus`, +`Softsign`, `HardSigmoid`, `HardSwish`. The original analytic derivatives and +kink conventions are preserved. `activation_expr` embeds the source activation +and its source reverse rule in an existing Autodiff Expr. + +Loss selectors are `MeanSquaredError`, `MeanAbsoluteError`, `Huber(parameter)`, +`SmoothL1(parameter)`, `BinaryCrossEntropy`, `CategoricalCrossEntropy`, +`NegativeLogLikelihood`, `KLDivergence`, `CosineLoss`, `Hinge(parameter)`. +Reduction is `Sum` or `Mean`. Probability-domain errors remain explicit; +impossible events are not silently clipped. Logit functions retain original +stable formulas. CTC blank indices, label sequences, log-probability matrices, +value/gradient outputs and unsupported cases remain unchanged. + +Initializers are `XavierUniform`, `XavierNormal`, `KaimingUniform`, +`KaimingNormal`, `Orthogonal(scale)`, +`TruncatedNormal(mean, standard_deviation, bound)`. Fans and RNG are explicit; +`initialize_weights` returns `(tensor, next_rng)`. + +| Python record | Fields in constructor order | +| --- | --- | +| `BatchNormState` | `running_mean`, `running_variance`, `batches_seen` | +| `ConvOptions` | `stride`, `padding`, `dilation`, `groups` | +| `LossScaler` | `scale`, `growth_interval`, `finite_steps` | +| `ClassificationMetrics` | `accuracy`, `precision`, `recall`, `f1` | + +These immutable Python records copy every original field; corresponding +original selector functions remain available. Constructor calls do not invent +validation absent from source constructors. Checked operations retain original +parameter validation and errors. Batch normalization preserves its population +variance for normalization and unbiased running-variance update. Layer, instance, +group, RMS and weight normalization retain original axis and epsilon rules. + +`KVCache` is an owned immutable original object. `empty_cache` fixes positive +capacity and key/value feature widths; `append_cache` returns a new cache and +rejects overflow or incompatible shapes without truncating history. +`cache_values` returns independently owned accumulated key/value tensors. + +## Automatic differentiation + +`activation_expr`, `loss_expr`, softmax/log-softmax/sparsemax Expr functions, +`ctc_loss_expr`, `dense_ad`, `convolution_ad`, `layer_norm_ad`, `rms_norm_ad` and +`scaled_dot_product_attention_ad` accept and return the existing +`hmath.autodiff.Expr` / `ADTensor` owners. They retain the original graphs and +reverse rules; no derivative is reconstructed by the binding. Callback owners +remain alive transitively through derived graphs. The additive +`hmath_ad_value_import`/`export` C functions interchange legacy AD handles with +Values287/288; original Autodiff Dual uses separate Value289 and never becomes +Numeric.Dual. + +## Quantization and reduced precision + +`quantize(Symmetric | Asymmetric, axis_or_none, tensor)` creates the actual +original `QuantizedTensor`, including exact INT8 values, scales, zero points, +shape and axis. `quantized_values`, `quantization_scales`, +`quantization_zero_points` expose the original fields; `dequantize` returns an +owned Double tensor. `int8_gemm` performs the original exact integer accumulation +with signed-32-bit overflow checks and original scale/axis restrictions. + +`reduced_gemm(FP16 | BF16, left, right)` retains the software format rounding, +ties-to-even input conversion, FP32 accumulation and final Double conversion. +`initial_loss_scaler`, `scale_loss`, `unscale_gradients`, `update_loss_scaler` +retain the original dynamic state transitions. Overflow decisions happen before +an update; original master-weight and scaling conventions are unchanged. + +## Metrics and errors + +Confusion-matrix rows are truth, columns prediction. Classification diagnostics +retain accuracy and per-class precision/recall/F1 with original zero-denominator +conventions. Top-k ties prefer smaller class indices. ROC ties count one half; +PR AUC uses grouped-threshold trapezoids from `(recall=0, precision=1)`, matching +the original algorithm. Empty/nonfinite/shape/label failures remain the source +MathError constructors. A C checked failure is status11; Python HMathError +retains the complete `.math_error` value. + +## Ownership and C calling convention + +C wrappers use context first, original arguments in source order, owned +`hmath_value **out` last. Selectors/records are actual immutable source objects; +constructor wrappers end in `_create`. Inputs are borrowed for the call; outputs +remain untouched on error. Release every result and every handle nested in +lists or tuples. Python Tensor/RNG/cache/quantized/AD owners support `.close()` +and context managers. Record fields containing ordinary copied numbers/lists +require no native cleanup. + +Source object kinds are Activation274, Loss275, Reduction276, Training277, +BatchNormState278, Initializer279, ConvOptions280, PoolMode281, KVCache282, +Quantization283, reduced Precision284, QuantizedTensor285, LossScaler286, +ClassificationMetrics290. They share actual Tensor161, RNG240 and AD287/288 +payloads across namespaces. All live owned handles reserve the runtime. + +## Function reference + +The source references document original formulas, validation and parameter +semantics: [Core](haskell/HMath-DeepLearning-Core.md), +[Layers](haskell/HMath-DeepLearning-Layers.md), +[Precision](haskell/HMath-DeepLearning-Precision.md), +[Metrics](haskell/HMath-DeepLearning-Metrics.md). + +### HMath.DeepLearning.Core + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `Sigmoid` | `Activation` | `hmath_neural_core_sigmoid_create` | +| `Tanh` | `Activation` | `hmath_neural_core_tanh_create` | +| `ReLU` | `Activation` | `hmath_neural_core_relu_create` | +| `SELU` | `Activation` | `hmath_neural_core_selu_create` | +| `GELU` | `Activation` | `hmath_neural_core_gelu_create` | +| `SiLU` | `Activation` | `hmath_neural_core_silu_create` | +| `Mish` | `Activation` | `hmath_neural_core_mish_create` | +| `Softplus` | `Activation` | `hmath_neural_core_softplus_create` | +| `Softsign` | `Activation` | `hmath_neural_core_softsign_create` | +| `HardSigmoid` | `Activation` | `hmath_neural_core_hard_sigmoid_create` | +| `HardSwish` | `Activation` | `hmath_neural_core_hard_swish_create` | +| `LeakyReLU(parameter)` | `Activation` | `hmath_neural_core_leaky_relu_create` | +| `PReLU(parameter)` | `Activation` | `hmath_neural_core_prelu_create` | +| `ELU(parameter)` | `Activation` | `hmath_neural_core_elu_create` | +| `Sum` | `Reduction` | `hmath_neural_core_sum_create` | +| `Mean` | `Reduction` | `hmath_neural_core_mean_create` | +| `MeanSquaredError` | `Loss` | `hmath_neural_core_mean_squared_error_create` | +| `MeanAbsoluteError` | `Loss` | `hmath_neural_core_mean_absolute_error_create` | +| `BinaryCrossEntropy` | `Loss` | `hmath_neural_core_binary_cross_entropy_create` | +| `CategoricalCrossEntropy` | `Loss` | `hmath_neural_core_categorical_cross_entropy_create` | +| `NegativeLogLikelihood` | `Loss` | `hmath_neural_core_negative_log_likelihood_create` | +| `KLDivergence` | `Loss` | `hmath_neural_core_kl_divergence_create` | +| `CosineLoss` | `Loss` | `hmath_neural_core_cosine_loss_create` | +| `Huber(parameter)` | `Loss` | `hmath_neural_core_huber_create` | +| `SmoothL1(parameter)` | `Loss` | `hmath_neural_core_smooth_l1_create` | +| `Hinge(parameter)` | `Loss` | `hmath_neural_core_hinge_create` | +| `activation(method, value)` | `Double` | `hmath_neural_core_activation` | +| `activation_derivative(method, value)` | `Double` | `hmath_neural_core_activation_derivative` | +| `activation_expr(method, value)` | `ADExpr` | `hmath_neural_core_activation_expr` | +| `softmax(values)` | `[Double]` | `hmath_neural_core_softmax` | +| `log_softmax(values)` | `[Double]` | `hmath_neural_core_log_softmax` | +| `sparsemax(values)` | `[Double]` | `hmath_neural_core_sparsemax` | +| `gated_linear_unit(values, gate)` | `[Double]` | `hmath_neural_core_gated_linear_unit` | +| `softmax_expr(values)` | `[ADExpr]` | `hmath_neural_core_softmax_expr` | +| `log_softmax_expr(values)` | `[ADExpr]` | `hmath_neural_core_log_softmax_expr` | +| `sparsemax_expr(values)` | `[ADExpr]` | `hmath_neural_core_sparsemax_expr` | +| `loss(method, reduction, target, prediction)` | `Double` | `hmath_neural_core_loss` | +| `loss_gradient(method, reduction, target, prediction)` | `[Double]` | `hmath_neural_core_loss_gradient` | +| `loss_expr(method, reduction, target, prediction)` | `ADExpr` | `hmath_neural_core_loss_expr` | +| `binary_cross_entropy_logits(reduction, target, logits)` | `Double` | `hmath_neural_core_binary_cross_entropy_logits` | +| `categorical_cross_entropy_logits(target, logits)` | `Double` | `hmath_neural_core_categorical_cross_entropy_logits` | +| `regularization(l1, l2, weights)` | `Double` | `hmath_neural_core_regularization` | +| `contrastive_loss(margin, similar, left, right)` | `Double` | `hmath_neural_core_contrastive_loss` | +| `triplet_loss(margin, anchor, positive, negative)` | `Double` | `hmath_neural_core_triplet_loss` | +| `focal_loss(alpha, gamma, target, prediction)` | `Double` | `hmath_neural_core_focal_loss` | +| `dice_loss(smooth, target, prediction)` | `Double` | `hmath_neural_core_dice_loss` | +| `iou_loss(smooth, target, prediction)` | `Double` | `hmath_neural_core_iou_loss` | +| `ctc_loss(blank, labels, log_probabilities)` | `Double` | `hmath_neural_core_ctc_loss` | +| `ctc_loss_gradient(blank, labels, log_probabilities)` | `(Double,[[Double]])` | `hmath_neural_core_ctc_loss_gradient` | +| `ctc_loss_expr(blank, labels, log_probabilities)` | `ADExpr` | `hmath_neural_core_ctc_loss_expr` | + +#### `activation(method, value)` + +Given Activation selector then finite scalar, evaluate the selected activation. Parameterized LeakyReLU/PReLU slopes must be finite and ELU alpha positive. Invalid input/parameters or non-finite output returns Left MathError. + +#### `activation_derivative(method, value)` + +Evaluate the analytic first derivative with documented kink conventions and stable saturated sigmoid/tanh behavior. + +#### `activation_expr(method, value)` + +Embed the checked activation and analytic custom reverse rule in an automatic differentiation graph. + +#### `softmax(values)` + +Exponentiate stable log-softmax values; the output sums to one within floating error. + +#### `log_softmax(values)` + +Normalize a nonempty finite vector in log space after subtracting its maximum. + +#### `sparsemax(values)` + +Project a finite vector onto the probability simplex using sorted active-support thresholds. + +#### `gated_linear_unit(values, gate)` + +Multiply values by sigmoid(gates), requiring equal vector lengths. + +#### `softmax_expr(values)` + +First-order softmax reverse rule, including cross-coordinate coupling. + +#### `log_softmax_expr(values)` + +First-order stable log-softmax rule; gradient rows sum to zero. + +#### `sparsemax_expr(values)` + +Sparsemax's piecewise-linear Jacobian. At a support boundary its inactive coordinate convention chooses zero, giving a defined subgradient. + +#### `loss(method, reduction, target, prediction)` + +Evaluate the selected checked loss. Mean divides elementwise losses by count; CosineLoss is one vector loss. + +#### `loss_gradient(method, reduction, target, prediction)` + +Analytic derivatives with respect to predictions under the exact loss/reduction convention. + +#### `loss_expr(method, reduction, target, prediction)` + +Use a constant target with symbolic prediction inputs and the matching analytic reverse rule. + +#### `binary_cross_entropy_logits(reduction, target, logits)` + +Stable binary cross entropy from logits and [0,1] targets, including extreme finite logits. + +#### `categorical_cross_entropy_logits(target, logits)` + +Cross entropy from one class-logit vector; nonnegative targets must sum to one. + +#### `regularization(l1, l2, weights)` + +Return l1*sum(abs(w)) + l2/2*sum(w*w); both coefficients must be finite and nonnegative. + +#### `contrastive_loss(margin, similar, left, right)` + +Pairwise Euclidean contrastive loss; similar=True penalizes squared distance and dissimilar pairs use the positive margin. + +#### `triplet_loss(margin, anchor, positive, negative)` + +Return max(0,positiveDistance-negativeDistance+margin) for equal nonempty vector dimensions. + +#### `focal_loss(alpha, gamma, target, prediction)` + +Mean binary focal loss with alpha in [0,1], gamma>=0, and exact zero/one targets. + +#### `ctc_loss(blank, labels, log_probabilities)` + +Single sequence, time-major log-probabilities [time,class]. Blank index is explicit; labels exclude blank. The forward/backward dynamic program sums alignments in log space, including adjacent repeated-label restrictions. Gradients are with respect to independent log probabilities, before a log-softmax chain rule. Impossible alignments return DomainError. + +#### `ctc_loss_gradient(blank, labels, log_probabilities)` + +Given blank class index, target labels, then rectangular time-by-class log probabilities, return CTC negative log likelihood and gradient rows. Validate class indices, finite/log-probability constraints and alignment feasibility. Empty time permits only empty labels; invalid/impossible inputs return Left MathError. + +#### `ctc_loss_expr(blank, labels, log_probabilities)` + +CTC graph operation on rectangular time-major log probabilities. Its custom backward uses forward/backward occupancies, rather than numerical differences. + +### HMath.DeepLearning.Layers + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `Training.TRAINING` | `Training` | `hmath_neural_layers_training_create` | +| `Inference` | `Training` | `hmath_neural_layers_inference_create` | +| `dropout(mode, probability, rng, input)` | `(Tensor,Tensor,RNG)` | `hmath_neural_layers_dropout` | +| `spatial_dropout(mode, probability, rng, input)` | `(Tensor,Tensor,RNG)` | `hmath_neural_layers_spatial_dropout` | +| `BatchNormState(running_mean, running_variance, batches_seen)` | `BatchNormState` | `hmath_neural_layers_batch_norm_state_create` | +| `running_mean(state)` | `[Double]` | `hmath_neural_layers_running_mean` | +| `running_variance(state)` | `[Double]` | `hmath_neural_layers_running_variance` | +| `batches_seen(state)` | `Int` | `hmath_neural_layers_batches_seen` | +| `batch_norm(mode, momentum, epsilon, gamma, beta, state, input)` | `(Tensor,BatchNormState)` | `hmath_neural_layers_batch_norm` | +| `layer_norm(axes, epsilon, input)` | `Tensor` | `hmath_neural_layers_layer_norm` | +| `rms_norm(axes, epsilon, input)` | `Tensor` | `hmath_neural_layers_rms_norm` | +| `instance_norm(epsilon, input)` | `Tensor` | `hmath_neural_layers_instance_norm` | +| `group_norm(groups, epsilon, input)` | `Tensor` | `hmath_neural_layers_group_norm` | +| `weight_norm(axis, scales, input)` | `Tensor` | `hmath_neural_layers_weight_norm` | +| `XavierUniform` | `Initializer` | `hmath_neural_layers_xavier_uniform_create` | +| `XavierNormal` | `Initializer` | `hmath_neural_layers_xavier_normal_create` | +| `KaimingUniform` | `Initializer` | `hmath_neural_layers_kaiming_uniform_create` | +| `KaimingNormal` | `Initializer` | `hmath_neural_layers_kaiming_normal_create` | +| `Orthogonal(scale)` | `Initializer` | `hmath_neural_layers_orthogonal_create` | +| `TruncatedNormal(mean, standard_deviation, bound)` | `Initializer` | `hmath_neural_layers_truncated_normal_create` | +| `initialize_weights(method, fan_in, fan_out, shape, rng)` | `(Tensor,RNG)` | `hmath_neural_layers_initialize_weights` | +| `embedding(weights, indices)` | `Tensor` | `hmath_neural_layers_embedding` | +| `dense(input, weights, bias)` | `Tensor` | `hmath_neural_layers_dense` | +| `dense_ad(input, weights, bias)` | `ADTensor` | `hmath_neural_layers_dense_ad` | +| `ConvOptions(stride, padding, dilation, groups)` | `ConvOptions` | `hmath_neural_layers_conv_options_create` | +| `convolution_stride(options)` | `[Int]` | `hmath_neural_layers_convolution_stride` | +| `convolution_padding(options)` | `[Int]` | `hmath_neural_layers_convolution_padding` | +| `convolution_dilation(options)` | `[Int]` | `hmath_neural_layers_convolution_dilation` | +| `convolution_groups(options)` | `Int` | `hmath_neural_layers_convolution_groups` | +| `convolution(options, input, weights, bias)` | `Tensor` | `hmath_neural_layers_convolution` | +| `depthwise_convolution(options, input, weights, bias)` | `Tensor` | `hmath_neural_layers_depthwise_convolution` | +| `convolution_ad(options, input, weights, bias)` | `ADTensor` | `hmath_neural_layers_convolution_ad` | +| `transposed_convolution(output_padding, options, input, weights, bias)` | `Tensor` | `hmath_neural_layers_transposed_convolution` | +| `MaxPool` | `PoolMode` | `hmath_neural_layers_max_pool_create` | +| `AveragePool` | `PoolMode` | `hmath_neural_layers_average_pool_create` | +| `pooling(mode, kernel, stride, padding, input)` | `Tensor` | `hmath_neural_layers_pooling` | +| `adaptive_pooling(mode, shape, input)` | `Tensor` | `hmath_neural_layers_adaptive_pooling` | +| `global_pooling(mode, input)` | `Tensor` | `hmath_neural_layers_global_pooling` | +| `scaled_dot_product_attention(query, key, value, mask, bias)` | `(Tensor,Tensor)` | `hmath_neural_layers_scaled_dot_product_attention` | +| `multihead_attention(heads, query, key, value, mask)` | `Tensor` | `hmath_neural_layers_multihead_attention` | +| `causal_mask(queries, keys, offset)` | `[[Bool]]` | `hmath_neural_layers_causal_mask` | +| `rotary_embedding(base, offset, input)` | `Tensor` | `hmath_neural_layers_rotary_embedding` | +| `sinusoidal_encoding(length, dimensions, offset)` | `Tensor` | `hmath_neural_layers_sinusoidal_encoding` | +| `alibi_bias(slope, queries, keys, offset)` | `[[Double]]` | `hmath_neural_layers_alibi_bias` | +| `empty_cache(capacity, key_dimensions, value_dimensions)` | `KVCache` | `hmath_neural_layers_empty_cache` | +| `append_cache(cache, key, value)` | `KVCache` | `hmath_neural_layers_append_cache` | +| `cache_values(cache)` | `(Tensor,Tensor)` | `hmath_neural_layers_cache_values` | +| `transformer_feed_forward(activation, input, first_weights, first_bias, second_weights, second_bias)` | `Tensor` | `hmath_neural_layers_transformer_feed_forward` | +| `layer_norm_ad(axes, epsilon, input)` | `ADTensor` | `hmath_neural_layers_layer_norm_ad` | +| `rms_norm_ad(axes, epsilon, input)` | `ADTensor` | `hmath_neural_layers_rms_norm_ad` | +| `scaled_dot_product_attention_ad(query, key, value, mask)` | `ADTensor` | `hmath_neural_layers_scaled_dot_product_attention_ad` | + +#### `dropout(mode, probability, rng, input)` + +Inverted dropout. Inference consumes no random numbers. Return a separate multiplicative mask so its exact graph can be replayed by backpropagation. + +#### `spatial_dropout(mode, probability, rng, input)` + +Sample one inverted dropout mask per N,C pair and share it across every spatial position. + +#### `batch_norm(mode, momentum, epsilon, gamma, beta, state, input)` + +Population variance normalizes a training batch; unbiased sample variance updates runningVariance (a one-element batch uses population variance). + +#### `layer_norm(axes, epsilon, input)` + +Normalize the selected number of trailing axes independently for each remaining prefix index. + +#### `rms_norm(axes, epsilon, input)` + +Divide trailing-axis groups by sqrt(mean(x*x)+epsilon), without subtracting a mean. + +#### `instance_norm(epsilon, input)` + +Normalize spatial axes separately per batch/channel in N,C,spatial layout. + +#### `group_norm(groups, epsilon, input)` + +Normalize channels/spatial positions per batch and channel group; channel count must be divisible by groups. + +#### `weight_norm(axis, scales, input)` + +Normalize each selected-axis slice and multiply it by the matching explicit magnitude; zero directions fail. + +#### `initialize_weights(method, fan_in, fan_out, shape, rng)` + +Generate an immutable tensor and advanced RNG. Fans are explicit; orthogonal initialization requires a positive matrix shape. + +#### `embedding(weights, indices)` + +Gather checked row indices from [vocabulary,features] weights in requested order. + +#### `dense(input, weights, bias)` + +Apply x*transpose(weights)+bias to [batch,in] inputs and [out,in] weights. + +#### `dense_ad(input, weights, bias)` + +Symbolic dense layer with gradients through inputs, weights, and explicit bias expressions. + +#### `convolution(options, input, weights, bias)` + +Direct checked 1D/2D/3D cross-correlation with grouped channels and explicit stride/padding/dilation. + +#### `depthwise_convolution(options, input, weights, bias)` + +Set groups to input channels; output channel multipliers remain explicit in the weight shape. + +#### `convolution_ad(options, input, weights, bias)` + +Construct the same direct convolution from scalar graph arithmetic, with automatic input/kernel/bias gradients. + +#### `transposed_convolution(output_padding, options, input, weights, bias)` + +Direct adjoint-layout convolution; output padding is per-axis and strictly less than stride. + +#### `pooling(mode, kernel, stride, padding, input)` + +Windowed max/average pooling. Padded elements are excluded from the average; entirely padded windows fail. + +#### `adaptive_pooling(mode, shape, input)` + +Partition spatial axes by floor/ceil output-bin boundaries, then reduce each bin. + +#### `global_pooling(mode, input)` + +Reduce all spatial positions to one value per N,C pair. + +#### `scaled_dot_product_attention(query, key, value, mask, bias)` + +Return attended values and normalized weights for Q[N,D],K[M,D],V[M,F]; True masks permit keys. + +#### `multihead_attention(heads, query, key, value, mask)` + +Split feature dimension into equal heads, attend independently, concatenate. Projection matrices are explicit dense layers composed by the caller. + +#### `causal_mask(queries, keys, offset)` + +Build a query-by-key allowed mask, with an explicit cached-prefix offset. + +#### `rotary_embedding(base, offset, input)` + +Rotate adjacent feature pairs at sequence positions offset+i; feature dimension must be even. + +#### `sinusoidal_encoding(length, dimensions, offset)` + +Return [position,feature] sine/cosine positional encoding with base 10000. + +#### `alibi_bias(slope, queries, keys, offset)` + +Return nonpositive slope-scaled absolute position offsets; combine with a causal allowed mask if required. + +#### `empty_cache(capacity, key_dimensions, value_dimensions)` + +Create an owned immutable key/value cache with fixed positive capacity and feature widths. + +#### `append_cache(cache, key, value)` + +Append equal-length key/value sequences without truncating history; reject capacity or feature mismatches. + +#### `cache_values(cache)` + +Return immutable accumulated key/value tensors, preserving insertion order. + +#### `transformer_feed_forward(activation, input, first_weights, first_bias, second_weights, second_bias)` + +Compose dense, checked elementwise activation, and dense layers with explicit parameters. + +#### `layer_norm_ad(axes, epsilon, input)` + +Symbolic trailing-axis layer normalization. Affine gamma/beta can be composed with broadcast multiplication/addition in HMath.Autodiff. + +#### `rms_norm_ad(axes, epsilon, input)` + +Symbolic RMS normalization; its denominator includes all trailing axes. + +#### `scaled_dot_product_attention_ad(query, key, value, mask)` + +First-order reverse attention graph, including Q/K score and V gradients. Masks have the same True=allowed semantics as the checked numeric operation; a fully masked row is a constant zero graph and backpropagates exact zeros. + +### HMath.DeepLearning.Precision + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `Symmetric` | `Quantization` | `hmath_neural_precision_symmetric_create` | +| `Asymmetric` | `Quantization` | `hmath_neural_precision_asymmetric_create` | +| `quantize(scheme, axis, input)` | `QuantizedTensor` | `hmath_neural_precision_quantize` | +| `dequantize(quantized)` | `Tensor` | `hmath_neural_precision_dequantize` | +| `quantized_values(quantized)` | `[Int8]` | `hmath_neural_precision_quantized_values` | +| `quantization_scales(quantized)` | `[Double]` | `hmath_neural_precision_quantization_scales` | +| `quantization_zero_points(quantized)` | `[Int]` | `hmath_neural_precision_quantization_zero_points` | +| `int8_gemm(left, right)` | `Tensor` | `hmath_neural_precision_int8_gemm` | +| `FP16` | `Precision` | `hmath_neural_precision_fp16_create` | +| `BF16` | `Precision` | `hmath_neural_precision_bf16_create` | +| `reduced_gemm(precision, left, right)` | `Tensor` | `hmath_neural_precision_reduced_gemm` | +| `LossScaler(scale, growth_interval, finite_steps)` | `LossScaler` | `hmath_neural_precision_loss_scaler_create` | +| `loss_scale(state)` | `Double` | `hmath_neural_precision_loss_scale` | +| `scale_growth_interval(state)` | `Int` | `hmath_neural_precision_scale_growth_interval` | +| `finite_steps(state)` | `Int` | `hmath_neural_precision_finite_steps` | +| `initial_loss_scaler(scale, growth_interval)` | `LossScaler` | `hmath_neural_precision_initial_loss_scaler` | +| `scale_loss(state, loss)` | `Double` | `hmath_neural_precision_scale_loss` | +| `unscale_gradients(state, gradients)` | `(Bool,[Double])` | `hmath_neural_precision_unscale_gradients` | +| `update_loss_scaler(finite, state)` | `LossScaler` | `hmath_neural_precision_update_loss_scaler` | +| `gradient_norm(gradient)` | `Double` | `hmath_neural_precision_gradient_norm` | +| `clip_gradients(maximum, gradient)` | `[Double]` | `hmath_neural_precision_clip_gradients` | + +#### `quantize(scheme, axis, input)` + +Calibrate finite nonempty values per tensor or selected axis. Symmetric uses [-127,127], asymmetric [-128,127], with ties-to-even rounding. + +#### `dequantize(quantized)` + +Decode owned INT8 values using scale*(q-zeroPoint), rejecting floating arithmetic overflow. + +#### `quantized_values(quantized)` + +Return signed INT8 storage in logical row-major order. + +#### `quantization_scales(quantized)` + +Return one positive scale per calibrated channel, or a single per-tensor scale. + +#### `quantization_zero_points(quantized)` + +Return integer zero offsets under the selected symmetric/asymmetric calibration. + +#### `int8_gemm(left, right)` + +Multiply two INT8 matrices with exact integer accumulation; supports per-row A/per-column B or per-tensor scales. + +#### `reduced_gemm(precision, left, right)` + +Round operands to the chosen 16-bit format, accumulate in Float32, and return checked Double values. + +#### `initial_loss_scaler(scale, growth_interval)` + +Create a positive finite loss scale and positive growth interval; zero accumulated finite steps. + +#### `scale_loss(state, loss)` + +Multiply a finite loss by the checked current scale; overflow is a structured failure. + +#### `unscale_gradients(state, gradients)` + +False means overflow: every caller must skip the entire optimizer update. Gradients are returned only when every scaled gradient is finite. + +#### `update_loss_scaler(finite, state)` + +Halve scale after overflow; double after growthInterval finite updates, with a bounded maximum. + +#### `gradient_norm(gradient)` + +Compute a checked scaled Euclidean norm; unrepresentable final norms fail explicitly. + +#### `clip_gradients(maximum, gradient)` + +Clip norm through the shared overflow-safe automatic-differentiation gradient utility. + +### HMath.DeepLearning.Metrics + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `ClassificationMetrics(accuracy, precision, recall, f1)` | `ClassificationMetrics` | `hmath_neural_metrics_classification_metrics_create` | +| `accuracy(metrics)` | `Double` | `hmath_neural_metrics_accuracy` | +| `precision_by_class(metrics)` | `[Double]` | `hmath_neural_metrics_precision_by_class` | +| `recall_by_class(metrics)` | `[Double]` | `hmath_neural_metrics_recall_by_class` | +| `f1_by_class(metrics)` | `[Double]` | `hmath_neural_metrics_f1_by_class` | +| `confusion_matrix(classes, truth, prediction)` | `[[Int]]` | `hmath_neural_metrics_confusion_matrix` | +| `classification_metrics(classes, truth, prediction)` | `ClassificationMetrics` | `hmath_neural_metrics_classification_metrics` | +| `top_k_accuracy(k, truth, scores)` | `Double` | `hmath_neural_metrics_top_k_accuracy` | +| `roc_auc(truth, scores)` | `Double` | `hmath_neural_metrics_roc_auc` | +| `pr_auc(truth, scores)` | `Double` | `hmath_neural_metrics_pr_auc` | +| `perplexity(negative_log_probabilities)` | `Double` | `hmath_neural_metrics_perplexity` | +| `cosine_similarity_matrix(left, right)` | `Tensor` | `hmath_neural_metrics_cosine_similarity_matrix` | +| `margin_ranking_loss(margin, left, right, labels)` | `Double` | `hmath_neural_metrics_margin_ranking_loss` | + +#### `confusion_matrix(classes, truth, prediction)` + +Count [trueClass,predictedClass] pairs for a positive explicit class count. + +#### `classification_metrics(classes, truth, prediction)` + +Return accuracy and per-class precision, recall, and F1 with zero for undefined class denominators. + +#### `top_k_accuracy(k, truth, scores)` + +Measure whether truth lies among descending top-k scores; equal scores prefer the smaller class index. + +#### `roc_auc(truth, scores)` + +Compute the exact positive/negative rank-pair ROC area; both classes are required and ties count half. + +#### `pr_auc(truth, scores)` + +Integrate the precision-recall curve by grouped-score trapezoids, requiring at least one positive example. + +#### `perplexity(negative_log_probabilities)` + +Exponentiate the negative mean true-token log probability; empty or positive log probabilities fail. + +#### `cosine_similarity_matrix(left, right)` + +Compare every [M,D] row with every [N,D] row using scale-safe unit vectors; zero vectors fail. + +#### `margin_ranking_loss(margin, left, right, labels)` + +Mean hinge on signed (+/-1) pair ordering with a nonnegative finite margin. diff --git a/docs/reference/errors.md b/docs/reference/errors.md new file mode 100644 index 0000000..e7d7346 --- /dev/null +++ b/docs/reference/errors.md @@ -0,0 +1,110 @@ +# Structured mathematical errors + +Checked Haskell APIs return `Either MathError a`. The C ABI reports those +failures as `HMATH_MATH_ERROR` (status 11); Python raises `hmath.HMathError` with +the complete original value in its `.math_error` attribute. A transport failure +(such as a NULL pointer or allocation failure) has a different status and no +`MathError` payload. + +```python +from hmath import HMathError, errors, optimization + +try: + optimization.checked_gradient(lambda point: [], [1.0]) +except HMathError as failure: + error = failure.math_error + assert error.kind == errors.MathErrorKind.VECTOR_LENGTH_MISMATCH + assert error.details == (1, 0) +``` + +`hmath.errors.MathError(kind, details=(), message="")` stores the constructor, +its ordered integer fields and its full string payload. The named constructors +below provide the original argument grouping. Integer fields must fit Haskell +`Int` (`ptrdiff_t` in the supported C ABI); they are never converted through a +floating-point number. Shapes and matrix indices are `(rows, columns)` pairs, +and indices are zero based. + +| Python constructor | C `kind` constant | `details` in order | `message` | +| --- | --- | --- | --- | +| `NegativeDimensions(shape)` | `HMATH_MATH_NEGATIVE_DIMENSIONS` | rows, columns | empty | +| `ElementCountOverflow(shape)` | `HMATH_MATH_ELEMENT_COUNT_OVERFLOW` | rows, columns | empty | +| `ElementCountMismatch(expected, actual)` | `HMATH_MATH_ELEMENT_COUNT_MISMATCH` | expected, actual | empty | +| `ShapeMismatch(left, right)` | `HMATH_MATH_SHAPE_MISMATCH` | left rows, left columns, right rows, right columns | empty | +| `InnerDimensionMismatch(left_columns, right_rows)` | `HMATH_MATH_INNER_DIMENSION_MISMATCH` | left columns, right rows | empty | +| `IndexOutOfBounds(shape, index)` | `HMATH_MATH_INDEX_OUT_OF_BOUNDS` | shape rows, shape columns, row, column | empty | +| `SliceOutOfBounds(shape, start, extent)` | `HMATH_MATH_SLICE_OUT_OF_BOUNDS` | shape rows, shape columns, start row, start column, extent rows, extent columns | empty | +| `VectorLengthMismatch(expected, actual)` | `HMATH_MATH_VECTOR_LENGTH_MISMATCH` | expected, actual | empty | +| `NonSquareMatrix(shape)` | `HMATH_MATH_NON_SQUARE_MATRIX` | rows, columns | empty | +| `InvalidTolerance()` | `HMATH_MATH_INVALID_TOLERANCE` | none | empty | +| `SingularMatrix(index)` | `HMATH_MATH_SINGULAR_MATRIX` | pivot index | empty | +| `NearSingularMatrix(index)` | `HMATH_MATH_NEAR_SINGULAR_MATRIX` | pivot index | empty | +| `NonFiniteMatrixEntry(index)` | `HMATH_MATH_NON_FINITE_MATRIX_ENTRY` | row, column | empty | +| `NonFiniteVectorEntry(index)` | `HMATH_MATH_NON_FINITE_VECTOR_ENTRY` | index | empty | +| `NonFiniteResult()` | `HMATH_MATH_NON_FINITE_RESULT` | none | empty | +| `RightHandSideMismatch(expected, actual)` | `HMATH_MATH_RIGHT_HAND_SIDE_MISMATCH` | expected, actual | empty | +| `DomainError(message)` | `HMATH_MATH_DOMAIN_ERROR` | none | original string | +| `InvalidArgument(message)` | `HMATH_MATH_INVALID_ARGUMENT` | none | original string | +| `NonConvergence(algorithm, iterations)` | `HMATH_MATH_NON_CONVERGENCE` | iterations | algorithm string | +| `RankDeficient(rank)` | `HMATH_MATH_RANK_DEFICIENT` | rank | empty | +| `NotPositiveDefinite(index)` | `HMATH_MATH_NOT_POSITIVE_DEFINITE` | index | empty | + +The defining Haskell type is [MathError](haskell/HMath-Error.md#t:MathError). +The condition that produces each error remains the condition in the original +function. The adapter does not add finite-value checks or replace a solver's +own recovery decisions. + +## Checked callbacks + +Return the ordinary successful Python value from a checked callback. Raise one +of the constructors above to return an original Haskell `Left`: + +```python +from hmath import errors, optimization + + +def objective(point): + if point[0] <= 0: + raise errors.DomainError("positive point required") + return point[0] * point[0] + + +value = optimization.checked_value(objective, [2.0]) +``` + +A solver receives that `Left` and follows its original algorithm. For example, +feasible barrier backtracking can reject a `DomainError` trial and retry a +shorter step. Unexpected Python exceptions abort the call and are re-raised as +the same Python exception after native temporary objects are released. For a +source callback whose type is pure rather than `Either`, a raised `MathError` +becomes a checked failure at the outer ABI boundary. + +## C and C++ + +Include `hmath_error.h`. The transport is a fixed-layout record: + +```c +typedef struct hmath_math_error { + uint32_t kind; + ptrdiff_t details[6]; + const char *message; + size_t message_length; +} hmath_math_error; +``` + +Fill `kind`, the used `details` entries and the optional message when returning +`HMATH_MATH_ERROR` from a checked callback. The message buffer is borrowed until +the callback result is consumed. An explicit length preserves embedded NUL; +use UTF-8, with the surrogatepass/WTF-8 extension if transporting isolated +Haskell surrogate `Char` values. Unused fields are ignored for constructors +that have no corresponding source payload. Invalid constructor tags or invalid +encoded strings produce a transport failure. + +`int hmath_last_math_error(hmath_math_error *out)` returns 1 when the current +thread has a complete mathematical failure, otherwise 0. It is a query and +does not clear or consume the last error. Its message is borrowed library memory +until the next checked operation on that thread: copy it before another API +call. The library owns a full dynamic copy, including long strings; the short +human-readable `hmath_last_error()` message is not a substitute for this +structured payload. Successful checked operations and nonmathematical failures +clear the structured error. Thread exit and normal clearing release its storage +in C without calling the Haskell runtime. diff --git a/docs/reference/execution.md b/docs/reference/execution.md new file mode 100644 index 0000000..a0b6412 --- /dev/null +++ b/docs/reference/execution.md @@ -0,0 +1,143 @@ +# Buffer execution + +The execution API provides an explicit route for CPU matrix products on caller +buffers. Include `hmath_execution.h` in C/C++; in Python use +`from hmath import execution`. It supports binary32 and binary64 and row-major +matrices with consecutive columns and optional padding between rows. + +This API is separate from the original dense matrix and tensor interfaces. +It does not change their arithmetic, limits, finite checks or failure behavior. +It is not a claim that the complete `HMath.Backend` API has been bound. + +## Provider and resource selection + +`hmath_execution_create(options, &out)` constructs an immutable execution handle. +A NULL options pointer selects the reference implementation with no artificial +resource caps. Python uses `execution.Execution(...)`. + +| Option | Meaning | Default | +| --- | --- | --- | +| `provider` | `REFERENCE`, `OPENBLAS`, `BLIS`, `MKL`, or `ACCELERATE`; Python also accepts lowercase names | `REFERENCE` | +| `integer_bits` | BLAS integer ABI: 32 for LP64 or 64 for ILP64; zero selects LP64 in C | 32 | +| `library_path` | Optional explicit provider library path; incompatible ABIs are rejected | NULL / None | +| `max_elements` | Maximum logical element count of each A, B and C view | 0, no artificial cap | +| `max_multiply_adds` | Maximum m×n×k work count per call | 0, no artificial cap | + +A requested provider never silently falls back when unavailable. The reference +path does not require OpenBLAS or another BLAS installation. Single-precision +SGEMM is an optional provider capability: if missing, FP32 execution returns +`HMATH_UNSUPPORTED`; double-precision DGEMM can remain available. No conversion to +FP64 is used as a fallback. Existing `HMATH_BACKEND` provider policy also applies. + +Checked dimension products, byte spans, pointer ranges and allocation failures +remain active when resource policies are zero. Provider calls must also fit the +selected LP64/ILP64 integer ABI, including all leading dimensions. These caps +are policies for logical sizes/work, not a guarantee of a fixed process heap +budget. The reference Haskell implementation needs temporary lists/matrices; +provider execution passes buffers directly without numeric staging allocations. +The legacy tensor limits of 1,048,576 elements and 16,777,216 multiply-adds do +not apply to this new API. + +Execution handles own provider library references. C callers use +`hmath_execution_retain/release`; NULL retain/release is a no-op. Python callers +use `close()` or a `with` block. A handle alone does not pin the Haskell runtime, +but each numerical call reserves it until execution finishes. Each concurrent +caller must hold a live handle reference and use an independent output buffer. +Provider interface-layer settings must not be changed concurrently by external +code; this is particularly relevant to MKL's process-wide integer ABI. + +## Views and GEMM + +`hmath_execution_view` describes a readable input; `hmath_execution_output` +describes a writable output. Both contain: + +| Field | Contract | +| --- | --- | +| `data` | Pointer aligned for the selected float32/float64 type | +| `storage_count` | Readable/writable backing count in elements | +| `rows`, `columns` | Logical dimensions | +| `leading_dimension` | Distance between row starts in elements, at least `columns` for a nonempty matrix | + +Columns must be consecutive. Negative strides, column-strided layouts and +transposition are not supported by this entry point. Empty shapes preserve their +metadata and need no data pointer. For a nonempty view, the reachable span is +`(rows - 1) * leading_dimension + columns`; it is checked against the backing +count without overflowing. The caller guarantees that the actual allocation +matches the described span. Arbitrary addresses and allocations cannot be +validated by a C library. + +```c +hmath_status hmath_execution_gemm_f32( + hmath_execution *execution, hmath_context *context, + float alpha, const hmath_execution_view *a, + const hmath_execution_view *b, float beta, + const hmath_execution_output *c); + +hmath_status hmath_execution_gemm_f64( + hmath_execution *execution, hmath_context *context, + double alpha, const hmath_execution_view *a, + const hmath_execution_view *b, double beta, + const hmath_execution_output *c); +``` + +Both compute **C := αAB + βC**. A has shape m×k, B has shape k×n, and C must have +shape m×n. A and B may overlap each other; the complete reachable output span, +including padding between rows, must not overlap either input span. Padding is +preserved. Inputs and metadata are borrowed for the synchronous call and must +remain live and unchanged, including through aliases. + +Runtime initialization is required. A NULL context disables cancellation; +cancellation is checked before and after execution. An in-flight BLAS call is +not interrupted. + +The reference path uses the existing Haskell `Matrix.multiplyChecked`, +`scaleMatrix` and `addMatrixChecked` at the selected `Float`/`Double` precision. +Optimized providers execute SGEMM/DGEMM on the supplied pointers and may use a +different reduction or FMA order. Numerical results can therefore differ in their +last bits across providers; selecting an optimized provider is explicit. + +## Finite values and output on failure + +The finite-input policy matches the existing checked Haskell `Backend.gemm`: +α, β and every logical A/B/C element must be finite, **including initial C when +β = 0**. Padding values are not numerical inputs. `NonFiniteVectorEntry i` is +reported through `HMATH_MATH_ERROR` / Python `HMathError(status=11)`, with indices +in `[alpha,beta] ++ logical(A) ++ logical(B) ++ logical(C)`. Output errors index +logical C. Shape, byte-span, alias, resource-limit and provider errors are +binding-level status codes. + +Validation errors preserve C. Once a kernel starts, numeric failure or +cancellation may leave C modified. Direct-output execution is not transactional. +The reference path calculates and checks its result before copying to C; an +optimized provider writes C directly and a later finite check may fail. A +post-kernel cancellation can also report failure after C has been written. + +## Python buffers + +`Execution.gemm(a, b, out, *, alpha=1, beta=0)` borrows NumPy arrays and returns +the same `out` object. Arrays must have the same native-endian float32/float64 +dtype, aligned storage, consecutive columns and nonnegative row strides. +`out` must be writable. Padded rows are accepted without copying. Unsupported +layouts and mixed dtypes are rejected rather than silently converted. + +`Execution.matmul(a, b)` is a convenience method that allocates a zeroed output +of the input dtype, then executes GEMM. Use `gemm` with a reusable output to avoid +that allocation. NumPy is an optional Python dependency; the C execution API does +not depend on NumPy. + +```python +import numpy as np +from hmath import execution + +with execution.Execution("reference") as engine: + a = np.array([[1, 2], [3, 4]], dtype=np.float32) + b = np.array([[2, 0], [1, 2]], dtype=np.float32) + out = np.zeros((2, 2), dtype=np.float32) + assert engine.gemm(a, b, out) is out + assert out.dtype == np.float32 + assert out.tolist() == [[4.0, 4.0], [10.0, 8.0]] +``` + +See also: [dense matrix contracts](matrix-bindings.md), +[numerical conventions](../explanation/numerical-conventions.md), +[C runtime and errors](c.md). diff --git a/docs/reference/expression-bindings.md b/docs/reference/expression-bindings.md new file mode 100644 index 0000000..263ea80 --- /dev/null +++ b/docs/reference/expression-bindings.md @@ -0,0 +1,438 @@ +# Expression and symbolic bindings + +`hmath.expression` exposes the original positioned expression language from +`HMath.Expression`. `hmath.symbolic` re-exports that language and the original +bounded symbolic operations from `HMath.Symbolic`. C and C++ include +`hmath_expression.h`. These expression trees are distinct from automatic +differentiation's `hmath.autodiff.Expr`. + +```python +from fractions import Fraction +from hmath import expression as expr, symbolic + +limits = expr.default_limits() +with expr.default_registry() as registry: + with expr.parse_expression(limits, "let a = x+1 in a*a") as expression: + result = expr.evaluate_expression( + limits, + expr.ExactRational, + registry, + {"x": expr.ExactValue(Fraction(2, 3))}, + expression, + ) + assert result == expr.ExactValue(Fraction(25, 9)) + +with symbolic.no_assumptions() as assumptions: + options = symbolic.SymbolicOptions(limits, assumptions) + with expr.parse_expression(limits, "x^2+x") as expression: + with symbolic.differentiate(options, "x", expression) as derivative: + print(expr.pretty_expression(derivative)) +``` + +## Expression trees and positions + +`Expr(position, node)` preserves the original `SourcePos` and `ExprNode`. +`SourcePos(offset, line, column)` uses a zero-based character offset and +one-based source line/column; `unknown_position()` is `(0, 0, 0)`. +`expression_position` and `expression_node` are also available as `.position` +and `.node` properties. Parsed nodes retain their actual positions. Original +expression equality and ordering ignore positions and compare tree structure; +Python `Expr` comparisons call those original instances. + +Use the raw node constructors `Literal(rational)`, `Variable(name)`, +`Constant(named_constant)`, `Unary(operator, child)`, +`Binary(operator, left, right)`, `Call(name, arguments)`, +`Let(name, value, body)`. The smart expression builders `literal`, `variable`, +`constant`, `unary`, `binary`, `call`, `let_in` use unknown positions. Builders +remain unevaluated and do not add validation that the original builders lack. + +An `ExprNode`'s `.fields` property exposes its complete tagged payload. In C, +`hmath_expression_node_fields` returns the same tuple of shared Values: + +| Code | Constructor | Remaining fields | +| --- | --- | --- | +| 0 | `Literal` | exact Rational | +| 1 | `Variable` | original name | +| 2 | `Constant` | `NamedConstant` | +| 3 | `Unary` | `UnaryOp`, child `Expr` | +| 4 | `Binary` | `BinaryOp`, left `Expr`, right `Expr` | +| 5 | `Call` | name, list of argument `Expr` | +| 6 | `Let` | name, value `Expr`, body `Expr` | + +The operators are `Negate`; `Add`, `Subtract`, `Multiply`, `Divide`, `Power`; +and named constants `Pi`, `Euler`, `Tau`. Their type enums are `UnaryOp`, +`BinaryOp`, `NamedConstant`. Child expressions returned by inspection are +independently owned native handles, retaining their complete positions and +structure. Tree equality is separate from `symbolic.simplify_relation` and +other mathematical transformations. + +## Values, registries and resource budgets + +`ExactRational` and `Float64` select the original `Precision`. Results retain +original tags: `ExactValue(value)` contains a `fractions.Fraction`, while +`FloatValue(value)` contains a binary64 float. Exact arithmetic never passes +through Double. The expression language has no FP32 evaluation mode. Exact mode +rejects transcendental functions and irrational square roots with the original +errors instead of rounding them. Finite-value and domain checks remain inside +the original evaluator. + +`Bindings` accepts a dictionary or a list of `(name, Value)` pairs; later +duplicate names replace earlier ones, matching `Map.fromList`. Lexical `let` is +strict and scoped. Unreferenced external values are not mathematically checked +by the evaluator. `type_check_expression` returns the original precision mode; +it is separate from value-dependent evaluation. + +`empty_registry` and `default_registry` create immutable closed registries. +`register_function(name, builtin, registry)` adds an alias for a permitted +`Builtin`; it never accepts host code. `allowed_functions` returns the original +sorted names. Builtins are `Sin`, `Cos`, `Tan`, `Exp`, `Log`, `Sqrt`, `Abs`, +`Signum`, `Floor`, `Ceiling`, `Min`, `Max`, `Asin`, `Acos`, `Atan`, `Sinh`, `Cosh`, +`Tanh`. The registry is checked again when a compiled expression is evaluated. + +`Limits` and `default_limits()` contain the original independent budgets: + +| Field | Default | Original accepted range | +| --- | --- | --- | +| `maximum_steps` | 100000 | 1..10000000 | +| `maximum_depth` | 128 | 1..256 | +| `maximum_nodes` | 20000 | 1..100000 | +| `maximum_input_chars` | 100000 | 1..1000000 | +| `maximum_integer_bits` | 1024 | 2..8192 | +| `maximum_cache_entries` | 64 | 0..1024 | + +These are expression work/storage limits, rather than byte or wall-clock quotas. +`validate_limits` checks hard bounds; `validate_expression` checks the supplied +AST. Pure builders remain caller controlled. Compilation/CSE and evaluation +have separate fresh budgets. `cached_expression(limits, source, cache)` returns +`(compiled, next_cache)` without changing its input cache; cache hits retain +original validation and aggregate-storage checks. `compiled_node_count` and +`cache_size` expose the original counts. + +`serialize_expression` preserves original expression structure using its safe +constructor vocabulary. The source serialization intentionally omits positions; +`deserialize_expression` rebuilds nodes with generated unknown positions. +`expression_hash` is the original 64-bit FNV-1a over serialization Unicode code +points, not UTF-8 bytes. `pretty_expression`, `format_scientific`, `format_radix`, +`to_la_te_x` and `to_math_ml` call original renderers with original limits and +escaping rules. + +## Symbolic operations and explicit conditions + +`assumptions([(name, properties), ...])` validates and merges original variable +facts, rejecting contradictions. `no_assumptions()` supplies none. +`SymbolicOptions(limits, assumptions)` retains both inputs; +`default_symbolic_options()` returns original defaults. The properties are +`Real`, `NonZero`, `Positive`, `NonNegative`, `Integral`, `Negative`, +`NonPositive`. `proves(assumptions, property, expression)` is conservative: +`False` means unproved, rather than disproved. + +Normalization, simplification, expansion, collection, factoring, differentiation, +integration, limits and series call their original algorithms. They preserve +partial-function domains and do not discard unproved cancellation or branch +conditions. Unsupported operations return `ExprError(Unsupported, ...)`; there +is no hidden numerical substitute. The original implementation is a bounded +real reference CAS. For example, series orders remain 0..20, formal Rational +jets at most 64 coefficients, symbolic matrices 1..8 by 1..8, cofactor +determinants at most 6 by 6, and symbolic eigenvalues only order 1 or 2. + +`Any`, `Exactly`, `UnaryPattern`, `BinaryPattern`, `CallPattern` construct native +patterns. `.fields` (C `hmath_symbolic_pattern_fields`) returns constructor codes +0..4 in that order and each constructor's full payload. Repeated wildcard names +retain original structural matching. `RewriteRule(pattern, replacement, +requirements)` applies a caller assertion at the root with its original property +requirements. `substitute` preserves capture avoidance and lexical scope. + +`to_polynomial` and `from_polynomial` share exact Rational `Polynomial` objects +with [the polynomial API](polynomial.md). Formal series share its exact Rational +`PowerSeries` owners. No coefficient string approximation or FP64 conversion is +introduced. Exact roots include original multiplicities and residual expression; +numerical roots retain original complex binary64 results and failure conditions. + +The returned records/sums retain every source field: + +| Type | Payload | +| --- | --- | +| `PolynomialFactorization` | `leading`: exact Rational; `terms`: `(Expr, multiplicity)` pairs | +| `Series` | exact `center`, integer `minimum_power`, ordered `terms` expressions | +| `LimitResult` | `.name`: `FiniteLimit`, `PositiveInfinity`, `NegativeInfinity`, `DoesNotExist`; `.arguments` contains the Rational only for `FiniteLimit` | +| `Relation` | `operator`, `left`, `right`; operators `Equal`, `NotEqual`, `Less`, `LessEqual`, `Greater`, `GreaterEqual` | +| `RelationResult` | `Truth(bool)` or `Unresolved(Relation)`, retained in `.name`/`.arguments` | +| `LinearSolution` | `Inconsistent` or `ParametricSolution(bindings, free_variables)`; bindings retain original names and Expr values | +| `Guarded` | `value`, `conditions`: complete `(Expr, Property)` premises | + +`symbolic_eigenvalues` returns `Guarded` expressions with every required condition +intact. `guarded_value` and `required_conditions` expose original fields. The +polymorphic `Guarded` record constructor/selectors accept the shared Value +transport's representable payloads; the eigenvalue specialization is the +original `[Expr]`. Native constructors, selectors and transformations remain +available even when Python uses immutable dataclasses or tagged records to +represent those source values. + +## Positioned expression errors + +Expression failures use **`HMATH_EXPRESSION_ERROR` (status 12)**, separate from +`MathError`. Python raises `HMathError` whose `.expression_error` holds the +original `ExprError(kind, position, message)`; `.math_error` is `None`. +The kind is one of `SyntaxError`, `UnknownName`, `TypeMismatch`, `DomainFailure`, +`NonFinite`, `StepLimit`, `DepthLimit`, `MemoryLimit`, `InvalidLimits`, +`Unsupported`. Original zero-based offsets, one-based line/column and full +messages are retained. + +C `hmath_last_expression_error(out)` queries a `hmath_expression_error` record: +`kind` is the original 0..9 kind; `source_offset`, `source_line`, +`source_column` are `ptrdiff_t`; `message`/`message_length` are a complete +library-owned UTF-8 payload (surrogatepass/WTF-8 for isolated Haskell surrogates, +with embedded NUL supported by the explicit length). Copy the message before +another checked operation on that thread. Queries do not consume or clear the +error; successful checked operations and other failures clear it. Error storage +is thread local and released in C without runtime callbacks. Source error-record +constructors/selectors also preserve full String payloads through shared Values. + +## C representation and ownership + +All wrappers use `context` first, original source arguments in order, and +`hmath_value **out` last. Successful outputs own one reference; errors leave +output pointer storage untouched. Include [the shared Value API](values.md) +to create typed scalars, text, lists and tuples and inspect structural results. +Enums use `Index` values. Integer fields fit original Haskell `Int`; Word64 +hashes and Rational coefficients never pass through floating-point intermediates. + +| Native Value kind | Original object | +| --- | --- | +| 80 | `Expr` | +| 81 | `ExprNode` | +| 82 | `Registry` | +| 83 | `Compiled` | +| 84 | `ExpressionCache` | +| 85 | `Pattern` | +| 86 | `Assumptions` | +| 87 | `SymbolicMatrix` | + +Plain records are tuples in original constructor order. `SourcePos` is three +Int indices; `Limits` is six; `ExprError` is `(kind, position, text)`. +`ExactValue` and `FloatValue` are `(tag, scalar)`, with tags 0 and 1 respectively. +`SymbolicOptions`, `PolynomialFactorization`, `RewriteRule`, `Series`, `Relation`, +`Guarded` follow their field order above. `LimitResult` is `(0, Rational)` or a +one-element tuple `(1,)`, `(2,)`, `(3,)` for positive infinity, negative infinity, +does-not-exist. `RelationResult` is `(0, Bool)` or `(1, Relation)`; +`LinearSolution` is `(0,)` or `(1, bindings, free_variables)`. Native constructor +wrappers are provided for every case, so callers need not reproduce these +structural layouts manually. Lists and tuples remain distinct. + +Handles are immutable and can be shared while each user owns a live reference. +C releases them with `hmath_value_release`; Python uses `.close()`/context +managers. Records may contain handles: release every returned child expression, +pattern, assumptions or matrix reference, including those in lists or guarded +results. Python destructors are a fallback. A live handle reserves the Haskell +runtime, so final shutdown returns `HMATH_BUSY` until every reference is released. Releasing +the final reference must not race a call using that reference. There are no +asynchronous callbacks or dynamically registered host functions in this domain. + +## Named API mapping + +The tables give exact argument order, result representation and C wrapper. +The original [Expression reference](haskell/HMath-Expression.md) and +[Symbolic reference](haskell/HMath-Symbolic.md) document formulas and original +validation conditions for each function. + +### Expression + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `SourcePos(offset, line, column)` | `SourcePos` | `hmath_expression_source_pos_create` | +| `unknown_position()` | `SourcePos` | `hmath_expression_unknown_position` | +| `source_offset(position)` | `Int` | `hmath_expression_source_offset` | +| `source_line(position)` | `Int` | `hmath_expression_source_line` | +| `source_column(position)` | `Int` | `hmath_expression_source_column` | +| `Negate` | `UnaryOp` | `hmath_expression_negate_create` | +| `Add` | `BinaryOp` | `hmath_expression_add_create` | +| `Subtract` | `BinaryOp` | `hmath_expression_subtract_create` | +| `Multiply` | `BinaryOp` | `hmath_expression_multiply_create` | +| `Divide` | `BinaryOp` | `hmath_expression_divide_create` | +| `Power` | `BinaryOp` | `hmath_expression_power_create` | +| `Pi` | `NamedConstant` | `hmath_expression_pi_create` | +| `Euler` | `NamedConstant` | `hmath_expression_euler_create` | +| `Tau` | `NamedConstant` | `hmath_expression_tau_create` | +| `ExactRational` | `Precision` | `hmath_expression_exact_rational_create` | +| `Float64` | `Precision` | `hmath_expression_float64_create` | +| `SyntaxError` | `ErrorKind` | `hmath_expression_syntax_error_create` | +| `UnknownName` | `ErrorKind` | `hmath_expression_unknown_name_create` | +| `TypeMismatch` | `ErrorKind` | `hmath_expression_type_mismatch_create` | +| `DomainFailure` | `ErrorKind` | `hmath_expression_domain_failure_create` | +| `NonFinite` | `ErrorKind` | `hmath_expression_non_finite_create` | +| `StepLimit` | `ErrorKind` | `hmath_expression_step_limit_create` | +| `DepthLimit` | `ErrorKind` | `hmath_expression_depth_limit_create` | +| `MemoryLimit` | `ErrorKind` | `hmath_expression_memory_limit_create` | +| `InvalidLimits` | `ErrorKind` | `hmath_expression_invalid_limits_create` | +| `Unsupported` | `ErrorKind` | `hmath_expression_unsupported_create` | +| `Sin` | `Builtin` | `hmath_expression_sin_create` | +| `Cos` | `Builtin` | `hmath_expression_cos_create` | +| `Tan` | `Builtin` | `hmath_expression_tan_create` | +| `Exp` | `Builtin` | `hmath_expression_exp_create` | +| `Log` | `Builtin` | `hmath_expression_log_create` | +| `Sqrt` | `Builtin` | `hmath_expression_sqrt_create` | +| `Abs` | `Builtin` | `hmath_expression_abs_create` | +| `Signum` | `Builtin` | `hmath_expression_signum_create` | +| `Floor` | `Builtin` | `hmath_expression_floor_create` | +| `Ceiling` | `Builtin` | `hmath_expression_ceiling_create` | +| `Min` | `Builtin` | `hmath_expression_min_create` | +| `Max` | `Builtin` | `hmath_expression_max_create` | +| `Asin` | `Builtin` | `hmath_expression_asin_create` | +| `Acos` | `Builtin` | `hmath_expression_acos_create` | +| `Atan` | `Builtin` | `hmath_expression_atan_create` | +| `Sinh` | `Builtin` | `hmath_expression_sinh_create` | +| `Cosh` | `Builtin` | `hmath_expression_cosh_create` | +| `Tanh` | `Builtin` | `hmath_expression_tanh_create` | +| `Expr(position, node)` | `Expr` | `hmath_expression_expr_create` | +| `expression_position(expression)` | `SourcePos` | `hmath_expression_expression_position` | +| `expression_node(expression)` | `ExprNode` | `hmath_expression_expression_node` | +| `Literal(value)` | `ExprNode` | `hmath_expression_literal_create` | +| `Variable(name)` | `ExprNode` | `hmath_expression_variable_create` | +| `Constant(constant)` | `ExprNode` | `hmath_expression_constant_create` | +| `Unary(operator, child)` | `ExprNode` | `hmath_expression_unary_create` | +| `Binary(operator, left, right)` | `ExprNode` | `hmath_expression_binary_create` | +| `Call(name, arguments)` | `ExprNode` | `hmath_expression_call_create` | +| `Let(name, value, body)` | `ExprNode` | `hmath_expression_let_create` | +| `literal(value)` | `Expr` | `hmath_expression_literal` | +| `variable(name)` | `Expr` | `hmath_expression_variable` | +| `constant(constant)` | `Expr` | `hmath_expression_constant` | +| `unary(operator, child)` | `Expr` | `hmath_expression_unary` | +| `binary(operator, left, right)` | `Expr` | `hmath_expression_binary` | +| `call(name, arguments)` | `Expr` | `hmath_expression_call` | +| `let_in(name, value, body)` | `Expr` | `hmath_expression_let_in` | +| `Limits(maximum_steps, maximum_depth, maximum_nodes, maximum_input_chars, maximum_integer_bits, maximum_cache_entries)` | `Limits` | `hmath_expression_limits_create` | +| `default_limits()` | `Limits` | `hmath_expression_default_limits` | +| `maximum_steps(limits)` | `Int` | `hmath_expression_maximum_steps` | +| `maximum_depth(limits)` | `Int` | `hmath_expression_maximum_depth` | +| `maximum_nodes(limits)` | `Int` | `hmath_expression_maximum_nodes` | +| `maximum_input_chars(limits)` | `Int` | `hmath_expression_maximum_input_chars` | +| `maximum_integer_bits(limits)` | `Int` | `hmath_expression_maximum_integer_bits` | +| `maximum_cache_entries(limits)` | `Int` | `hmath_expression_maximum_cache_entries` | +| `ExprError(kind, position, message)` | `ExprError` | `hmath_expression_expr_error_create` | +| `error_kind(error)` | `ErrorKind` | `hmath_expression_error_kind_get` | +| `error_position(error)` | `SourcePos` | `hmath_expression_error_position` | +| `error_message(error)` | `String` | `hmath_expression_error_message` | +| `validate_limits(limits)` | `Unit` | `hmath_expression_validate_limits` | +| `validate_expression(limits, expression)` | `Unit` | `hmath_expression_validate_expression` | +| `parse_expression(limits, source)` | `Expr` | `hmath_expression_parse_expression` | +| `pretty_expression(expression)` | `String` | `hmath_expression_pretty_expression` | +| `free_variables(expression)` | `[String]` | `hmath_expression_free_variables` | +| `ExactValue(value)` | `ExpressionValue` | `hmath_expression_exact_value_create` | +| `FloatValue(value)` | `ExpressionValue` | `hmath_expression_float_value_create` | +| `default_registry()` | `Registry` | `hmath_expression_default_registry` | +| `empty_registry()` | `Registry` | `hmath_expression_empty_registry` | +| `register_function(name, builtin, registry)` | `Registry` | `hmath_expression_register_function` | +| `allowed_functions(registry)` | `[String]` | `hmath_expression_allowed_functions` | +| `type_check_expression(limits, precision, registry, bindings, expression)` | `Precision` | `hmath_expression_type_check_expression` | +| `evaluate_expression(limits, precision, registry, bindings, expression)` | `ExpressionValue` | `hmath_expression_evaluate_expression` | +| `evaluate_text(limits, precision, registry, bindings, source)` | `ExpressionValue` | `hmath_expression_evaluate_text` | +| `evaluate_compiled(limits, precision, registry, bindings, compiled)` | `ExpressionValue` | `hmath_expression_evaluate_compiled` | +| `compile_expression(limits, expression)` | `Compiled` | `hmath_expression_compile_expression` | +| `compiled_node_count(compiled)` | `Int` | `hmath_expression_compiled_node_count` | +| `optimize_expression(limits, precision, expression)` | `Expr` | `hmath_expression_optimize_expression` | +| `empty_expression_cache()` | `ExpressionCache` | `hmath_expression_empty_expression_cache` | +| `cache_size(cache)` | `Int` | `hmath_expression_cache_size` | +| `cached_expression(limits, source, cache)` | `(Compiled,ExpressionCache)` | `hmath_expression_cached_expression` | +| `format_scientific(digits, value)` | `String` | `hmath_expression_format_scientific` | +| `format_radix(radix, value)` | `String` | `hmath_expression_format_radix` | +| `serialize_expression(limits, expression)` | `String` | `hmath_expression_serialize_expression` | +| `deserialize_expression(limits, serialized)` | `Expr` | `hmath_expression_deserialize_expression` | +| `expression_hash(limits, expression)` | `Word64` | `hmath_expression_expression_hash` | + +### Symbolic + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `Real` | `Property` | `hmath_symbolic_real_create` | +| `NonZero` | `Property` | `hmath_symbolic_non_zero_create` | +| `Positive` | `Property` | `hmath_symbolic_positive_create` | +| `NonNegative` | `Property` | `hmath_symbolic_non_negative_create` | +| `Integral` | `Property` | `hmath_symbolic_integral_create` | +| `Negative` | `Property` | `hmath_symbolic_negative_create` | +| `NonPositive` | `Property` | `hmath_symbolic_non_positive_create` | +| `FromLeft` | `Direction` | `hmath_symbolic_from_left_create` | +| `FromRight` | `Direction` | `hmath_symbolic_from_right_create` | +| `TwoSided` | `Direction` | `hmath_symbolic_two_sided_create` | +| `Equal` | `RelationOp` | `hmath_symbolic_equal_create` | +| `NotEqual` | `RelationOp` | `hmath_symbolic_not_equal_create` | +| `Less` | `RelationOp` | `hmath_symbolic_less_create` | +| `LessEqual` | `RelationOp` | `hmath_symbolic_less_equal_create` | +| `Greater` | `RelationOp` | `hmath_symbolic_greater_create` | +| `GreaterEqual` | `RelationOp` | `hmath_symbolic_greater_equal_create` | +| `assumptions(entries)` | `Assumptions` | `hmath_symbolic_assumptions` | +| `no_assumptions()` | `Assumptions` | `hmath_symbolic_no_assumptions` | +| `proves(assumptions, property, expression)` | `Bool` | `hmath_symbolic_proves` | +| `SymbolicOptions(limits, assumptions)` | `SymbolicOptions` | `hmath_symbolic_symbolic_options_create` | +| `default_symbolic_options()` | `SymbolicOptions` | `hmath_symbolic_default_symbolic_options` | +| `symbolic_limits(options)` | `Limits` | `hmath_symbolic_symbolic_limits` | +| `symbolic_assumptions(options)` | `Assumptions` | `hmath_symbolic_symbolic_assumptions` | +| `normalize(options, expression)` | `Expr` | `hmath_symbolic_normalize` | +| `simplify(options, expression)` | `Expr` | `hmath_symbolic_simplify` | +| `expand(options, expression)` | `Expr` | `hmath_symbolic_expand` | +| `collect_terms(options, expression)` | `Expr` | `hmath_symbolic_collect_terms` | +| `trigonometric_simplify(options, expression)` | `Expr` | `hmath_symbolic_trigonometric_simplify` | +| `logarithmic_simplify(options, expression)` | `Expr` | `hmath_symbolic_logarithmic_simplify` | +| `factor_polynomial(options, variable, expression)` | `PolynomialFactorization` | `hmath_symbolic_factor_polynomial` | +| `rational_simplify(options, variable, expression)` | `Expr` | `hmath_symbolic_rational_simplify` | +| `differentiate(options, variable, expression)` | `Expr` | `hmath_symbolic_differentiate` | +| `integrate_basic(options, variable, expression)` | `Expr` | `hmath_symbolic_integrate_basic` | +| `to_polynomial(options, variable, expression)` | `Polynomial` | `hmath_symbolic_to_polynomial` | +| `exact_polynomial_roots(options, variable, expression)` | `([(Rational,Int)],Expr)` | `hmath_symbolic_exact_polynomial_roots` | +| `numerical_polynomial_roots(options, variable, expression)` | `[Complex]` | `hmath_symbolic_numerical_polynomial_roots` | +| `PolynomialFactorization(leading, terms)` | `PolynomialFactorization` | `hmath_symbolic_polynomial_factorization_create` | +| `factor_leading(factorization)` | `Rational` | `hmath_symbolic_factor_leading` | +| `factor_terms(factorization)` | `[(Expr,Int)]` | `hmath_symbolic_factor_terms` | +| `substitute(limits, bindings, expression)` | `Expr` | `hmath_symbolic_substitute` | +| `Any(name)` | `Pattern` | `hmath_symbolic_any_create` | +| `Exactly(expression)` | `Pattern` | `hmath_symbolic_exactly_create` | +| `UnaryPattern(operator, child)` | `Pattern` | `hmath_symbolic_unary_pattern_create` | +| `BinaryPattern(operator, left, right)` | `Pattern` | `hmath_symbolic_binary_pattern_create` | +| `CallPattern(name, arguments)` | `Pattern` | `hmath_symbolic_call_pattern_create` | +| `match_pattern(limits, pattern, expression)` | `Maybe[(String,Expr)]` | `hmath_symbolic_match_pattern` | +| `RewriteRule(pattern, replacement, requirements)` | `RewriteRule` | `hmath_symbolic_rewrite_rule_create` | +| `rewrite_pattern(rule)` | `Pattern` | `hmath_symbolic_rewrite_pattern` | +| `rewrite_replacement(rule)` | `Expr` | `hmath_symbolic_rewrite_replacement` | +| `rewrite_requirements(rule)` | `[(String,Property)]` | `hmath_symbolic_rewrite_requirements` | +| `apply_rewrite(options, rule, expression)` | `Expr` | `hmath_symbolic_apply_rewrite` | +| `gradient(options, variables, expression)` | `[Expr]` | `hmath_symbolic_gradient` | +| `hessian(options, variables, expression)` | `[[Expr]]` | `hmath_symbolic_hessian` | +| `jacobian(options, variables, expressions)` | `[[Expr]]` | `hmath_symbolic_jacobian` | +| `integrate_by_parts(options, variable, u, dv)` | `Expr` | `hmath_symbolic_integrate_by_parts` | +| `integrate_substitution(options, variable, temporary, inner, outer, integrand)` | `Expr` | `hmath_symbolic_integrate_substitution` | +| `integrate_rational(options, variable, numerator, denominator)` | `Expr` | `hmath_symbolic_integrate_rational` | +| `FiniteLimit(value)` | `LimitResult` | `hmath_symbolic_finite_limit_create` | +| `PositiveInfinity` | `LimitResult` | `hmath_symbolic_positive_infinity_create` | +| `NegativeInfinity` | `LimitResult` | `hmath_symbolic_negative_infinity_create` | +| `DoesNotExist` | `LimitResult` | `hmath_symbolic_does_not_exist_create` | +| `symbolic_limit(options, variable, center, direction, expression)` | `LimitResult` | `hmath_symbolic_symbolic_limit` | +| `Series(center, minimum_power, terms)` | `Series` | `hmath_symbolic_series_create` | +| `series_center(series)` | `Rational` | `hmath_symbolic_series_center` | +| `series_minimum_power(series)` | `Int` | `hmath_symbolic_series_minimum_power` | +| `series_terms(series)` | `[Expr]` | `hmath_symbolic_series_terms` | +| `taylor_series(options, variable, center, order, expression)` | `Series` | `hmath_symbolic_taylor_series` | +| `laurent_series(options, variable, center, order, expression)` | `Series` | `hmath_symbolic_laurent_series` | +| `maclaurin_series(options, variable, order, expression)` | `Series` | `hmath_symbolic_maclaurin_series` | +| `formal_power_series(options, coefficients)` | `PowerSeries` | `hmath_symbolic_formal_power_series` | +| `multiply_formal_series(options, left, right)` | `PowerSeries` | `hmath_symbolic_multiply_formal_series` | +| `reciprocal_formal_series(options, series)` | `PowerSeries` | `hmath_symbolic_reciprocal_formal_series` | +| `from_polynomial(variable, polynomial)` | `Expr` | `hmath_symbolic_from_polynomial` | +| `Relation(operator, left, right)` | `Relation` | `hmath_symbolic_relation_create` | +| `Truth(value)` | `RelationResult` | `hmath_symbolic_truth_create` | +| `Unresolved(relation)` | `RelationResult` | `hmath_symbolic_unresolved_create` | +| `simplify_relation(options, relation)` | `RelationResult` | `hmath_symbolic_simplify_relation` | +| `solve_linear_inequality(options, variable, relation)` | `RelationResult` | `hmath_symbolic_solve_linear_inequality` | +| `Inconsistent` | `LinearSolution` | `hmath_symbolic_inconsistent_create` | +| `ParametricSolution(bindings, free_variables)` | `LinearSolution` | `hmath_symbolic_parametric_solution_create` | +| `solve_linear_equations(options, variables, equations)` | `LinearSolution` | `hmath_symbolic_solve_linear_equations` | +| `symbolic_matrix(options, rows)` | `SymbolicMatrix` | `hmath_symbolic_symbolic_matrix` | +| `matrix_expressions(matrix)` | `[[Expr]]` | `hmath_symbolic_matrix_expressions` | +| `matrix_add(options, left, right)` | `SymbolicMatrix` | `hmath_symbolic_matrix_add` | +| `matrix_multiply(options, left, right)` | `SymbolicMatrix` | `hmath_symbolic_matrix_multiply` | +| `symbolic_determinant(options, matrix)` | `Expr` | `hmath_symbolic_symbolic_determinant` | +| `Guarded(value, conditions)` | `Guarded` | `hmath_symbolic_guarded_create` | +| `guarded_value(guarded)` | `Generic` | `hmath_symbolic_guarded_value` | +| `required_conditions(guarded)` | `[(Expr,Property)]` | `hmath_symbolic_required_conditions` | +| `symbolic_eigenvalues(options, matrix)` | `Guarded[Expr]` | `hmath_symbolic_symbolic_eigenvalues` | +| `numerical_substitution(options, precision, bindings, expression)` | `ExpressionValue` | `hmath_symbolic_numerical_substitution` | +| `to_la_te_x(limits, expression)` | `String` | `hmath_symbolic_to_la_te_x` | +| `to_math_ml(limits, expression)` | `String` | `hmath_symbolic_to_math_ml` | diff --git a/docs/reference/foundation.md b/docs/reference/foundation.md new file mode 100644 index 0000000..9442b95 --- /dev/null +++ b/docs/reference/foundation.md @@ -0,0 +1,808 @@ +# Foundation, discrete structures and convergence + +These functions call the original Haskell algorithms. Persistent heaps/multisets retain the actual original element ordering dictionary; exact integers, coefficient dtypes, strings, tuples and registered mathematical values are not converted through FP64. Sampling/combinatorial output limits, bit widths, logic depth/input caps, resource defaults and source error conventions remain unchanged. Objects own independent immutable references and support `close()`/context management. + +Generic checked callbacks use plain successful return values and raise a `MathError` to return source Left. Pure callbacks abort on failure. Unexpected Python exceptions are rethrown after native cleanup. Callback owners are retained transitively. Convergence reports retain their estimate even when iteration/stagnation limits stop execution; inspect `stop_reason` or use `require_convergence`. Generic Either results use explicit Left/Right owners; optional Just(None) is preserved as a Just owner. + +## Ordered element prototypes + +Ord operations infer an actual Haskell dictionary from the supplied values. For all-None or recursively empty inputs, supply an explicit `prototype=`; it selects a type without adding data to the source algorithm. C uses the corresponding `_typed` overload. `ordered_type(example)` retains a representative original Ord dictionary and `optional_type(prototype)` constructs the original `Ord (Maybe a)` dictionary, including nesting. Empty heaps/multisets normally defer their dictionary until the first element arrives. + +```python +from hmath import convergence, datastructure + +with convergence.optional_type(0) as optional_integer: + with datastructure.heap_from_list([None, None], prototype=optional_integer) as heap: + first, remaining = datastructure.heap_pop(heap) + assert first is None + remaining.close() +``` + +`None` represents Nothing; `convergence.just(None)` distinguishes Just Nothing when optional layers nest. Generic Either values retain explicit Left/Right via `left`, `right`, and `.parts`. Prototypes and every returned owner support `close()`/context management. Equality-dependent grouping uses original dictionaries for supported scalar/recursive values, Foundation records, Polynomial/PowerSeries/RationalFunction, numeric/Bool/String/Exact Matrix and Tensor, and original AD.Dual full-field equality. NaNs and tensor views retain their source equality behavior. This finite transport does not invent Eq/Ord for arbitrary custom Haskell types. + +## `datastructure.fenwick` + +Build an immutable Fenwick prefix-sum tree from at most 1048576 Integers. Oversized input fails; indices in public operations are zero based. + +Original signature: `[Integer] -> Either MathError Fenwick`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.fenwick_add` + +Given zero-based index,delta,then Fenwick tree, return a new tree with that value incremented. Invalid index returns Left InvalidArgument. + +Original signature: `Int -> Integer -> Fenwick -> Either MathError Fenwick`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.fenwick_prefix` + +Given exclusive end then tree, return exact sum over [0,end). Require 0\<=end\<=length; invalid bounds fail. + +Original signature: `Int -> Fenwick -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.fenwick_range` + +Given lo,hi,then tree, return exact half-open sum over [lo,hi). Invalid/reversed bounds fail; empty range gives zero. + +Original signature: `Int -> Int -> Fenwick -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.segment_tree` + +Build an immutable Integer sum segment tree from at most 1048576 values. Invalid size fails; later queries use half-open bounds. + +Original signature: `[Integer] -> Either MathError SegmentTree`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.segment_set` + +Given zero-based index,new Integer,then segment tree, return an updated tree. Invalid index fails; the original remains unchanged. + +Original signature: `Int -> Integer -> SegmentTree -> Either MathError SegmentTree`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.segment_range` + +Given lo,hi,then segment tree, return Integer sum over [lo,hi). Invalid bounds fail; an empty range gives zero. + +Original signature: `Int -> Int -> SegmentTree -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.sparse_table` + +Precompute range minima for at most 1048576 Integers. Return immutable sparse table; oversized input fails. + +Original signature: `[Integer] -> Either MathError SparseTable`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.sparse_minimum` + +Given lo,hi,then sparse table, return minimum over nonempty [lo,hi). Out-of-range/reversed or empty bounds fail. + +Original signature: `Int -> Int -> SparseTable -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.disjoint_sparse_table` + +Suffix/prefix blocks for associative integer addition, O(n log n) build and O(1) arithmetic for nonempty queries. Also handles an empty range as zero. + +Original signature: `[Integer] -> Either MathError DisjointSparseTable`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.disjoint_range` + +Given lo,hi,then disjoint sparse sum table, return exact sum over [lo,hi). Invalid bounds fail; empty range yields zero. + +Original signature: `Int -> Int -> DisjointSparseTable -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.next_greater` + +For each list position, return Maybe index of its first strictly greater element to the right, using a monotone stack. Preserve input length; absent successors yield Nothing. + +Original signature: `[a] -> [Maybe Int]`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.empty_heap` + +Construct an empty persistent leftist min-heap. heapPop returns Nothing until values are inserted. + +Original signature: `Heap a`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.heap_insert` + +Given value then persistent min-heap, return a new heap containing it. Duplicate values are retained; original heap remains valid. + +Original signature: `a -> Heap a -> Heap a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.heap_pop` + +Return Nothing for empty heap, otherwise Just (smallest value,remaining heap). Ties follow lawful Ord without discarding duplicates. + +Original signature: `Heap a -> Maybe (a, Heap a)`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.heap_from_list` + +Build a persistent min-heap from a finite list, retaining all elements including duplicates. + +Original signature: `[a] -> Heap a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.binary_heap` + +Build an array-backed Integer min-heap from at most 1048576 values. Oversized input fails. + +Original signature: `[Integer] -> Either MathError BinaryHeap`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.binary_insert` + +Given Integer then binary heap, return a persistent updated min-heap. The insert operation itself has no Either size check. + +Original signature: `Integer -> BinaryHeap -> BinaryHeap`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.binary_pop` + +Return Nothing if empty, otherwise the smallest Integer and a new binary heap containing the remaining values. + +Original signature: `BinaryHeap -> Maybe (Integer, BinaryHeap)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.indexed_heap` + +Construct an empty indexed priority queue. Each Int key has at most one Integer priority. + +Original signature: `IndexedHeap`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.indexed_set` + +Given Int key,Integer priority,then indexed heap, set or replace that key's priority. Return a new queue; an existing key is updated, not duplicated. + +Original signature: `Int -> Integer -> IndexedHeap -> IndexedHeap`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.indexed_pop` + +Return Just ((key,priority),remaining queue) for the minimum (priority,key) pair, or Nothing if empty. + +Original signature: `IndexedHeap -> Maybe ((Int, Integer), IndexedHeap)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.union_find` + +Construct disjoint singleton sets for n zero-based elements, requiring n in [0,1048576]. Invalid size fails. + +Original signature: `Int -> Either MathError UnionFind`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.find_root` + +Given element index then union-find structure, return representative root. Invalid index fails; this pure query does not mutate/compress the stored structure. + +Original signature: `Int -> UnionFind -> Either MathError Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.union` + +Given two valid indices then union-find, return a new structure merging their components by size. Invalid indices fail; already connected inputs leave connectivity unchanged. + +Original signature: `Int -> Int -> UnionFind -> Either MathError UnionFind`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.connected` + +Given two indices then union-find, return whether their roots match. Invalid indices return Left InvalidArgument. + +Original signature: `Int -> Int -> UnionFind -> Either MathError Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.components` + +Return all disjoint components as lists of zero-based element indices, including singleton sets. + +Original signature: `UnionFind -> [[Int]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.bloom` + +Given bit count m in [1,1048576] then hash count k in [1,64], construct an empty Bloom filter. Invalid dimensions fail. + +Original signature: `Int -> Int -> Either MathError Bloom`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.bloom_insert` + +Given Word64 key then Bloom filter, set its k hash positions and return updated filter. Reinsertions are permitted; false positives remain possible. + +Original signature: `Word64 -> Bloom -> Bloom`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.bloom_member` + +Test a Word64 key against all Bloom hash positions. False means definitely absent; True may be a false positive under the documented hash model. + +Original signature: `Word64 -> Bloom -> Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.bloom_false_positive_bound` + +Conservative union bound `min(1,k*n/m)^k` under independent uniform query hashes, since at most k*n bits can be occupied. This is a bound rather than the common exponential occupancy approximation. + +Original signature: `Bloom -> Double`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.count_min` + +Given positive width and depth with product\<=1048576, construct an empty count-min sketch. Invalid dimensions fail. + +Original signature: `Int -> Int -> Either MathError CountMin`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.count_min_add` + +Given Word64 key,nonnegative Integer increment,then sketch, increment its hash counters. Negative updates fail; return a persistent updated sketch. + +Original signature: `Word64 -> Integer -> CountMin -> Either MathError CountMin`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.count_min_estimate` + +Given Word64 key then sketch, return minimum associated counter as an Integer frequency estimate. It may overestimate through collisions; use countMinErrorBound for the documented model. + +Original signature: `Word64 -> CountMin -> Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.count_min_error_bound` + +`(additive error, failure probability)` under the uniform-hash model. + +Original signature: `CountMin -> (Double, Double)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.hyper_log_log` + +Construct an empty cardinality sketch from precision p in [4,16], using 2^p registers. Invalid precision fails; hllEstimate returns its probabilistic estimate. + +Original signature: `Int -> Either MathError HyperLogLog`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.hll_add` + +Given Word64 item then HyperLogLog sketch, hash and update its register maximum. Return persistent updated sketch; repeated items do not add a new exact count. + +Original signature: `Word64 -> HyperLogLog -> HyperLogLog`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.hll_estimate` + +HyperLogLog with linear-counting small-range correction. Typical relative standard error is approximately `1.04/sqrt(2^p)` under uniform hashing. + +Original signature: `HyperLogLog -> Double`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.reservoir` + +Given sample capacity in [0,1048576] then Word64 seed, construct an empty deterministic Algorithm-R reservoir. Invalid capacity fails. + +Original signature: `Int -> Word64 -> Either MathError (Reservoir a)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.reservoir_add` + +Algorithm R with rejection sampling (no modulo bias). The 64-bit stream index is bounded; uniform sampling assumes the pseudorandom stream model. + +Original signature: `a -> Reservoir a -> Either MathError (Reservoir a)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.reservoir_values` + +Return retained reservoir sample values. Their count never exceeds capacity; output order is storage order, not a sorted or arrival-order guarantee. + +Original signature: `Reservoir a -> [a]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.online_quantiles` + +Given exact-storage cap in [0,1048576], create an empty online order-statistics container. Invalid capacity fails; this retains exact values rather than a bounded-memory approximate sketch. + +Original signature: `Int -> Either MathError OnlineQuantiles`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.quantile_add` + +Given finite Double then quantile container, insert in sorted order. Non-finite values or a full cap fail without eviction; original container is unchanged. + +Original signature: `Double -> OnlineQuantiles -> Either MathError OnlineQuantiles`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `datastructure.online_quantile` + +Given finite q in [0,1] then nonempty quantile container, linearly interpolate order statistics at q*(n-1). Invalid q or empty state returns Left InvalidArgument. + +Original signature: `Double -> OnlineQuantiles -> Either MathError Double`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset` + +Construct a finite multiset by counting equal ordered values with exact nonnegative Integer multiplicities. + +Original signature: `[a] -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiplicity` + +Given value then multiset, return its Integer frequency, or zero when absent. + +Original signature: `a -> MultiSet a -> Integer`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_entries` + +Return (value,positive multiplicity) pairs in ascending value order. + +Original signature: `MultiSet a -> [(a, Integer)]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_insert` + +Given value then multiset, increment its multiplicity by one and return a new multiset. + +Original signature: `a -> MultiSet a -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_delete` + +Given value then multiset, remove one occurrence, deleting its entry at zero. Absent values are a no-op. + +Original signature: `a -> MultiSet a -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_union` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `MultiSet a -> MultiSet a -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_intersection` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `MultiSet a -> MultiSet a -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.multiset_difference` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `MultiSet a -> MultiSet a -> MultiSet a`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_set` + +Given width in [0,1048576] then nonnegative Integer less than 2^width, construct an opaque bitset. Invalid width/value fails; bit zero is least significant. + +Original signature: `Int -> Integer -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_width` + +Return declared number of bits, including leading zeros. + +Original signature: `BitSet -> Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_value` + +Return unsigned Integer value of all bits within the declared width. + +Original signature: `BitSet -> Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_member` + +Given bitset then zero-based bit index, return membership. Out-of-width or negative indices return Left InvalidArgument. + +Original signature: `BitSet -> Int -> Either MathError Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_insert` + +Given bitset then valid bit index, return a new bitset with that bit set. Invalid index fails. + +Original signature: `BitSet -> Int -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_delete` + +Given bitset then valid bit index, return a new bitset with that bit cleared. Invalid index fails. + +Original signature: `BitSet -> Int -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_union` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `BitSet -> BitSet -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_intersection` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `BitSet -> BitSet -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.bit_difference` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `BitSet -> BitSet -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.resize_bit_set` + +Shrinking explicitly discards high bits. + +Original signature: `Int -> BitSet -> Either MathError BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.population_count` + +Count set bits within declared width, returning Int. + +Original signature: `BitSet -> Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.leading_zeros` + +Count high-end zero bits within declared width. All-zero bitset returns its full width. + +Original signature: `BitSet -> Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.trailing_zeros` + +Count low-end zero bits; an all-zero bitset returns its declared width. + +Original signature: `BitSet -> Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.rotate_bits` + +Given signed rotation count then bitset, rotate left modulo width (negative counts rotate right). Width-zero input is unchanged. + +Original signature: `Int -> BitSet -> BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.reverse_bits` + +Reverse exactly the declared width of bits, preserving width and leading/trailing zero positions. + +Original signature: `BitSet -> BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.gray_encode` + +Return width-preserving reflected Gray code v xor (v shifted right one). + +Original signature: `BitSet -> BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.gray_decode` + +Decode reflected Gray bits to the corresponding width-preserving binary value. + +Original signature: `BitSet -> BitSet`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.hamming_distance` + +Count differing bit positions between equal-width bitsets. Different widths return Left InvalidArgument. + +Original signature: `BitSet -> BitSet -> Either MathError Int`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.transitive_closure` + +Warshall closure. Paths must have positive length; use 'equivalenceClosure' when a reflexive closure is wanted. + +Original signature: `[[Bool]] -> Either MathError [[Bool]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.equivalence_closure` + +Given square Bool relation matrix, add reflexivity and symmetry then compute transitive closure. Reject nonsquare or oversized (>512) relations. + +Original signature: `[[Bool]] -> Either MathError [[Bool]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.is_equivalence` + +Return whether a bounded square Bool relation is already reflexive, symmetric and transitive. Invalid matrix shape/size fails. + +Original signature: `[[Bool]] -> Either MathError Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.boolean_multiply` + +Multiply compatible square Bool relation matrices over OR/AND, representing relational composition. Invalid dimensions or size bounds fail. + +Original signature: `[[Bool]] -> [[Bool]] -> Either MathError [[Bool]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.evaluate_prop` + +Given variable Bool assignment list then proposition, evaluate literals/variables/connectives. Invalid variable index or excessive expression depth returns Left MathError. + +Original signature: `[Bool] -> Prop -> Either MathError Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.truth_table` + +Assignments in binary order, variable zero the least-significant bit. + +Original signature: `Int -> Prop -> Either MathError [([Bool], Bool)]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.implicant_covers` + +Given implicant then Integer minterm, compare bits where implicantMask is clear. True means this Boolean cube covers the minterm. + +Original signature: `Implicant -> Integer -> Bool`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.quine_mc_cluskey` + +Exact Quine--McCluskey prime generation followed by branch-and-bound cover selection. Objective is fewest terms, then literals, then lexical order. The explicit budget counts prime comparisons and covering-search nodes. + +Original signature: `Int -> Int -> [Integer] -> [Integer] -> Either MathError [Implicant]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.literal` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.variable` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.logical_not` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.logical_and` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.logical_or` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.xor` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.implies` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.iff` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.implicant_value` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Implicant -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.implicant_mask` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Implicant -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `discrete.Implicant` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.binary_search` + +Given target and ascending list, return Just the first matching zero-based index or Nothing if absent. Reject unsorted input. Example: binarySearch 2 [1,2,2] == Right (Just 1). + +Original signature: `a -> [a] -> Either MathError (Maybe Int)`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.interpolation_search` + +Search ascending Integer values using value-based interpolation, returning the first matching index or Nothing. Reject unsorted input. Example: interpolationSearch 20 [10,20,30] == Right (Just 1). + +Original signature: `Integer -> [Integer] -> Either MathError (Maybe Int)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.exponential_search` + +Given a target and ascending finite list, grow a search range then find a matching index or Nothing. Reject unsorted input. The implementation returns a matching index without a general first-duplicate guarantee. + +Original signature: `a -> [a] -> Either MathError (Maybe Int)`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.ternary_search` + +Fixed-iteration minimization of a unimodal finite function on [lo,hi]. Returns the final bracket; unimodality is a caller precondition. + +Original signature: `Int -> (Double -> Double) -> Double -> Double -> Either MathError (Double, Double)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.numeric_groups` + +Sort ascending and return each distinct value paired with its frequency. Example: numericGroups [2,1,2] == [(1,1),(2,2)]. + +Original signature: `[a] -> [(a, Int)]`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.run_length_encode` + +Encode adjacent equal runs as (value,count), preserving run order without sorting. Example: runLengthEncode [1,1,2,1] == [(1,2),(2,1),(1,1)]. + +Original signature: `[a] -> [(a, Int)]`. Constraints: `(Eq a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.run_length_decode` + +Given maximum output length then (value,count) runs, expand runs. Negative budget/count fails; output beyond the budget returns NonConvergence before allocation. Zero-length runs are allowed. + +Original signature: `Int -> [(a, Int)] -> Either MathError [a]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.coordinate_compression` + +Return sorted unique keys and zero-based ranks for the original input order. Example: coordinateCompression [8,2,8] == ([2,8],[1,0,1]). + +Original signature: `[a] -> ([a], [Int])`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.interval_sweep` + +Half-open interval union length and peak overlap; zero-length intervals contribute neither. End events precede starts at the same coordinate. + +Original signature: `[(Integer, Integer)] -> Either MathError (Integer, Int)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.divide_conquer_dp` + +One DP layer `next[j] = min_{0<=k (Int -> Int -> Double) -> Either MathError [Double]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.tabulate_dp` + +Bottom-up bounded DAG recurrence; dependencies must have lower indices. + +Original signature: `Int -> (Int -> [(Int, Integer)]) -> Either MathError [Integer]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.memoized_dp` + +Top-down memoization with a node budget. Recurrence supplies an additive constant and weighted dependencies; cycles are rejected. + +Original signature: `Int -> (Int -> (Integer, [(Int, Integer)])) -> Int -> Either MathError Integer`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `algorithms.integer_matrix_power` + +Given square Integer rows and a nonnegative exponent, return exact matrix exponentiation by squaring; exponent zero returns identity. Reject ragged/non-square matrices, order >128, or negative exponent. + +Original signature: `[[Integer]] -> Integer -> Either MathError [[Integer]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.permutations_of` + +Distinct positions, including when values compare equal. + +Original signature: `Int -> Int -> [a] -> Either MathError [[a]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.combinations_of` + +Given output budget, selection length k, then list, enumerate position-distinct k-element combinations in source order. Invalid order or insufficient budget fails before output construction. + +Original signature: `Int -> Int -> [a] -> Either MathError [[a]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.derangements` + +Enumeration uses the factorial upper bound, so a request may be rejected even if its filtered derangement output would fit. + +Original signature: `Int -> Int -> Either MathError [[Int]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.integer_partitions` + +Nonincreasing positive parts. The budget counts search nodes as well as outputs, preventing long searches with a tiny output limit. + +Original signature: `Int -> Int -> Either MathError [[Int]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.set_partitions` + +Set partitions of `[0,n)`, using restricted-growth order of block labels. + +Original signature: `Int -> Int -> Either MathError [[[Int]]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.pascal_triangle` + +Return Pascal rows zero through n inclusive, starting [[1]]. n must lie in [0,512]; invalid orders fail. + +Original signature: `Int -> Either MathError [[Integer]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.subsets` + +Given maximum output count then list, enumerate its position-based powerset. Reject input order >4096 or a budget smaller than 2^length. Equal input values can yield equal-valued subsets. + +Original signature: `Int -> [a] -> Either MathError [[a]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.cartesian_product` + +Given output budget then a list of lists, return all ordered choices using sequence. Reject negative/insufficient budget before constructing results. Empty outer list yields one empty choice. + +Original signature: `Int -> [[a]] -> Either MathError [[a]]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.multiset_permutations` + +Given budget then ordered values, enumerate distinct multiset permutations in ascending lexicographic order. Invalid size or insufficient output budget fails before enumeration. + +Original signature: `Int -> [a] -> Either MathError [[a]]`. Constraints: `(Ord a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.generating_coefficients` + +Formal power-series division `P(x)/Q(x)` around zero, exact rationals. The denominator constant must be nonzero; no analytic convergence is claimed. + +Original signature: `Int -> [Rational] -> [Rational] -> Either MathError [Rational]`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `combinatorics.finite_differences` + +Return successive forward-difference rows beginning with the original list and ending at the last singleton. Empty input yields no rows. Example: finiteDifferences [1,4,9] == [[1,4,9],[3,5],[2]]. + +Original signature: `[a] -> [[a]]`. Constraints: `(Num a)`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.default_iteration_options` + +Default iteration budget 1000, absolute tolerance 1e-12, relative tolerance 1e-10. Use record updates to configure a solver; iterateUntil validates nonnegative finite tolerances. + +Original signature: `IterationOptions`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.iterate_until` + +Stop at residual <= atol + rtol * initialResidual. Comparisons are scaled to avoid overflow in that sum. The initial value is tested at iteration zero. + +Original signature: `IterationOptions -> (a -> Either MathError a) -> (a -> Either MathError Double) -> (a -> a -> Bool) -> a -> Either MathError (Convergence a)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.require_convergence` + +Given operation name then convergence report, return its estimate only for ResidualSatisfied. IterationLimit or Stagnation becomes Left (NonConvergence name iterationCount), preserving the distinction between execution and convergence. + +Original signature: `String -> Convergence a -> Either MathError a`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.result_maybe` + +Explicitly discard error details for callers retaining a Maybe interface. + +Original signature: `Either e a -> Maybe a`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.from_maybe_error` + +Given error value then Maybe result, convert Nothing to Left error and Just x to Right x. Example: fromMaybeError "missing" (Just 3) == Right 3. + +Original signature: `e -> Maybe a -> Either e a`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.residual_satisfied` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.iteration_limit` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.stagnation` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.estimate` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Convergence -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.iteration_count` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Convergence -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.final_residual` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Convergence -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.stop_reason` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Convergence -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.Convergence` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.maximum_iterations` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterationOptions -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.absolute_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterationOptions -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.relative_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterationOptions -> field`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.IterationOptions` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + +## `convergence.converged` + +Read-only successful view. The report still retains its residual and count. + +Original signature: `Convergence a -> Maybe a (read-only source pattern)`. Constraints: `none`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched. + diff --git a/docs/reference/geometry-bindings.md b/docs/reference/geometry-bindings.md new file mode 100644 index 0000000..94bfe84 --- /dev/null +++ b/docs/reference/geometry-bindings.md @@ -0,0 +1,1778 @@ +# Geometry bindings + +`from hmath import geometry` calls the original checked geometry algorithms. C includes `hmath_geometry.h`. Coordinates retain their finite1e50 cap, ND dimension1..16 bounds, exact Rational orientation/incircle predicates, source algorithm budgets, tie order and Double outputs. Raw public constructors retain their unchecked behavior; checked operations validate them without adapter changes. + +Objects are immutable owned [structured values](values.md); inputs are borrowed for a synchronous call and success transfers one output reference. Outputs stay untouched on failure. Each live owner pins the runtime. Independent readers retain their own references; original MathError/status11 includes its complete constructor and payload. Cancellation is checked before entry. + +Use `parts(value)` or `value.parts` for a public data constructor: it returns `(constructor_name, tuple_of_fields)` with typed child owners. A child remains valid after its parent closes. `value.coordinates` returns coordinates for Point2/Point3/PointND. Abstract PointCloud/SpatialIndex remain abstract; their original query functions are available. `describe(value)` exposes the original Show representation for inspection, without parsing or dispatching mathematics through text. + +`line_plane_intersection` and `plane_intersection` return `(outer_present, inner_optional)`: `(False, None)` is no intersection, `(True, None)` is coincidence, `(True, value)` is one intersection. This preserves all three source `Maybe (Maybe a)` states. `incircle` returns `Ordering.LT/EQ/GT` (C Haskell-Int values -1/0/1). Indexed triangles remain tuples of three zero-based original input indices. Matrix operations exchange actual shared `Matrix Double` objects. + +Polygon Boolean rings retain exterior/hole orientation. Constraints in Delaunay triangulation do not become a polygon/hole specification. Nearest-neighbor results keep original IDs, distance/ID tie order and explicit budget/exhaustive fields. Collision/penetration error estimates retain their source meaning; transforms retain the documented OpenGL depth conventions. + +The existing hamming/jaccard compatibility functions expose Float/Double numeric variants; they do not claim arbitrary user-defined Haskell Eq instances. + +## `penetration` + +`geometry.penetration(number, point2, number2, count)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Point2 -> Double -> Int -> Penetration +``` + +```c +hmath_status hmath_geometry_penetration(hmath_context *context, const hmath_value *number, const hmath_value *point2, const hmath_value *number2, const hmath_value *count, hmath_value **out); +``` + +## `epa` + +`geometry.epa(count, number, values, values2)` + + Expanding polytope penetration estimate. The tolerance is an absolute support-gap stopping threshold, positive finite and <=1e50. + +```haskell +Int -> Double -> [Point2] -> [Point2] -> Either MathError (Maybe Penetration) +``` + +```c +hmath_status hmath_geometry_epa(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `gjk` + +`geometry.gjk(count, values, values2)` + +Convex intersection by Gilbert-Johnson-Keerthi support/simplex iterations. + +```haskell +Int -> [Point2] -> [Point2] -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_gjk(hmath_context *context, const hmath_value *count, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `penetration_depth` + +`geometry.penetration_depth(penetration)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Penetration -> Double +``` + +```c +hmath_status hmath_geometry_penetration_depth(hmath_context *context, const hmath_value *penetration, hmath_value **out); +``` + +## `penetration_error` + +`geometry.penetration_error(penetration)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Penetration -> Double +``` + +```c +hmath_status hmath_geometry_penetration_error(hmath_context *context, const hmath_value *penetration, hmath_value **out); +``` + +## `penetration_iterations` + +`geometry.penetration_iterations(penetration)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Penetration -> Int +``` + +```c +hmath_status hmath_geometry_penetration_iterations(hmath_context *context, const hmath_value *penetration, hmath_value **out); +``` + +## `penetration_normal` + +`geometry.penetration_normal(penetration)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Penetration -> Point2 +``` + +```c +hmath_status hmath_geometry_penetration_normal(hmath_context *context, const hmath_value *penetration, hmath_value **out); +``` + +## `separating_axis` + +`geometry.separating_axis(values, values2)` + + Separating-axis collision and minimum overlap for convex polygons. Shapes must have nonzero area; containment depth uses the distance to the nearer separating interval endpoint, rather than only the interval intersection. + +```haskell +[Point2] -> [Point2] -> Either MathError (Maybe Penetration) +``` + +```c +hmath_status hmath_geometry_separating_axis(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `aabb` + +`geometry.aabb(point_nd, point_nd2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PointND -> PointND -> AABB +``` + +```c +hmath_status hmath_geometry_aabb(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `boundary` + +`geometry.boundary()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Location +``` + +```c +hmath_status hmath_geometry_boundary(hmath_context *context, hmath_value **out); +``` + +## `capsule` + +`geometry.capsule(point3, point32, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Point3 -> Double -> Capsule +``` + +```c +hmath_status hmath_geometry_capsule(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +``` + +## `circle` + +`geometry.circle(point2, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Double -> Circle +``` + +```c +hmath_status hmath_geometry_circle(hmath_context *context, const hmath_value *point2, const hmath_value *number, hmath_value **out); +``` + +## `clockwise` + +`geometry.clockwise()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Orientation +``` + +```c +hmath_status hmath_geometry_clockwise(hmath_context *context, hmath_value **out); +``` + +## `collinear` + +`geometry.collinear()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Orientation +``` + +```c +hmath_status hmath_geometry_collinear(hmath_context *context, hmath_value **out); +``` + +## `cone` + +`geometry.cone(point3, point32, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Point3 -> Double -> Cone +``` + +```c +hmath_status hmath_geometry_cone(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +``` + +## `counterclockwise` + +`geometry.counterclockwise()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Orientation +``` + +```c +hmath_status hmath_geometry_counterclockwise(hmath_context *context, hmath_value **out); +``` + +## `cylinder` + +`geometry.cylinder(point3, point32, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Point3 -> Double -> Cylinder +``` + +```c +hmath_status hmath_geometry_cylinder(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +``` + +## `ellipse` + +`geometry.ellipse(point2, number, number2, number3)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Double -> Double -> Double -> Ellipse +``` + +```c +hmath_status hmath_geometry_ellipse(hmath_context *context, const hmath_value *point2, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +``` + +## `frustum` + +`geometry.frustum(values)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[Plane] -> Frustum +``` + +```c +hmath_status hmath_geometry_frustum(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `inside` + +`geometry.inside()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Location +``` + +```c +hmath_status hmath_geometry_inside(hmath_context *context, hmath_value **out); +``` + +## `line` + +`geometry.line(point_nd, point_nd2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PointND -> PointND -> Line +``` + +```c +hmath_status hmath_geometry_line(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `obb` + +`geometry.obb(point3, values, point32)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> [Point3] -> Point3 -> OBB +``` + +```c +hmath_status hmath_geometry_obb(hmath_context *context, const hmath_value *point3, const hmath_value *values, const hmath_value *point32, hmath_value **out); +``` + +## `outside` + +`geometry.outside()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Location +``` + +```c +hmath_status hmath_geometry_outside(hmath_context *context, hmath_value **out); +``` + +## `p2` + +`geometry.p2(number, number2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Double -> Point2 +``` + +```c +hmath_status hmath_geometry_p2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +``` + +## `p3` + +`geometry.p3(number, number2, number3)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Double -> Double -> Point3 +``` + +```c +hmath_status hmath_geometry_p3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +``` + +## `plane` + +`geometry.plane(point3, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Double -> Plane +``` + +```c +hmath_status hmath_geometry_plane(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out); +``` + +## `point_nd_raw` + +`geometry.point_nd(values)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[Double] -> PointND +``` + +```c +hmath_status hmath_geometry_point_nd_raw(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `polygon` + +`geometry.polygon(values)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[Point2] -> Polygon +``` + +```c +hmath_status hmath_geometry_polygon(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `ray` + +`geometry.ray(point3, point32)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Point3 -> Ray +``` + +```c +hmath_status hmath_geometry_ray(hmath_context *context, const hmath_value *point3, const hmath_value *point32, hmath_value **out); +``` + +## `rectangle` + +`geometry.rectangle(point2, point22)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Point2 -> Rectangle +``` + +```c +hmath_status hmath_geometry_rectangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out); +``` + +## `segment` + +`geometry.segment(point_nd, point_nd2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PointND -> PointND -> Segment +``` + +```c +hmath_status hmath_geometry_segment(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `sphere` + +`geometry.sphere(point3, number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point3 -> Double -> Sphere +``` + +```c +hmath_status hmath_geometry_sphere(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out); +``` + +## `triangle` + +`geometry.triangle(point2, point22, point23)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Point2 -> Point2 -> Triangle +``` + +```c +hmath_status hmath_geometry_triangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out); +``` + +## `point2` + +`geometry.point2(number, number2)` + + Given x,y, construct Point2 after bounded finite-coordinate validation. Invalid values return DomainError. + +```haskell +Double -> Double -> Either MathError Point2 +``` + +```c +hmath_status hmath_geometry_point2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +``` + +## `point3` + +`geometry.point3(number, number2, number3)` + + Given x,y,z, construct Point3 after bounded finite-coordinate validation. Invalid values return DomainError. + +```haskell +Double -> Double -> Double -> Either MathError Point3 +``` + +```c +hmath_status hmath_geometry_point3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +``` + +## `point_nd` + +`geometry.point_nd(values)` + + Construct a checked ND point from 1..16 bounded finite coordinates. Invalid dimension/value returns DomainError. + +```haskell +[Double] -> Either MathError PointND +``` + +```c +hmath_status hmath_geometry_point_nd(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `difference` + +`geometry.difference()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BooleanOperation +``` + +```c +hmath_status hmath_geometry_difference(hmath_context *context, hmath_value **out); +``` + +## `gift_wrapping` + +`geometry.gift_wrapping()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +HullAlgorithm +``` + +```c +hmath_status hmath_geometry_gift_wrapping(hmath_context *context, hmath_value **out); +``` + +## `graham_scan` + +`geometry.graham_scan()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +HullAlgorithm +``` + +```c +hmath_status hmath_geometry_graham_scan(hmath_context *context, hmath_value **out); +``` + +## `intersection` + +`geometry.intersection()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BooleanOperation +``` + +```c +hmath_status hmath_geometry_intersection(hmath_context *context, hmath_value **out); +``` + +## `monotone_chain` + +`geometry.monotone_chain()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +HullAlgorithm +``` + +```c +hmath_status hmath_geometry_monotone_chain(hmath_context *context, hmath_value **out); +``` + +## `quickhull` + +`geometry.quickhull()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +HullAlgorithm +``` + +```c +hmath_status hmath_geometry_quickhull(hmath_context *context, hmath_value **out); +``` + +## `union` + +`geometry.union()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BooleanOperation +``` + +```c +hmath_status hmath_geometry_union(hmath_context *context, hmath_value **out); +``` + +## `clip_polygon` + +`geometry.clip_polygon(polygon, polygon2)` + + Sutherland-Hodgman clipping against a convex CCW/clockwise clip polygon. Output may be empty; nonconvex clippers fail instead of silently corrupting output. + +```haskell +Polygon -> Polygon -> Either MathError [Point2] +``` + +```c +hmath_status hmath_geometry_clip_polygon(hmath_context *context, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out); +``` + +## `convex_hull` + +`geometry.convex_hull(hull_algorithm, values)` + +Convex hull with at most 4096 input points. Exact orientation breaks degeneracies. + +```haskell +HullAlgorithm -> [Point2] -> Either MathError [Point2] +``` + +```c +hmath_status hmath_geometry_convex_hull(hmath_context *context, const hmath_value *hull_algorithm, const hmath_value *values, hmath_value **out); +``` + +## `minimum_bounding_circle` + +`geometry.minimum_bounding_circle(values)` + + Deterministic incremental minimum enclosing circle, O(n^3), at most 256 points. Each violated boundary introduces a 1-, 2-, or 3-point support. + +```haskell +[Point2] -> Either MathError Circle +``` + +```c +hmath_status hmath_geometry_minimum_bounding_circle(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `minimum_bounding_rectangle` + +`geometry.minimum_bounding_rectangle(values)` + + Minimum-area oriented enclosing rectangle. Testing every hull edge uses the rotating-calipers extremal-orientation theorem; the reference scans all vertices for each orientation (O(h^2)), at most 4096 points. + +```haskell +[Point2] -> Either MathError [Point2] +``` + +```c +hmath_status hmath_geometry_minimum_bounding_rectangle(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `minkowski_sum` + +`geometry.minkowski_sum(values, values2)` + + Convex Minkowski sum, via pairwise sums followed by a hull. Nonconvex inputs are deliberately convexified; at most 64 vertices per operand. + +```haskell +[Point2] -> [Point2] -> Either MathError [Point2] +``` + +```c +hmath_status hmath_geometry_minkowski_sum(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `polygon_area` + +`geometry.polygon_area(polygon)` + +Unsigned simple polygon area. + +```haskell +Polygon -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_polygon_area(hmath_context *context, const hmath_value *polygon, hmath_value **out); +``` + +## `polygon_boolean` + +`geometry.polygon_boolean(boolean_operation, polygon, polygon2)` + + Exact edge-arrangement Boolean. Empty output is allowed, including an intersection that consists only of points/segments (zero-area components). + +```haskell +BooleanOperation -> Polygon -> Polygon -> Either MathError [Polygon] +``` + +```c +hmath_status hmath_geometry_polygon_boolean(hmath_context *context, const hmath_value *boolean_operation, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out); +``` + +## `polygon_centroid` + +`geometry.polygon_centroid(polygon)` + +Area-weighted centroid; works for nonconvex simple polygons. + +```haskell +Polygon -> Either MathError Point2 +``` + +```c +hmath_status hmath_geometry_polygon_centroid(hmath_context *context, const hmath_value *polygon, hmath_value **out); +``` + +## `shoelace` + +`geometry.shoelace(polygon)` + +Signed shoelace area; clockwise polygons have negative area. + +```haskell +Polygon -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_shoelace(hmath_context *context, const hmath_value *polygon, hmath_value **out); +``` + +## `chebyshev` + +`geometry.chebyshev()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Metric +``` + +```c +hmath_status hmath_geometry_chebyshev(hmath_context *context, hmath_value **out); +``` + +## `circle_points` + +`geometry.circle_points(values)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[Point2] -> CircleIntersection +``` + +```c +hmath_status hmath_geometry_circle_points(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `coincident_circles` + +`geometry.coincident_circles()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +CircleIntersection +``` + +```c +hmath_status hmath_geometry_coincident_circles(hmath_context *context, hmath_value **out); +``` + +## `coincident_line` + +`geometry.coincident_line()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Intersection2 +``` + +```c +hmath_status hmath_geometry_coincident_line(hmath_context *context, hmath_value **out); +``` + +## `disjoint_circles` + +`geometry.disjoint_circles()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +CircleIntersection +``` + +```c +hmath_status hmath_geometry_disjoint_circles(hmath_context *context, hmath_value **out); +``` + +## `euclidean` + +`geometry.euclidean()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Metric +``` + +```c +hmath_status hmath_geometry_euclidean(hmath_context *context, hmath_value **out); +``` + +## `intersection_point` + +`geometry.intersection_point(point2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Intersection2 +``` + +```c +hmath_status hmath_geometry_intersection_point(hmath_context *context, const hmath_value *point2, hmath_value **out); +``` + +## `manhattan` + +`geometry.manhattan()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Metric +``` + +```c +hmath_status hmath_geometry_manhattan(hmath_context *context, hmath_value **out); +``` + +## `minkowski` + +`geometry.minkowski(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Metric +``` + +```c +hmath_status hmath_geometry_minkowski(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `no_intersection` + +`geometry.no_intersection()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Intersection2 +``` + +```c +hmath_status hmath_geometry_no_intersection(hmath_context *context, hmath_value **out); +``` + +## `overlap_segment` + +`geometry.overlap_segment(point2, point22)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Point2 -> Point2 -> Intersection2 +``` + +```c +hmath_status hmath_geometry_overlap_segment(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out); +``` + +## `box_contains` + +`geometry.box_contains(aabb, point_nd)` + +Closed axis-aligned box containment. + +```haskell +AABB -> PointND -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_box_contains(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out); +``` + +## `box_sdf` + +`geometry.box_sdf(aabb, point_nd)` + +Axis-aligned box exact signed Euclidean distance in 1..16 dimensions. + +```haskell +AABB -> PointND -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_box_sdf(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out); +``` + +## `capsule_sdf` + +`geometry.capsule_sdf(capsule, point3)` + +Capsule distance from its closed axis minus radius. + +```haskell +Capsule -> Point3 -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_capsule_sdf(hmath_context *context, const hmath_value *capsule, const hmath_value *point3, hmath_value **out); +``` + +## `circle_intersection` + +`geometry.circle_intersection(circle, circle2)` + + Given two circles, return DisjointCircles, CoincidentCircles, or CirclePoints for their intersection. Require valid finite centers and nonnegative bounded radii. Tangency yields one point; identical zero-radius circles yield their single center. + +```haskell +Circle -> Circle -> Either MathError CircleIntersection +``` + +```c +hmath_status hmath_geometry_circle_intersection(hmath_context *context, const hmath_value *circle, const hmath_value *circle2, hmath_value **out); +``` + +## `circumcenter` + +`geometry.circumcenter(triangle)` + +Circumcenter, obtained from exact rational perpendicular-bisector equations. + +```haskell +Triangle -> Either MathError Point2 +``` + +```c +hmath_status hmath_geometry_circumcenter(hmath_context *context, const hmath_value *triangle, hmath_value **out); +``` + +## `cone_sdf` + +`geometry.cone_sdf(cone, point3)` + +Exact finite-cone distance by reducing to its radial/axial cross-section. + +```haskell +Cone -> Point3 -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_cone_sdf(hmath_context *context, const hmath_value *cone, const hmath_value *point3, hmath_value **out); +``` + +## `cosine_distance` + +`geometry.cosine_distance(point_nd, point_nd2)` + +One minus cosine similarity; zero vectors are undefined. + +```haskell +PointND -> PointND -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_cosine_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `cylinder_sdf` + +`geometry.cylinder_sdf(cylinder, point3)` + +Exact capped finite-cylinder signed distance. + +```haskell +Cylinder -> Point3 -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_cylinder_sdf(hmath_context *context, const hmath_value *cylinder, const hmath_value *point3, hmath_value **out); +``` + +## `distance` + +`geometry.distance(metric, point_nd, point_nd2)` + +Euclidean, L1, Linfinity, or scaled Lp distance. + +```haskell +Metric -> PointND -> PointND -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_distance(hmath_context *context, const hmath_value *metric, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `ellipse_contains` + +`geometry.ellipse_contains(ellipse, point2)` + +Closed ellipse containment after rotation to its principal axes. + +```haskell +Ellipse -> Point2 -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_ellipse_contains(hmath_context *context, const hmath_value *ellipse, const hmath_value *point2, hmath_value **out); +``` + +## `hausdorff_distance` + +`geometry.hausdorff_distance(values, values2)` + +Symmetric Hausdorff distance on two nonempty finite clouds, at most 1024 each. + +```haskell +[PointND] -> [PointND] -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_hausdorff_distance(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `incenter` + +`geometry.incenter(triangle)` + +Incenter weighted by opposite side lengths. + +```haskell +Triangle -> Either MathError Point2 +``` + +```c +hmath_status hmath_geometry_incenter(hmath_context *context, const hmath_value *triangle, hmath_value **out); +``` + +## `incircle` + +`geometry.incircle(point2, point22, point23, point24)` + + Exact in-circle sign, orientation-independent: positive means inside. A collinear defining triangle is rejected. + +```haskell +Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Ordering +``` + +```c +hmath_status hmath_geometry_incircle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +``` + +## `line_intersection` + +`geometry.line_intersection(point2, point22, point23, point24)` + +Infinite-line intersection from origins and nonzero direction vectors. + +```haskell +Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2 +``` + +```c +hmath_status hmath_geometry_line_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +``` + +## `line_plane_intersection` + +`geometry.line_plane_intersection(line, plane)` + + Line/plane result: Nothing parallel/disjoint, Just Nothing coincident, Just (Just p) a unique intersection. The line must have dimension three. + +```haskell +Line -> Plane -> Either MathError (Maybe (Maybe Point3)) +``` + +```c +hmath_status hmath_geometry_line_plane_intersection(hmath_context *context, const hmath_value *line, const hmath_value *plane, hmath_value **out); +``` + +## `mahalanobis_distance` + +`geometry.mahalanobis_distance(values, point_nd, point_nd2)` + + Mahalanobis distance using a checked symmetric positive-definite covariance. A Cholesky triangular solve avoids an explicit inverse. + +```haskell +[[Double]] -> PointND -> PointND -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_mahalanobis_distance(hmath_context *context, const hmath_value *values, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +``` + +## `obb_sdf` + +`geometry.obb_sdf(obb, point3)` + +Oriented box distance after validating its orthonormal axes. + +```haskell +OBB -> Point3 -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_obb_sdf(hmath_context *context, const hmath_value *obb, const hmath_value *point3, hmath_value **out); +``` + +## `orientation` + +`geometry.orientation(point2, point22, point23)` + +Exact orientation of the represented finite Double coordinates. + +```haskell +Point2 -> Point2 -> Point2 -> Either MathError Orientation +``` + +```c +hmath_status hmath_geometry_orientation(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out); +``` + +## `plane_intersection` + +`geometry.plane_intersection(plane, plane2)` + + Plane intersection: same nested convention as linePlaneIntersection, with the unique intersection represented by a line. + +```haskell +Plane -> Plane -> Either MathError (Maybe (Maybe Line)) +``` + +```c +hmath_status hmath_geometry_plane_intersection(hmath_context *context, const hmath_value *plane, const hmath_value *plane2, hmath_value **out); +``` + +## `point_line_distance` + +`geometry.point_line_distance(point_nd, line)` + +Distance to an infinite line; a zero direction is an error. + +```haskell +PointND -> Line -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_point_line_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *line, hmath_value **out); +``` + +## `point_plane_distance` + +`geometry.point_plane_distance(point3, plane)` + +Unsigned perpendicular plane distance. + +```haskell +Point3 -> Plane -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_point_plane_distance(hmath_context *context, const hmath_value *point3, const hmath_value *plane, hmath_value **out); +``` + +## `point_segment_distance` + +`geometry.point_segment_distance(point_nd, segment)` + +Distance to a closed segment, including a zero-length segment. + +```haskell +PointND -> Segment -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_point_segment_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *segment, hmath_value **out); +``` + +## `polygon_location` + +`geometry.polygon_location(polygon, point2)` + +Simple polygon position, with boundary separate from interior. + +```haskell +Polygon -> Point2 -> Either MathError Location +``` + +```c +hmath_status hmath_geometry_polygon_location(hmath_context *context, const hmath_value *polygon, const hmath_value *point2, hmath_value **out); +``` + +## `ray_box` + +`geometry.ray_box(ray, aabb)` + +Slab intersection interval [entry,exit], clipped to the ray t>=0. + +```haskell +Ray -> AABB -> Either MathError (Maybe (Double, Double)) +``` + +```c +hmath_status hmath_geometry_ray_box(hmath_context *context, const hmath_value *ray, const hmath_value *aabb, hmath_value **out); +``` + +## `ray_sphere` + +`geometry.ray_sphere(ray, sphere)` + +Ray-sphere near/far nonnegative parameters; tangent gives equal roots. + +```haskell +Ray -> Sphere -> Either MathError (Maybe (Double, Double)) +``` + +```c +hmath_status hmath_geometry_ray_sphere(hmath_context *context, const hmath_value *ray, const hmath_value *sphere, hmath_value **out); +``` + +## `ray_triangle` + +`geometry.ray_triangle(ray, tuple_value)` + + Moller-Trumbore ray intersection; coplanar rays return Nothing because their hit set is not a unique transverse surface crossing. Degenerate triangles fail. + +```haskell +Ray -> (Point3, Point3, Point3) -> Either MathError (Maybe Double) +``` + +```c +hmath_status hmath_geometry_ray_triangle(hmath_context *context, const hmath_value *ray, const hmath_value *tuple_value, hmath_value **out); +``` + +## `segment_intersection` + +`geometry.segment_intersection(point2, point22, point23, point24)` + +Closed segment intersection with exact degeneracy predicates. + +```haskell +Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2 +``` + +```c +hmath_status hmath_geometry_segment_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +``` + +## `sphere_contains` + +`geometry.sphere_contains(sphere, point3)` + +Closed sphere containment. + +```haskell +Sphere -> Point3 -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_sphere_contains(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out); +``` + +## `sphere_sdf` + +`geometry.sphere_sdf(sphere, point3)` + +Sphere signed distance (negative inside). + +```haskell +Sphere -> Point3 -> Either MathError Double +``` + +```c +hmath_status hmath_geometry_sphere_sdf(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out); +``` + +## `triangle_barycentric` + +`geometry.triangle_barycentric(triangle, point2)` + +Weights (a,b,c) summing to one; valid outside the triangle as well. + +```haskell +Triangle -> Point2 -> Either MathError [Double] +``` + +```c +hmath_status hmath_geometry_triangle_barycentric(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out); +``` + +## `triangle_intersection` + +`geometry.triangle_intersection(triangle, triangle2)` + +Closed triangle overlap polygon, including isolated tangencies as vertices. + +```haskell +Triangle -> Triangle -> Either MathError [Point2] +``` + +```c +hmath_status hmath_geometry_triangle_intersection(hmath_context *context, const hmath_value *triangle, const hmath_value *triangle2, hmath_value **out); +``` + +## `triangle_location` + +`geometry.triangle_location(triangle, point2)` + +Triangle position using exact orientation signs. + +```haskell +Triangle -> Point2 -> Either MathError Location +``` + +```c +hmath_status hmath_geometry_triangle_location(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out); +``` + +## `bvh` + +`geometry.bvh()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_bvh(hmath_context *context, hmath_value **out); +``` + +## `ball_tree` + +`geometry.ball_tree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_ball_tree(hmath_context *context, hmath_value **out); +``` + +## `kd_tree` + +`geometry.kd_tree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_kd_tree(hmath_context *context, hmath_value **out); +``` + +## `neighbor_query` + +`geometry.neighbor_query(values, count, flag)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[(Int, Double)] -> Int -> Bool -> NeighborQuery +``` + +```c +hmath_status hmath_geometry_neighbor_query(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out); +``` + +## `octree` + +`geometry.octree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_octree(hmath_context *context, hmath_value **out); +``` + +## `quadtree` + +`geometry.quadtree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_quadtree(hmath_context *context, hmath_value **out); +``` + +## `r_tree` + +`geometry.r_tree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SpatialKind +``` + +```c +hmath_status hmath_geometry_r_tree(hmath_context *context, hmath_value **out); +``` + +## `spatial_hash` + +`geometry.spatial_hash(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> SpatialKind +``` + +```c +hmath_status hmath_geometry_spatial_hash(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `build_spatial_index` + +`geometry.build_spatial_index(spatial_kind, point_cloud)` + + Build the named structure. RTree uses sort-tile-recursive leaf packing (fanout 8); BVH splits longest-axis medians; quadrant trees split cells at their midplanes with a depth limit of 64 for coincident/near-coincident data. + +```haskell +SpatialKind -> PointCloud -> Either MathError SpatialIndex +``` + +```c +hmath_status hmath_geometry_build_spatial_index(hmath_context *context, const hmath_value *spatial_kind, const hmath_value *point_cloud, hmath_value **out); +``` + +## `cloud_points` + +`geometry.cloud_points(point_cloud)` + +Original cloud observations. + +```haskell +PointCloud -> [PointND] +``` + +```c +hmath_status hmath_geometry_cloud_points(hmath_context *context, const hmath_value *point_cloud, hmath_value **out); +``` + +## `nearest_query` + +`geometry.nearest_query(count, count2, spatial_index, point_nd)` + + Given neighbor count k, positive leaf budget, index, then query point, search for nearest neighbors. Require matching finite coordinate dimension and 1<=k<=65536. The result reports neighbors, visited leaves and whether search was exhaustive; an exhausted budget is not an exact-neighbor guarantee. + +```haskell +Int -> Int -> SpatialIndex -> PointND -> Either MathError NeighborQuery +``` + +```c +hmath_status hmath_geometry_nearest_query(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *point_nd, hmath_value **out); +``` + +## `point_cloud` + +`geometry.point_cloud(values)` + +Construct a nonempty cloud of at most 65536 points, with consistent dimensions. + +```haskell +[PointND] -> Either MathError PointCloud +``` + +```c +hmath_status hmath_geometry_point_cloud(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `query_exhaustive` + +`geometry.query_exhaustive(neighbor_query)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborQuery -> Bool +``` + +```c +hmath_status hmath_geometry_query_exhaustive(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +``` + +## `query_leaves` + +`geometry.query_leaves(neighbor_query)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborQuery -> Int +``` + +```c +hmath_status hmath_geometry_query_leaves(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +``` + +## `query_neighbors` + +`geometry.query_neighbors(neighbor_query)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborQuery -> [(Int, Double)] +``` + +```c +hmath_status hmath_geometry_query_neighbors(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +``` + +## `radius_query` + +`geometry.radius_query(spatial_index, point_nd, number)` + +Exact closed radius query; uses the index range query then Euclidean filtering. + +```haskell +SpatialIndex -> PointND -> Double -> Either MathError [Int] +``` + +```c +hmath_status hmath_geometry_radius_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *point_nd, const hmath_value *number, hmath_value **out); +``` + +## `range_query` + +`geometry.range_query(spatial_index, aabb)` + + Closed range search, sorted original IDs. Hash queries inspect occupied bucket bounds, avoiding an unbounded Cartesian enumeration of empty cells. + +```haskell +SpatialIndex -> AABB -> Either MathError [Int] +``` + +```c +hmath_status hmath_geometry_range_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *aabb, hmath_value **out); +``` + +## `affine_transform` + +`geometry.affine_transform(matrix, point_nd)` + +Construct an affine matrix [linear,translation;0,1]. + +```haskell +Matrix Double -> PointND -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_affine_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out); +``` + +## `apply_transform` + +`geometry.apply_transform(matrix, point_nd)` + +Apply an affine or projective matrix and divide by homogeneous w. + +```haskell +Matrix Double -> PointND -> Either MathError PointND +``` + +```c +hmath_status hmath_geometry_apply_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out); +``` + +## `compose_transforms` + +`geometry.compose_transforms(matrix, matrix2)` + +Checked matrix composition; projective and affine matrices may be mixed. + +```haskell +Matrix Double -> Matrix Double -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_compose_transforms(hmath_context *context, const hmath_value *matrix, const hmath_value *matrix2, hmath_value **out); +``` + +## `cull_box` + +`geometry.cull_box(frustum, aabb)` + +True means the closed 3D AABB may be visible; corners need not be allocated. + +```haskell +Frustum -> AABB -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_cull_box(hmath_context *context, const hmath_value *frustum, const hmath_value *aabb, hmath_value **out); +``` + +## `cull_sphere` + +`geometry.cull_sphere(frustum, sphere)` + +True means the closed sphere may be visible (conservative plane culling). + +```haskell +Frustum -> Sphere -> Either MathError Bool +``` + +```c +hmath_status hmath_geometry_cull_sphere(hmath_context *context, const hmath_value *frustum, const hmath_value *sphere, hmath_value **out); +``` + +## `extract_frustum` + +`geometry.extract_frustum(matrix)` + + Extract six inward clipping planes from projection*view. Plane normals are normalized so signed plane values are distances in world coordinates. + +```haskell +Matrix Double -> Either MathError Frustum +``` + +```c +hmath_status hmath_geometry_extract_frustum(hmath_context *context, const hmath_value *matrix, hmath_value **out); +``` + +## `inverse_transform` + +`geometry.inverse_transform(matrix)` + +Gauss-Jordan inverse with partial pivoting, bounded to matrices of size 17. + +```haskell +Matrix Double -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_inverse_transform(hmath_context *context, const hmath_value *matrix, hmath_value **out); +``` + +## `look_at` + +`geometry.look_at(point3, point32, point33)` + +World-to-camera transform from eye, target and nonparallel up direction. + +```haskell +Point3 -> Point3 -> Point3 -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_look_at(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *point33, hmath_value **out); +``` + +## `orthographic` + +`geometry.orthographic(number, number2, number3, number4, number5, number6)` + +Orthographic bounds with left Double -> Double -> Double -> Double -> Double -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_orthographic(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, const hmath_value *number5, const hmath_value *number6, hmath_value **out); +``` + +## `perspective` + +`geometry.perspective(number, number2, number3, number4)` + +Vertical field of view in (0,pi), positive aspect, 0 Double -> Double -> Double -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_geometry_perspective(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, hmath_value **out); +``` + +## `constrained_delaunay` + +`geometry.constrained_delaunay(values, values2)` + + Insert noncrossing constrained edges by convex quadrilateral flips, then Lawson-flip every unconstrained illegal edge. Work is bounded explicitly. + +```haskell +[Point2] -> [(Int, Int)] -> Either MathError [IndexedTriangle] +``` + +```c +hmath_status hmath_geometry_constrained_delaunay(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `delaunay` + +`geometry.delaunay(values)` + + Incremental cavity replacement. Cocircular insertion uses a strict in-circle predicate, giving a deterministic (not unique) valid diagonal. + +```haskell +[Point2] -> Either MathError [IndexedTriangle] +``` + +```c +hmath_status hmath_geometry_delaunay(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `ear_clip` + +`geometry.ear_clip(polygon)` + + Ear clipping of a simple polygon. Collinear boundary vertices are removed from the active ring; returned triangles retain original indices. + +```haskell +Polygon -> Either MathError [IndexedTriangle] +``` + +```c +hmath_status hmath_geometry_ear_clip(hmath_context *context, const hmath_value *polygon, hmath_value **out); +``` + +## `voronoi` + +`geometry.voronoi(rectangle, values)` + + Voronoi cells clipped to an ordered nonzero rectangle, one polygon ring per site (empty only if the site lies outside the clipping rectangle). Direct pairwise half-plane clipping is O(n^3), limited to 128 sites. Bisector classification and intersections use exact Rational arithmetic; final vertices are rounded once to Double. + +```haskell +Rectangle -> [Point2] -> Either MathError [[Point2]] +``` + +```c +hmath_status hmath_geometry_voronoi(hmath_context *context, const hmath_value *rectangle, const hmath_value *values, hmath_value **out); +``` + diff --git a/docs/reference/graph-bindings.md b/docs/reference/graph-bindings.md new file mode 100644 index 0000000..bf95f64 --- /dev/null +++ b/docs/reference/graph-bindings.md @@ -0,0 +1,2133 @@ +# Graph bindings + +These adapters call the original Graph functions. Vertex/edge limits, tie order, loops, parallel edges, exact flow capacities and original algorithm budgets are preserved. + +C uses `hmath_graph.h` with owned [structured values](values.md). Python uses `from hmath import graph`. Opaque graph objects support `close()` and context managers. Returned lists, tuples, Booleans, strings, integers, optional values and binary64 values use ordinary Python representations. + +C output handles are owned and remain untouched on failure. Inputs are borrowed throughout a call; callers retain references. Independent calls may share immutable objects and must use independent output addresses. Source `Left MathError` uses status 11 with a lossless structured error. `Maybe` uses `None`/value kind 0. Checked cancellation occurs before entry; source algorithm budgets are not changed. + +## `betweenness_centrality` + +`graph.betweenness_centrality(graph)` + + Return unweighted shortest-path betweenness by vertex, accounting for shortest-path multiplicities. Undirected scores are halved; edge weights are not path lengths here. + +Original: [`HMath.Graph.Analysis.betweennessCentrality`](haskell/HMath-Graph-Analysis.md#v:betweennessCentrality). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Double] +``` + +```c +hmath_status hmath_graph_betweenness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `bipartite_colors` + +`graph.bipartite_colors(graph)` + + Return Just Bool colors for every vertex if the underlying undirected adjacency is bipartite, including disconnected components; conflicting edges/loops yield Nothing. + +Original: [`HMath.Graph.Analysis.bipartiteColors`](haskell/HMath-Graph-Analysis.md#v:bipartiteColors). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Maybe [Bool] +``` + +```c +hmath_status hmath_graph_bipartite_colors( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `closeness_centrality` + +`graph.closeness_centrality(graph)` + + Return unweighted closeness with reachable-component correction: reachable^2/((n-1)*sumDistances). Isolated/singleton vertices yield zero. + +Original: [`HMath.Graph.Analysis.closenessCentrality`](haskell/HMath-Graph-Analysis.md#v:closenessCentrality). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Double] +``` + +```c +hmath_status hmath_graph_closeness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `clustering_coefficients` + +`graph.clustering_coefficients(graph)` + + Return local undirected clustering coefficients from distinct non-self neighbor sets. Degree below two yields zero. Directed graphs fail. + +Original: [`HMath.Graph.Analysis.clusteringCoefficients`](haskell/HMath-Graph-Analysis.md#v:clusteringCoefficients). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Double] +``` + +```c +hmath_status hmath_graph_clustering_coefficients( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `degree_centrality` + +`graph.degree_centrality(graph)` + + Return outgoing traversal degree divided by n-1 for each vertex; n<=1 yields zeros. Undirected loops contribute twice and parallel edges are retained, so values can exceed one. + +Original: [`HMath.Graph.Analysis.degreeCentrality`](haskell/HMath-Graph-Analysis.md#v:degreeCentrality). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Double] +``` + +```c +hmath_status hmath_graph_degree_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `density` + +`graph.density(graph)` + +Simple graph density: parallel edges and loops are ignored. + +Original: [`HMath.Graph.Analysis.density`](haskell/HMath-Graph-Analysis.md#v:density). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Double +``` + +```c +hmath_status hmath_graph_density( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `diameter_radius` + +`graph.diameter_radius(graph)` + + Nothing if disconnected (not strongly connected for directed graphs). The empty graph has no diameter/radius; a singleton has (0,0). + +Original: [`HMath.Graph.Analysis.diameterRadius`](haskell/HMath-Graph-Analysis.md#v:diameterRadius). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Maybe (Int, Int) +``` + +```c +hmath_status hmath_graph_diameter_radius( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `eigenvector_centrality` + +`graph.eigenvector_centrality(iterations, tolerance, graph)` + + Shifted power iteration on (I+A), avoiding sign oscillation on bipartite graphs. For reducible graphs the initial all-ones vector selects a Perron combination; convergence and uniqueness are not promised. + +Original: [`HMath.Graph.Analysis.eigenvectorCentrality`](haskell/HMath-Graph-Analysis.md#v:eigenvectorCentrality). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Double -> Graph -> Either MathError [Double] +``` + +```c +hmath_status hmath_graph_eigenvector_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *graph, + hmath_value **out); +``` + +## `eulerian_path` + +`graph.eulerian_path(graph)` + + Hierholzer trail, consuming each original edge identity once. A directed trail follows edge directions; disconnected nonisolated components fail. + +Original: [`HMath.Graph.Analysis.eulerianPath`](haskell/HMath-Graph-Analysis.md#v:eulerianPath). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError (Maybe ([Int], [Int])) +``` + +```c +hmath_status hmath_graph_eulerian_path( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `exact_coloring` + +`graph.exact_coloring(fuel, graph)` + + Given work budget then graph with at most 24 vertices, search for a minimum proper coloring. Invalid budget/size or self-loops fail; exhausted search returns NonConvergence. + +Original: [`HMath.Graph.Analysis.exactColoring`](haskell/HMath-Graph-Analysis.md#v:exactColoring). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_exact_coloring( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out); +``` + +## `graph_edit_distance` + +`graph.graph_edit_distance(budget, left, right)` + + Exact unlabeled graph edit distance: unit vertex/edge insertion/deletion, edge weights are exact labels; relabeling vertices is free. Substitution is deletion plus insertion. Enumerates padded vertex bijections, at most 9 nodes. + +Original: [`HMath.Graph.Analysis.graphEditDistance`](haskell/HMath-Graph-Analysis.md#v:graphEditDistance). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Graph -> Either MathError Int +``` + +```c +hmath_status hmath_graph_graph_edit_distance( + hmath_context *context, + const hmath_value *budget, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); +``` + +## `graph_laplacian` + +`graph.graph_laplacian(normalized, graph)` + + Given normalized Bool then nonnegative-weight undirected graph, return dense combinatorial or normalized Laplacian rows. Directed/negative-weight graphs or non-finite arithmetic fail. + +Original: [`HMath.Graph.Analysis.graphLaplacian`](haskell/HMath-Graph-Analysis.md#v:graphLaplacian). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> Graph -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_graph_graph_laplacian( + hmath_context *context, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out); +``` + +## `graph_similarity` + +`graph.graph_similarity(left, right)` + + Jaccard similarity of labeled weighted edge multisets (vertex labels fixed), counting matching multiplicities. Empty edge multisets have similarity one. + +Original: [`HMath.Graph.Analysis.graphSimilarity`](haskell/HMath-Graph-Analysis.md#v:graphSimilarity). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Graph -> Either MathError Double +``` + +```c +hmath_status hmath_graph_graph_similarity( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); +``` + +## `greedy_coloring` + +`graph.greedy_coloring(graph)` + + Return zero-based greedy colors in vertex order using underlying undirected adjacency. A self-loop makes proper coloring impossible and returns Left DomainError. Minimal color count is not guaranteed. + +Original: [`HMath.Graph.Analysis.greedyColoring`](haskell/HMath-Graph-Analysis.md#v:greedyColoring). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_greedy_coloring( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `hamiltonian_path` + +`graph.hamiltonian_path(fuel, graph)` + + Given search budget then graph, find a path visiting every vertex once, returning Maybe vertex list. Invalid options/exhausted budget fail; Nothing means exhaustive search found no path. + +Original: [`HMath.Graph.Analysis.hamiltonianPath`](haskell/HMath-Graph-Analysis.md#v:hamiltonianPath). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Either MathError (Maybe [Int]) +``` + +```c +hmath_status hmath_graph_hamiltonian_path( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out); +``` + +## `katz_centrality` + +`graph.katz_centrality(iterations, tolerance, alpha, beta, graph)` + + Given iterations,tolerance,alpha,beta,then graph, iterate weighted Katz scores. Require finite alpha>=0 and alpha times maximum absolute incoming weight sum \<1. Invalid input or nonconvergence fails. + +Original: [`HMath.Graph.Analysis.katzCentrality`](haskell/HMath-Graph-Analysis.md#v:katzCentrality). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Double -> Double -> Double -> Graph -> Either MathError [Double] +``` + +```c +hmath_status hmath_graph_katz_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *alpha, + const hmath_value *beta, + const hmath_value *graph, + hmath_value **out); +``` + +## `label_propagation` + +`graph.label_propagation(iterations, graph)` + + Deterministic asynchronous label propagation. Budget counts full sweeps; equal weighted votes retain the current label when possible. + +Original: [`HMath.Graph.Analysis.labelPropagation`](haskell/HMath-Graph-Analysis.md#v:labelPropagation). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_label_propagation( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + hmath_value **out); +``` + +## `laplacian_spectrum` + +`graph.laplacian_spectrum(iterations, tolerance, normalized, graph)` + + Symmetric Jacobi rotations; eigenvalues sorted ascending. Budget counts rotations, tolerance is relative to the matrix's largest absolute entry. + +Original: [`HMath.Graph.Analysis.laplacianSpectrum`](haskell/HMath-Graph-Analysis.md#v:laplacianSpectrum). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Double -> Bool -> Graph -> Either MathError [Double] +``` + +```c +hmath_status hmath_graph_laplacian_spectrum( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out); +``` + +## `louvain` + +`graph.louvain(budget, graph)` + + Louvain local modularity moves followed by graph aggregation, repeated until no communities merge. Deterministic local optimum, not a global optimum. Budget counts every modularity candidate evaluation across levels. + +Original: [`HMath.Graph.Analysis.louvain`](haskell/HMath-Graph-Analysis.md#v:louvain). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_louvain( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + hmath_value **out); +``` + +## `modularity` + +`graph.modularity(graph, labels)` + + Given undirected nonnegative-weight graph then one community label per vertex, return weighted modularity. Invalid graph/label length or arithmetic fails; loops follow the module degree convention. + +Original: [`HMath.Graph.Analysis.modularity`](haskell/HMath-Graph-Analysis.md#v:modularity). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Int] -> Either MathError Double +``` + +```c +hmath_status hmath_graph_modularity( + hmath_context *context, + const hmath_value *graph, + const hmath_value *labels, + hmath_value **out); +``` + +## `nearest_neighbor_tour` + +`graph.nearest_neighbor_tour(graph, start)` + + Nearest-neighbor closed tour heuristic; incomplete graphs may fail. This heuristic promises a valid tour, without an optimality/approximation bound. + +Original: [`HMath.Graph.Analysis.nearestNeighborTour`](haskell/HMath-Graph-Analysis.md#v:nearestNeighborTour). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError (Maybe (Double, [Int])) +``` + +```c +hmath_status hmath_graph_nearest_neighbor_tour( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +``` + +## `page_rank` + +`graph.page_rank(iterations, tolerance, damping, graph)` + + Given iteration budget,tolerance,damping,then graph, return vertex PageRank scores with dangling-node redistribution. Require nonnegative weights, finite damping in [0,1), valid tolerance/budget; nonconvergence/numeric failure returns Left MathError. + +Original: [`HMath.Graph.Analysis.pageRank`](haskell/HMath-Graph-Analysis.md#v:pageRank). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Double -> Double -> Graph -> Either MathError [Double] +``` + +```c +hmath_status hmath_graph_page_rank( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *damping, + const hmath_value *graph, + hmath_value **out); +``` + +## `random_walk` + +`graph.random_walk(count, seed, graph, start)` + + Weighted walk with a reproducible 64-bit SplitMix stream. At a sink it remains in place. Zero-weight edges are never selected. + +Original: [`HMath.Graph.Analysis.randomWalk`](haskell/HMath-Graph-Analysis.md#v:randomWalk). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Word64 -> Graph -> Int -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_random_walk( + hmath_context *context, + const hmath_value *count, + const hmath_value *seed, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +``` + +## `two_opt_tour` + +`graph.two_opt_tour(iterations, graph, tour)` + + Given improvement-step budget,graph,then closed Hamiltonian tour, improve via pairwise segment reversals. Validate the tour permutation/edges and finite cost. Return (cost,tour); invalid input or missing edges fails. + +Original: [`HMath.Graph.Analysis.twoOptTour`](haskell/HMath-Graph-Analysis.md#v:twoOptTour). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> [Int] -> Either MathError (Double, [Int]) +``` + +```c +hmath_status hmath_graph_two_opt_tour( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + const hmath_value *tour, + hmath_value **out); +``` + +## `csr` + +`graph.csr(directed, vertex_count, offsets, targets, weights, edge_ids, orientations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.CSR`](haskell/HMath-Graph-Core.md#v:CSR). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> Int -> [Int] -> [Int] -> [Double] -> [Int] -> [(Int, Int)] -> CSR +``` + +```c +hmath_status hmath_graph_csr( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *offsets, + const hmath_value *targets, + const hmath_value *weights, + const hmath_value *edge_ids, + const hmath_value *orientations, + hmath_value **out); +``` + +## `edge` + +`graph.edge(edge_id, source, target, weight)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.Edge`](haskell/HMath-Graph-Core.md#v:Edge). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Int -> Int -> Double -> Edge +``` + +```c +hmath_status hmath_graph_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *weight, + hmath_value **out); +``` + +## `adjacency_list` + +`graph.adjacency_list(graph)` + + Return one sorted neighbors row per zero-based vertex, retaining weight and edge identity for every traversal arc. + +Original: [`HMath.Graph.Core.adjacencyList`](haskell/HMath-Graph-Core.md#v:adjacencyList). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [[(Int, Double, Int)]] +``` + +```c +hmath_status hmath_graph_adjacency_list( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `adjacency_matrix` + +`graph.adjacency_matrix(graph)` + +Cells contain every @(edge ID,weight)@, preserving edge multiplicity. + +Original: [`HMath.Graph.Core.adjacencyMatrix`](haskell/HMath-Graph-Core.md#v:adjacencyMatrix). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [[[(Int, Double)]]] +``` + +```c +hmath_status hmath_graph_adjacency_matrix( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `arcs` + +`graph.arcs(graph)` + + Return directed traversal arcs. An undirected edge yields forward and reverse arcs sharing one original ID; a loop therefore yields two arcs. + +Original: [`HMath.Graph.Core.arcs`](haskell/HMath-Graph-Core.md#v:arcs). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Edge] +``` + +```c +hmath_status hmath_graph_arcs( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `articulation_points` + +`graph.articulation_points(graph)` + +Removal-based reference algorithms, retaining parallel-edge identity. + +Original: [`HMath.Graph.Core.articulationPoints`](haskell/HMath-Graph-Core.md#v:articulationPoints). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_articulation_points( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `bfs` + +`graph.bfs(graph, start)` + + Given graph then valid start vertex, return breadth-first reachable-vertex order with sorted neighbor tie-breaking. Invalid start fails; disconnected unreachable vertices are omitted. + +Original: [`HMath.Graph.Core.bfs`](haskell/HMath-Graph-Core.md#v:bfs). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_bfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +``` + +## `bipartite_base` + +`graph.bipartite_base(bipartite_graph)` + + Return underlying undirected graph, whose right-part global labels start at the left-part count. + +Original: [`HMath.Graph.Core.bipartiteBase`](haskell/HMath-Graph-Core.md#v:bipartiteBase). Argument order and the full contract are defined there; the original type is: + +```haskell +BipartiteGraph -> Graph +``` + +```c +hmath_status hmath_graph_bipartite_base( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out); +``` + +## `bipartite_graph` + +`graph.bipartite_graph(left_vertices, right_vertices, edges)` + + Given left count,right count,then (left-local,right-local,weight) triples, construct an undirected bipartite graph. Right vertices are offset by left count internally. Negative/out-of-range endpoints, non-finite weights or graph size bounds fail. + +Original: [`HMath.Graph.Core.bipartiteGraph`](haskell/HMath-Graph-Core.md#v:bipartiteGraph). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Int -> [(Int, Int, Double)] -> Either MathError BipartiteGraph +``` + +```c +hmath_status hmath_graph_bipartite_graph( + hmath_context *context, + const hmath_value *left_vertices, + const hmath_value *right_vertices, + const hmath_value *edges, + hmath_value **out); +``` + +## `bipartite_parts` + +`graph.bipartite_parts(bipartite_graph)` + +Return (left vertex count,right vertex count) of a bipartite graph. + +Original: [`HMath.Graph.Core.bipartiteParts`](haskell/HMath-Graph-Core.md#v:bipartiteParts). Argument order and the full contract are defined there; the original type is: + +```haskell +BipartiteGraph -> (Int, Int) +``` + +```c +hmath_status hmath_graph_bipartite_parts( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out); +``` + +## `boruvka` + +`graph.boruvka(graph)` + + Return an undirected minimum spanning forest by repeatedly merging components along cheapest outgoing edges. Preserve original edge identity; directed input fails. + +Original: [`HMath.Graph.Core.boruvka`](haskell/HMath-Graph-Core.md#v:boruvka). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Edge] +``` + +```c +hmath_status hmath_graph_boruvka( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `bridges` + +`graph.bridges(graph)` + + Return original IDs of bridges in an undirected multigraph; parallel edges are treated distinctly. Directed input returns Left InvalidArgument. + +Original: [`HMath.Graph.Core.bridges`](haskell/HMath-Graph-Core.md#v:bridges). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_bridges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `check_vertex` + +`graph.check_vertex(graph, vertex)` + + Given graph then vertex index, return Right () only for a label in [0,vertexCount). Invalid labels return Left InvalidArgument. + +Original: [`HMath.Graph.Core.checkVertex`](haskell/HMath-Graph-Core.md#v:checkVertex). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError () +``` + +```c +hmath_status hmath_graph_check_vertex( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out); +``` + +## `connected_components` + +`graph.connected_components(graph)` + + Return weak connected components as sorted vertex lists, ignoring edge direction and retaining isolated vertices. + +Original: [`HMath.Graph.Core.connectedComponents`](haskell/HMath-Graph-Core.md#v:connectedComponents). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [[Int]] +``` + +```c +hmath_status hmath_graph_connected_components( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `csr_directed` + +`graph.csr_directed(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrDirected`](haskell/HMath-Graph-Core.md#v:csrDirected). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> Bool +``` + +```c +hmath_status hmath_graph_csr_directed( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_ids` + +`graph.csr_ids(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrIds`](haskell/HMath-Graph-Core.md#v:csrIds). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> [Int] +``` + +```c +hmath_status hmath_graph_csr_ids( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_offsets` + +`graph.csr_offsets(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrOffsets`](haskell/HMath-Graph-Core.md#v:csrOffsets). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> [Int] +``` + +```c +hmath_status hmath_graph_csr_offsets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_orientations` + +`graph.csr_orientations(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrOrientations`](haskell/HMath-Graph-Core.md#v:csrOrientations). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> [(Int, Int)] +``` + +```c +hmath_status hmath_graph_csr_orientations( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_targets` + +`graph.csr_targets(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrTargets`](haskell/HMath-Graph-Core.md#v:csrTargets). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> [Int] +``` + +```c +hmath_status hmath_graph_csr_targets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_vertices` + +`graph.csr_vertices(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrVertices`](haskell/HMath-Graph-Core.md#v:csrVertices). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> Int +``` + +```c +hmath_status hmath_graph_csr_vertices( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `csr_weights` + +`graph.csr_weights(csr)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.csrWeights`](haskell/HMath-Graph-Core.md#v:csrWeights). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> [Double] +``` + +```c +hmath_status hmath_graph_csr_weights( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `deserialize_bipartite_graph` + +`graph.deserialize_bipartite_graph(text)` + + Read a versioned bipartite serialization, then validate part counts, endpoints and weights. Reject unknown/malformed encoding or input longer than 16777216 characters. + +Original: [`HMath.Graph.Core.deserializeBipartiteGraph`](haskell/HMath-Graph-Core.md#v:deserializeBipartiteGraph). Argument order and the full contract are defined there; the original type is: + +```haskell +String -> Either MathError BipartiteGraph +``` + +```c +hmath_status hmath_graph_deserialize_bipartite_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +``` + +## `deserialize_graph` + +`graph.deserialize_graph(text)` + + Read complete HMath.Graph/1 encoding and reconstruct via checked graph constructor. Unknown version, malformed text, input over 16777216 characters or invalid graph data fails. + +Original: [`HMath.Graph.Core.deserializeGraph`](haskell/HMath-Graph-Core.md#v:deserializeGraph). Argument order and the full contract are defined there; the original type is: + +```haskell +String -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_deserialize_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +``` + +## `deserialize_hypergraph` + +`graph.deserialize_hypergraph(text)` + + Read versioned hypergraph encoding and validate through hypergraph. Reject unknown/malformed input, more than 16777216 characters or invalid graph bounds. + +Original: [`HMath.Graph.Core.deserializeHypergraph`](haskell/HMath-Graph-Core.md#v:deserializeHypergraph). Argument order and the full contract are defined there; the original type is: + +```haskell +String -> Either MathError Hypergraph +``` + +```c +hmath_status hmath_graph_deserialize_hypergraph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +``` + +## `dfs` + +`graph.dfs(graph, start)` + + Given graph then valid start vertex, return depth-first reachable-vertex order with deterministic sorted neighbors. Invalid start fails; each reached vertex appears once. + +Original: [`HMath.Graph.Core.dfs`](haskell/HMath-Graph-Core.md#v:dfs). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_dfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +``` + +## `directed` + +`graph.directed(graph)` + + Return whether the graph is directed. Undirected edges are represented once in edges and twice in arcs, including loops. + +Original: [`HMath.Graph.Core.directed`](haskell/HMath-Graph-Core.md#v:directed). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Bool +``` + +```c +hmath_status hmath_graph_directed( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `edge_from` + +`graph.edge_from(edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.edgeFrom`](haskell/HMath-Graph-Core.md#v:edgeFrom). Argument order and the full contract are defined there; the original type is: + +```haskell +Edge -> Int +``` + +```c +hmath_status hmath_graph_edge_from( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +``` + +## `edge_id` + +`graph.edge_id(edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.edgeId`](haskell/HMath-Graph-Core.md#v:edgeId). Argument order and the full contract are defined there; the original type is: + +```haskell +Edge -> Int +``` + +```c +hmath_status hmath_graph_edge_id( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +``` + +## `edge_to` + +`graph.edge_to(edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.edgeTo`](haskell/HMath-Graph-Core.md#v:edgeTo). Argument order and the full contract are defined there; the original type is: + +```haskell +Edge -> Int +``` + +```c +hmath_status hmath_graph_edge_to( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +``` + +## `edge_weight` + +`graph.edge_weight(edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Core.edgeWeight`](haskell/HMath-Graph-Core.md#v:edgeWeight). Argument order and the full contract are defined there; the original type is: + +```haskell +Edge -> Double +``` + +```c +hmath_status hmath_graph_edge_weight( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +``` + +## `edges` + +`graph.edges(graph)` + + Return original labeled edges in input order, preserving loops, multiplicity and stable edge IDs. + +Original: [`HMath.Graph.Core.edges`](haskell/HMath-Graph-Core.md#v:edges). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Edge] +``` + +```c +hmath_status hmath_graph_edges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `finite` + +`graph.finite(x)` + + Test whether a Double is neither NaN nor infinite; used by checked graph weight/arithmetic validation. + +Original: [`HMath.Graph.Core.finite`](haskell/HMath-Graph-Core.md#v:finite). Argument order and the full contract are defined there; the original type is: + +```haskell +Double -> Bool +``` + +```c +hmath_status hmath_graph_finite( + hmath_context *context, + const hmath_value *x, + hmath_value **out); +``` + +## `from_adjacency_list` + +`graph.from_adjacency_list(directed, rows, orientations)` + + Lossless labeled adjacency-list conversion. The final argument records the original direction of each undirected edge, which symmetric arcs alone cannot distinguish. IDs must be contiguous; rows are canonical sorted order. + +Original: [`HMath.Graph.Core.fromAdjacencyList`](haskell/HMath-Graph-Core.md#v:fromAdjacencyList). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> [[(Int, Double, Int)]] -> [(Int, Int)] -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_from_adjacency_list( + hmath_context *context, + const hmath_value *directed, + const hmath_value *rows, + const hmath_value *orientations, + hmath_value **out); +``` + +## `from_adjacency_matrix` + +`graph.from_adjacency_matrix(directed, cells)` + + Matrix cells are weights; undirected matrices must be exactly symmetric. Diagonal entries denote one loop each, rather than duplicated traversal arcs. + +Original: [`HMath.Graph.Core.fromAdjacencyMatrix`](haskell/HMath-Graph-Core.md#v:fromAdjacencyMatrix). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> [[[Double]]] -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_from_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + hmath_value **out); +``` + +## `from_csr` + +`graph.from_csr(csr)` + + Validate CSR sizes, offsets, endpoint/weight/ID arrays and original orientations, then reconstruct a canonical graph. Malformed or noncanonical data returns Left InvalidArgument. + +Original: [`HMath.Graph.Core.fromCSR`](haskell/HMath-Graph-Core.md#v:fromCSR). Argument order and the full contract are defined there; the original type is: + +```haskell +CSR -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_from_csr( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +``` + +## `from_labeled_adjacency_matrix` + +`graph.from_labeled_adjacency_matrix(directed, cells, orientations)` + + Given directed flag,square cells of (edge ID,weight) lists,then original edge orientations, reconstruct a lossless graph. Validate square shape, canonical IDs/arcs and graph bounds through fromCSR; malformed input fails. + +Original: [`HMath.Graph.Core.fromLabeledAdjacencyMatrix`](haskell/HMath-Graph-Core.md#v:fromLabeledAdjacencyMatrix). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> [[[(Int, Double)]]] -> [(Int, Int)] -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_from_labeled_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + const hmath_value *orientations, + hmath_value **out); +``` + +## `graph` + +`graph.graph(directed, vertex_count, edges)` + + Given directed flag,vertex count,then (from,to,weight) triples, construct a multigraph with stable input-order edge IDs. Require 0<=vertices<=512, <=65536 edges, valid endpoints and finite weights; otherwise return Left InvalidArgument. + +Original: [`HMath.Graph.Core.graph`](haskell/HMath-Graph-Core.md#v:graph). Argument order and the full contract are defined there; the original type is: + +```haskell +Bool -> Int -> [(Int, Int, Double)] -> Either MathError Graph +``` + +```c +hmath_status hmath_graph_graph( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out); +``` + +## `has_cycle` + +`graph.has_cycle(graph)` + + Test for a directed or undirected cycle, respecting original edge identities. Loops and parallel undirected edges can form cycles. + +Original: [`HMath.Graph.Core.hasCycle`](haskell/HMath-Graph-Core.md#v:hasCycle). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Bool +``` + +```c +hmath_status hmath_graph_has_cycle( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `hyper_vertices` + +`graph.hyper_vertices(hypergraph)` + +Return the number of zero-based vertices in a hypergraph. + +Original: [`HMath.Graph.Core.hyperVertices`](haskell/HMath-Graph-Core.md#v:hyperVertices). Argument order and the full contract are defined there; the original type is: + +```haskell +Hypergraph -> Int +``` + +```c +hmath_status hmath_graph_hyper_vertices( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +``` + +## `hyperedges` + +`graph.hyperedges(hypergraph)` + + Return canonical hyperedge lists with sorted distinct member vertices, preserving hyperedge list order. + +Original: [`HMath.Graph.Core.hyperedges`](haskell/HMath-Graph-Core.md#v:hyperedges). Argument order and the full contract are defined there; the original type is: + +```haskell +Hypergraph -> [[Int]] +``` + +```c +hmath_status hmath_graph_hyperedges( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +``` + +## `hypergraph` + +`graph.hypergraph(vertex_count, hyperedges)` + + Given vertex count then hyperedge vertex lists, validate bounded size/endpoints and construct a hypergraph. Canonicalize vertices within each hyperedge by sorting/deduplicating. Invalid bounds fail. + +Original: [`HMath.Graph.Core.hypergraph`](haskell/HMath-Graph-Core.md#v:hypergraph). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> [[Int]] -> Either MathError Hypergraph +``` + +```c +hmath_status hmath_graph_hypergraph( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *hyperedges, + hmath_value **out); +``` + +## `iterative_deepening` + +`graph.iterative_deepening(budget, graph, source, target)` + +Iterative deepening simple-path DFS. Fuel counts visited search nodes. + +Original: [`HMath.Graph.Core.iterativeDeepening`](haskell/HMath-Graph-Core.md#v:iterativeDeepening). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Graph -> Int -> Int -> Either MathError (Maybe [Int]) +``` + +```c +hmath_status hmath_graph_iterative_deepening( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +``` + +## `kosaraju_scc` + +`graph.kosaraju_scc(graph)` + + Return sorted strongly connected components via Kosaraju traversal; undirected graphs reduce to ordinary connected components. + +Original: [`HMath.Graph.Core.kosarajuSCC`](haskell/HMath-Graph-Core.md#v:kosarajuSCC). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [[Int]] +``` + +```c +hmath_status hmath_graph_kosaraju_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `kruskal` + +`graph.kruskal(graph)` + + Return a minimum spanning forest of an undirected weighted graph by Kruskal, breaking ties by stable edge ID. Disconnected graphs return a forest; directed input fails. + +Original: [`HMath.Graph.Core.kruskal`](haskell/HMath-Graph-Core.md#v:kruskal). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Edge] +``` + +```c +hmath_status hmath_graph_kruskal( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `neighbors` + +`graph.neighbors(graph, vertex)` + + Given graph then vertex, return sorted (destination,weight,edge ID) traversal entries leaving that vertex. Parallel edges/loops are preserved. This query does not itself reject invalid vertex labels. + +Original: [`HMath.Graph.Core.neighbors`](haskell/HMath-Graph-Core.md#v:neighbors). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> [(Int, Double, Int)] +``` + +```c +hmath_status hmath_graph_neighbors( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out); +``` + +## `prim` + +`graph.prim(graph)` + + All three MST routines return a minimum spanning forest on disconnected inputs. Self-loops are ignored, negative finite weights are supported. + +Original: [`HMath.Graph.Core.prim`](haskell/HMath-Graph-Core.md#v:prim). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Edge] +``` + +```c +hmath_status hmath_graph_prim( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `require_undirected` + +`graph.require_undirected(graph)` + + Return Right () for an undirected graph; directed input returns Left InvalidArgument. No graph conversion occurs. + +Original: [`HMath.Graph.Core.requireUndirected`](haskell/HMath-Graph-Core.md#v:requireUndirected). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError () +``` + +```c +hmath_status hmath_graph_require_undirected( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `serialize_bipartite_graph` + +`graph.serialize_bipartite_graph(bipartite)` + + Serialize a bipartite graph with HMath.BipartiteGraph/1 version marker and local part labels. Pair with deserializeBipartiteGraph for checked round-trip. + +Original: [`HMath.Graph.Core.serializeBipartiteGraph`](haskell/HMath-Graph-Core.md#v:serializeBipartiteGraph). Argument order and the full contract are defined there; the original type is: + +```haskell +BipartiteGraph -> String +``` + +```c +hmath_status hmath_graph_serialize_bipartite_graph( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out); +``` + +## `serialize_graph` + +`graph.serialize_graph(graph)` + + Serialize graph direction, vertex count and input-ordered edges with HMath.Graph/1 marker; stable IDs reconstruct from edge order. + +Original: [`HMath.Graph.Core.serializeGraph`](haskell/HMath-Graph-Core.md#v:serializeGraph). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> String +``` + +```c +hmath_status hmath_graph_serialize_graph( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `serialize_hypergraph` + +`graph.serialize_hypergraph(hypergraph)` + +Serialize vertex count and canonical hyperedges with HMath.Hypergraph/1 version marker. + +Original: [`HMath.Graph.Core.serializeHypergraph`](haskell/HMath-Graph-Core.md#v:serializeHypergraph). Argument order and the full contract are defined there; the original type is: + +```haskell +Hypergraph -> String +``` + +```c +hmath_status hmath_graph_serialize_hypergraph( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +``` + +## `tarjan_scc` + +`graph.tarjan_scc(graph)` + +Tarjan's single-pass index/low-link stack algorithm. + +Original: [`HMath.Graph.Core.tarjanSCC`](haskell/HMath-Graph-Core.md#v:tarjanSCC). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [[Int]] +``` + +```c +hmath_status hmath_graph_tarjan_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `to_csr` + +`graph.to_csr(graph)` + + Convert a graph to lossless CSR rows with offsets, targets, weights, IDs and original edge orientations. Preserve loops and multiedge identity. + +Original: [`HMath.Graph.Core.toCSR`](haskell/HMath-Graph-Core.md#v:toCSR). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> CSR +``` + +```c +hmath_status hmath_graph_to_csr( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `topological_sort` + +`graph.topological_sort(graph)` + + Return a deterministic topological order of all vertices of a directed acyclic graph. Undirected graphs or directed cycles return Left MathError. + +Original: [`HMath.Graph.Core.topologicalSort`](haskell/HMath-Graph-Core.md#v:topologicalSort). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [Int] +``` + +```c +hmath_status hmath_graph_topological_sort( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `vertex_count` + +`graph.vertex_count(graph)` + + Return graph vertex count. Valid vertex labels are zero-based integers below this count. + +Original: [`HMath.Graph.Core.vertexCount`](haskell/HMath-Graph-Core.md#v:vertexCount). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int +``` + +```c +hmath_status hmath_graph_vertex_count( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `flow_result` + +`graph.flow_result(value, edge_flows, cost)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.FlowResult`](haskell/HMath-Graph-Flow.md#v:FlowResult). Argument order and the full contract are defined there; the original type is: + +```haskell +Integer -> [Integer] -> Integer -> FlowResult +``` + +```c +hmath_status hmath_graph_flow_result( + hmath_context *context, + const hmath_value *value, + const hmath_value *edge_flows, + const hmath_value *cost, + hmath_value **out); +``` + +## `network_edge` + +`graph.network_edge(edge_id, source, target, capacity, cost)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.NetworkEdge`](haskell/HMath-Graph-Flow.md#v:NetworkEdge). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Int -> Int -> Integer -> Integer -> NetworkEdge +``` + +```c +hmath_status hmath_graph_network_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *capacity, + const hmath_value *cost, + hmath_value **out); +``` + +## `dinic` + +`graph.dinic(budget, network, source, target)` + + Given work budget,network,source,sink, compute maximum flow with level graphs and blocking-flow augmentation. Invalid source/sink/budget or exhausted work returns Left MathError; result includes flows in original edge order. + +Original: [`HMath.Graph.Flow.dinic`](haskell/HMath-Graph-Flow.md#v:dinic). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError FlowResult +``` + +```c +hmath_status hmath_graph_dinic( + hmath_context *context, + const hmath_value *budget, + const hmath_value *network, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +``` + +## `edge_flows` + +`graph.edge_flows(flow_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.edgeFlows`](haskell/HMath-Graph-Flow.md#v:edgeFlows). Argument order and the full contract are defined there; the original type is: + +```haskell +FlowResult -> [Integer] +``` + +```c +hmath_status hmath_graph_edge_flows( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +``` + +## `edmonds_karp` + +`graph.edmonds_karp(value, network, value3, value4)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.edmondsKarp`](haskell/HMath-Graph-Flow.md#v:edmondsKarp). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError FlowResult +``` + +```c +hmath_status hmath_graph_edmonds_karp( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +``` + +## `flow_cost` + +`graph.flow_cost(flow_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.flowCost`](haskell/HMath-Graph-Flow.md#v:flowCost). Argument order and the full contract are defined there; the original type is: + +```haskell +FlowResult -> Integer +``` + +```c +hmath_status hmath_graph_flow_cost( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +``` + +## `flow_value` + +`graph.flow_value(flow_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.flowValue`](haskell/HMath-Graph-Flow.md#v:flowValue). Argument order and the full contract are defined there; the original type is: + +```haskell +FlowResult -> Integer +``` + +```c +hmath_status hmath_graph_flow_value( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +``` + +## `ford_fulkerson` + +`graph.ford_fulkerson(value, network, value3, value4)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.fordFulkerson`](haskell/HMath-Graph-Flow.md#v:fordFulkerson). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError FlowResult +``` + +```c +hmath_status hmath_graph_ford_fulkerson( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +``` + +## `hopcroft_karp` + +`graph.hopcroft_karp(bipartite)` + + Hopcroft--Karp layered augmenting paths. Returns @(left,right)@ matching; parallel edges are coalesced and weights are ignored. + +Original: [`HMath.Graph.Flow.hopcroftKarp`](haskell/HMath-Graph-Flow.md#v:hopcroftKarp). Argument order and the full contract are defined there; the original type is: + +```haskell +BipartiteGraph -> [(Int, Int)] +``` + +```c +hmath_status hmath_graph_hopcroft_karp( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out); +``` + +## `hungarian` + +`graph.hungarian(costs)` + + Rectangular Hungarian primal-dual assignment, rows <= columns <= 256. Every row is assigned to a distinct column; exact integer costs may be negative. + +Original: [`HMath.Graph.Flow.hungarian`](haskell/HMath-Graph-Flow.md#v:hungarian). Argument order and the full contract are defined there; the original type is: + +```haskell +[[Integer]] -> Either MathError (Integer, [(Int, Int)]) +``` + +```c +hmath_status hmath_graph_hungarian( + hmath_context *context, + const hmath_value *costs, + hmath_value **out); +``` + +## `minimum_cost_maximum_flow` + +`graph.minimum_cost_maximum_flow(value, network, value3, value4)` + + Maximum flow followed by exact negative-residual-cycle cancellation. This supports negative costs (including disconnected cycles) and finds the minimum cost among all maximum flows. The same budget bounds each phase separately. + +Original: [`HMath.Graph.Flow.minimumCostMaximumFlow`](haskell/HMath-Graph-Flow.md#v:minimumCostMaximumFlow). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError FlowResult +``` + +```c +hmath_status hmath_graph_minimum_cost_maximum_flow( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +``` + +## `minimum_cut` + +`graph.minimum_cut(value, network, value3, value4)` + +Source-side vertices and cut capacity, using Edmonds--Karp residual reach. + +Original: [`HMath.Graph.Flow.minimumCut`](haskell/HMath-Graph-Flow.md#v:minimumCut). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError ([Int], Integer) +``` + +```c +hmath_status hmath_graph_minimum_cut( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +``` + +## `network` + +`graph.network(vertex_count, edges)` + + Given vertex count then (from,to,capacity,cost) edges, construct an exact integral network with stable edge IDs. Require <=512 vertices, <=65536 edges, valid endpoints and nonnegative capacities. Costs may be negative. + +Original: [`HMath.Graph.Flow.network`](haskell/HMath-Graph-Flow.md#v:network). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> [(Int, Int, Integer, Integer)] -> Either MathError Network +``` + +```c +hmath_status hmath_graph_network( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out); +``` + +## `network_capacity` + +`graph.network_capacity(network_edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.networkCapacity`](haskell/HMath-Graph-Flow.md#v:networkCapacity). Argument order and the full contract are defined there; the original type is: + +```haskell +NetworkEdge -> Integer +``` + +```c +hmath_status hmath_graph_network_capacity( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +``` + +## `network_cost` + +`graph.network_cost(network_edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.networkCost`](haskell/HMath-Graph-Flow.md#v:networkCost). Argument order and the full contract are defined there; the original type is: + +```haskell +NetworkEdge -> Integer +``` + +```c +hmath_status hmath_graph_network_cost( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +``` + +## `network_edge_id` + +`graph.network_edge_id(network_edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.networkEdgeId`](haskell/HMath-Graph-Flow.md#v:networkEdgeId). Argument order and the full contract are defined there; the original type is: + +```haskell +NetworkEdge -> Int +``` + +```c +hmath_status hmath_graph_network_edge_id( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +``` + +## `network_edges` + +`graph.network_edges(network)` + +Return original network edges in input/ID order, retaining capacities and costs. + +Original: [`HMath.Graph.Flow.networkEdges`](haskell/HMath-Graph-Flow.md#v:networkEdges). Argument order and the full contract are defined there; the original type is: + +```haskell +Network -> [NetworkEdge] +``` + +```c +hmath_status hmath_graph_network_edges( + hmath_context *context, + const hmath_value *network, + hmath_value **out); +``` + +## `network_from` + +`graph.network_from(network_edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.networkFrom`](haskell/HMath-Graph-Flow.md#v:networkFrom). Argument order and the full contract are defined there; the original type is: + +```haskell +NetworkEdge -> Int +``` + +```c +hmath_status hmath_graph_network_from( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +``` + +## `network_to` + +`graph.network_to(network_edge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Graph.Flow.networkTo`](haskell/HMath-Graph-Flow.md#v:networkTo). Argument order and the full contract are defined there; the original type is: + +```haskell +NetworkEdge -> Int +``` + +```c +hmath_status hmath_graph_network_to( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +``` + +## `push_relabel` + +`graph.push_relabel(value, network, value3, value4)` + + Given push/relabel work budget,network,source,sink, compute exact maximum flow by preflow and relabel operations. Reject invalid endpoints/budget; work exhaustion returns NonConvergence. + +Original: [`HMath.Graph.Flow.pushRelabel`](haskell/HMath-Graph-Flow.md#v:pushRelabel). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Network -> Int -> Int -> Either MathError FlowResult +``` + +```c +hmath_status hmath_graph_push_relabel( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +``` + +## `a_star` + +`graph.a_star(graph, heuristic, source, target)` + + A* requires a finite consistent heuristic, h(target)=0, checked on all arcs. This guarantees optimality without trusting an arbitrary heuristic. + +Original: [`HMath.Graph.Paths.aStar`](haskell/HMath-Graph-Paths.md#v:aStar). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> (Int -> Double) -> Int -> Int -> Either MathError (Maybe (Double, [Int])) +``` + +```c +hmath_status hmath_graph_a_star( + hmath_context *context, + const hmath_value *graph, + hmath_graph_heuristic heuristic, + void *userdata, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +``` + +## `bellman_ford` + +`graph.bellman_ford(graph, source)` + + Given graph then source, return minimum distances including negative weights. Invalid source, reachable negative cycle or non-finite arithmetic returns Left MathError; unreachable vertices are Nothing. + +Original: [`HMath.Graph.Paths.bellmanFord`](haskell/HMath-Graph-Paths.md#v:bellmanFord). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError [Maybe Double] +``` + +```c +hmath_status hmath_graph_bellman_ford( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +``` + +## `bidirectional_dijkstra` + +`graph.bidirectional_dijkstra(graph, source, target)` + + Two settled-frontier Dijkstra searches, alternating the frontier with the smaller minimum key. The best meeting bound stops the search safely. + +Original: [`HMath.Graph.Paths.bidirectionalDijkstra`](haskell/HMath-Graph-Paths.md#v:bidirectionalDijkstra). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Int -> Either MathError (Maybe Double) +``` + +```c +hmath_status hmath_graph_bidirectional_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +``` + +## `dijkstra` + +`graph.dijkstra(graph, source)` + + Given graph then source, return minimum distances in vertex order, with Nothing for unreachable vertices. Require valid source and nonnegative weights; invalid input or non-finite arithmetic fails. + +Original: [`HMath.Graph.Paths.dijkstra`](haskell/HMath-Graph-Paths.md#v:dijkstra). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError [Maybe Double] +``` + +```c +hmath_status hmath_graph_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +``` + +## `floyd_warshall` + +`graph.floyd_warshall(graph)` + + Return all-pairs minimum-distance rows, with Nothing for unreachable pairs. Negative edges are allowed; any negative cycle or non-finite arithmetic fails. + +Original: [`HMath.Graph.Paths.floydWarshall`](haskell/HMath-Graph-Paths.md#v:floydWarshall). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [[Maybe Double]] +``` + +```c +hmath_status hmath_graph_floyd_warshall( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `johnson` + +`graph.johnson(graph)` + + Johnson reweighting: Bellman--Ford potentials from an implicit zero-cost super-source, followed by independent Dijkstra searches. + +Original: [`HMath.Graph.Paths.johnson`](haskell/HMath-Graph-Paths.md#v:johnson). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Either MathError [[Maybe Double]] +``` + +```c +hmath_status hmath_graph_johnson( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +``` + +## `k_shortest_paths` + +`graph.k_shortest_paths(budget, count, graph, source, target)` + + K cheapest simple vertex paths, best-first expansion, for nonnegative weights. Parallel edges generate distinct edge paths; output includes edge IDs to preserve this identity. Fuel counts expanded partial paths. + +Original: [`HMath.Graph.Paths.kShortestPaths`](haskell/HMath-Graph-Paths.md#v:kShortestPaths). Argument order and the full contract are defined there; the original type is: + +```haskell +Int -> Int -> Graph -> Int -> Int -> Either MathError [(Double, [Int], [Int])] +``` + +```c +hmath_status hmath_graph_k_shortest_paths( + hmath_context *context, + const hmath_value *budget, + const hmath_value *count, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +``` + +## `longest_dag_paths` + +`graph.longest_dag_paths(graph, source)` + + Given directed acyclic graph then source, return maximum path-weight distance to each vertex, Nothing for unreachable vertices. Invalid source, cycles/undirected input or non-finite arithmetic fails. + +Original: [`HMath.Graph.Paths.longestDAGPaths`](haskell/HMath-Graph-Paths.md#v:longestDAGPaths). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> Int -> Either MathError [Maybe Double] +``` + +```c +hmath_status hmath_graph_longest_dag_paths( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +``` + +## `multi_source_dijkstra` + +`graph.multi_source_dijkstra(graph, sources)` + + Given graph then source list, return distance to the nearest supplied source, each seeded at zero. Invalid sources, negative weights or non-finite arithmetic fail. Empty sources give all Nothing. + +Original: [`HMath.Graph.Paths.multiSourceDijkstra`](haskell/HMath-Graph-Paths.md#v:multiSourceDijkstra). Argument order and the full contract are defined there; the original type is: + +```haskell +Graph -> [Int] -> Either MathError [Maybe Double] +``` + +```c +hmath_status hmath_graph_multi_source_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *sources, + hmath_value **out); +``` + diff --git a/docs/reference/image-bindings.md b/docs/reference/image-bindings.md new file mode 100644 index 0000000..95b1fbf --- /dev/null +++ b/docs/reference/image-bindings.md @@ -0,0 +1,1156 @@ +# Image bindings + +`from hmath import image` exposes the original ND CPU image algorithms. Storage is spatial row-major with interleaved channels. Intensities have no implicit range; color/histogram functions retain their source restrictions. Haskell algorithms, limits, normalization and errors are unchanged. + +C includes `hmath_image.h` and uses [owned structured values](values.md). Inputs are borrowed, outputs transfer one owner and stay untouched on failure. Immutable values support independent readers with their own references. All real values are Double; Python uses floats, lists and tuples matching each signature. Original MathError constructors/payloads remain available. Callbacks are synchronous and deterministic; Python exceptions rethrow after native cleanup. The Image result is fully evaluated before callbacks are released. + +Images retain the source rank1..8, channels1..16 and262144-sample limits. Filtering/interpolation retain per-algorithm budgets. No intensity clipping, dtype promotion, coordinate normalization or substituted boundary policy is added. The TensorDouble bridge retains the actual `HMath.Tensor.Tensor Double`; helpers construct it and expose shape/logical values without claiming the remaining Tensor operations. + +## `image` + +`image.image(shape, channels, values)` + +Validate all dimensions before allocating boxed immutable array storage. + +```haskell +[Int] -> Int -> [Double] -> Either MathError Image +``` + +```c +hmath_status hmath_image_image(hmath_context *context, const hmath_value *shape, const hmath_value *channels, const hmath_value *values, hmath_value **out); +``` + +## `from_tensor` + +`image.from_tensor(tensor)` + +Tensor shape must be spatial dimensions followed by a channel axis. + +```haskell +Tensor Double -> Either MathError Image +``` + +```c +hmath_status hmath_image_from_tensor(hmath_context *context, const hmath_value *tensor, hmath_value **out); +``` + +## `to_tensor` + +`image.to_tensor(image)` + + Copy an image to Tensor Double with shape spatial dimensions followed by channel count. Values remain row-major with interleaved channels; checked tensor size errors propagate. + +```haskell +Image -> Either MathError Tensor Double +``` + +```c +hmath_status hmath_image_to_tensor(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `image_shape` + +`image.image_shape(image)` + +Return spatial dimensions only, excluding the last implicit channel axis. + +```haskell +Image -> [Int] +``` + +```c +hmath_status hmath_image_image_shape(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `image_channels` + +`image.image_channels(image)` + +Return channel count, between one and sixteen for validated images. + +```haskell +Image -> Int +``` + +```c +hmath_status hmath_image_image_channels(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `image_values` + +`image.image_values(image)` + +Return flat row-major samples with channels interleaved at each spatial coordinate. + +```haskell +Image -> [Double] +``` + +```c +hmath_status hmath_image_image_values(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `pixel` + +`image.pixel(image, coordinates)` + + Given image then complete spatial coordinates, return all channel values in order. Invalid coordinate rank/range returns Left InvalidArgument. + +```haskell +Image -> [Int] -> Either MathError [Double] +``` + +```c +hmath_status hmath_image_pixel(hmath_context *context, const hmath_value *image, const hmath_value *coordinates, hmath_value **out); +``` + +## `channel` + +`image.channel(index, image)` + + Given zero-based channel index then image, return a copied one-channel image of the same spatial shape. Invalid channel index fails. + +```haskell +Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_channel(hmath_context *context, const hmath_value *index, const hmath_value *image, hmath_value **out); +``` + +## `combine_channels` + +`image.combine_channels(images)` + + Concatenate channels of a nonempty same-spatial-shape image list in input order. Require total channels<=16; shape/count or checked storage limits fail. + +```haskell +[Image] -> Either MathError Image +``` + +```c +hmath_status hmath_image_combine_channels(hmath_context *context, const hmath_value *images, hmath_value **out); +``` + +## `map_image` + +`image.map_image(function, image)` + +Output is validated, including arithmetic overflow inside the callback. + +```haskell +(Double -> Double) -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_map_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *image, hmath_value **out); +``` + +## `zip_image` + +`image.zip_image(function, a, b)` + + Given binary sample function then equally shaped/channel-count images, return a new validated image. Mismatched shape/channels or non-finite output returns Left MathError. + +```haskell +(Double -> Double -> Double) -> Image -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_zip_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `normalize` + +`image.normalize(low, high, image)` + +Global min/max scaling; a constant image maps to the requested lower bound. + +```haskell +Double -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_normalize(hmath_context *context, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out); +``` + +## `brightness` + +`image.brightness(offset, image)` + +Add a finite offset without implicit clipping. + +```haskell +Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_brightness(hmath_context *context, const hmath_value *offset, const hmath_value *image, hmath_value **out); +``` + +## `contrast` + +`image.contrast(factor, pivot, image)` + +Scale about a caller-defined pivot, without clipping. + +```haskell +Double -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_contrast(hmath_context *context, const hmath_value *factor, const hmath_value *pivot, const hmath_value *image, hmath_value **out); +``` + +## `gamma` + +`image.gamma(power, image)` + +Positive gamma, nonnegative inputs; computes x^gamma without clipping. + +```haskell +Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_gamma(hmath_context *context, const hmath_value *power, const hmath_value *image, hmath_value **out); +``` + +## `constant` + +`image.constant(fill)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Boundary +``` + +```c +hmath_status hmath_image_constant(hmath_context *context, const hmath_value *fill, hmath_value **out); +``` + +## `clamp` + +`image.clamp()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Boundary +``` + +```c +hmath_status hmath_image_clamp(hmath_context *context, hmath_value **out); +``` + +## `reflect` + +`image.reflect()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Boundary +``` + +```c +hmath_status hmath_image_reflect(hmath_context *context, hmath_value **out); +``` + +## `wrap` + +`image.wrap()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Boundary +``` + +```c +hmath_status hmath_image_wrap(hmath_context *context, hmath_value **out); +``` + +## `convolve` + +`image.convolve(boundary, shape, weights, image)` + + Given boundary,kernel dimensions,flat weights,then image, reverse all kernel axes and correlate. Channels are filtered independently; require odd extents<=65, matching rank/count, <=4096 weights and <=20000000 sample operations. Invalid/non-finite input/result fails. + +```haskell +Boundary -> [Int] -> [Double] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_convolve(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out); +``` + +## `correlate` + +`image.correlate(boundary, shape, weights, image)` + + Correlation uses sample(ix+kernelOffset-center). Convolution reverses all kernel axes; channels are filtered independently without channel mixing. + +```haskell +Boundary -> [Int] -> [Double] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_correlate(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out); +``` + +## `gaussian_blur` + +`image.gaussian_blur(boundary, sigma, radius, image)` + +Separable Gaussian, truncated at an explicitly supplied integer radius. + +```haskell +Boundary -> Double -> Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_gaussian_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `box_blur` + +`image.box_blur(boundary, radius, image)` + + Given boundary,radius,then image, average a centered full-dimensional box neighborhood independently per channel. Neighborhood/work bounds and boundary finiteness are checked; invalid/non-finite output fails. + +```haskell +Boundary -> Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_box_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `median_blur` + +`image.median_blur(boundary, radius, image)` + + Given boundary,radius,then image, choose the median of each centered odd-sized neighborhood independently per channel. Invalid boundary/neighborhood/work bounds fail. + +```haskell +Boundary -> Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_median_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `bilateral_blur` + +`image.bilateral_blur(boundary, sigma_space, sigma_range, radius, image)` + + Per-channel bilateral filtering: spatial and range Gaussian weights are multiplied, normalized locally, and computed relative to the center sample. + +```haskell +Boundary -> Double -> Double -> Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_bilateral_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma_space, const hmath_value *sigma_range, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `sharpen` + +`image.sharpen(boundary, amount, sigma, radius, image)` + +Unsharp mask x+amount*(x-Gaussian(x)); no implicit range clipping. + +```haskell +Boundary -> Double -> Double -> Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_sharpen(hmath_context *context, const hmath_value *boundary, const hmath_value *amount, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `gradient` + +`image.gradient(method, boundary, image)` + + Returns row derivative, column derivative, magnitude, and atan2(row,col) direction in radians. Smoothing/derivative kernels are normalized so an interior unit ramp has derivative one. + +```haskell +GradientOperator -> Boundary -> Image -> Either MathError (Image, Image, Image, Image) +``` + +```c +hmath_status hmath_image_gradient(hmath_context *context, const hmath_value *method, const hmath_value *boundary, const hmath_value *image, hmath_value **out); +``` + +## `laplacian` + +`image.laplacian(boundary, image)` + + Given boundary then one-channel 2D image, apply the four-neighbor 3-by-3 Laplacian [0,1,0;1,-4,1;0,1,0]. Invalid image/boundary or non-finite output fails. + +```haskell +Boundary -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_laplacian(hmath_context *context, const hmath_value *boundary, const hmath_value *image, hmath_value **out); +``` + +## `canny` + +`image.canny(boundary, sigma, radius, low, high, image)` + + Canny: Gaussian smoothing, Sobel gradient, four-direction nonmaximum suppression, and 8-connected hysteresis. low/high are absolute normalized gradient magnitudes, not quantiles. Output is exactly zero or one. + +```haskell +Boundary -> Double -> Int -> Double -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_canny(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out); +``` + +## `morphology` + +`image.morphology(operation, boundary, shape, mask, image)` + + Flat grayscale morphology with an explicit odd-rank Boolean footprint. Erosion samples x+offset; dilation samples x-offset (reflected footprint), so asymmetric footprints obey the usual adjunction. Opening/closing compose these operators under the same caller-selected boundary extension. + +```haskell +Morphology -> Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_morphology(hmath_context *context, const hmath_value *operation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out); +``` + +## `morphological_gradient` + +`image.morphological_gradient(boundary, shape, mask, image)` + + Given boundary,footprint dimensions,Bool footprint,then image, return dilation minus erosion. Shape/footprint/work/boundary validation and finite output checks propagate from morphology. + +```haskell +Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_morphological_gradient(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out); +``` + +## `validate_boundary` + +`image.validate_boundary(boundary)` + + Validate Constant boundary value as finite; Clamp,Reflect,Wrap are always valid. Non-finite constant returns Left InvalidArgument. + +```haskell +Boundary -> Either MathError () +``` + +```c +hmath_status hmath_image_validate_boundary(hmath_context *context, const hmath_value *boundary, hmath_value **out); +``` + +## `scalar2_d` + +`image.scalar2_d(image)` + + Require a two-dimensional one-channel image and return (height,width). Other spatial/channel layouts return Left InvalidArgument. + +```haskell +Image -> Either MathError (Int, Int) +``` + +```c +hmath_status hmath_image_scalar2_d(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `window_offsets` + +`image.window_offsets(radius, image)` + + Given radius then image, enumerate centered neighborhood offsets. Require radius in [0,16], <=4096 neighbors and <=20000000 sample operations; otherwise fail. + +```haskell +Int -> Image -> Either MathError [[Int]] +``` + +```c +hmath_status hmath_image_window_offsets(hmath_context *context, const hmath_value *radius, const hmath_value *image, hmath_value **out); +``` + +## `sobel` + +`image.sobel()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GradientOperator +``` + +```c +hmath_status hmath_image_sobel(hmath_context *context, hmath_value **out); +``` + +## `prewitt` + +`image.prewitt()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GradientOperator +``` + +```c +hmath_status hmath_image_prewitt(hmath_context *context, hmath_value **out); +``` + +## `scharr` + +`image.scharr()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GradientOperator +``` + +```c +hmath_status hmath_image_scharr(hmath_context *context, hmath_value **out); +``` + +## `erosion` + +`image.erosion()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Morphology +``` + +```c +hmath_status hmath_image_erosion(hmath_context *context, hmath_value **out); +``` + +## `dilation` + +`image.dilation()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Morphology +``` + +```c +hmath_status hmath_image_dilation(hmath_context *context, hmath_value **out); +``` + +## `opening` + +`image.opening()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Morphology +``` + +```c +hmath_status hmath_image_opening(hmath_context *context, hmath_value **out); +``` + +## `closing` + +`image.closing()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Morphology +``` + +```c +hmath_status hmath_image_closing(hmath_context *context, hmath_value **out); +``` + +## `histogram` + +`image.histogram(bins, image)` + + Given bin count in [2,4096] then image with every sample in [0,1], return one Int count list per channel. Values at 1 enter the final bin. Invalid count/range fails. + +```haskell +Int -> Image -> Either MathError [[Int]] +``` + +```c +hmath_status hmath_image_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +``` + +## `equalize_histogram` + +`image.equalize_histogram(bins, image)` + + CDF-min equalization with quantized bin mapping. A single occupied bin is left unchanged, avoiding an arbitrary jump on constant images. + +```haskell +Int -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_equalize_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +``` + +## `clahe` + +`image.clahe(bins, tiles, clip_limit, image)` + + 2D adaptive equalization. clipFactor>=1 is relative to uniform tile occupancy; the cap is max(ceil(tileSamples/bins),floor(factor*tileSamples/bins)). Tiles at image ends may be smaller. Intensities are quantized without channel coupling. At most 4,096 tiles and 1,048,576 stored histogram bins. + +```haskell +Int -> (Int, Int) -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_clahe(hmath_context *context, const hmath_value *bins, const hmath_value *tiles, const hmath_value *clip_limit, const hmath_value *image, hmath_value **out); +``` + +## `threshold` + +`image.threshold(level, image)` + +Strict comparison x>level; each channel is thresholded independently. + +```haskell +Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_threshold(hmath_context *context, const hmath_value *level, const hmath_value *image, hmath_value **out); +``` + +## `otsu` + +`image.otsu(bins, image)` + + Otsu between-class variance maximum. Lowest threshold wins ties. Returns one bin-edge threshold per channel; a constant channel returns its value. + +```haskell +Int -> Image -> Either MathError ([Double], Image) +``` + +```c +hmath_status hmath_image_otsu(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +``` + +## `adaptive_threshold` + +`image.adaptive_threshold(gaussian, boundary, radius, offset, image)` + + Local mean or Gaussian threshold: x > localMean-offset. Gaussian uses sigma=max(0.5,radius/2); boundary extension is explicit. + +```haskell +Bool -> Boundary -> Int -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_adaptive_threshold(hmath_context *context, const hmath_value *gaussian, const hmath_value *boundary, const hmath_value *radius, const hmath_value *offset, const hmath_value *image, hmath_value **out); +``` + +## `template_match` + +`image.template_match(metric, needle, haystack)` + + Valid 2D, one-channel matching. Each output is one template origin. NCC centers both patches and divides by their energies; constant templates or candidate patches have undefined correlation and return MathError. + +```haskell +TemplateMetric -> Image -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_template_match(hmath_context *context, const hmath_value *metric, const hmath_value *needle, const hmath_value *haystack, hmath_value **out); +``` + +## `raw_moment` + +`image.raw_moment(row_order, column_order, image)` + +Raw M_pq=sum(row^p*column^q*intensity), orders 0..8 each. + +```haskell +Int -> Int -> Image -> Either MathError Double +``` + +```c +hmath_status hmath_image_raw_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out); +``` + +## `central_moment` + +`image.central_moment(row_order, column_order, image)` + + Given row exponent p,column exponent q,then scalar 2D image, compute the unnormalized intensity-weighted central moment around its centroid. Require orders in [0,8]; invalid image/zero mass or non-finite result fails. + +```haskell +Int -> Int -> Image -> Either MathError Double +``` + +```c +hmath_status hmath_image_central_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out); +``` + +## `image_centroid` + +`image.image_centroid(image)` + + Intensity-weighted (row,column) centroid. Signed intensities are allowed; a zero total mass is undefined and reported explicitly. + +```haskell +Image -> Either MathError (Double, Double) +``` + +```c +hmath_status hmath_image_image_centroid(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `integral_image` + +`image.integral_image(image)` + + Padded 2D summed-area image, per channel: output shape (height+1,width+1) has a leading zero row/column. Rectangle queries use half-open bounds. + +```haskell +Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_integral_image(hmath_context *context, const hmath_value *image, hmath_value **out); +``` + +## `rectangle_sum` + +`image.rectangle_sum(origin, extent, image)` + + Given (row,column) origin,(height,width) extent,then padded integralImage output, return per-channel sum of the half-open rectangle. Reject invalid/out-of-range bounds; zero extents are allowed. + +```haskell +(Int, Int) -> (Int, Int) -> Image -> Either MathError [Double] +``` + +```c +hmath_status hmath_image_rectangle_sum(hmath_context *context, const hmath_value *origin, const hmath_value *extent, const hmath_value *image, hmath_value **out); +``` + +## `mean_squared_error` + +`image.mean_squared_error(a, b)` + + Given two images of equal spatial shape and channels, return average squared sample difference. Shape mismatch or non-finite arithmetic returns Left MathError. + +```haskell +Image -> Image -> Either MathError Double +``` + +```c +hmath_status hmath_image_mean_squared_error(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `peak_signal_to_noise` + +`image.peak_signal_to_noise(data_range, a, b)` + + PSNR in decibels. Exactly identical images return positive infinity by definition; this is the sole intentional nonfinite measurement result. + +```haskell +Double -> Image -> Image -> Either MathError Double +``` + +```c +hmath_status hmath_image_peak_signal_to_noise(hmath_context *context, const hmath_value *data_range, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `structural_similarity` + +`image.structural_similarity(data_range, window, a, b)` + + Mean local SSIM with uniform valid windows and population covariance. C1=(0.01*range)^2, C2=(0.03*range)^2; all channels are measured separately. Windows do not include padding and both spatial extents must fit the window. Wang et al., Image Quality Assessment: From Error Visibility to Structural Similarity (2004), https://ece.uwaterloo.ca/~z70wang/publications/ssim.html . + +```haskell +Double -> Int -> Image -> Image -> Either MathError Double +``` + +```c +hmath_status hmath_image_structural_similarity(hmath_context *context, const hmath_value *data_range, const hmath_value *window, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `squared_difference` + +`image.squared_difference()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +TemplateMetric +``` + +```c +hmath_status hmath_image_squared_difference(hmath_context *context, hmath_value **out); +``` + +## `normalized_correlation` + +`image.normalized_correlation()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +TemplateMetric +``` + +```c +hmath_status hmath_image_normalized_correlation(hmath_context *context, hmath_value **out); +``` + +## `resize` + +`image.resize(interpolation, boundary, shape, image)` + + 2D resize uses pixel-center mapping (i+0.5)*old/new-0.5, independently per channel, without antialiasing. Bicubic is Keys a=-0.5; Lanczos has radius three. Downsampling callers can explicitly prefilter first. + +```haskell +Interpolation -> Boundary -> (Int, Int) -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_resize(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *image, hmath_value **out); +``` + +## `warp` + +`image.warp(interpolation, boundary, shape, matrix, image)` + + Forward 3x3 homogeneous transform acts on [x(column),y(row),1]. The matrix is inverted once for output-to-input sampling. Points at projective infinity or with magnitude over 1e9 are errors, even with constant padding. + +```haskell +Interpolation -> Boundary -> (Int, Int) -> [[Double]] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_warp(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *matrix, const hmath_value *image, hmath_value **out); +``` + +## `translate` + +`image.translate(interpolation, boundary, row_shift, column_shift, image)` + +Translation in pixel columns/rows; output dimensions equal input. + +```haskell +Interpolation -> Boundary -> Double -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_translate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *row_shift, const hmath_value *column_shift, const hmath_value *image, hmath_value **out); +``` + +## `rotate` + +`image.rotate(interpolation, boundary, angle, image)` + + Angle in radians, clockwise on row-down image coordinates; rotate about the center pixel coordinate while preserving the input canvas dimensions. + +```haskell +Interpolation -> Boundary -> Double -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_rotate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *angle, const hmath_value *image, hmath_value **out); +``` + +## `connected_components` + +`image.connected_components(connectivity, image)` + + Nonzero is foreground. Label zero is background; component labels start at one in first-pixel row-major order. Returns labels as exact Doubles and component sizes in that same order. Connectivity has no wraparound. + +```haskell +Connectivity -> Image -> Either MathError (Image, [Int]) +``` + +```c +hmath_status hmath_image_connected_components(hmath_context *context, const hmath_value *connectivity, const hmath_value *image, hmath_value **out); +``` + +## `distance_transform` + +`image.distance_transform(spacing, image)` + + Exact brute-force Euclidean distance to the nearest zero-valued spatial sample, with strictly positive per-axis spacing. No implicit outside zeros; an all-foreground image has no finite answer and returns DomainError. + +```haskell +[Double] -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_distance_transform(hmath_context *context, const hmath_value *spacing, const hmath_value *image, hmath_value **out); +``` + +## `nearest` + +`image.nearest()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Interpolation +``` + +```c +hmath_status hmath_image_nearest(hmath_context *context, hmath_value **out); +``` + +## `bilinear` + +`image.bilinear()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Interpolation +``` + +```c +hmath_status hmath_image_bilinear(hmath_context *context, hmath_value **out); +``` + +## `bicubic` + +`image.bicubic()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Interpolation +``` + +```c +hmath_status hmath_image_bicubic(hmath_context *context, hmath_value **out); +``` + +## `lanczos` + +`image.lanczos()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Interpolation +``` + +```c +hmath_status hmath_image_lanczos(hmath_context *context, hmath_value **out); +``` + +## `axis_connected` + +`image.axis_connected()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Connectivity +``` + +```c +hmath_status hmath_image_axis_connected(hmath_context *context, hmath_value **out); +``` + +## `fully_connected` + +`image.fully_connected()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Connectivity +``` + +```c +hmath_status hmath_image_fully_connected(hmath_context *context, hmath_value **out); +``` + +## `convert_color` + +`image.convert_color(source, destination, image)` + +Explicit source/destination spaces; three interleaved channels required. + +```haskell +ColorSpace -> ColorSpace -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_convert_color(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *image, hmath_value **out); +``` + +## `grayscale` + +`image.grayscale(source, image)` + +Rec.709 luminance, explicitly converting the stated source to linear RGB. + +```haskell +ColorSpace -> Image -> Either MathError Image +``` + +```c +hmath_status hmath_image_grayscale(hmath_context *context, const hmath_value *source, const hmath_value *image, hmath_value **out); +``` + +## `srgb` + +`image.srgb()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_srgb(hmath_context *context, hmath_value **out); +``` + +## `linear_rgb` + +`image.linear_rgb()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_linear_rgb(hmath_context *context, hmath_value **out); +``` + +## `hsv` + +`image.hsv()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_hsv(hmath_context *context, hmath_value **out); +``` + +## `hsl` + +`image.hsl()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_hsl(hmath_context *context, hmath_value **out); +``` + +## `xyz` + +`image.xyz()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_xyz(hmath_context *context, hmath_value **out); +``` + +## `lab` + +`image.lab()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_lab(hmath_context *context, hmath_value **out); +``` + +## `y_cb_cr` + +`image.y_cb_cr()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ColorSpace +``` + +```c +hmath_status hmath_image_y_cb_cr(hmath_context *context, hmath_value **out); +``` + +## `tensor` + +`image.tensor(shape, values)` + + Given shape then flat row-major values, construct an immutable CPU tensor. Require exactly the shape product values; invalid dimensions/count return Left MathError. Generic values are not validated for finiteness. + +```haskell +[Int] -> [Double] -> Either MathError Tensor Double +``` + +```c +hmath_status hmath_image_tensor(hmath_context *context, const hmath_value *shape, const hmath_value *values, hmath_value **out); +``` + +## `tensor_shape` + +`image.tensor_shape(tensor)` + +Return dimensions in axis order. Scalar shape is []; empty axes are retained. + +```haskell +Tensor Double -> [Int] +``` + +```c +hmath_status hmath_image_tensor_shape(hmath_context *context, const hmath_value *tensor, hmath_value **out); +``` + +## `tensor_values` + +`image.tensor_values(tensor)` + + Return logical values in row-major coordinate order, honoring strides/offsets rather than exposing raw backing storage. + +```haskell +Tensor Double -> [Double] +``` + +```c +hmath_status hmath_image_tensor_values(hmath_context *context, const hmath_value *tensor, hmath_value **out); +``` + diff --git a/docs/reference/interchange-bindings.md b/docs/reference/interchange-bindings.md new file mode 100644 index 0000000..acfc239 --- /dev/null +++ b/docs/reference/interchange-bindings.md @@ -0,0 +1,1494 @@ +# Array interchange + +Python uses `from hmath import interchange`; C includes `hmath_interchange.h`. These adapters call the original Haskell array, binary/text/NumPy, compression, streaming and mapped-file functions. Source byte/shape/archive budgets, checksums, metadata, byte order, stride/offset semantics and errors remain unchanged. + +Each successful C output owns one [structured value](values.md); inputs are borrowed during the call and failure leaves output pointers untouched. `InterchangeError` uses status13 with its original four-way constructor and full message available through `hmath_last_interchange_error`. Python raises `HMathError` with `interchange_error`. Callbacks may supply the original checked Left by raising `InterchangeError`. Unexpected exceptions abort and are re-raised after cleanup. + +ByteString results are owned `Bytes` objects. `bytes(result)` copies; `result.view()` borrows a read-only span retaining an independent reference. C uses `hmath_bytes_data` while retaining the owner. No terminator is implied. Binary/raw preserve IEEE bits; text follows the source policy and does not promise NaN payload preservation. `boxed=True` on scalar/list decoders retains native typed values when Python scalar conversion is undesirable. + +Element-polymorphic operations select one original fixed-width instance using a scalar/Boolean prototype in C or `dtype=` in Python. Supported types are Bool8, signed/unsigned8/16/32/64, Float32/64 and Complex64/128. Array dtype and requested result type must match as in Haskell. Matrix/Tensor conversions preserve actual element types; they do not route FP32 through FP64. `get_element` returns the original parser program; `run_decoder` executes the original strict decoder, including trailing-byte checks. `put_element` returns the original Put program and `put_bytes` runs it. + +Mapped array access is callback-scoped. A retained mapping capability rejects data reads after scope exit through the original closed-state checks; copied Bytes remain valid. File writes retain the source's IO effects and partial-write behavior. `open_handle`/`close_handle` and seek/tell/flush expose real binary Haskell handles for the original chunked APIs. Handles are shared resources; close them explicitly before releasing their owners. + +## `big_endian` + +`interchange.big_endian()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.BigEndian`](haskell/HMath-Interchange-Array.md#v:BigEndian). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Endian +``` + +```c +hmath_status hmath_interchange_value_big_endian(hmath_context *context, hmath_value **out); +``` + +## `bool8` + +`interchange.bool8()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.Bool8`](haskell/HMath-Interchange-Array.md#v:Bool8). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_bool8(hmath_context *context, hmath_value **out); +``` + +## `c128` + +`interchange.c128()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.C128`](haskell/HMath-Interchange-Array.md#v:C128). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_c128(hmath_context *context, hmath_value **out); +``` + +## `c64` + +`interchange.c64()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.C64`](haskell/HMath-Interchange-Array.md#v:C64). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_c64(hmath_context *context, hmath_value **out); +``` + +## `c_order` + +`interchange.c_order()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.COrder`](haskell/HMath-Interchange-Array.md#v:COrder). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Order +``` + +```c +hmath_status hmath_interchange_value_c_order(hmath_context *context, hmath_value **out); +``` + +## `f32` + +`interchange.f32()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.F32`](haskell/HMath-Interchange-Array.md#v:F32). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_f32(hmath_context *context, hmath_value **out); +``` + +## `f64` + +`interchange.f64()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.F64`](haskell/HMath-Interchange-Array.md#v:F64). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_f64(hmath_context *context, hmath_value **out); +``` + +## `f_order` + +`interchange.f_order()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.FOrder`](haskell/HMath-Interchange-Array.md#v:FOrder). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Order +``` + +```c +hmath_status hmath_interchange_value_f_order(hmath_context *context, hmath_value **out); +``` + +## `i16` + +`interchange.i16()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.I16`](haskell/HMath-Interchange-Array.md#v:I16). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_i16(hmath_context *context, hmath_value **out); +``` + +## `i32` + +`interchange.i32()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.I32`](haskell/HMath-Interchange-Array.md#v:I32). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_i32(hmath_context *context, hmath_value **out); +``` + +## `i64` + +`interchange.i64()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.I64`](haskell/HMath-Interchange-Array.md#v:I64). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_i64(hmath_context *context, hmath_value **out); +``` + +## `i8` + +`interchange.i8()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.I8`](haskell/HMath-Interchange-Array.md#v:I8). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_i8(hmath_context *context, hmath_value **out); +``` + +## `interchange_io_error` + +`interchange.interchange_io_error(message)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.InterchangeIOError`](haskell/HMath-Interchange-Array.md#v:InterchangeIOError). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +String -> InterchangeError +``` + +```c +hmath_status hmath_interchange_value_interchange_io_error(hmath_context *context, const hmath_value *message, hmath_value **out); +``` + +## `invalid_data` + +`interchange.invalid_data(message)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.InvalidData`](haskell/HMath-Interchange-Array.md#v:InvalidData). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +String -> InterchangeError +``` + +```c +hmath_status hmath_interchange_value_invalid_data(hmath_context *context, const hmath_value *message, hmath_value **out); +``` + +## `limit_exceeded` + +`interchange.limit_exceeded(message)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.LimitExceeded`](haskell/HMath-Interchange-Array.md#v:LimitExceeded). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +String -> InterchangeError +``` + +```c +hmath_status hmath_interchange_value_limit_exceeded(hmath_context *context, const hmath_value *message, hmath_value **out); +``` + +## `limits` + +`interchange.limits(max_bytes, max_elements, max_rank, max_metadata, max_archive_entries)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.Limits`](haskell/HMath-Interchange-Array.md#v:Limits). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Int -> Int -> Int -> Int -> Int -> Limits +``` + +```c +hmath_status hmath_interchange_value_limits(hmath_context *context, const hmath_value *max_bytes, const hmath_value *max_elements, const hmath_value *max_rank, const hmath_value *max_metadata, const hmath_value *max_archive_entries, hmath_value **out); +``` + +## `little_endian` + +`interchange.little_endian()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.LittleEndian`](haskell/HMath-Interchange-Array.md#v:LittleEndian). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Endian +``` + +```c +hmath_status hmath_interchange_value_little_endian(hmath_context *context, hmath_value **out); +``` + +## `u16` + +`interchange.u16()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.U16`](haskell/HMath-Interchange-Array.md#v:U16). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_u16(hmath_context *context, hmath_value **out); +``` + +## `u32` + +`interchange.u32()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.U32`](haskell/HMath-Interchange-Array.md#v:U32). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_u32(hmath_context *context, hmath_value **out); +``` + +## `u64` + +`interchange.u64()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.U64`](haskell/HMath-Interchange-Array.md#v:U64). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_u64(hmath_context *context, hmath_value **out); +``` + +## `u8` + +`interchange.u8()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.U8`](haskell/HMath-Interchange-Array.md#v:U8). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType +``` + +```c +hmath_status hmath_interchange_value_u8(hmath_context *context, hmath_value **out); +``` + +## `unsupported` + +`interchange.unsupported(message)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.Unsupported`](haskell/HMath-Interchange-Array.md#v:Unsupported). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +String -> InterchangeError +``` + +```c +hmath_status hmath_interchange_value_unsupported(hmath_context *context, const hmath_value *message, hmath_value **out); +``` + +## `array` + +`interchange.array(lim, dt, en, sh, st, off, bs)` + + Construct a bounded view. Bool8 bytes reachable through the view must be 0 or 1. Floating payloads preserve IEEE NaNs, signed zero and infinities. + +Original: [`HMath.Interchange.Array.array`](haskell/HMath-Interchange-Array.md#v:array). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> DType -> Endian -> [Int] -> [Int] -> Int -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *sh, const hmath_value *st, const hmath_value *off, const hmath_value *bs, hmath_value **out); +``` + +## `array_bytes` + +`interchange.array_bytes(value)` + + Return immutable backing bytes, which may include padding or data not reached by the logical strided view. Use toValues or repack for logical contents. + +Original: [`HMath.Interchange.Array.arrayBytes`](haskell/HMath-Interchange-Array.md#v:arrayBytes). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> ByteString +``` + +```c +hmath_status hmath_interchange_value_array_bytes(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_d_type` + +`interchange.array_d_type(value)` + + Return the fixed-width wire dtype of an Array; this is independent of Haskell host Int/Double defaults. + +Original: [`HMath.Interchange.Array.arrayDType`](haskell/HMath-Interchange-Array.md#v:arrayDType). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> DType +``` + +```c +hmath_status hmath_interchange_value_array_d_type(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_endian` + +`interchange.array_endian(value)` + +Return explicit payload byte order; single-byte dtypes are endian-independent. + +Original: [`HMath.Interchange.Array.arrayEndian`](haskell/HMath-Interchange-Array.md#v:arrayEndian). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> Endian +``` + +```c +hmath_status hmath_interchange_value_array_endian(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_metadata` + +`interchange.array_metadata(value)` + + Return descriptive UTF-8-compatible key/value metadata strings in stored order; metadata is not executable. + +Original: [`HMath.Interchange.Array.arrayMetadata`](haskell/HMath-Interchange-Array.md#v:arrayMetadata). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> [(String, String)] +``` + +```c +hmath_status hmath_interchange_value_array_metadata(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_offset` + +`interchange.array_offset(value)` + +Return byte offset of logical origin within arrayBytes backing storage. + +Original: [`HMath.Interchange.Array.arrayOffset`](haskell/HMath-Interchange-Array.md#v:arrayOffset). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> Int +``` + +```c +hmath_status hmath_interchange_value_array_offset(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_shape` + +`interchange.array_shape(value)` + +Return logical dimensions in axis order; [] is scalar and zero axes are valid. + +Original: [`HMath.Interchange.Array.arrayShape`](haskell/HMath-Interchange-Array.md#v:arrayShape). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> [Int] +``` + +```c +hmath_status hmath_interchange_value_array_shape(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `array_strides` + +`interchange.array_strides(value)` + + Return signed byte strides for each axis. Unlike HMath.Tensor strides, these are bytes, not elements. + +Original: [`HMath.Interchange.Array.arrayStrides`](haskell/HMath-Interchange-Array.md#v:arrayStrides). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> [Int] +``` + +```c +hmath_status hmath_interchange_value_array_strides(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `contiguous_array` + +`interchange.contiguous_array(lim, dt, en, order, sh, bs)` + + Given limits,dtype,endian,physical order,shape,then exact packed bytes, construct a canonical byte-strided array. Require exact byte count; invalid shape/data/limits fail. + +Original: [`HMath.Interchange.Array.contiguousArray`](haskell/HMath-Interchange-Array.md#v:contiguousArray). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_contiguous_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *order, const hmath_value *sh, const hmath_value *bs, hmath_value **out); +``` + +## `default_limits` + +`interchange.default_limits()` + +128 MiB of bytes, 8 million samples, rank 16, 64 KiB metadata, 256 members. + +Original: [`HMath.Interchange.Array.defaultLimits`](haskell/HMath-Interchange-Array.md#v:defaultLimits). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits +``` + +```c +hmath_status hmath_interchange_value_default_limits(hmath_context *context, hmath_value **out); +``` + +## `dense_strides` + +`interchange.dense_strides(c_order, w, sh)` + + Dense strides use Integer arithmetic before conversion. Call only on validated shape/byte sizes; zero axes use zero strides to avoid overflow. + +Original: [`HMath.Interchange.Array.denseStrides`](haskell/HMath-Interchange-Array.md#v:denseStrides). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Order -> Int -> [Int] -> [Int] +``` + +```c +hmath_status hmath_interchange_value_dense_strides(hmath_context *context, const hmath_value *c_order, const hmath_value *w, const hmath_value *sh, hmath_value **out); +``` + +## `element_bytes` + +`interchange.element_bytes(dt)` + + Return fixed byte width of a DType, including complex pairs (C64=8,C128=16) and Bool8=1. + +Original: [`HMath.Interchange.Array.elementBytes`](haskell/HMath-Interchange-Array.md#v:elementBytes). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType -> Int +``` + +```c +hmath_status hmath_interchange_value_element_bytes(hmath_context *context, const hmath_value *dt, hmath_value **out); +``` + +## `element_count` + +`interchange.element_count(value)` + +Return logical shape product; scalar arrays have one element and empty axes have zero. + +Original: [`HMath.Interchange.Array.elementCount`](haskell/HMath-Interchange-Array.md#v:elementCount). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> Int +``` + +```c +hmath_status hmath_interchange_value_element_count(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `element_type` + +`interchange.element_type(*, dtype="float64")` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.elementType`](haskell/HMath-Interchange-Array.md#v:elementType). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => proxy a -> DType +``` + +```c +hmath_status hmath_interchange_value_element_type(hmath_context *context, const hmath_value *prototype, hmath_value **out); +``` + +## `from_matrix` + +`interchange.from_matrix(value, value2, value3)` + + Given limits,endian,then typed Matrix, encode its row-major values as a rank-two Array. Dtype comes from Element; resource limits can fail. + +Original: [`HMath.Interchange.Array.fromMatrix`](haskell/HMath-Interchange-Array.md#v:fromMatrix). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Limits -> Endian -> HMath.Matrix.Matrix a -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_from_matrix(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `from_tensor` + +`interchange.from_tensor(value, value2, value3)` + + Given limits,endian,then typed Haskell Tensor, encode logical row-major values and preserve shape. The Element instance determines wire dtype; resource bounds can fail. + +Original: [`HMath.Interchange.Array.fromTensor`](haskell/HMath-Interchange-Array.md#v:fromTensor). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Limits -> Endian -> HMath.Tensor.Tensor a -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_from_tensor(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `from_values` + +`interchange.from_values(limits,endian,shape,values, *, dtype="float64")` + + Given limits,endian,shape,then typed Element list, encode to a contiguous array with that Element dtype. Require exact shape/count match and resource bounds; failures return InterchangeError. + +Original: [`HMath.Interchange.Array.fromValues`](haskell/HMath-Interchange-Array.md#v:fromValues). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Limits -> Endian -> [Int] -> [a] -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_from_values(hmath_context *context, const hmath_value *prototype, const hmath_value *limits, const hmath_value *endian, const hmath_value *shape, const hmath_value *values, hmath_value **out); +``` + +## `get_element` + +`interchange.get_element(endian, *, dtype="float64")` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.getElement`](haskell/HMath-Interchange-Array.md#v:getElement). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Endian -> Data.Binary.Get.Internal.Get a +``` + +```c +hmath_status hmath_interchange_value_get_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, hmath_value **out); +``` + +## `max_archive_entries` + +`interchange.max_archive_entries(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.maxArchiveEntries`](haskell/HMath-Interchange-Array.md#v:maxArchiveEntries). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Int +``` + +```c +hmath_status hmath_interchange_value_max_archive_entries(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `max_bytes` + +`interchange.max_bytes(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.maxBytes`](haskell/HMath-Interchange-Array.md#v:maxBytes). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Int +``` + +```c +hmath_status hmath_interchange_value_max_bytes(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `max_elements` + +`interchange.max_elements(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.maxElements`](haskell/HMath-Interchange-Array.md#v:maxElements). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Int +``` + +```c +hmath_status hmath_interchange_value_max_elements(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `max_metadata` + +`interchange.max_metadata(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.maxMetadata`](haskell/HMath-Interchange-Array.md#v:maxMetadata). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Int +``` + +```c +hmath_status hmath_interchange_value_max_metadata(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `max_rank` + +`interchange.max_rank(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.maxRank`](haskell/HMath-Interchange-Array.md#v:maxRank). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Int +``` + +```c +hmath_status hmath_interchange_value_max_rank(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `put_element` + +`interchange.put_element(endian,value, *, dtype="float64")` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Array.putElement`](haskell/HMath-Interchange-Array.md#v:putElement). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Endian -> a -> Data.Binary.Put.Put +``` + +```c +hmath_status hmath_interchange_value_put_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, const hmath_value *value, hmath_value **out); +``` + +## `raw_decode` + +`interchange.raw_decode(value, value2, value3, value4, value5, value6)` + + Given limits,dtype,endian,order,shape,then bytes, construct a packed Array. Caller supplies all metadata; exact byte-count and shape/resource validation is enforced. + +Original: [`HMath.Interchange.Array.rawDecode`](haskell/HMath-Interchange-Array.md#v:rawDecode). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_raw_decode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +``` + +## `raw_encode` + +`interchange.raw_encode(value, value2, value3, value4)` + + Given limits,destination endian,physical order,then Array, repack its logical payload and return raw bytes without shape/header metadata. Checked resource/layout failures propagate. + +Original: [`HMath.Interchange.Array.rawEncode`](haskell/HMath-Interchange-Array.md#v:rawEncode). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Endian -> Order -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_raw_encode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `repack` + +`interchange.repack(lim, en, order, a)` + + Pack arbitrary views, preserving dtype and exact component bits. Complex byte swapping reverses each real/imaginary component separately. + +Original: [`HMath.Interchange.Array.repack`](haskell/HMath-Interchange-Array.md#v:repack). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Endian -> Order -> Array -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_repack(hmath_context *context, const hmath_value *lim, const hmath_value *en, const hmath_value *order, const hmath_value *a, hmath_value **out); +``` + +## `to_matrix` + +`interchange.to_matrix(array, *, dtype=None)` + + Decode a matching typed rank-two Array to Matrix. Rank/dtype or checked shape conversion failures return InterchangeError. + +Original: [`HMath.Interchange.Array.toMatrix`](haskell/HMath-Interchange-Array.md#v:toMatrix). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Array -> Either InterchangeError (HMath.Matrix.Matrix a) +``` + +```c +hmath_status hmath_interchange_value_to_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +``` + +## `to_tensor` + +`interchange.to_tensor(array, *, dtype=None)` + + Decode an Array of matching Element dtype to a contiguous Haskell Tensor, preserving logical shape/order. Dtype or checked tensor-construction failure returns InterchangeError. + +Original: [`HMath.Interchange.Array.toTensor`](haskell/HMath-Interchange-Array.md#v:toTensor). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Array -> Either InterchangeError (HMath.Tensor.Tensor a) +``` + +```c +hmath_status hmath_interchange_value_to_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +``` + +## `to_values` + +`interchange.to_values(array, *, dtype=None, boxed=False)` + + Decode logical row-major values as the requested Element type, requiring an exact dtype match. No silent numeric cast occurs; mismatch returns Unsupported/InvalidData. + +Original: [`HMath.Interchange.Array.toValues`](haskell/HMath-Interchange-Array.md#v:toValues). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Element a => Array -> Either InterchangeError [a] +``` + +```c +hmath_status hmath_interchange_value_to_values(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +``` + +## `validate_shape` + +`interchange.validate_shape(lim, sh)` + + Given limits then dimensions, validate rank, nonnegative axes and element product, returning Int element count. Invalid data or exceeded limits return InterchangeError. + +Original: [`HMath.Interchange.Array.validateShape`](haskell/HMath-Interchange-Array.md#v:validateShape). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> [Int] -> Either InterchangeError Int +``` + +```c +hmath_status hmath_interchange_value_validate_shape(hmath_context *context, const hmath_value *lim, const hmath_value *sh, hmath_value **out); +``` + +## `with_metadata` + +`interchange.with_metadata(value, value2, value3)` + + Metadata is UTF-8 in binary files; keys must be unique and nonempty. The four-byte-per-codepoint bound is intentionally conservative before encoding. + +Original: [`HMath.Interchange.Array.withMetadata`](haskell/HMath-Interchange-Array.md#v:withMetadata). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> [(String, String)] -> Array -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_with_metadata(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `crc32` + +`interchange.crc32(value)` + +Standard CRC-32, compatible with ZIP and zlib, with a fixed 256-entry table. + +Original: [`HMath.Interchange.Binary.crc32`](haskell/HMath-Interchange-Binary.md#v:crc32). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +ByteString -> Word32 +``` + +```c +hmath_status hmath_interchange_value_crc32(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `decode_binary` + +`interchange.decode_binary(lim, input)` + + Given limits then bytes, validate HMath v1 magic/header/flags/CRC and exact framing, returning an Array. Truncation, corruption, unsupported metadata or exceeded budgets return InterchangeError. + +Original: [`HMath.Interchange.Binary.decodeBinary`](haskell/HMath-Interchange-Binary.md#v:decodeBinary). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_decode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +``` + +## `encode_binary` + +`interchange.encode_binary(lim, a)` + + Given limits then Array, encode HMath wire-format v1 including shape/strides/offset/metadata/backing storage and CRC-32. Invalid metadata/layout or exceeded aggregate byte budget fails. + +Original: [`HMath.Interchange.Binary.encodeBinary`](haskell/HMath-Interchange-Binary.md#v:encodeBinary). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_encode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +``` + +## `gzip` + +`interchange.gzip()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Compression.Gzip`](haskell/HMath-Interchange-Compression.md#v:Gzip). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Compression +``` + +```c +hmath_status hmath_interchange_value_gzip(hmath_context *context, hmath_value **out); +``` + +## `raw_deflate` + +`interchange.raw_deflate()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Compression.RawDeflate`](haskell/HMath-Interchange-Compression.md#v:RawDeflate). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Compression +``` + +```c +hmath_status hmath_interchange_value_raw_deflate(hmath_context *context, hmath_value **out); +``` + +## `zlib` + +`interchange.zlib()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.Compression.Zlib`](haskell/HMath-Interchange-Compression.md#v:Zlib). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Compression +``` + +```c +hmath_status hmath_interchange_value_zlib(hmath_context *context, hmath_value **out); +``` + +## `compress` + +`interchange.compress(lim, wrapper, input)` + + Given limits,RawDeflate/Zlib/Gzip wrapper,then bytes, compress within a bounded output allocation. Return InterchangeError for unavailable provider, invalid limits, byte-budget excess or compression failure in IO. + +Original: [`HMath.Interchange.Compression.compress`](haskell/HMath-Interchange-Compression.md#v:compress). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Compression -> ByteString -> IO (Either InterchangeError ByteString) +``` + +```c +hmath_status hmath_interchange_value_compress(hmath_context *context, const hmath_value *lim, const hmath_value *wrapper, const hmath_value *input, hmath_value **out); +``` + +## `compression_available` + +`interchange.compression_available()` + + Probe whether the optional native zlib adapter is available, returning IO Bool. False means compressed operations cannot run; no payload is processed. + +Original: [`HMath.Interchange.Compression.compressionAvailable`](haskell/HMath-Interchange-Compression.md#v:compressionAvailable). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +IO Bool +``` + +```c +hmath_status hmath_interchange_value_compression_available(hmath_context *context, hmath_value **out); +``` + +## `decompress` + +`interchange.decompress(value, value2, value3, value4)` + + The output length may be smaller than the budget. Archives additionally compare it to the declared member size before accepting their payload. + +Original: [`HMath.Interchange.Compression.decompress`](haskell/HMath-Interchange-Compression.md#v:decompress). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Compression -> Int -> ByteString -> IO (Either InterchangeError ByteString) +``` + +```c +hmath_status hmath_interchange_value_decompress(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `raw_spec` + +`interchange.raw_spec(dtype, endian, order, shape)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interchange.IO.RawSpec`](haskell/HMath-Interchange-IO.md#v:RawSpec). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +DType -> Endian -> Order -> [Int] -> RawSpec +``` + +```c +hmath_status hmath_interchange_value_raw_spec(hmath_context *context, const hmath_value *dtype, const hmath_value *endian, const hmath_value *order, const hmath_value *shape, hmath_value **out); +``` + +## `mapped_read_bytes` + +`interchange.mapped_read_bytes(mapping, offset, count)` + +Copy a bounded byte range. Copies may safely survive mapping closure. + +Original: [`HMath.Interchange.IO.mappedReadBytes`](haskell/HMath-Interchange-IO.md#v:mappedReadBytes). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +forall {k} (s :: k). MappedArray s -> Int -> Int -> IO (Either InterchangeError ByteString) +``` + +```c +hmath_status hmath_interchange_value_mapped_read_bytes(hmath_context *context, const hmath_value *mapping, const hmath_value *offset, const hmath_value *count, hmath_value **out); +``` + +## `mapped_shape` + +`interchange.mapped_shape(mapping)` + + Return dimensions of a callback-scoped read-only mapped array. The region token prevents its raw view escaping withMappedArray. + +Original: [`HMath.Interchange.IO.mappedShape`](haskell/HMath-Interchange-IO.md#v:mappedShape). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +forall {k} (s :: k). MappedArray s -> [Int] +``` + +```c +hmath_status hmath_interchange_value_mapped_shape(hmath_context *context, const hmath_value *mapping, hmath_value **out); +``` + +## `mapped_value` + +`interchange.mapped_value(mapping,indices, *, dtype="float64",boxed=False)` + + Read one typed scalar using checked multidimensional indexing. Physical endian conversion happens through the same Element decoder as normal arrays. + +Original: [`HMath.Interchange.IO.mappedValue`](haskell/HMath-Interchange-IO.md#v:mappedValue). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +forall {k} a (s :: k). Element a => MappedArray s -> [Int] -> IO (Either InterchangeError a) +``` + +```c +hmath_status hmath_interchange_value_mapped_value(hmath_context *context, const hmath_value *prototype, const hmath_value *mapping, const hmath_value *indices, hmath_value **out); +``` + +## `read_array_file` + +`interchange.read_array_file(lim, decode, path)` + + File reading checks the declared size before allocating, then caps the actual read too, handling concurrent growth. Files are closed before return. + +Original: [`HMath.Interchange.IO.readArrayFile`](haskell/HMath-Interchange-IO.md#v:readArrayFile). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> (ByteString -> Either InterchangeError Array) -> FilePath -> IO (Either InterchangeError Array) +``` + +```c +hmath_status hmath_interchange_value_read_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *decode, const hmath_value *path, hmath_value **out); +``` + +## `read_raw_chunks` + +`interchange.read_raw_chunks(value, value2, value3, value4, value5)` + + Read physical-order chunks (one-dimensional arrays); the caller retains the original RawSpec for reconstructing dimensions. Memory is O(chunk), excluding any data retained by the callback. False cancels successfully without consuming the rest. Full completion requires EOF, detecting tails. + +Original: [`HMath.Interchange.IO.readRawChunks`](haskell/HMath-Interchange-IO.md#v:readRawChunks). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> RawSpec -> Int -> Handle -> (Array -> IO (Either InterchangeError Bool)) -> IO (Either InterchangeError ()) +``` + +```c +hmath_status hmath_interchange_value_read_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `with_mapped_array` + +`interchange.with_mapped_array(limits, specification, path, callback)` + + Given limits,RawSpec,path,then rank-2 callback, map read-only raw data for that callback's lifetime and unmap on exit. Validate exact file size/spec/budgets; path/IO/format failures return InterchangeError. Do not retain borrowed pointers beyond the callback. + +Original: [`HMath.Interchange.IO.withMappedArray`](haskell/HMath-Interchange-IO.md#v:withMappedArray). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> RawSpec -> FilePath -> (forall (s :: k). MappedArray s -> IO a) -> IO (Either InterchangeError a) +``` + +```c +hmath_status hmath_interchange_value_with_mapped_array(hmath_context *context, const hmath_value *limits, const hmath_value *specification, const hmath_value *path, const hmath_value *callback, hmath_value **out); +``` + +## `write_array_file` + +`interchange.write_array_file(lim, encode, path, a)` + + Writes to the supplied path after encoding succeeds. Applications needing transactional replacement can write a sibling temporary and rename it. + +Original: [`HMath.Interchange.IO.writeArrayFile`](haskell/HMath-Interchange-IO.md#v:writeArrayFile). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> (Limits -> Array -> Either InterchangeError ByteString) -> FilePath -> Array -> IO (Either InterchangeError ()) +``` + +```c +hmath_status hmath_interchange_value_write_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *encode, const hmath_value *path, const hmath_value *a, hmath_value **out); +``` + +## `write_raw_chunks` + +`interchange.write_raw_chunks(value, value2, value3, value4, value5)` + + Write fixed-size raw chunks. The producer receives a maximum byte count, must return whole elements, and signals EOF with Nothing. Short streams, overlong streams, noncanonical bools and empty nonfinal chunks fail. Errors may leave a partial output; the handle remains owned by the caller. + +Original: [`HMath.Interchange.IO.writeRawChunks`](haskell/HMath-Interchange-IO.md#v:writeRawChunks). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> RawSpec -> Int -> Handle -> (Int -> IO (Either InterchangeError (Maybe ByteString))) -> IO (Either InterchangeError ()) +``` + +```c +hmath_status hmath_interchange_value_write_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `decode_npy` + +`interchange.decode_npy(lim, input)` + + Given limits then NPY bytes, decode supported v1/v2/v3 fixed-width scalar dtype arrays. Reject pickle/object/record/string dtypes, malformed headers, unknown endian/layout, trailing bytes or exceeded budgets. + +Original: [`HMath.Interchange.Numpy.decodeNpy`](haskell/HMath-Interchange-Numpy.md#v:decodeNpy). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_decode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +``` + +## `decode_npz` + +`interchange.decode_npz(lim, input)` + + Checks directory/local consistency, CRC, exact deflate length, duplicate names, overlapping member ranges and aggregate expanded bytes. Data descriptors/encryption/multi-disk/ZIP64 directories are explicitly rejected. + +Original: [`HMath.Interchange.Numpy.decodeNpz`](haskell/HMath-Interchange-Numpy.md#v:decodeNpz). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> ByteString -> IO (Either InterchangeError [(String, Array)]) +``` + +```c +hmath_status hmath_interchange_value_decode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +``` + +## `encode_npy` + +`interchange.encode_npy(lim, order, a)` + + Given limits,physical C/F order,then Array, repack and write a NumPy NPY v1 payload with explicit dtype/endian/shape. Oversized header/output or unsupported layout conversion fails. + +Original: [`HMath.Interchange.Numpy.encodeNpy`](haskell/HMath-Interchange-Numpy.md#v:encodeNpy). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Order -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_encode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *order, const hmath_value *a, hmath_value **out); +``` + +## `encode_npz` + +`interchange.encode_npz(lim, compressed, arrays)` + + Deterministic archives, DOS epoch timestamps and no ZIP comments. True selects raw DEFLATE and requires the optional zlib build feature. + +Original: [`HMath.Interchange.Numpy.encodeNpz`](haskell/HMath-Interchange-Numpy.md#v:encodeNpz). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Bool -> [(String, Array)] -> IO (Either InterchangeError ByteString) +``` + +```c +hmath_status hmath_interchange_value_encode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *compressed, const hmath_value *arrays, hmath_value **out); +``` + +## `decode_delimited` + +`interchange.decode_delimited(lim, separator, dt, bs)` + + Given limits,comma/tab separator,target DType,then CSV/TSV bytes, parse rectangular real numeric cells to a rank-two Array. Complex dtype, malformed rows/tokens or exceeded budgets fail. + +Original: [`HMath.Interchange.Text.decodeDelimited`](haskell/HMath-Interchange-Text.md#v:decodeDelimited). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Char -> DType -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_decode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *dt, const hmath_value *bs, hmath_value **out); +``` + +## `decode_matrix_market` + +`interchange.decode_matrix_market(lim, bs)` + + Array and coordinate input, real/integer/complex/pattern fields and general/symmetric/skew-symmetric/Hermitian storage. Coordinate duplicates are added exactly for integers and checked for finite overflow for floats. Dense output is bounded by maxElements even for sparse input. + +Original: [`HMath.Interchange.Text.decodeMatrixMarket`](haskell/HMath-Interchange-Text.md#v:decodeMatrixMarket). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_decode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out); +``` + +## `decode_text` + +`interchange.decode_text(lim, bs)` + + Given limits then HMath text bytes, parse dtype/shape/tokens and return a checked Array. Invalid ASCII/header/value counts or exceeded budgets fail. + +Original: [`HMath.Interchange.Text.decodeText`](haskell/HMath-Interchange-Text.md#v:decodeText). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> ByteString -> Either InterchangeError Array +``` + +```c +hmath_status hmath_interchange_value_decode_text(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out); +``` + +## `encode_delimited` + +`interchange.encode_delimited(lim, separator, a)` + + Given limits,comma or tab separator,then rank-two noncomplex Array, encode CSV/TSV numeric cells. No shape/dtype metadata is embedded; unsupported input/separator or output bounds fail. + +Original: [`HMath.Interchange.Text.encodeDelimited`](haskell/HMath-Interchange-Text.md#v:encodeDelimited). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Char -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_encode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *a, hmath_value **out); +``` + +## `encode_matrix_market` + +`interchange.encode_matrix_market(lim, a)` + +Dense general Matrix Market; exact Int64, Float64, or Complex128. + +Original: [`HMath.Interchange.Text.encodeMatrixMarket`](haskell/HMath-Interchange-Text.md#v:encodeMatrixMarket). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_encode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +``` + +## `encode_text` + +`interchange.encode_text(lim, a)` + + Given limits then Array, encode self-describing HMath text with dtype/shape and scalar tokens. Invalid/unsupported values or output exceeding limits returns InterchangeError. + +Original: [`HMath.Interchange.Text.encodeText`](haskell/HMath-Interchange-Text.md#v:encodeText). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Array -> Either InterchangeError ByteString +``` + +```c +hmath_status hmath_interchange_value_encode_text(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +``` + +## `bounded_int` + +`interchange.bounded_int(name, upper, x)` + + Given diagnostic name,nonnegative upper bound,then Integer value, convert only if value lies in [0,upper] and fits Int. Otherwise return LimitExceeded with that name. + +Original: [`HMath.Interchange.Array.boundedInt`](haskell/HMath-Interchange-Array.md#v:boundedInt). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +String -> Integer -> Integer -> Either InterchangeError Int +``` + +```c +hmath_status hmath_interchange_value_bounded_int(hmath_context *context, const hmath_value *name, const hmath_value *upper, const hmath_value *x, hmath_value **out); +``` + +## `byte_offsets` + +`interchange.byte_offsets(a)` + + Return backing byte offsets for each logical element in row-major coordinate order, honoring signed strides and offset. + +Original: [`HMath.Interchange.Array.byteOffsets`](haskell/HMath-Interchange-Array.md#v:byteOffsets). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Array -> [Int] +``` + +```c +hmath_status hmath_interchange_value_byte_offsets(hmath_context *context, const hmath_value *a, hmath_value **out); +``` + +## `check_limits` + +`interchange.check_limits(lim)` + + Validate nonnegative finite resource caps, rank<=255 and Int-safe byte/element/metadata/archive budgets. Invalid settings return InvalidData. + +Original: [`HMath.Interchange.Array.checkLimits`](haskell/HMath-Interchange-Array.md#v:checkLimits). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Limits -> Either InterchangeError () +``` + +```c +hmath_status hmath_interchange_value_check_limits(hmath_context *context, const hmath_value *lim, hmath_value **out); +``` + +## `guard_i` + +`interchange.guard_i(p, e)` + + Given condition then InterchangeError, return Right () when True and Left that error otherwise. This helper performs no IO. + +Original: [`HMath.Interchange.Array.guardI`](haskell/HMath-Interchange-Array.md#v:guardI). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Bool -> InterchangeError -> Either InterchangeError () +``` + +```c +hmath_status hmath_interchange_value_guard_i(hmath_context *context, const hmath_value *p, const hmath_value *e, hmath_value **out); +``` + +## `run_decoder` + +`interchange.run_decoder(parser, data, *, boxed=False)` + +Strict, exact decoder: trailing bytes are an error rather than ignored. + +Original: [`HMath.Interchange.Binary.runDecoder`](haskell/HMath-Interchange-Binary.md#v:runDecoder). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation. + +```haskell +Get a -> ByteString -> Either InterchangeError a +``` + +```c +hmath_status hmath_interchange_value_run_decoder(hmath_context *context, const hmath_value *parser, const hmath_value *data, hmath_value **out); +``` + +## `dtype_code` + +`interchange.dtype_code(dtype)` + +Return the original DType enumeration code as an integer (Bool8=0 through C128=12). + +```c +hmath_status hmath_interchange_value_dtype_code(hmath_context *context, const hmath_value *dtype, hmath_value **out); +``` + +## `error_fields` + +`interchange.error_fields(error)` + +Return an InterchangeError's original constructor code and full message; embedded NUL and Unicode are retained. + +```c +hmath_status hmath_interchange_value_error_fields(hmath_context *context, const hmath_value *error, hmath_value **out); +``` + +## `put_bytes` + +`interchange.put_bytes(program)` + +Execute the original Put program and return owned Bytes. This does not perform file IO. + +```c +hmath_status hmath_interchange_value_put_bytes(hmath_context *context, const hmath_value *program, hmath_value **out); +``` + +## `open_handle` + +`interchange.open_handle(path, mode)` + +Open a real binary handle. Modes are rb, wb, ab or r+b; wb truncates and ab appends. IO failures raise the original InterchangeIOError. Close the shared resource explicitly before releasing its value owner. + +```c +hmath_status hmath_interchange_value_open_handle(hmath_context *context, const hmath_value *path, const hmath_value *mode, hmath_value **out); +``` + +## `close_handle` + +`interchange.close_handle(handle)` + +Close the shared Haskell handle. Other retained owners refer to that same closed resource. Python BinaryHandle.close() closes the resource and releases its own value reference. + +```c +hmath_status hmath_interchange_value_close_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +``` + +## `seek_handle` + +`interchange.seek_handle(handle, whence, offset)` + +Seek the binary handle with whence 0 (absolute), 1 (relative) or 2 (from end) and an exact integer byte offset. Original handle IO errors become InterchangeIOError. + +```c +hmath_status hmath_interchange_value_seek_handle(hmath_context *context, const hmath_value *handle, const hmath_value *whence, const hmath_value *offset, hmath_value **out); +``` + +## `tell_handle` + +`interchange.tell_handle(handle)` + +Return the handle's current byte position as an exact integer. + +```c +hmath_status hmath_interchange_value_tell_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +``` + +## `flush_handle` + +`interchange.flush_handle(handle)` + +Flush the original Haskell handle. This has the source hFlush contract and does not promise a filesystem durability barrier. + +```c +hmath_status hmath_interchange_value_flush_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +``` + +## `equal_array` + +`interchange.equal_array(left, right)` + +Compare the original Array values, including dtype, endian, layout, metadata and backing bytes. This is structural equality, not a converted numerical comparison. + +```c +hmath_status hmath_interchange_value_equal_array(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + diff --git a/docs/reference/linear-bindings.md b/docs/reference/linear-bindings.md new file mode 100644 index 0000000..5e87091 --- /dev/null +++ b/docs/reference/linear-bindings.md @@ -0,0 +1,2704 @@ +# Linear algebra bindings + +All operations below call the original Haskell functions. Generic coefficients support standard Float/Double/Integer/Rational/Complex and bounded integral instances where the source constraints permit. No automatic dtype promotion occurs. RealFloat-only operations retain Float/Double; optional native LAPACK routines retain their original Double/ComplexDouble types and explicit unavailable-provider failures. + +## `vector.vector` + +Wrap a list as an immutable dynamic vector without numeric validation. The list order is preserved. Example: vectorValues (vector [1,2]) == [1,2]. + +Original signature: `[a] -> Vector a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +``` + +## `vector.vector_values` + +Extract the immutable list of vector values in order; no shape conversion or numeric validation occurs. + +Original signature: `Vector a -> [a]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.vector_dimension` + +Return the number of coordinates in a dynamic vector. Empty vectors have dimension zero. + +Original signature: `Vector a -> Int`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_dimension(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.fixed_vector` + +Construct a vector whose list length equals the type-level KnownNat size. A mismatch returns Left InvalidArgument. For example, fixedVector `3 requires exactly three values. + +Original signature: `[a] -> Either MathError (FixedVector n a)`. Original constraints: `(KnownNat n)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_fixed_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out); +``` + +## `vector.fixed_values` + +Extract the ordered coordinates of a type-indexed vector; its length is the type-level size. + +Original signature: `FixedVector n a -> [a]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_fixed_values(hmath_context *context, const hmath_value *prototype, const hmath_value *fixed_vector1, hmath_value **out); +``` + +## `vector.sparse_vector` + +Given nonnegative dimension and (zero-based index,value) entries, sum duplicate indices and remove explicit zeros. Reject out-of-range indices or negative dimension. + +Original signature: `Int -> [(Int, a)] -> Either MathError (SparseVector a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_sparse_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out); +``` + +## `vector.sparse_vector_values` + +Expand a sparse vector to a dense list of its declared dimension, filling absent entries with zero. + +Original signature: `SparseVector a -> [a]`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_sparse_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_vector1, hmath_value **out); +``` + +## `vector.vector_slice` + +Given start, count, then vector, return the half-open slice [start,start+count). Reject negative or out-of-range bounds; an empty end slice is valid. + +Original signature: `Int -> Int -> Vector a -> Either MathError (Vector a)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_slice(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *vector3, hmath_value **out); +``` + +## `vector.vector_concat` + +Concatenate a list of vectors in order. Return Left InvalidArgument if the combined dimension would overflow Int; an empty list gives an empty vector. + +Original signature: `[Vector a] -> Either MathError (Vector a)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_concat(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +``` + +## `vector.vector_add` + +Add corresponding values of equally sized vectors, returning a new vector. Unequal dimensions return VectorLengthMismatch. Generic Num arithmetic is unchecked. + +Original signature: `Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_add(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.vector_subtract` + +Subtract corresponding right-hand coordinates from left-hand coordinates. Unequal dimensions return VectorLengthMismatch; Num arithmetic is unchecked. + +Original signature: `Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.vector_scale` + +Given scalar then vector, multiply every coordinate by the scalar. Return a new vector, retaining the original dimension and Num arithmetic behavior. + +Original signature: `a -> Vector a -> Vector a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_scale(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.vector_dot` + +Sum coordinatewise products of equally sized vectors. Empty vectors give zero; unequal dimensions return VectorLengthMismatch. No floating-point finiteness check is added. + +Original signature: `Vector a -> Vector a -> Either MathError a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_vector_dot(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.cross` + +Compute the right-handed cross product of two three-dimensional vectors. Any other dimension returns Left InvalidArgument. + +Original signature: `Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_cross(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.outer` + +Return the matrix of pairwise products a[i]*b[j], with shape (dimension a,dimension b). Matrix construction can return shape/count errors. + +Original signature: `Vector a -> Vector a -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_outer(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.triple` + +Given a,b,c, compute scalar triple product a dot (b cross c). All three vectors must have dimension three; dimension errors propagate. + +Original signature: `Vector a -> Vector a -> Vector a -> Either MathError a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_triple(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out); +``` + +## `vector.norm0` + +Count nonzero coordinates, returning Int. This is the usual sparsity count rather than a norm satisfying homogeneity. + +Original signature: `Vector a -> Int`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_norm0(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.norm1` + +Sum absolute coordinate values. Empty vector returns zero; arithmetic follows the chosen Num type. + +Original signature: `Vector a -> a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.norm2` + +Compute Euclidean length using a scaled stable norm to reduce intermediate overflow/underflow. Empty vector returns zero; the result itself is not wrapped in Either. + +Original signature: `Vector a -> a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_norm2(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.norm_infinity` + +Return maximum absolute coordinate, or zero for an empty vector. NaN coordinates propagate rather than being silently discarded. + +Original signature: `Vector a -> a`. Original constraints: `(Ord a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.norm_p` + +Given positive exponent p then finite vector, compute the scaled p-norm. Positive infinity selects normInfinity. NaN/nonpositive p or non-finite coordinates fail; p\<1 is accepted as a quasi-norm. + +Original signature: `a -> Vector a -> Either MathError a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_norm_p(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.normalize_vector` + +Return a unit-length vector in the same direction. Reject non-finite coordinates, zero norm, or non-finite resulting norm. Empty input is a zero vector and fails. + +Original signature: `Vector a -> Either MathError (Vector a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_normalize_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +``` + +## `vector.project` + +Given a then b, return the projection of a onto b. Dimensions must agree and b must have nonzero finite norm; non-finite input/result fails. + +Original signature: `Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_project(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.reflect` + +Given incident vector then surface normal, return incident minus twice its projection onto the normal. The normal is normalized internally; invalid dimensions, zero normal, or non-finite values fail. + +Original signature: `Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_reflect(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.refract` + +Given positive finite refractive-index ratio, incident vector, then normal, return the refracted unit-direction expression. Normalize both inputs; reject invalid dimensions, zero vectors, non-finite values, or total internal reflection. + +Original signature: `a -> Vector a -> Vector a -> Either MathError (Vector a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_refract(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out); +``` + +## `vector.distance` + +Return Euclidean distance between equal-sized finite vectors. Dimension mismatch and non-finite input/intermediate/result return Left MathError. + +Original signature: `Vector a -> Vector a -> Either MathError a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_distance(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.cosine_similarity` + +Return normalized dot product clamped to [-1,1]. Equal dimensions and nonzero finite vectors are required; validation errors propagate. + +Original signature: `Vector a -> Vector a -> Either MathError a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_cosine_similarity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.angle` + +Return the angle in radians, acos of cosineSimilarity, between two nonzero finite equally sized vectors. Invalid dimensions or zero/non-finite vectors fail. + +Original signature: `Vector a -> Vector a -> Either MathError a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_angle(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +``` + +## `vector.gram_schmidt` + +Given finite nonnegative relative tolerance then vectors, perform two-pass modified Gram-Schmidt, returning an orthonormal basis in input order. Reject unequal dimensions, zero/dependent vectors (RankDeficient), invalid tolerance, or non-finite data. + +Original signature: `a -> [Vector a] -> Either MathError [Vector a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_vector_gram_schmidt(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, hmath_value **out); +``` + +## `matrix_advanced.generate_matrix` + +Given row count, column count, then zero-based (row,column) generator, construct a row-major matrix. Negative dimensions or Int-size element product overflow return Left MathError. + +Original signature: `Int -> Int -> (Int -> Int -> a) -> Either MathError (Matrix a)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_generate_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *function3, hmath_value **out); +``` + +## `matrix_advanced.triangular_matrix` + +Given lower flag then matrix, preserve entries on/below the diagonal if True, on/above if False, and zero the rest. Rectangular matrices are allowed; return checked construction result. + +Original signature: `Bool -> Matrix a -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_triangular_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.symmetric_matrix` + +Return (A+transpose(A))/2 for a square matrix. Non-square input returns NonSquareMatrix; arithmetic follows Fractional. + +Original signature: `Matrix a -> Either MathError (Matrix a)`. Original constraints: `(Fractional a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_symmetric_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.hermitian_matrix` + +Return (A+conjugateTranspose(A))/2 for a square complex matrix. Non-square input fails; this symmetrizes rather than merely asserting the original is Hermitian. + +Original signature: `Matrix (Complex a) -> Either MathError (Matrix (Complex a))`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_hermitian_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.permutation_matrix` + +Given a permutation p of [0..n-1], construct n-by-n P with P[i,p[i]]=1. Duplicate, missing, or out-of-range indices return Left InvalidArgument. + +Original signature: `[Int] -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_permutation_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +``` + +## `matrix_advanced.block_matrix` + +Assemble a rectangular grid of matrix blocks. Require equal heights within each block row and equal widths within each block column. Ragged grids or total-size overflow fail; empty grids yield a 0-by-0 matrix. + +Original signature: `[[Matrix a]] -> Either MathError (Matrix a)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_block_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +``` + +## `matrix_advanced.banded_matrix` + +Given rows, columns, then (diagonal offset,values) pairs, construct a matrix with zeros elsewhere. Offset k means column-row=k. Each list must match that diagonal's length; duplicates add. Invalid dimensions/counts fail. + +Original signature: `Int -> Int -> [(Int, [a])] -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_banded_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +``` + +## `matrix_advanced.conjugate_transpose` + +Transpose a complex matrix and conjugate every entry, exchanging its row/column dimensions. + +Original signature: `Matrix (Complex a) -> Matrix (Complex a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_conjugate_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.zip_matrix_with` + +Given elementwise function and two identically shaped matrices, apply it to corresponding entries and return a new matrix. Mismatched shapes return ShapeMismatch. + +Original signature: `(a -> b -> c) -> Matrix a -> Matrix b -> Either MathError (Matrix c)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_zip_matrix_with(hmath_context *context, const hmath_value *prototype, const hmath_value *function1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out); +``` + +## `matrix_advanced.batched_multiply` + +Multiply pairs of matrices from equally long lists, preserving batch order. Different batch lengths or any checked multiplication failure return Left MathError. + +Original signature: `[Matrix a] -> [Matrix a] -> Either MathError [Matrix a]`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_batched_multiply(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out); +``` + +## `matrix_advanced.kronecker` + +Return the block Kronecker product of matrices A and B, of shape (Arows*Brows,Acols*Bcols). Reject dimension/element-count overflow. + +Original signature: `Matrix a -> Matrix a -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.khatri_rao` + +Return columnwise Kronecker product, requiring equal column counts. Shape is (Arows*Brows,columns); mismatched columns or dimension overflow fail. + +Original signature: `Matrix a -> Matrix a -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_khatri_rao(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.matrix_power` + +Given Integer exponent then square real matrix, compute power by squaring. Zero yields identity; negative exponent inverts first. Non-square/singular input or multiplication errors propagate. + +Original signature: `Integer -> Matrix a -> Either MathError (Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_power(hmath_context *context, const hmath_value *prototype, const hmath_value *integer1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.trace` + +Return sum of main diagonal of a square matrix; non-square input returns NonSquareMatrix. A 0-by-0 matrix has trace zero. + +Original signature: `Matrix a -> Either MathError a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_trace(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.matrix_norm1` + +Return maximum absolute column sum (induced one norm). Empty dimensions give zero; no finiteness check is added. + +Original signature: `Matrix a -> a`. Original constraints: `(Ord a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.matrix_norm_infinity` + +Return maximum absolute row sum (induced infinity norm). A matrix with no elements gives zero. + +Original signature: `Matrix a -> a`. Original constraints: `(Ord a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.frobenius_norm` + +Return scaled Euclidean norm of all entries, reducing intermediate overflow; empty matrix norm is zero. No Either result is added. + +Original signature: `Matrix a -> a`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_frobenius_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.spectral_norm` + +Return largest singular value via SVD, or zero for an empty singular spectrum. Invalid input/backend decomposition failures return Left MathError. + +Original signature: `Matrix Double -> Either MathError Double`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_spectral_norm(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.matrix_rank` + +Given finite nonnegative relative tolerance then matrix, count positive singular values whose ratio to the largest exceeds tolerance. Zero tolerance counts all positive singular values. Invalid tolerance or SVD failure propagates. + +Original signature: `Double -> Matrix Double -> Either MathError Int`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_rank(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.pseudoinverse` + +Given relative singular-value tolerance then m-by-n matrix, return n-by-m Moore-Penrose pseudoinverse via thresholded SVD. Rectangular/rank-deficient inputs are supported; invalid tolerance or numeric/decomposition failures propagate. + +Original signature: `Double -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.condition_number` + +Return largest/smallest singular-value ratio; singular matrices yield positive infinity, empty spectrum yields 1. Input/SVD failures return Left MathError. + +Original signature: `Matrix Double -> Either MathError Double`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_condition_number(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.column_space` + +Given relative SVD rank tolerance then matrix, return columns of left singular vectors spanning its numerical column space. Invalid tolerance/decomposition errors propagate. + +Original signature: `Double -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_column_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.row_space` + +Given relative rank tolerance then matrix, return a column basis for its row space by applying columnSpace to its transpose. + +Original signature: `Double -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_row_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.null_space` + +Given relative singular-value tolerance then m-by-n matrix, return an n-by-(n-rank) basis for its numerical right null space using full SVD. Invalid tolerance/decomposition failures propagate. + +Original signature: `Double -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_null_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.change_coordinates` + +Given source basis matrix, target square basis matrix, then source coordinate list, map to physical coordinates and solve in target basis. Shape mismatch, singular target, and checked solve errors propagate. + +Original signature: `Matrix a -> Matrix a -> [a] -> Either MathError [a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_change_coordinates(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +``` + +## `matrix_advanced.matrix_exp` + +Given positive finite tolerance, positive iteration budget, then square finite matrix, approximate exp(A) by scaling, Taylor series and squaring. Return NonConvergence on exhausted series budget; input/shape/numerical failures propagate. + +Original signature: `a -> Int -> Matrix a -> Either MathError (Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_exp(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +``` + +## `matrix_advanced.matrix_log` + +Compute principal real matrix logarithm of a symmetric positive-definite Double matrix using symmetric eigendecomposition. Reject non-square/asymmetric matrices, nonpositive spectrum, non-real decomposition, or numeric failure. + +Original signature: `Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_log(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.matrix_sqrt` + +Compute symmetric positive-semidefinite matrix square root by spectral decomposition; tolerate eigenvalues down to -1e-12 and clamp them to zero. Invalid shape/symmetry/spectrum or decomposition failure returns Left MathError. + +Original signature: `Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_sqrt(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.polar` + +Return (U,P) from SVD so A=U*P, with P positive semidefinite; rectangular input uses the thin polar factors. Validation/decomposition/multiplication errors propagate. + +Original signature: `Matrix Double -> Either MathError (Matrix Double, Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_polar(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `matrix_advanced.complex_pseudoinverse` + +Complex128 Moore-Penrose pseudoinverse, thresholded relative to the largest singular value. Both rectangular and rank-deficient inputs are supported. + +Original signature: `Double -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double))`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_complex_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +``` + +## `matrix_advanced.matrix_sqrt_general` + +Principal square root for invertible real matrices whose spectra avoid the nonpositive real axis. This nonsymmetric reference method uses scaled Denman-Beavers iteration with private inverse solves. The budget bounds the number of coupled iterations; failure to meet the reconstruction tolerance returns NonConvergence. Ill-conditioned inverse steps may report a LU error. The existing matrixSqrt additionally handles symmetric singular PSD inputs. + +Original signature: `Double -> Int -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_sqrt_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +``` + +## `matrix_advanced.matrix_log_general` + +Real principal matrix logarithm on the same spectral domain as matrixSqrtGeneral. Inverse scaling by successive principal square roots makes the Mercator series converge in matrix 1-norm. The budget bounds each phase: root reductions, each inner Denman-Beavers solve, series terms, and the final exponential reconstruction check. There is no unbounded convergence loop. + +Original signature: `Double -> Int -> Matrix Double -> Either MathError (Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_matrix_advanced_matrix_log_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +``` + +## `decomposition.gaussian_elimination` + +Given finite nonnegative relative tolerance then finite matrix, return normalized row-echelon form and zero-based pivot columns. Partial row pivoting skips pivots below tolerance times the global entry scale. Invalid tolerance/non-finite arithmetic fails. + +Original signature: `a -> Matrix a -> Either MathError (Matrix a, [Int])`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_gaussian_elimination(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out); +``` + +## `decomposition.gauss_jordan` + +Given relative tolerance then finite matrix, return reduced row-echelon form and zero-based pivot columns using row pivoting. Invalid tolerance/non-finite arithmetic fails. + +Original signature: `a -> Matrix a -> Either MathError (Matrix a, [Int])`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_gauss_jordan(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out); +``` + +## `decomposition.cholesky` + +Factor a finite symmetric positive-definite matrix as L*transpose(L), returning lower-triangular L. Non-square/asymmetric/non-finite input or a nonpositive diagonal pivot returns Left MathError. + +Original signature: `Matrix a -> Either MathError (Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `decomposition.ldlt` + +Factor a finite symmetric matrix as L*diag(d)*transpose(L), returning unit lower L and diagonal list d. This unpivoted method requires nonzero scalar pivots; it can reject invertible indefinite matrices needing block pivots. + +Original signature: `Matrix a -> Either MathError (Matrix a, [a])`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_ldlt(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `decomposition.givens_qr` + +Factor finite m-by-n matrix as Q*R using Givens rotations, returning square m-by-m Q and m-by-n R without column pivoting. Non-finite input/intermediate results fail. + +Original signature: `Matrix a -> Either MathError (Matrix a, Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_givens_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `decomposition.bidiagonalize` + +Reduce a finite rectangular matrix to bidiagonal form with orthogonal factors, returning Bidiagonal fields. Input/numeric validation errors propagate; inspect the factor types and module reconstruction example. + +Original signature: `Matrix a -> Either MathError (Bidiagonal a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_bidiagonalize(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `decomposition.tridiagonalize` + +Reduce a symmetric finite square matrix to `(Q,T)`, satisfying `A = Q * T * transpose Q` with tridiagonal `T`. Non-square/asymmetric input or numerical failure returns Left MathError. + +Original signature: `Matrix Double -> Either MathError (Matrix Double, Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_tridiagonalize(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `decomposition.power_iteration` + +Given positive finite tolerance,positive budget,square finite matrix,then nonzero starting vector, estimate a dominant eigenpair. Return Iteration with value/vector/residual/count; invalid dimensions/options, non-finite arithmetic or exhausted budget fails. + +Original signature: `a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_power_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +``` + +## `decomposition.inverse_iteration` + +Given tolerance,budget,shift,square matrix,then starting vector, estimate an eigenpair near shift by repeated shifted solves. Require valid finite inputs and nonzero start; singular shifted systems or convergence/numerical failures return Left MathError. + +Original signature: `a -> Int -> a -> Matrix a -> [a] -> Either MathError (Iteration a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_inverse_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *matrix4, const hmath_value *values5, hmath_value **out); +``` + +## `decomposition.rayleigh_iteration` + +Given tolerance,budget,square matrix,then nonzero initial vector, refine an eigenpair with Rayleigh-quotient shifts. Shape/options, singular shifted solves or convergence/numerical failures return Left MathError. + +Original signature: `a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_rayleigh_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +``` + +## `decomposition.arnoldi` + +Given positive finite tolerance,requested basis size,square matrix,then nonzero initial vector, build Arnoldi basis/projection. Require 1\<=requested\<=matrix order. Invalid input or numerical failures return Left MathError; exact Krylov breakdown terminates the basis. + +Original signature: `a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +``` + +## `decomposition.lanczos` + +Symmetric Lanczos with the three-term recurrence and two full reorthogonalization passes. Small correction coefficients are retained in H so the projection residual remains meaningful after floating-point rounding. + +Original signature: `a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_lanczos(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +``` + +## `decomposition.qr_iteration` + +Given positive finite tolerance,positive budget,then finite square matrix, iterate QR to return `(Q,T)`: accumulated orthogonal vectors and the resulting iterate. Invalid options/shape or failure to converge within budget returns Left MathError. + +Original signature: `a -> Int -> Matrix a -> Either MathError (Matrix a, Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_qr_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +``` + +## `decomposition.jordan_chains` + +Verify supplied Jordan chains against A and lambda and construct J and P. Computing a Jordan structure from floating input is ill posed; the caller supplies chain vectors ordered eigenvector first. A P = P J is checked. This API never pretends a Schur form is a Jordan form. + +Original signature: `a -> Matrix a -> [(a, [[a]])] -> Either MathError (Matrix a, Matrix a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_jordan_chains(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +``` + +## `decomposition.jordan_form` + +Exact Jordan construction over Rational with a caller-provided complete set of distinct rational eigenvalues (multiplicities are inferred). Unlike floating Jordan algorithms this never uses a tolerance to decide structure. Nullspaces of successive (A-lambda I) powers construct generalized chains. An incomplete/nonrational spectrum is rejected rather than approximated. + +Original signature: `Matrix Rational -> [Rational] -> Either MathError (Matrix Rational, Matrix Rational)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_jordan_form(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out); +``` + +## `decomposition.bidiagonal_u` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Bidiagonal -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_bidiagonal_u(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +``` + +## `decomposition.bidiagonal_b` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Bidiagonal -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_bidiagonal_b(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +``` + +## `decomposition.bidiagonal_v` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Bidiagonal -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_bidiagonal_v(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +``` + +## `decomposition.Bidiagonal` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_decomposition_new_bidiagonal(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out); +``` + +## `decomposition.iteration_value` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Iteration -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_iteration_value(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +``` + +## `decomposition.iteration_vector` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Iteration -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_iteration_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +``` + +## `decomposition.iteration_residual` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Iteration -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_iteration_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +``` + +## `decomposition.iteration_count` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Iteration -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_iteration_count(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +``` + +## `decomposition.Iteration` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_decomposition_new_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out); +``` + +## `decomposition.arnoldi_basis` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Arnoldi -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_arnoldi_basis(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out); +``` + +## `decomposition.arnoldi_hessenberg` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Arnoldi -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_decomposition_arnoldi_hessenberg(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out); +``` + +## `decomposition.Arnoldi` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_decomposition_new_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `iterative.default_iterative_options` + +1000 iterations, zero absolute tolerance and relative tolerance 1e-10. + +Original signature: `IterativeOptions a`. Original constraints: `(Fractional a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_default_iterative_options(hmath_context *context, const hmath_value *prototype, hmath_value **out); +``` + +## `iterative.apply_preconditioner` + +Apply an inverse action; wrong vector lengths and nonfinite values fail. + +Original signature: `Preconditioner a -> [a] -> Either MathError [a]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_apply_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *preconditioner1, const hmath_value *values2, hmath_value **out); +``` + +## `iterative.identity_preconditioner` + +Identity inverse action in a nonnegative dimension. + +Original signature: `Int -> Either MathError (Preconditioner a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_identity_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, hmath_value **out); +``` + +## `iterative.jacobi_preconditioner` + +Inverse diagonal preconditioner. Every diagonal entry must be nonzero. + +Original signature: `Matrix a -> Either MathError (Preconditioner a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `iterative.block_jacobi_preconditioner` + +Block Jacobi from contiguous positive block sizes summing to the dimension. Each diagonal block is factored with pivoted LU; off-block entries are ignored. + +Original signature: `[Int] -> Matrix a -> Either MathError (Preconditioner a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_block_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out); +``` + +## `iterative.ilu0_preconditioner` + +Incomplete LU with zero fill and no pivoting. The exact nonzero pattern of A is retained, diagonal pivots are mandatory, and zero pivots fail explicitly. + +Original signature: `Matrix a -> Either MathError (Preconditioner a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_ilu0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `iterative.ic0_preconditioner` + +Incomplete Cholesky with zero fill for a symmetric positive-definite input. Dropping can itself cause a nonpositive pivot; that reports NotPositiveDefinite. + +Original signature: `Matrix a -> Either MathError (Preconditioner a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_ic0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `iterative.conjugate_gradient` + +Conjugate gradient for symmetric positive-definite matrices. Symmetry is checked; nonpositive Krylov curvature rejects indefinite matrices encountered. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_conjugate_gradient(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.preconditioned_cg` + +Preconditioned conjugate gradient. The inverse action must be SPD; a nonpositive r^T M^-1 r or search curvature is reported as a domain error. + +Original signature: `IterativeOptions a -> Preconditioner a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_preconditioned_cg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *preconditioner2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `iterative.gmres` + +Restarted GMRES with modified Gram--Schmidt Arnoldi and a second orthogonalization pass. Restart length must be positive; total iterations are bounded by options. Each projected least-squares problem is solved by QR. + +Original signature: `IterativeOptions a -> Int -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_gmres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `iterative.minres` + +Minimum residual on the symmetric Lanczos Krylov space, including indefinite systems. A full tridiagonal projected least-squares problem is solved by QR each iteration (the mathematical MINRES objective, without short recurrences). + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_minres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.bicg` + +Bi-conjugate gradient for nonsymmetric square matrices; the initial shadow residual equals the initial residual. Biorthogonality breakdown fails explicitly. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_bicg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.bicgstab` + +Stabilized BiCG with a fixed initial shadow residual and a minimal-residual omega step. Zero projection/omega denominators return explicit breakdown errors. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_bicgstab(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.lsqr` + +LSQR by Golub--Kahan bidiagonalization and plane-rotation recurrences. Rectangular and rank-deficient systems are supported. The least-squares stopping test uses the original normal residual as well as the true residual. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_lsqr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.lsmr` + +LSMR's minimum-normal-residual Krylov objective using explicit Golub--Kahan bases and QR on the projected tridiagonal normal operator. A^T A is never formed. This full-basis reference version uses more storage than short-recurrence implementations; it minimizes ||A^T(b-Ax)|| over the generated Krylov space. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_lsmr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.jacobi_solve` + +Simultaneous Jacobi stationary iteration. Convergence requires an appropriate splitting (for example strict diagonal dominance); it is not assumed. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_jacobi_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.gauss_seidel_solve` + +Forward Gauss--Seidel stationary iteration. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_gauss_seidel_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.sor_solve` + +Successive over-relaxation, requiring a finite relaxation 0 a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_sor_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *scalar2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `iterative.iterative_refinement` + +Residual-correction refinement using a reusable partial-pivoted LU. Residuals and corrections use the scalar type's precision. This does not claim mixed-precision accuracy; callers may provide an initial guess from any solver. + +Original signature: `IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_iterative_refinement(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `iterative.absolute_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +``` + +## `iterative.relative_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +``` + +## `iterative.maximum_iterations` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_maximum_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +``` + +## `iterative.IterativeOptions` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_iterative_new_iterative_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, hmath_value **out); +``` + +## `iterative.iterative_solution` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_iterative_solution(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +``` + +## `iterative.iterative_iterations` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_iterative_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +``` + +## `iterative.iterative_residual_norm` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_iterative_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +``` + +## `iterative.iterative_normal_residual_norm` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `IterativeResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_iterative_iterative_normal_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +``` + +## `iterative.IterativeResult` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_iterative_new_iterative_result(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *scalar4, hmath_value **out); +``` + +## `lapack.svd` + +Compute thin real SVD A=U*diag(s)*VT via LAPACK, with descending nonnegative singular values and k=min(m,n). Return m-by-k U and k-by-n VT. Invalid input, unavailable backend, allocation bounds or LAPACK failure returns Left MathError. + +Original signature: `Matrix Double -> Either MathError SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.full_svd` + +Full square U and V^T, including null-space completion. + +Original signature: `Matrix Double -> Either MathError SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_full_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.truncated_svd` + +Given retained rank k then real matrix, compute thin SVD and retain its first k components. Reject k outside the available rank dimensions; decomposition failures propagate. + +Original signature: `Int -> Matrix Double -> Either MathError SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_truncated_svd(hmath_context *context, const hmath_value *index1, const hmath_value *matrix2, hmath_value **out); +``` + +## `lapack.randomized_svd` + +Randomized range finder with an explicit seed, oversampling, and power iterations, followed by a small deterministic SVD. The Gaussian test matrix uses Box-Muller on a local LCG, so results are reproducible, not cryptographic. + +Original signature: `Int -> Int -> Int -> Integer -> Matrix Double -> Either MathError SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_randomized_svd(hmath_context *context, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *integer4, const hmath_value *matrix5, hmath_value **out); +``` + +## `lapack.eigen` + +Compute complex eigenvalues and right eigenvectors of a finite real square matrix via LAPACK. Complex-conjugate pairs are decoded into complex columns. Invalid shape/backend/numeric failures return Left MathError. + +Original signature: `Matrix Double -> Either MathError Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.symmetric_eigen` + +Real symmetric eigensolver with orthonormal columns, sorted ascending. + +Original signature: `Matrix Double -> Either MathError Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.generalized_eigen` + +Given equally sized square matrices A,B, compute generalized alpha/beta eigenvalue representation and right eigenvectors. Retain alpha/beta to represent infinite eigenvalues safely; invalid input or LAPACK failure propagates. + +Original signature: `Matrix Double -> Matrix Double -> Either MathError GeneralizedEigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_generalized_eigen(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `lapack.schur` + +Compute real Schur form A=Q*T*transpose(Q), returning orthogonal Q, quasi-upper-triangular T and complex eigenvalues. Require finite square input and available LAPACK; failures return Left MathError. + +Original signature: `Matrix Double -> Either MathError Schur`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_schur(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.qz` + +Compute generalized real Schur factors for a finite square matrix pair A,B, retaining Q,Z,S,T and alpha/beta eigenvalues. Shape/backend/LAPACK errors return Left MathError. + +Original signature: `Matrix Double -> Matrix Double -> Either MathError QZ`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `lapack.hessenberg` + +Reduce finite real square A to upper Hessenberg H with orthogonal Q, satisfying A=Q*H*transpose(Q). Invalid shape or backend/decomposition failures propagate. + +Original signature: `Matrix Double -> Either MathError Hessenberg`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_hessenberg(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.balance` + +Balance a real square matrix by diagonal scaling, returning the balanced matrix and scales needed to interpret its basis. Invalid finite-input/shape checks or LAPACK failures return Left MathError. + +Original signature: `Matrix Double -> Either MathError Balance`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_balance(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.complex_svd` + +Compute thin complex SVD with conjugate-transposed right factor VT and real nonnegative singular values. Require finite complex entries and available LAPACK. Invalid storage sizes/backend/decomposition fails. + +Original signature: `Matrix (Complex Double) -> Either MathError ComplexSVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_complex_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.complex_eigen` + +Compute complex eigenvalues and right eigenvectors of a finite complex square matrix via LAPACK. Invalid shape, backend availability, bounds or decomposition errors return Left MathError. + +Original signature: `Matrix (Complex Double) -> Either MathError Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_complex_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `lapack.svd_u` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_svd_u(hmath_context *context, const hmath_value *svd1, hmath_value **out); +``` + +## `lapack.singular_values` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_singular_values(hmath_context *context, const hmath_value *svd1, hmath_value **out); +``` + +## `lapack.svd_vt` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_svd_vt(hmath_context *context, const hmath_value *svd1, hmath_value **out); +``` + +## `lapack.SVD` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +``` + +## `lapack.eigenvalues` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Eigen -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_eigenvalues(hmath_context *context, const hmath_value *eigen1, hmath_value **out); +``` + +## `lapack.eigenvectors` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Eigen -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_eigenvectors(hmath_context *context, const hmath_value *eigen1, hmath_value **out); +``` + +## `lapack.Eigen` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out); +``` + +## `lapack.eigen_alpha` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `GeneralizedEigen -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_eigen_alpha(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +``` + +## `lapack.eigen_beta` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `GeneralizedEigen -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_eigen_beta(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +``` + +## `lapack.generalized_eigenvectors` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `GeneralizedEigen -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_generalized_eigenvectors(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +``` + +## `lapack.GeneralizedEigen` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_generalized_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +``` + +## `lapack.schur_q` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Schur -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_schur_q(hmath_context *context, const hmath_value *schur1, hmath_value **out); +``` + +## `lapack.schur_t` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Schur -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_schur_t(hmath_context *context, const hmath_value *schur1, hmath_value **out); +``` + +## `lapack.schur_eigenvalues` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Schur -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_schur_eigenvalues(hmath_context *context, const hmath_value *schur1, hmath_value **out); +``` + +## `lapack.Schur` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_schur(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +``` + +## `lapack.qz_q` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_q(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.qz_z` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_z(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.qz_s` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_s(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.qz_t` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_t(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.qz_alpha` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_alpha(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.qz_beta` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `QZ -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_qz_beta(hmath_context *context, const hmath_value *qz1, hmath_value **out); +``` + +## `lapack.QZ` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *values6, hmath_value **out); +``` + +## `lapack.hessenberg_q` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Hessenberg -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_hessenberg_q(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out); +``` + +## `lapack.hessenberg_h` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Hessenberg -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_hessenberg_h(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out); +``` + +## `lapack.Hessenberg` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_hessenberg(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +``` + +## `lapack.balanced_matrix` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Balance -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_balanced_matrix(hmath_context *context, const hmath_value *balance1, hmath_value **out); +``` + +## `lapack.balance_scales` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `Balance -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_balance_scales(hmath_context *context, const hmath_value *balance1, hmath_value **out); +``` + +## `lapack.Balance` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_balance(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out); +``` + +## `lapack.complex_u` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `ComplexSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_complex_u(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +``` + +## `lapack.complex_singular_values` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `ComplexSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_complex_singular_values(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +``` + +## `lapack.complex_vt` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `ComplexSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_lapack_complex_vt(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +``` + +## `lapack.ComplexSVD` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_lapack_new_complex_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +``` + +## `sparse.sparse` + +Given rows,columns,then (row,column,value) entries, validate coordinates, sum duplicates and remove explicit zeros. Return canonical ordered sparse storage; invalid shape/indices or size overflow fail. + +Original signature: `Int -> Int -> [(Int, Int, a)] -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +``` + +## `sparse.sparse_shape` + +Return declared (row count,column count), including empty dimensions. + +Original signature: `Sparse a -> (Int, Int)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_entries` + +Return canonical nonzero (row,column,value) triples in ascending coordinate order. + +Original signature: `Sparse a -> [(Int, Int, a)]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.nonzeros` + +Return stored nonzero count after duplicate coalescing and zero removal. + +Original signature: `Sparse a -> Int`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_nonzeros(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.from_format` + +Validate COO/CSR/CSC/DIA/BSR/ELLPACK dimensions, pointers/indices and values, then construct canonical sparse storage. Invalid layout or coordinates return Left MathError. + +Original signature: `SparseFormat a -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_from_format(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_format1, hmath_value **out); +``` + +## `sparse.to_coo` + +Return coordinate-list SparseFormat with explicit row/column/value arrays, preserving canonical nonzeros. + +Original signature: `Sparse a -> SparseFormat a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.to_csr` + +Return compressed sparse row format with row offsets, column indices and nonzero values. + +Original signature: `Sparse a -> SparseFormat a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.to_csc` + +Return compressed sparse column format with column offsets, row indices and values. + +Original signature: `Sparse a -> SparseFormat a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.to_dia` + +Return diagonal sparse format; absent positions in represented diagonals are padded with zero. + +Original signature: `Sparse a -> SparseFormat a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.to_bsr` + +Given positive block rows,block columns,then sparse matrix, build block-sparse-row format with zero padding within edge blocks. Invalid block dimensions or size overflow fails. + +Original signature: `Int -> Int -> Sparse a -> Either MathError (SparseFormat a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *sparse3, hmath_value **out); +``` + +## `sparse.to_ellpack` + +Return ELLPACK padded row storage, using row width equal to maximum nonzeros per row. Invalid/overflowing storage dimensions fail. + +Original signature: `Sparse a -> Either MathError (SparseFormat a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_to_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_to_dense` + +Return a dense Matrix with the same dimensions and zeros for missing entries. Checked dense element-count overflow can fail. + +Original signature: `Sparse a -> Either MathError (Matrix a)`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_to_dense(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.dense_to_sparse` + +Convert a dense matrix to canonical sparse storage, discarding exact zeros and preserving dimensions. + +Original signature: `Matrix a -> Sparse a`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_dense_to_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +``` + +## `sparse.sparse_transpose` + +Exchange row/column coordinates and dimensions without changing values, returning canonical sparse order. + +Original signature: `Sparse a -> Sparse a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_add` + +Add equal-shaped sparse matrices, coalescing entries and dropping resulting zeros. Shape mismatch or checked construction errors fail. + +Original signature: `Sparse a -> Sparse a -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_add(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_subtract` + +Subtract right sparse values from left for equal shapes; coalesce and remove zeros. Shape mismatch fails. + +Original signature: `Sparse a -> Sparse a -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.spmv` + +Given sparse matrix then dense vector, return matrix-vector product. Vector length must equal column count; mismatch returns Left MathError. + +Original signature: `Sparse a -> [a] -> Either MathError [a]`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spmv(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.spmm` + +Multiply compatible sparse matrices using sparse row contributions. Inner-dimension mismatch or output construction errors return Left MathError. + +Original signature: `Sparse a -> Sparse a -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spmm(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_kronecker` + +Return sparse Kronecker product, multiplying row/column dimensions and nonzero pairs. Dimension/product overflow fails. + +Original signature: `Sparse a -> Sparse a -> Either MathError (Sparse a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_triangular_solve` + +Given lower Bool,square finite sparse matrix,then RHS list, solve by forward/back substitution. Require correct triangular structure and matching RHS length; zero diagonal pivots or non-finite arithmetic fail. + +Original signature: `Bool -> Sparse a -> [a] -> Either MathError [a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_triangular_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out); +``` + +## `sparse.sparse_diagonal_solve` + +Given diagonal square sparse matrix then RHS, divide by each diagonal pivot. Off-diagonal entries, shape mismatch, zero pivots or non-finite data fail. + +Original signature: `Sparse a -> [a] -> Either MathError [a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_diagonal_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.sparse_lu_lower` + +Extract unit lower-triangular sparse factor from a SparseLU result. + +Original signature: `SparseLU a -> Sparse a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_lu_lower(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +``` + +## `sparse.sparse_lu_upper` + +Extract upper-triangular sparse factor from a SparseLU result. + +Original signature: `SparseLU a -> Sparse a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_lu_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +``` + +## `sparse.sparse_lu_permutation` + +Return LU row permutation in pivoted order, for reconstructing P*A=L*U. + +Original signature: `SparseLU a -> [Int]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_lu_permutation(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +``` + +## `sparse.sparse_lu` + +Given finite nonnegative relative pivot tolerance then square finite sparse matrix, compute sparse LU with row pivoting. Invalid tolerance/input, zero/near-singular pivots or numerical failure returns Left MathError. + +Original signature: `a -> Sparse a -> Either MathError (SparseLU a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_solve_lu` + +Given sparse LU factors then RHS list, apply row permutation and triangular solves. Dimension mismatch, singularity or non-finite input/result fails. + +Original signature: `SparseLU a -> [a] -> Either MathError [a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_solve_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.sparse_cholesky` + +Factor a symmetric positive-definite finite sparse matrix into a lower sparse factor. Invalid shape/symmetry, nonpositive pivots or numerical failure returns Left MathError. + +Original signature: `Sparse a -> Either MathError (Sparse a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_qr_upper` + +Extract upper-triangular/trapezoidal sparse R from a sparse QR factorization. + +Original signature: `SparseQR a -> Sparse a`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_qr_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, hmath_value **out); +``` + +## `sparse.sparse_qr` + +Given finite nonnegative tolerance then sparse matrix, compute its checked sparse QR factors. Invalid tolerance, input or numerical failure returns Left MathError. + +Original signature: `Sparse a -> Either MathError (SparseQR a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_qr_apply_qt` + +Given sparse QR factors then compatible RHS list, apply transpose(Q) without constructing dense Q. Invalid length or non-finite arithmetic fails. + +Original signature: `SparseQR a -> [a] -> Either MathError [a]`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_qr_apply_qt(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.sparse_graph` + +For a square sparse matrix, return one adjacency row per vertex with stored (column,value) neighbors. Non-square matrix returns Left MathError. + +Original signature: `Sparse a -> Either MathError [(Int, [(Int, a)])]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_graph(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +``` + +## `sparse.sparse_storage_bytes` + +Logical payload bytes: two machine-width indices and caller-provided scalar width per nonzero. Runtime Map node overhead is implementation dependent. + +Original signature: `Int -> Sparse a -> Either MathError Integer`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_storage_bytes(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_tensor` + +Given dimensions then (coordinate-list,value) entries, validate rank/bounds, sum duplicate coordinates and remove zeros. Invalid shape/indices return Left MathError. + +Original signature: `[Int] -> [([Int], a)] -> Either MathError (SparseTensor a)`. Original constraints: `(Eq a, Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.sparse_tensor_shape` + +Return axis dimensions of a sparse tensor; [] denotes a scalar. + +Original signature: `SparseTensor a -> [Int]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_tensor_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out); +``` + +## `sparse.sparse_tensor_entries` + +Return canonical nonzero (coordinate list,value) pairs in lexicographic coordinate order. + +Original signature: `SparseTensor a -> [([Int], a)]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_tensor_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out); +``` + +## `sparse.sparse_tensor_lookup` + +Given sparse tensor then full zero-based coordinates, return stored value or zero. Wrong rank or out-of-range indices fail. + +Original signature: `SparseTensor a -> [Int] -> Either MathError a`. Original constraints: `(Num a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_tensor_lookup(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, const hmath_value *values2, hmath_value **out); +``` + +## `sparse.sparse_eigen_reference` + +Small-problem spectral reference backend. The caller explicitly authorizes a dense element budget; oversized matrices fail before generating zeros. This is not a scalable sparse eigensolver/SVD and never silently densifies. + +Original signature: `Integer -> Sparse Double -> Either MathError Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_eigen_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.sparse_svd_reference` + +Given explicit dense-byte budget then sparse Double matrix, densify only if within budget and run checked dense SVD. This is a reference fallback, not a sparse iterative SVD; budget/backend/numeric errors fail. + +Original signature: `Integer -> Sparse Double -> Either MathError SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_sparse_svd_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out); +``` + +## `sparse.coo` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +``` + +## `sparse.csr` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `sparse.csc` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `sparse.dia` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +``` + +## `sparse.bsr` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *values5, const hmath_value *values6, const hmath_value *values7, hmath_value **out); +``` + +## `sparse.ellpack` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_new_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `sparse_spectral.default_sparse_spectral_options` + +Absolute tolerance 1e-12, relative tolerance 1e-10, 1000 iterations per pair and a workspace limit of ten million scalar elements. + +Original signature: `SparseSpectralOptions a`. Original constraints: `(Fractional a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_default_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, hmath_value **out); +``` + +## `sparse_spectral.sparse_dominant_eigen` + +Symmetric power iteration targeting the eigenvalue of largest magnitude. Exact symmetry and finite input are required. The caller supplies a nonzero finite initial vector; its projection onto the desired eigenspace must be nonzero. An initial eigenvector can converge with a zero budget. Equal opposite dominant eigenvalues may cause non-convergence. Returned residuals do not prove that the converged eigenvalue is the largest when the initial projection is zero. + +Original signature: `SparseSpectralOptions a -> Sparse a -> [a] -> Either MathError (SparseEigenResult a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_dominant_eigen(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out); +``` + +## `sparse_spectral.sparse_truncated_svd` + +Truncated SVD by two-sided power iteration and two-pass orthogonal deflation. The seed initializes a local deterministic stream, with no global RNG state. Both original singular residuals must meet the configured tolerance. The algorithm targets descending singular values if starting vectors have nonzero projection and the successive singular values are separated; it does not claim a certified rank or ordering when these power-method assumptions fail. Exact null images report RankDeficient, rather than inventing zero singular vectors. Small positive singular values may be returned within tolerance; requesting more vectors than the numerical rank can also exhaust the budget. k=0 returns empty factors, including for empty/zero inputs. + +Original signature: `SparseSpectralOptions a -> Int -> Integer -> Sparse a -> Either MathError (SparseSVD a)`. Original constraints: `(RealFloat a)`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_truncated_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *index2, const hmath_value *integer3, const hmath_value *sparse4, hmath_value **out); +``` + +## `sparse_spectral.sparse_absolute_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSpectralOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +``` + +## `sparse_spectral.sparse_relative_tolerance` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSpectralOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +``` + +## `sparse_spectral.sparse_iteration_limit` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSpectralOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_iteration_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +``` + +## `sparse_spectral.sparse_workspace_limit` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSpectralOptions -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_workspace_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +``` + +## `sparse_spectral.SparseSpectralOptions` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_spectral_new_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, const hmath_value *integer4, hmath_value **out); +``` + +## `sparse_spectral.sparse_eigenvalue` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseEigenResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_eigenvalue(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +``` + +## `sparse_spectral.sparse_eigenvector` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseEigenResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_eigenvector(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +``` + +## `sparse_spectral.sparse_eigen_residual` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseEigenResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_eigen_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +``` + +## `sparse_spectral.sparse_eigen_iterations` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseEigenResult -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_eigen_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +``` + +## `sparse_spectral.SparseEigenResult` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_spectral_new_sparse_eigen_result(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out); +``` + +## `sparse_spectral.sparse_singular_values` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_singular_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +``` + +## `sparse_spectral.sparse_left_vectors` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_left_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +``` + +## `sparse_spectral.sparse_right_vectors` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_right_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +``` + +## `sparse_spectral.sparse_singular_residuals` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_singular_residuals(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +``` + +## `sparse_spectral.sparse_singular_iterations` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `SparseSVD -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_sparse_spectral_sparse_singular_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +``` + +## `sparse_spectral.SparseSVD` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_sparse_spectral_new_sparse_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +``` + +## `backend.backend_info` + +Provider identity is immutable for the lifetime of a handle. + +Original signature: `Backend -> BackendInfo`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_info(hmath_context *context, const hmath_value *backend1, hmath_value **out); +``` + +## `backend.pure_backend` + +Construct the deterministic reference backend without dynamically loading BLAS. Its lifetime is garbage-collected; selected numeric reference decomposition limits still apply. + +Original signature: `Backend`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_pure_backend(hmath_context *context, hmath_value **out); +``` + +## `backend.lapack_available` + +Availability of the once-initialized independent LAPACKE loader. + +Original signature: `IO Bool`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_lapack_available(hmath_context *context, hmath_value **out); +``` + +## `backend.select_backend` + +Given AutoBackend or explicit provider/integer-ABI/library request, select a reference or native BLAS backend in IO. Auto honors HMATH_BACKEND, HMATH_BLAS_PROVIDER, HMATH_BLAS_INTEGER_BITS and HMATH_BLAS_LIBRARY; unknown settings or unavailable explicit providers fail. Keep the Backend alive while calling it. + +Original signature: `BackendRequest -> IO (Either MathError Backend)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_select_backend(hmath_context *context, const hmath_value *backend_request1, hmath_value **out); +``` + +## `backend.set_backend_threads` + +Positive thread count; Pure supports one thread. Accelerate has no supported runtime setter and returns an explicit error. No implicit global restoration. + +Original signature: `Backend -> Int -> IO (Either MathError ())`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_set_backend_threads(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, hmath_value **out); +``` + +## `backend.lapack_status` + +Convert the LAPACK convention without losing the distinction between an invalid argument and failed numerical convergence. For factorization pivots callers may instead map a positive code to SingularMatrix (info - 1). + +Original signature: `String -> Int -> Either MathError ()`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_lapack_status(hmath_context *context, const hmath_value *text1, const hmath_value *index2, hmath_value **out); +``` + +## `backend.matrix_from_layout` + +Layout conversion is a checked, explicit copy; zero shapes retain rank. + +Original signature: `BackendLayout -> Int -> Int -> [a] -> Either MathError (M.Matrix a)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_matrix_from_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, hmath_value **out); +``` + +## `backend.matrix_to_layout` + +Given RowMajor/ColumnMajor layout then Matrix, return values in that physical order without changing the logical matrix. + +Original signature: `BackendLayout -> M.Matrix a -> [a]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_matrix_to_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.axpy` + +Given backend,alpha,x,y, return alpha*x+y as a new Double list. Require equal lengths, finite inputs/result and provider-supported integer extents; validation/provider failures return Left MathError in IO. + +Original signature: `Backend -> Double -> [Double] -> [Double] -> IO (Either MathError [Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *double2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `backend.dot` + +Real inner product. Finite input and output; accumulation can overflow even when exact cancellation would produce a finite mathematical result. + +Original signature: `Backend -> [Double] -> [Double] -> IO (Either MathError Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, const hmath_value *values3, hmath_value **out); +``` + +## `backend.nrm2` + +Given backend then finite Double vector, return Euclidean norm through the selected provider or reference path. Empty input gives zero; invalid/non-finite output or provider bounds fail in IO. + +Original signature: `Backend -> [Double] -> IO (Either MathError Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out); +``` + +## `backend.gemv` + +y := alpha op(A) x + beta y. Finite inputs are checked even for zero alpha. + +Original signature: `Backend -> Transpose -> Double -> M.Matrix Double -> [Double] -> Double -> [Double] -> IO (Either MathError [Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *double3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *double6, const hmath_value *values7, hmath_value **out); +``` + +## `backend.gemm` + +C := alpha op(A) op(B) + beta C. Matrices and output must have compatible shapes; all zero-dimensional cases use the reference arithmetic. + +Original signature: `Backend -> Transpose -> Transpose -> Double -> M.Matrix Double -> M.Matrix Double -> Double -> M.Matrix Double -> IO (Either MathError (M.Matrix Double))`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *double7, const hmath_value *matrix8, hmath_value **out); +``` + +## `backend.complex_gemm` + +Given backend,transpose A,transpose B,alpha,A,B,beta,C, return alpha*op(A)*op(B)+beta*C as a new complex matrix. Validate compatible dimensions, finite components and provider integer/allocation bounds. + +Original signature: `Backend -> Transpose -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> M.Matrix (Complex Double) -> Complex Double -> M.Matrix (Complex Double) -> IO (Either MathError (M.Matrix (Complex Double)))`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_complex_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *complex4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *complex7, const hmath_value *matrix8, hmath_value **out); +``` + +## `backend.complex_axpy` + +Given backend,complex alpha,x,y, compute alpha*x+y, requiring equal lengths and finite real/imaginary components. Return a new list or checked shape/provider/numeric error in IO. + +Original signature: `Backend -> Complex Double -> [Complex Double] -> [Complex Double] -> IO (Either MathError [Complex Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_complex_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *complex2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `backend.complex_dot` + +Set the Boolean to True for the Hermitian dot product (conjugate x). + +Original signature: `Backend -> Bool -> [Complex Double] -> [Complex Double] -> IO (Either MathError (Complex Double))`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_complex_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *flag2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +``` + +## `backend.complex_nrm2` + +Given backend then complex vector, return real Euclidean norm of all real/imaginary components. Non-finite input/output or provider extent errors return Left MathError in IO. + +Original signature: `Backend -> [Complex Double] -> IO (Either MathError Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_complex_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out); +``` + +## `backend.complex_gemv` + +Given backend,transpose selector,alpha,A,x,beta,y, return alpha*op(A)*x+beta*y as a new complex list. ConjugateTranspose conjugates matrix values; dimensions, finite values and provider bounds are checked. + +Original signature: `Backend -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> [Complex Double] -> Complex Double -> [Complex Double] -> IO (Either MathError [Complex Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_complex_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *complex3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *complex6, const hmath_value *values7, hmath_value **out); +``` + +## `backend.batched_gemm` + +Uniform scalar/transpose options, independently checked matrix triples. Earlier calls may execute before a later invalid item; no input is mutated. + +Original signature: `Backend -> Transpose -> Transpose -> Double -> Double -> [(M.Matrix Double, M.Matrix Double, M.Matrix Double)] -> IO (Either MathError [M.Matrix Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *double5, const hmath_value *values6, hmath_value **out); +``` + +## `backend.strided_batched_gemm` + +Row-major batches of A(m,k) and B(k,n). Strides count elements, may include padding, and may be zero for broadcast. Extents are checked with Integer before slicing; output batches are contiguous m*n matrices. No implicit transposes. + +Original signature: `Backend -> Int -> Int -> Int -> Int -> Int -> [Double] -> Int -> [Double] -> IO (Either MathError [M.Matrix Double])`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_strided_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *index5, const hmath_value *index6, const hmath_value *values7, const hmath_value *index8, const hmath_value *values9, hmath_value **out); +``` + +## `backend.backend_lu` + +Given backend then real matrix, compute checked column-independent LU using the reference pivoted LU implementation. The backend argument does not change this routine's provider. Shape/pivot/numeric failures propagate. + +Original signature: `Backend -> M.Matrix Double -> Either MathError (LU.LU Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_lu(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.backend_qr` + +Given backend then real matrix, compute reference column-pivoted Householder QR; selection does not change this routine's provider. Validation/numeric errors propagate. + +Original signature: `Backend -> M.Matrix Double -> Either MathError (QR.QR Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_qr(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.backend_solve` + +Given backend,square real matrix,then RHS list, solve via reference LU for Pure or the independent LAPACKE solve bridge for a native backend. Invalid dimensions, unavailable solver, singularity or non-finite arithmetic returns Left MathError. + +Original signature: `Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_solve(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +``` + +## `backend.backend_cholesky` + +Given backend then finite symmetric positive-definite matrix, return reference lower Cholesky factor. Invalid shape/symmetry/pivots/numeric results fail; provider selection is not used by this wrapper. + +Original signature: `Backend -> M.Matrix Double -> Either MathError (M.Matrix Double)`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_cholesky(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.backend_least_squares` + +Given backend,design matrix,then RHS list, solve using reference pivoted QR. Require compatible overdetermined/full-rank input; shape/rank/numeric failures propagate. + +Original signature: `Backend -> M.Matrix Double -> [Double] -> Either MathError [Double]`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_least_squares(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +``` + +## `backend.backend_svd` + +Given backend then finite real matrix, use bounded pure reference SVD for Pure or LAPACK thin SVD for native selection. Return factors or checked shape/budget/provider/convergence errors. + +Original signature: `Backend -> M.Matrix Double -> Either MathError L.SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_svd(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.backend_symmetric_eigen` + +Given backend then finite symmetric square matrix, use bounded cyclic-Jacobi reference solver for Pure or LAPACK otherwise. Return eigenvalues/vectors or input/provider/convergence errors. + +Original signature: `Backend -> M.Matrix Double -> Either MathError L.Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_backend_symmetric_eigen(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +``` + +## `backend.pure_symmetric_eigen` + +Cyclic Jacobi symmetric eigensolver, at most 100 sweeps, ascending eigenvalues. Scaled input avoids squared-norm overflow. This reference path is limited to order 128 and reports nonconvergence rather than returning an unchecked factor. + +Original signature: `M.Matrix Double -> Either MathError L.Eigen`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_pure_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `backend.pure_svd` + +Thin real SVD by one-sided Jacobi orthogonalization, at most 100 sweeps, dimensions <=128. Unlike a normal-equation SVD it does not form A^T A. A deterministic orthogonal completion supplies zero-singular-value columns. + +Original signature: `M.Matrix Double -> Either MathError L.SVD`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_pure_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +``` + +## `backend.pure` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_pure(hmath_context *context, hmath_value **out); +``` + +## `backend.open_blas` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_open_blas(hmath_context *context, hmath_value **out); +``` + +## `backend.blis` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_blis(hmath_context *context, hmath_value **out); +``` + +## `backend.one_mkl` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_one_mkl(hmath_context *context, hmath_value **out); +``` + +## `backend.accelerate` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_accelerate(hmath_context *context, hmath_value **out); +``` + +## `backend.lp64` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_lp64(hmath_context *context, hmath_value **out); +``` + +## `backend.ilp64` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_ilp64(hmath_context *context, hmath_value **out); +``` + +## `backend.auto_backend` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_auto_backend(hmath_context *context, hmath_value **out); +``` + +## `backend.require_backend` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_require_backend(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, const hmath_value *maybe3, hmath_value **out); +``` + +## `backend.selected_provider` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `BackendInfo -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_selected_provider(hmath_context *context, const hmath_value *backend_info1, hmath_value **out); +``` + +## `backend.selected_integer_abi` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `BackendInfo -> field`. Original constraints: `none`. Return the original function result and original Either/Maybe failure convention. + +```c +hmath_status hmath_linear_backend_selected_integer_abi(hmath_context *context, const hmath_value *backend_info1, hmath_value **out); +``` + +## `backend.BackendInfo` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_backend_info(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, hmath_value **out); +``` + +## `backend.row_major` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_row_major(hmath_context *context, hmath_value **out); +``` + +## `backend.column_major` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_column_major(hmath_context *context, hmath_value **out); +``` + +## `backend.no_transpose` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_no_transpose(hmath_context *context, hmath_value **out); +``` + +## `backend.Transpose` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_transpose(hmath_context *context, hmath_value **out); +``` + +## `backend.conjugate_transpose` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Original constraints: `none`. Construct the original public record/variant without inventing validation. + +```c +hmath_status hmath_linear_backend_new_conjugate_transpose(hmath_context *context, hmath_value **out); +``` + diff --git a/docs/reference/machinelearning-bindings.md b/docs/reference/machinelearning-bindings.md new file mode 100644 index 0000000..63e0383 --- /dev/null +++ b/docs/reference/machinelearning-bindings.md @@ -0,0 +1,2194 @@ +# Machine-learning bindings + +`from hmath import machinelearning` exposes the original dense CPU estimators. `Dataset` is a list of finite Double observation rows. No estimator, preprocessing rule, seed, stopping rule, feature ordering or class tie order is substituted. Fit preprocessing inside each training fold; successful fitting preserves the source residual, completed iterations and convergence flag rather than implying an optimum was reached. + +C includes `hmath_machinelearning.h`; values follow the [owned structured protocol](values.md). All inputs are borrowed for a synchronous call; outputs transfer one reference and stay untouched on failure. Original MathError/status11 retains full constructor/payload. Immutable owners support independent readers holding their own references; final shutdown is BUSY while owners exist. Python supports close()/context managers. + +`fitted(result)` returns an independently owned model/payload. `fit_iterations`, `fit_residual`, and `fit_converged` preserve the original diagnostics. Generic Fit payloads retain their structure and native precision. Search callbacks receive `(configuration, Fold)` as two positional arguments and return a Double loss; original mathematical failures remain checked Left errors, while unexpected Python exceptions rethrow after native cleanup. Retained callback owners travel with returned objects. + +Categorical encoders retain actual native Ord/Eq dictionaries, including exact integers/rationals, typed FP32/64, bounded integers, Bool/String, recursive collection labels and supported native domain types. No labels become Double approximations or text keys. Explicit `prototype=` is required when collection/optional element types cannot be inferred; it is a type example, never a training label. Empty input failures retain the original source error. Existing encoders retain their learned native label type for every subsequent operation. + +## `average` + +`machinelearning.average()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Linkage +``` + +```c +hmath_status hmath_ml_average(hmath_context *context, hmath_value **out); +``` + +## `complete` + +`machinelearning.complete()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Linkage +``` + +```c +hmath_status hmath_ml_complete(hmath_context *context, hmath_value **out); +``` + +## `merge` + +`machinelearning.merge(count, count2, number, count3)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Int -> Int -> Double -> Int -> Merge +``` + +```c +hmath_status hmath_ml_merge(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *count3, hmath_value **out); +``` + +## `single` + +`machinelearning.single()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Linkage +``` + +```c +hmath_status hmath_ml_single(hmath_context *context, hmath_value **out); +``` + +## `ward` + +`machinelearning.ward()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Linkage +``` + +```c +hmath_status hmath_ml_ward(hmath_context *context, hmath_value **out); +``` + +## `affinity_propagation` + +`machinelearning.affinity_propagation(ml_config, number, number2, dataset)` + + The preference is the common diagonal similarity; damping is in [0.5,1). Stops only after exemplar identities remain unchanged for ten iterations. + +```haskell +MLConfig -> Double -> Double -> Dataset -> Either MathError (Fit [Int]) +``` + +```c +hmath_status hmath_ml_affinity_propagation(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out); +``` + +## `cluster_centers` + +`machinelearning.cluster_centers(cluster_model)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ClusterModel -> Dataset +``` + +```c +hmath_status hmath_ml_cluster_centers(hmath_context *context, const hmath_value *cluster_model, hmath_value **out); +``` + +## `cut_hierarchy` + +`machinelearning.cut_hierarchy(count, count2, values)` + +Validate the entire hierarchy and return k cluster labels in original observation order. + +```haskell +Int -> Int -> [Merge] -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_cut_hierarchy(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *values, hmath_value **out); +``` + +## `dbscan` + +`machinelearning.dbscan(number, count, dataset)` + +Density expansion using a positive Euclidean radius; minimumPoints includes the observation itself. + +```haskell +Double -> Int -> Dataset -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_dbscan(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `extract_optics` + +`machinelearning.extract_optics(number, values)` + +Extract DBSCAN-style labels at epsilon from a checked OPTICS ordering; noise is -1. + +```haskell +Double -> [(Int, Maybe Double, Maybe Double)] -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_extract_optics(hmath_context *context, const hmath_value *number, const hmath_value *values, hmath_value **out); +``` + +## `fit_gaussian_mixture` + +`machinelearning.fit_gaussian_mixture(ml_config, count, number, dataset)` + +Full-covariance EM initialized by k-means++; positive ridge is added at each covariance update. Collapsed component mass fails. + +```haskell +MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit GaussianMixture) +``` + +```c +hmath_status hmath_ml_fit_gaussian_mixture(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `hierarchical` + +`machinelearning.hierarchical(linkage, dataset)` + +Agglomerate the closest active clusters to produce all n-1 linkage rows. + +```haskell +Linkage -> Dataset -> Either MathError [Merge] +``` + +```c +hmath_status hmath_ml_hierarchical(hmath_context *context, const hmath_value *linkage, const hmath_value *dataset, hmath_value **out); +``` + +## `k_means` + +`machinelearning.k_means(ml_config, count, dataset)` + +Seeded random-center Lloyd iteration; residual is total center displacement. + +```haskell +MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel) +``` + +```c +hmath_status hmath_ml_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `k_means_plus_plus` + +`machinelearning.k_means_plus_plus(ml_config, count, dataset)` + +D-squared k-means++ initialization followed by Lloyd center updates. + +```haskell +MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel) +``` + +```c +hmath_status hmath_ml_k_means_plus_plus(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `k_medoids` + +`machinelearning.k_medoids(ml_config, count, dataset)` + +PAM exhaustive medoid swaps. Return original row indices; residual is the objective decrease. + +```haskell +MLConfig -> Int -> Dataset -> Either MathError (Fit [Int]) +``` + +```c +hmath_status hmath_ml_k_medoids(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `left_cluster` + +`machinelearning.left_cluster(merge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Merge -> Int +``` + +```c +hmath_status hmath_ml_left_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out); +``` + +## `mean_shift` + +`machinelearning.mean_shift(ml_config, number, dataset)` + +Gaussian-kernel mean shift from every training point; modes within bandwidth/2 are merged. + +```haskell +MLConfig -> Double -> Dataset -> Either MathError (Fit ClusterModel) +``` + +```c +hmath_status hmath_ml_mean_shift(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `merge_distance` + +`machinelearning.merge_distance(merge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Merge -> Double +``` + +```c +hmath_status hmath_ml_merge_distance(hmath_context *context, const hmath_value *merge, hmath_value **out); +``` + +## `merged_size` + +`machinelearning.merged_size(merge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Merge -> Int +``` + +```c +hmath_status hmath_ml_merged_size(hmath_context *context, const hmath_value *merge, hmath_value **out); +``` + +## `mini_batch_k_means` + +`machinelearning.mini_batch_k_means(ml_config, count, count2, dataset)` + + Online center updates with per-cluster counts and seeded shuffled batches. One outer iteration consumes batchSize observations, cycling shuffled data. + +```haskell +MLConfig -> Int -> Int -> Dataset -> Either MathError (Fit ClusterModel) +``` + +```c +hmath_status hmath_ml_mini_batch_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +``` + +## `mixture_covariances` + +`machinelearning.mixture_covariances(gaussian_mixture)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GaussianMixture -> [Dataset] +``` + +```c +hmath_status hmath_ml_mixture_covariances(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +``` + +## `mixture_means` + +`machinelearning.mixture_means(gaussian_mixture)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GaussianMixture -> Dataset +``` + +```c +hmath_status hmath_ml_mixture_means(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +``` + +## `mixture_responsibilities` + +`machinelearning.mixture_responsibilities(gaussian_mixture, dataset)` + +Compute normalized posterior component probabilities with log-sum-exp stabilization. + +```haskell +GaussianMixture -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_mixture_responsibilities(hmath_context *context, const hmath_value *gaussian_mixture, const hmath_value *dataset, hmath_value **out); +``` + +## `mixture_weights` + +`machinelearning.mixture_weights(gaussian_mixture)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GaussianMixture -> [Double] +``` + +```c +hmath_status hmath_ml_mixture_weights(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +``` + +## `optics` + +`machinelearning.optics(number, count, dataset)` + + OPTICS (Ankerst et al., SIGMOD 1999): ordered point index, core distance, reachability distance. Undefined reachability starts each connected expansion. + +```haskell +Double -> Int -> Dataset -> Either MathError [(Int, Maybe Double, Maybe Double)] +``` + +```c +hmath_status hmath_ml_optics(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_clusters` + +`machinelearning.predict_clusters(cluster_model, dataset)` + +Assign each row to its closest squared-Euclidean center; ties use the first center. + +```haskell +ClusterModel -> Dataset -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_predict_clusters(hmath_context *context, const hmath_value *cluster_model, const hmath_value *dataset, hmath_value **out); +``` + +## `right_cluster` + +`machinelearning.right_cluster(merge)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Merge -> Int +``` + +```c +hmath_status hmath_ml_right_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out); +``` + +## `spectral_clustering` + +`machinelearning.spectral_clustering(ml_config, count, number, dataset)` + +Cluster row-normalized leading eigenvectors of the normalized Gaussian affinity matrix. + +```haskell +MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit [Int]) +``` + +```c +hmath_status hmath_ml_spectral_clustering(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `canonical_correlations` + +`machinelearning.canonical_correlations(cca)` + +Singular values of the whitened cross-covariance, in descending order. + +```haskell +CCA -> [Double] +``` + +```c +hmath_status hmath_ml_canonical_correlations(hmath_context *context, const hmath_value *cca, hmath_value **out); +``` + +## `classical_mds` + +`machinelearning.classical_mds(count, dataset)` + + Classical metric MDS. Negative eigenvalues are omitted; requesting a dimension beyond positive rank fails instead of creating imaginary axes. + +```haskell +Int -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_classical_mds(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `factor_loadings` + +`machinelearning.factor_loadings(factor_analysis)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +FactorAnalysis -> Dataset +``` + +```c +hmath_status hmath_ml_factor_loadings(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out); +``` + +## `factor_noise` + +`machinelearning.factor_noise(factor_analysis)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +FactorAnalysis -> [Double] +``` + +```c +hmath_status hmath_ml_factor_noise(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out); +``` + +## `finish_pca` + +`machinelearning.finish_pca(count, incremental_pca)` + +Extract principal axes from accumulated sample covariance; requires at least two observations. + +```haskell +Int -> IncrementalPCA -> Either MathError PCA +``` + +```c +hmath_status hmath_ml_finish_pca(hmath_context *context, const hmath_value *count, const hmath_value *incremental_pca, hmath_value **out); +``` + +## `fit_cca` + +`machinelearning.fit_cca(count, number, dataset, dataset2)` + +Fit paired canonical directions with a strictly positive diagonal covariance ridge. + +```haskell +Int -> Double -> Dataset -> Dataset -> Either MathError CCA +``` + +```c +hmath_status hmath_ml_fit_cca(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +``` + +## `fit_factor_analysis` + +`machinelearning.fit_factor_analysis(ml_config, count, number, dataset)` + + Gaussian factor-analysis EM with diagonal noise floor. Unlike PCA, each observed feature has its own learned residual variance. + +```haskell +MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit FactorAnalysis) +``` + +```c +hmath_status hmath_ml_fit_factor_analysis(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_ica` + +`machinelearning.fit_ica(ml_config, count, dataset)` + + Symmetric FastICA with tanh nonlinearity (Hyvarinen 1999), whitening by sample covariance. Convergence accounts for independent component signs. + +```haskell +MLConfig -> Int -> Dataset -> Either MathError (Fit ICA) +``` + +```c +hmath_status hmath_ml_fit_ica(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_kernel_pca` + +`machinelearning.fit_kernel_pca(count, kernel, dataset)` + +Fit kernel principal axes; count must be smaller than n and within positive numerical rank. + +```haskell +Int -> Kernel -> Dataset -> Either MathError KernelPCA +``` + +```c +hmath_status hmath_ml_fit_kernel_pca(hmath_context *context, const hmath_value *count, const hmath_value *kernel, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_pca` + +`machinelearning.fit_pca(count, dataset)` + +Fit count principal axes from at least two observations; uses sample covariance (denominator n-1). + +```haskell +Int -> Dataset -> Either MathError PCA +``` + +```c +hmath_status hmath_ml_fit_pca(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_pls` + +`machinelearning.fit_pls(ml_config, count, dataset, dataset2)` + + PLS2 NIPALS with regression deflation; count cannot exceed the predictor rank. Inner fixed-point iteration obeys the supplied convergence budget. + +```haskell +MLConfig -> Int -> Dataset -> Dataset -> Either MathError (Fit PLS) +``` + +```c +hmath_status hmath_ml_fit_pls(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +``` + +## `incremental_pca` + +`machinelearning.incremental_pca(count)` + +Create empty running covariance state for a positive feature dimension. + +```haskell +Int -> Either MathError IncrementalPCA +``` + +```c +hmath_status hmath_ml_incremental_pca(hmath_context *context, const hmath_value *count, hmath_value **out); +``` + +## `inverse_pca` + +`machinelearning.inverse_pca(pca, dataset)` + +Reconstruct original features from retained scores and restore the training mean. + +```haskell +PCA -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_inverse_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out); +``` + +## `isomap` + +`machinelearning.isomap(count, count2, dataset)` + +Build a symmetric k-neighbor graph, compute geodesics, then metric MDS. Disconnected graphs fail. + +```haskell +Int -> Int -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_isomap(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +``` + +## `merge_pca` + +`machinelearning.merge_pca(incremental_pca, incremental_pca2)` + +Combine independent batch statistics with the between-mean scatter correction. + +```haskell +IncrementalPCA -> IncrementalPCA -> Either MathError IncrementalPCA +``` + +```c +hmath_status hmath_ml_merge_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *incremental_pca2, hmath_value **out); +``` + +## `pca_components` + +`machinelearning.pca_components(pca)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PCA -> Dataset +``` + +```c +hmath_status hmath_ml_pca_components(hmath_context *context, const hmath_value *pca, hmath_value **out); +``` + +## `pca_mean` + +`machinelearning.pca_mean(pca)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PCA -> [Double] +``` + +```c +hmath_status hmath_ml_pca_mean(hmath_context *context, const hmath_value *pca, hmath_value **out); +``` + +## `pca_variances` + +`machinelearning.pca_variances(pca)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +PCA -> [Double] +``` + +```c +hmath_status hmath_ml_pca_variances(hmath_context *context, const hmath_value *pca, hmath_value **out); +``` + +## `predict_pls` + +`machinelearning.predict_pls(pls, dataset)` + +Predict response rows using fitted PLS coefficients and training centers. + +```haskell +PLS -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_predict_pls(hmath_context *context, const hmath_value *pls, const hmath_value *dataset, hmath_value **out); +``` + +## `random_projection` + +`machinelearning.random_projection(ml_config, count, dataset)` + +Seeded Gaussian projection with variance 1/dimension per coefficient. Returns transformed rows. + +```haskell +MLConfig -> Int -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_random_projection(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `transform_cca` + +`machinelearning.transform_cca(cca, dataset, dataset2)` + +Project paired query rows with fitted training centers and canonical directions. + +```haskell +CCA -> Dataset -> Dataset -> Either MathError (Dataset, Dataset) +``` + +```c +hmath_status hmath_ml_transform_cca(hmath_context *context, const hmath_value *cca, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +``` + +## `transform_ica` + +`machinelearning.transform_ica(ica, dataset)` + +Apply the fitted centering and unmixing directions to new observations. + +```haskell +ICA -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_transform_ica(hmath_context *context, const hmath_value *ica, const hmath_value *dataset, hmath_value **out); +``` + +## `transform_kernel_pca` + +`machinelearning.transform_kernel_pca(kernel_pca, dataset)` + +Center query kernels with training means before projection, without fitting query statistics. + +```haskell +KernelPCA -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_transform_kernel_pca(hmath_context *context, const hmath_value *kernel_pca, const hmath_value *dataset, hmath_value **out); +``` + +## `transform_pca` + +`machinelearning.transform_pca(pca, dataset)` + +Center with the training mean and project onto retained axes; no whitening is applied. + +```haskell +PCA -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_transform_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out); +``` + +## `truncated_svd` + +`machinelearning.truncated_svd(count, dataset)` + +Return reduced (U, singular values, V-transpose) from LAPACK, keeping the largest count values. + +```haskell +Int -> Dataset -> Either MathError (Dataset, [Double], Dataset) +``` + +```c +hmath_status hmath_ml_truncated_svd(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `tsne` + +`machinelearning.tsne(ml_config, count, number, dataset)` + +Exact all-pairs t-SNE; perplexity must be strictly between one and n. + +```haskell +MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit Dataset) +``` + +```c +hmath_status hmath_ml_tsne(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `umap` + +`machinelearning.umap(ml_config, count, count2, number, number2, dataset)` + + Exact full fuzzy-set cross entropy, caller supplies fitted curve a,b. Local connectivity rho is the first positive neighbor distance. This dense reference resolves every repulsive pair instead of sampling negatives. + +```haskell +MLConfig -> Int -> Int -> Double -> Double -> Dataset -> Either MathError (Fit Dataset) +``` + +```c +hmath_status hmath_ml_umap(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out); +``` + +## `update_pca` + +`machinelearning.update_pca(incremental_pca, dataset)` + +Merge observations by Welford updates. Empty batches preserve the previous state. + +```haskell +IncrementalPCA -> Dataset -> Either MathError IncrementalPCA +``` + +```c +hmath_status hmath_ml_update_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *dataset, hmath_value **out); +``` + +## `fit` + +`machinelearning.fit(value, count, number, flag)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +a -> Int -> Double -> Bool -> Fit a +``` + +```c +hmath_status hmath_ml_fit(hmath_context *context, const hmath_value *value, const hmath_value *count, const hmath_value *number, const hmath_value *flag, hmath_value **out); +``` + +## `ml_config` + +`machinelearning.ml_config(count, number, number2, seed)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Int -> Double -> Double -> Word64 -> MLConfig +``` + +```c +hmath_status hmath_ml_ml_config(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, const hmath_value *seed, hmath_value **out); +``` + +## `default_ml_config` + +`machinelearning.default_ml_config()` + +500 iterations, absolute residual tolerance 1e-8, rate 0.05, PCG seed 42. + +```haskell +MLConfig +``` + +```c +hmath_status hmath_ml_default_ml_config(hmath_context *context, hmath_value **out); +``` + +## `fit_converged` + +`machinelearning.fit_converged(fit)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fit a -> Bool +``` + +```c +hmath_status hmath_ml_fit_converged(hmath_context *context, const hmath_value *fit, hmath_value **out); +``` + +## `fit_iterations` + +`machinelearning.fit_iterations(fit)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fit a -> Int +``` + +```c +hmath_status hmath_ml_fit_iterations(hmath_context *context, const hmath_value *fit, hmath_value **out); +``` + +## `fit_residual` + +`machinelearning.fit_residual(fit)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fit a -> Double +``` + +```c +hmath_status hmath_ml_fit_residual(hmath_context *context, const hmath_value *fit, hmath_value **out); +``` + +## `fitted` + +`machinelearning.fitted(fit)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fit a -> a +``` + +```c +hmath_status hmath_ml_fitted(hmath_context *context, const hmath_value *fit, hmath_value **out); +``` + +## `ml_iterations` + +`machinelearning.ml_iterations(ml_config)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +MLConfig -> Int +``` + +```c +hmath_status hmath_ml_ml_iterations(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +``` + +## `ml_rate` + +`machinelearning.ml_rate(ml_config)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +MLConfig -> Double +``` + +```c +hmath_status hmath_ml_ml_rate(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +``` + +## `ml_seed` + +`machinelearning.ml_seed(ml_config)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +MLConfig -> Word64 +``` + +```c +hmath_status hmath_ml_ml_seed(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +``` + +## `ml_tolerance` + +`machinelearning.ml_tolerance(ml_config)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +MLConfig -> Double +``` + +```c +hmath_status hmath_ml_ml_tolerance(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +``` + +## `ball_tree` + +`machinelearning.ball_tree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +IndexKind +``` + +```c +hmath_status hmath_ml_ball_tree(hmath_context *context, hmath_value **out); +``` + +## `kd_tree` + +`machinelearning.kd_tree()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +IndexKind +``` + +```c +hmath_status hmath_ml_kd_tree(hmath_context *context, hmath_value **out); +``` + +## `neighbor_result` + +`machinelearning.neighbor_result(values, count, flag)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[(Int, Double)] -> Int -> Bool -> NeighborResult +``` + +```c +hmath_status hmath_ml_neighbor_result(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out); +``` + +## `build_index` + +`machinelearning.build_index(index_kind, count, dataset)` + +Build an exact search tree with at most leafSize observations per leaf. + +```haskell +IndexKind -> Int -> Dataset -> Either MathError SpatialIndex +``` + +```c +hmath_status hmath_ml_build_index(hmath_context *context, const hmath_value *index_kind, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `build_lsh` + +`machinelearning.build_lsh(seed, count, count2, number, dataset)` + +Build tables with projections scalar hashes each and positive bucket width. Storage budget is explicit. + +```haskell +Word64 -> Int -> Int -> Double -> Dataset -> Either MathError LSH +``` + +```c +hmath_status hmath_ml_build_lsh(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `decision_one_class_svm` + +`machinelearning.decision_one_class_svm(one_class_svm, dataset)` + +Return signed novelty margins: positive indicates an inlier under the fitted kernel boundary. + +```haskell +OneClassSVM -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_decision_one_class_svm(hmath_context *context, const hmath_value *one_class_svm, const hmath_value *dataset, hmath_value **out); +``` + +## `exhaustive` + +`machinelearning.exhaustive(neighbor_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborResult -> Bool +``` + +```c +hmath_status hmath_ml_exhaustive(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +``` + +## `fit_isolation_forest` + +`machinelearning.fit_isolation_forest(seed, count, count2, dataset)` + +Seeded independent isolation trees using subsamples of 2..2048 observations. + +```haskell +Word64 -> Int -> Int -> Dataset -> Either MathError IsolationForest +``` + +```c +hmath_status hmath_ml_fit_isolation_forest(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_one_class_svm` + +`machinelearning.fit_one_class_svm(ml_config, kernel, number, dataset)` + + nu-SVM dual coordinate descent: sum alpha=1, 0<=alpha<=1/(nu*n). The reported gap is the pairwise box-constrained KKT violation. + +```haskell +MLConfig -> Kernel -> Double -> Dataset -> Either MathError (Fit OneClassSVM) +``` + +```c +hmath_status hmath_ml_fit_one_class_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +``` + +## `knn_classify` + +`machinelearning.knn_classify(count, spatial_index, values, dataset)` + +Majority vote among k exact neighbors; targets follow original training row order. + +```haskell +Int -> SpatialIndex -> [Int] -> Dataset -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_knn_classify(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out); +``` + +## `knn_regress` + +`machinelearning.knn_regress(count, spatial_index, values, dataset)` + +Average the k exact nearest training responses for each query row. + +```haskell +Int -> SpatialIndex -> [Double] -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_knn_regress(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out); +``` + +## `local_outlier_factor` + +`machinelearning.local_outlier_factor(count, dataset)` + + Training-set LOF with ties included at the kth neighbor distance. Identical neighborhoods have LOF 1, including the infinite-density 0/0 limiting case. + +```haskell +Int -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_local_outlier_factor(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +``` + +## `nearest_neighbors` + +`machinelearning.nearest_neighbors(count, count2, spatial_index, values)` + + maxLeaves is a query work budget. A False exhaustive flag means unexplored nodes might improve the result. Even approximate results have exact distances. + +```haskell +Int -> Int -> SpatialIndex -> [Double] -> Either MathError NeighborResult +``` + +```c +hmath_status hmath_ml_nearest_neighbors(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *values, hmath_value **out); +``` + +## `neighbors` + +`machinelearning.neighbors(neighbor_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborResult -> [(Int, Double)] +``` + +```c +hmath_status hmath_ml_neighbors(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +``` + +## `query_lsh` + +`machinelearning.query_lsh(count, lsh, values)` + +Rank matching-bucket candidates by exact distance; may return fewer than k results, including none. + +```haskell +Int -> LSH -> [Double] -> Either MathError [(Int, Double)] +``` + +```c +hmath_status hmath_ml_query_lsh(hmath_context *context, const hmath_value *count, const hmath_value *lsh, const hmath_value *values, hmath_value **out); +``` + +## `score_isolation_forest` + +`machinelearning.score_isolation_forest(isolation_forest, dataset)` + +Return 2^(-mean corrected path length / expected random-tree path length); larger means more anomalous. + +```haskell +IsolationForest -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_score_isolation_forest(hmath_context *context, const hmath_value *isolation_forest, const hmath_value *dataset, hmath_value **out); +``` + +## `visited_leaves` + +`machinelearning.visited_leaves(neighbor_result)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +NeighborResult -> Int +``` + +```c +hmath_status hmath_ml_visited_leaves(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +``` + +## `box_cox` + +`machinelearning.box_cox(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> PowerTransform +``` + +```c +hmath_status hmath_ml_box_cox(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `constant_impute` + +`machinelearning.constant_impute(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Imputation +``` + +```c +hmath_status hmath_ml_constant_impute(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `fold` + +`machinelearning.fold(values, values2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +[Int] -> [Int] -> Fold +``` + +```c +hmath_status hmath_ml_fold(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `mean_impute` + +`machinelearning.mean_impute()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Imputation +``` + +```c +hmath_status hmath_ml_mean_impute(hmath_context *context, hmath_value **out); +``` + +## `median_impute` + +`machinelearning.median_impute()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Imputation +``` + +```c +hmath_status hmath_ml_median_impute(hmath_context *context, hmath_value **out); +``` + +## `min_max` + +`machinelearning.min_max()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Scaling +``` + +```c +hmath_status hmath_ml_min_max(hmath_context *context, hmath_value **out); +``` + +## `reject_unknown` + +`machinelearning.reject_unknown()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +UnknownCategory +``` + +```c +hmath_status hmath_ml_reject_unknown(hmath_context *context, hmath_value **out); +``` + +## `robust_scale` + +`machinelearning.robust_scale()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Scaling +``` + +```c +hmath_status hmath_ml_robust_scale(hmath_context *context, hmath_value **out); +``` + +## `standardize` + +`machinelearning.standardize()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Scaling +``` + +```c +hmath_status hmath_ml_standardize(hmath_context *context, hmath_value **out); +``` + +## `yeo_johnson` + +`machinelearning.yeo_johnson(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> PowerTransform +``` + +```c +hmath_status hmath_ml_yeo_johnson(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `zero_unknown` + +`machinelearning.zero_unknown()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +UnknownCategory +``` + +```c +hmath_status hmath_ml_zero_unknown(hmath_context *context, hmath_value **out); +``` + +## `fit_encoder` + +`machinelearning.fit_encoder(values, *, prototype=None)` + +Learn sorted category levels from a nonempty training label vector. + +```haskell +Ord a => [a] -> Either MathError (Encoder a) +``` + +```c +hmath_status hmath_ml_fit_encoder(hmath_context *context, const hmath_value *values, const hmath_value *prototype, hmath_value **out); +``` + +## `fit_imputer` + +`machinelearning.fit_imputer(imputation, dataset)` + +Treat NaN as missing and reject infinities. All-missing columns require ConstantImpute. + +```haskell +Imputation -> Dataset -> Either MathError Imputer +``` + +```c +hmath_status hmath_ml_fit_imputer(hmath_context *context, const hmath_value *imputation, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_quantile_transformer` + +`machinelearning.fit_quantile_transformer(dataset)` + +Fit empirical feature quantiles using training rows only. + +```haskell +Dataset -> Either MathError QuantileTransformer +``` + +```c +hmath_status hmath_ml_fit_quantile_transformer(hmath_context *context, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_scaler` + +`machinelearning.fit_scaler(scaling, dataset)` + +Estimate one center and scale per training feature. Empty/ragged or nonfinite data fail. + +```haskell +Scaling -> Dataset -> Either MathError Scaler +``` + +```c +hmath_status hmath_ml_fit_scaler(hmath_context *context, const hmath_value *scaling, const hmath_value *dataset, hmath_value **out); +``` + +## `grid_search` + +`machinelearning.grid_search(values, values2, function)` + + Minimize a user-supplied validation loss, evaluated independently for every candidate/fold. The callback receives only the split indices, so it can fit preprocessing/model state inside each fold. Ties preserve candidate order. + +```haskell +[p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double) +``` + +```c +hmath_status hmath_ml_grid_search(hmath_context *context, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out); +``` + +## `impute` + +`machinelearning.impute(imputer, dataset)` + +Replace NaN with fitted training values while preserving observed entries and row order. + +```haskell +Imputer -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_impute(hmath_context *context, const hmath_value *imputer, const hmath_value *dataset, hmath_value **out); +``` + +## `inverse_power_transform` + +`machinelearning.inverse_power_transform(power_transform, dataset)` + +Invert the selected power, rejecting values outside the transform range. + +```haskell +PowerTransform -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_inverse_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out); +``` + +## `inverse_quantile_transform` + +`machinelearning.inverse_quantile_transform(quantile_transformer, dataset)` + +Interpolate training order statistics at probabilities in [0,1]. + +```haskell +QuantileTransformer -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_inverse_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out); +``` + +## `inverse_transform` + +`machinelearning.inverse_transform(scaler, dataset)` + +Undo a fitted affine scaler, including its constant-feature convention. + +```haskell +Scaler -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_inverse_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out); +``` + +## `k_fold` + +`machinelearning.k_fold(seed, count, count2)` + +Partition n shuffled indices into k nonempty validation folds; each row is held out exactly once. + +```haskell +Word64 -> Int -> Int -> Either MathError [Fold] +``` + +```c +hmath_status hmath_ml_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, hmath_value **out); +``` + +## `label_decode` + +`machinelearning.label_decode(encoder, values)` + +Recover categories from checked integer codes. + +```haskell +Encoder a -> [Int] -> Either MathError [a] +``` + +```c +hmath_status hmath_ml_label_decode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +``` + +## `label_encode` + +`machinelearning.label_encode(encoder, values)` + +Map known categories to zero-based codes; unseen categories fail. + +```haskell +Eq a => Encoder a -> [a] -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_label_encode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +``` + +## `one_hot_encode` + +`machinelearning.one_hot_encode(unknown_category, encoder, values)` + +Emit one column per sorted training category under the explicit unknown-category policy. + +```haskell +Eq a => UnknownCategory -> Encoder a -> [a] -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_one_hot_encode(hmath_context *context, const hmath_value *unknown_category, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +``` + +## `power_transform` + +`machinelearning.power_transform(power_transform, dataset)` + +Apply the selected power to features. Box-Cox requires positive values; Yeo-Johnson allows signs. + +```haskell +PowerTransform -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out); +``` + +## `quantile_transform` + +`machinelearning.quantile_transform(quantile_transformer, dataset)` + +Map values to [0,1]. Ties use their average rank and values outside training extrema clamp. + +```haskell +QuantileTransformer -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out); +``` + +## `random_search` + +`machinelearning.random_search(seed, count, values, values2, function)` + +Sample count distinct candidates from a finite set, then evaluate the supplied folds. Lower loss wins. + +```haskell +Word64 -> Int -> [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double) +``` + +```c +hmath_status hmath_ml_random_search(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out); +``` + +## `stratified_k_fold` + +`machinelearning.stratified_k_fold(seed, count, values, *, prototype=None)` + +Round-robin each shuffled class across k folds. Every class needs at least k observations. + +```haskell +Ord a => Word64 -> Int -> [a] -> Either MathError [Fold] +``` + +```c +hmath_status hmath_ml_stratified_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *prototype, hmath_value **out); +``` + +## `train_test_split` + +`machinelearning.train_test_split(seed, number, count)` + +Seeded split of n row indices. The fraction denotes test rows, rounded and clamped to [1,n-1]. + +```haskell +Word64 -> Double -> Int -> Either MathError Fold +``` + +```c +hmath_status hmath_ml_train_test_split(hmath_context *context, const hmath_value *seed, const hmath_value *number, const hmath_value *count, hmath_value **out); +``` + +## `training_indices` + +`machinelearning.training_indices(fold)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fold -> [Int] +``` + +```c +hmath_status hmath_ml_training_indices(hmath_context *context, const hmath_value *fold, hmath_value **out); +``` + +## `transform` + +`machinelearning.transform(scaler, dataset)` + +Apply training centers/scales to rows with the original feature count; no state is updated. + +```haskell +Scaler -> Dataset -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out); +``` + +## `validation_indices` + +`machinelearning.validation_indices(fold)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Fold -> [Int] +``` + +```c +hmath_status hmath_ml_validation_indices(hmath_context *context, const hmath_value *fold, hmath_value **out); +``` + +## `bernoulli_bayes` + +`machinelearning.bernoulli_bayes()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BayesFamily +``` + +```c +hmath_status hmath_ml_bernoulli_bayes(hmath_context *context, hmath_value **out); +``` + +## `binomial_logit` + +`machinelearning.binomial_logit()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GLMFamily +``` + +```c +hmath_status hmath_ml_binomial_logit(hmath_context *context, hmath_value **out); +``` + +## `elastic_net` + +`machinelearning.elastic_net(number, number2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Double -> Penalty +``` + +```c +hmath_status hmath_ml_elastic_net(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +``` + +## `gaussian_bayes` + +`machinelearning.gaussian_bayes()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BayesFamily +``` + +```c +hmath_status hmath_ml_gaussian_bayes(hmath_context *context, hmath_value **out); +``` + +## `lasso` + +`machinelearning.lasso(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Penalty +``` + +```c +hmath_status hmath_ml_lasso(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `linear_kernel` + +`machinelearning.linear_kernel()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Kernel +``` + +```c +hmath_status hmath_ml_linear_kernel(hmath_context *context, hmath_value **out); +``` + +## `multinomial_bayes` + +`machinelearning.multinomial_bayes()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BayesFamily +``` + +```c +hmath_status hmath_ml_multinomial_bayes(hmath_context *context, hmath_value **out); +``` + +## `ordinary` + +`machinelearning.ordinary()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Penalty +``` + +```c +hmath_status hmath_ml_ordinary(hmath_context *context, hmath_value **out); +``` + +## `poisson_log` + +`machinelearning.poisson_log()` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +GLMFamily +``` + +```c +hmath_status hmath_ml_poisson_log(hmath_context *context, hmath_value **out); +``` + +## `polynomial_kernel` + +`machinelearning.polynomial_kernel(count, number, number2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Int -> Double -> Double -> Kernel +``` + +```c +hmath_status hmath_ml_polynomial_kernel(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out); +``` + +## `rbf_kernel` + +`machinelearning.rbf_kernel(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Kernel +``` + +```c +hmath_status hmath_ml_rbf_kernel(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `ridge` + +`machinelearning.ridge(number)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Penalty +``` + +```c +hmath_status hmath_ml_ridge(hmath_context *context, const hmath_value *number, hmath_value **out); +``` + +## `bayesian_covariance` + +`machinelearning.bayesian_covariance(bayesian_linear)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BayesianLinear -> Dataset +``` + +```c +hmath_status hmath_ml_bayesian_covariance(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out); +``` + +## `bayesian_mean` + +`machinelearning.bayesian_mean(bayesian_linear)` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +BayesianLinear -> LinearModel +``` + +```c +hmath_status hmath_ml_bayesian_mean(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out); +``` + +## `coefficients` + +`machinelearning.coefficients(linear_model)` + +Intercept followed by slopes in input feature order. + +```haskell +LinearModel -> [Double] +``` + +```c +hmath_status hmath_ml_coefficients(hmath_context *context, const hmath_value *linear_model, hmath_value **out); +``` + +## `decision_svm` + +`machinelearning.decision_svm(svm, dataset)` + +Return signed kernel margins; zero is the fitted decision boundary. + +```haskell +SVM -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_decision_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out); +``` + +## `fit_bayesian` + +`machinelearning.fit_bayesian(number, number2, dataset, values)` + + Isotropic zero-mean Gaussian prior, observation precision beta. Unlike frequentist ridge the prior also regularizes the intercept. + +```haskell +Double -> Double -> Dataset -> [Double] -> Either MathError BayesianLinear +``` + +```c +hmath_status hmath_ml_fit_bayesian(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_discriminant` + +`machinelearning.fit_discriminant(flag, number, dataset, values)` + + False = pooled covariance LDA; True = class covariance QDA. A positive diagonal ridge makes singular/constant-feature data explicitly regularized. + +```haskell +Bool -> Double -> Dataset -> [Int] -> Either MathError Discriminant +``` + +```c +hmath_status hmath_ml_fit_discriminant(hmath_context *context, const hmath_value *flag, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_glm` + +`machinelearning.fit_glm(ml_config, glm_family, number, dataset, values)` + +Damped Newton/IRLS with nonnegative slope ridge. Residual is the penalized likelihood gradient norm. + +```haskell +MLConfig -> GLMFamily -> Double -> Dataset -> [Double] -> Either MathError (Fit GLM) +``` + +```c +hmath_status hmath_ml_fit_glm(hmath_context *context, const hmath_value *ml_config, const hmath_value *glm_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_gp_classifier` + +`machinelearning.fit_gp_classifier(ml_config, kernel, dataset, values)` + +Newton mode fitting for 0/1 labels. A 1e-10 diagonal jitter stabilizes the prior covariance. + +```haskell +MLConfig -> Kernel -> Dataset -> [Double] -> Either MathError (Fit GPClassifier) +``` + +```c +hmath_status hmath_ml_fit_gp_classifier(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_gaussian_process` + +`machinelearning.fit_gaussian_process(kernel, number, dataset, values)` + +Fit a GP with strictly positive observation-noise variance and a checked PSD kernel. + +```haskell +Kernel -> Double -> Dataset -> [Double] -> Either MathError GaussianProcess +``` + +```c +hmath_status hmath_ml_fit_gaussian_process(hmath_context *context, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_linear` + +`machinelearning.fit_linear(ml_config, penalty, dataset, values)` + +Fit affine least squares or coordinate-descent elastic net. Ordinary/ridge use an SVD minimum-norm solve; iterative residual is coefficient displacement. + +```haskell +MLConfig -> Penalty -> Dataset -> [Double] -> Either MathError (Fit LinearModel) +``` + +```c +hmath_status hmath_ml_fit_linear(hmath_context *context, const hmath_value *ml_config, const hmath_value *penalty, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_multinomial` + +`machinelearning.fit_multinomial(ml_config, number, dataset, values)` + +Fit all class logits by full-batch gradient descent with slope ridge. Residual is weight displacement. + +```haskell +MLConfig -> Double -> Dataset -> [Int] -> Either MathError (Fit MultinomialModel) +``` + +```c +hmath_status hmath_ml_fit_multinomial(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_naive_bayes` + +`machinelearning.fit_naive_bayes(bayes_family, number, dataset, values)` + +Fit class likelihoods. Smoothing is a variance floor for Gaussian and a pseudocount otherwise. + +```haskell +BayesFamily -> Double -> Dataset -> [Int] -> Either MathError NaiveBayes +``` + +```c +hmath_status hmath_ml_fit_naive_bayes(hmath_context *context, const hmath_value *bayes_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_robust` + +`machinelearning.fit_robust(ml_config, number, dataset, values)` + +Huber IRLS with fixed positive residual threshold, including intercept. + +```haskell +MLConfig -> Double -> Dataset -> [Double] -> Either MathError (Fit LinearModel) +``` + +```c +hmath_status hmath_ml_fit_robust(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_svm` + +`machinelearning.fit_svm(ml_config, kernel, number, dataset, values)` + + Deterministic two-coordinate SMO for binary labels -1/+1. The reported residual is the largest box-constrained dual KKT violation. + +```haskell +MLConfig -> Kernel -> Double -> Dataset -> [Double] -> Either MathError (Fit SVM) +``` + +```c +hmath_status hmath_ml_fit_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +``` + +## `fit_weighted` + +`machinelearning.fit_weighted(dataset, values, values2)` + +Fit affine least squares with nonnegative observation weights. Zero-weight rows contribute no error. + +```haskell +Dataset -> [Double] -> [Double] -> Either MathError LinearModel +``` + +```c +hmath_status hmath_ml_fit_weighted(hmath_context *context, const hmath_value *dataset, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `kernel` + +`machinelearning.kernel(kernel, values, values2)` + +Evaluate a checked PSD kernel on equal-length finite feature vectors. + +```haskell +Kernel -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_ml_kernel(hmath_context *context, const hmath_value *kernel, const hmath_value *values, const hmath_value *values2, hmath_value **out); +``` + +## `polynomial_features` + +`machinelearning.polynomial_features(count, values)` + +Build univariate columns x, x^2, ..., x^degree; the regression intercept supplies the constant. + +```haskell +Int -> [Double] -> Either MathError Dataset +``` + +```c +hmath_status hmath_ml_polynomial_features(hmath_context *context, const hmath_value *count, const hmath_value *values, hmath_value **out); +``` + +## `predict_discriminant` + +`machinelearning.predict_discriminant(discriminant, dataset)` + +Classify with Gaussian discriminant log likelihoods using training covariance state. + +```haskell +Discriminant -> Dataset -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_predict_discriminant(hmath_context *context, const hmath_value *discriminant, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_glm` + +`machinelearning.predict_glm(glm, dataset)` + +Return conditional means: probabilities for BinomialLogit, positive rates for PoissonLog. + +```haskell +GLM -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_predict_glm(hmath_context *context, const hmath_value *glm, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_gp_classifier` + +`machinelearning.predict_gp_classifier(gp_classifier, dataset)` + +Approximate class-one probabilities using the logistic Gaussian variance correction. + +```haskell +GPClassifier -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_predict_gp_classifier(hmath_context *context, const hmath_value *gp_classifier, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_gaussian_process` + +`machinelearning.predict_gaussian_process(gaussian_process, dataset)` + +Return posterior latent-function (mean, variance), excluding observation noise. + +```haskell +GaussianProcess -> Dataset -> Either MathError [(Double, Double)] +``` + +```c +hmath_status hmath_ml_predict_gaussian_process(hmath_context *context, const hmath_value *gaussian_process, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_linear` + +`machinelearning.predict_linear(linear_model, dataset)` + +Predict one finite response per query row using the fitted intercept and slopes. + +```haskell +LinearModel -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_predict_linear(hmath_context *context, const hmath_value *linear_model, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_multinomial` + +`machinelearning.predict_multinomial(multinomial_model, dataset)` + +Return sorted (original label, probability) pairs for each observation. + +```haskell +MultinomialModel -> Dataset -> Either MathError [[(Int, Double)]] +``` + +```c +hmath_status hmath_ml_predict_multinomial(hmath_context *context, const hmath_value *multinomial_model, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_naive_bayes` + +`machinelearning.predict_naive_bayes(naive_bayes, dataset)` + +Select the class with greatest log posterior; preserve the original integer labels. + +```haskell +NaiveBayes -> Dataset -> Either MathError [Int] +``` + +```c +hmath_status hmath_ml_predict_naive_bayes(hmath_context *context, const hmath_value *naive_bayes, const hmath_value *dataset, hmath_value **out); +``` + +## `predict_svm` + +`machinelearning.predict_svm(svm, dataset)` + +Classify margins as -1 or +1, with zero assigned +1. + +```haskell +SVM -> Dataset -> Either MathError [Double] +``` + +```c +hmath_status hmath_ml_predict_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out); +``` + +## `recursive_coefficients` + +`machinelearning.recursive_coefficients(recursive_ls)` + +Current intercept and slopes; updating creates a new state. + +```haskell +RecursiveLS -> [Double] +``` + +```c +hmath_status hmath_ml_recursive_coefficients(hmath_context *context, const hmath_value *recursive_ls, hmath_value **out); +``` + +## `recursive_ls` + +`machinelearning.recursive_ls(count, number, number2)` + + Initial inverse information delta I; forgetting factor in (0,1]. Input dimension excludes the automatically supplied intercept. + +```haskell +Int -> Double -> Double -> Either MathError RecursiveLS +``` + +```c +hmath_status hmath_ml_recursive_ls(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out); +``` + +## `update_recursive_ls` + +`machinelearning.update_recursive_ls(recursive_ls, values, number)` + +Assimilate one feature row/response using the matrix inversion lemma. Reject lost definiteness. + +```haskell +RecursiveLS -> [Double] -> Double -> Either MathError RecursiveLS +``` + +```c +hmath_status hmath_ml_update_recursive_ls(hmath_context *context, const hmath_value *recursive_ls, const hmath_value *values, const hmath_value *number, hmath_value **out); +``` + diff --git a/docs/reference/matrix-bindings.md b/docs/reference/matrix-bindings.md new file mode 100644 index 0000000..1d9c51b --- /dev/null +++ b/docs/reference/matrix-bindings.md @@ -0,0 +1,1077 @@ +# Dense matrix, LU and QR bindings + +These APIs directly call the original `HMath.Matrix`, `HMath.Matrix.LU` and `HMath.Matrix.QR` functions, specialized to Haskell `Float` (binary32) or `Double` (binary64). Other generic Haskell element types are not yet exposed. + +Python: `from hmath import matrix`. C/C++: include `hmath_matrix.h`. Original argument order and mathematical validation are retained. Coordinates and extents are flattened into individual arguments; vectors are a typed pointer plus element count in C. + +## Results and errors + +Original `Maybe` functions return Python `None` on failure; in C, they return `HMATH_OK` and a NULL object, or `found=0` for scalar `at` (leaving the scalar output untouched). Checked `Either MathError` functions raise `HMathError` in Python and return `HMATH_MATH_ERROR` in C; the original constructor and payload remain in the error message. Pure functions add no finite-value validation. Empty dimensions, shape validation order, LU singularity/tolerance policy, QR rank estimation, permutations and ridge regularization retain their original contracts. + +## Ownership and precision + +Matrix, LU and QR objects are immutable and independently owned. Close every Python object explicitly or use `with`; in C, call `hmath_dense_release` for each returned object. `hmath_dense_retain` adds a reference and both retain/release accept NULL. Each live object keeps the Haskell runtime alive, so final shutdown returns `HMATH_BUSY` until all such objects are released. A derived factor/matrix remains valid after its parent is closed. + +Constructors without an input object accept keyword-only `dtype="float64"` or `dtype="float32"`. Other operations infer dtype from their input objects and reject mixed dtypes. C names end in `_f32` or `_f64` and require the matching object precision; query it with `hmath_dense_precision`. No FP32-to-FP64 intermediate is introduced. The original pure reference algorithms are used, with the original precision-specific default pivot tolerances. + +Each caller must hold a live reference for the entire operation. Threads may share immutable inputs but must use independent outputs. Inputs are borrowed for the call; output regions must not overlap inputs or each other. C output pointers/buffers remain untouched on error. Cancellation is checked before the operation, not during the original Haskell algorithm. Haskell dimensions use `ptrdiff_t`, preserving negative-shape errors; checked byte spans and allocation failures are binding-level errors. No legacy tensor element/work cap is added to these dense APIs. + +## shape and to_list + +`matrix.shape(value)` returns the original `(rows, columns)`, including zero dimensions. `matrix.to_list(value)` returns original row-major storage as a Python list. In C use `hmath_dense_shape`, or `hmath_dense_count` followed by `hmath_dense_values_f32/f64`; capacity is in elements and is checked. Vector solve results use an owned `hmath_dense_vector` with the same count/value-copy helpers. Permutations use `hmath_dense_indices` and `hmath_dense_indices_copy`; they are the original final row/column orders, not swap sequences. + +## `from_list` + +`matrix.from_list(rows, columns, values, *, dtype="float64")` + +Original contract: [`HMath.Matrix.fromList`](haskell/HMath-Matrix.md#v:fromList). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `values` | finite-length sequence of elements (C: typed pointer + count) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_from_list_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_from_list_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out); +``` + +## `zero_matrix` + +`matrix.zero_matrix(rows, columns, *, dtype="float64")` + +Original contract: [`HMath.Matrix.zeroMatrix`](haskell/HMath-Matrix.md#v:zeroMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_zero_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_zero_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +``` + +## `diagonal` + +`matrix.diagonal(values, *, dtype="float64")` + +Original contract: [`HMath.Matrix.diagonal`](haskell/HMath-Matrix.md#v:diagonal). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `values` | finite-length sequence of elements (C: typed pointer + count) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_diagonal_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_diagonal_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out); +``` + +## `at` + +`matrix.at(matrix, row, column)` + +Original contract: [`HMath.Matrix.at`](haskell/HMath-Matrix.md#v:at). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `row` | Haskell Int (C: ptrdiff_t) | +| `column` | Haskell Int (C: ptrdiff_t) | + +Returns a scalar. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_at_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out, int *found); +``` + +```c +hmath_status hmath_dense_at_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out, int *found); +``` + +## `slice_matrix` + +`matrix.slice_matrix(start_row, start_column, rows, columns, matrix)` + +Original contract: [`HMath.Matrix.sliceMatrix`](haskell/HMath-Matrix.md#v:sliceMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `start_row` | Haskell Int (C: ptrdiff_t) | +| `start_column` | Haskell Int (C: ptrdiff_t) | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_slice_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_slice_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +``` + +## `reshape` + +`matrix.reshape(rows, columns, matrix)` + +Original contract: [`HMath.Matrix.reshape`](haskell/HMath-Matrix.md#v:reshape). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_reshape_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_reshape_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + +## `add_matrix` + +`matrix.add_matrix(matrix, right)` + +Original contract: [`HMath.Matrix.addMatrix`](haskell/HMath-Matrix.md#v:addMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_add_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_add_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `subtract_matrix` + +`matrix.subtract_matrix(matrix, right)` + +Original contract: [`HMath.Matrix.subtractMatrix`](haskell/HMath-Matrix.md#v:subtractMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_subtract_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_subtract_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `hadamard` + +`matrix.hadamard(matrix, right)` + +Original contract: [`HMath.Matrix.hadamard`](haskell/HMath-Matrix.md#v:hadamard). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_hadamard_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_hadamard_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `multiply` + +`matrix.multiply(matrix, right)` + +Original contract: [`HMath.Matrix.multiply`](haskell/HMath-Matrix.md#v:multiply). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_multiply_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_multiply_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `identity` + +`matrix.identity(order, *, dtype="float64")` + +Original contract: [`HMath.Matrix.identity`](haskell/HMath-Matrix.md#v:identity). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `order` | Haskell Int (C: ptrdiff_t) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Nothing result becomes None / NULL (or found=0). + +```c +hmath_status hmath_dense_identity_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_identity_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +``` + +## `from_list_checked` + +`matrix.from_list_checked(rows, columns, values, *, dtype="float64")` + +Original contract: [`HMath.Matrix.fromListChecked`](haskell/HMath-Matrix.md#v:fromListChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `values` | finite-length sequence of elements (C: typed pointer + count) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_from_list_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_from_list_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out); +``` + +## `zero_matrix_checked` + +`matrix.zero_matrix_checked(rows, columns, *, dtype="float64")` + +Original contract: [`HMath.Matrix.zeroMatrixChecked`](haskell/HMath-Matrix.md#v:zeroMatrixChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_zero_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_zero_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +``` + +## `diagonal_checked` + +`matrix.diagonal_checked(values, *, dtype="float64")` + +Original contract: [`HMath.Matrix.diagonalChecked`](haskell/HMath-Matrix.md#v:diagonalChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `values` | finite-length sequence of elements (C: typed pointer + count) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_diagonal_checked_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_diagonal_checked_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out); +``` + +## `at_checked` + +`matrix.at_checked(matrix, row, column)` + +Original contract: [`HMath.Matrix.atChecked`](haskell/HMath-Matrix.md#v:atChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `row` | Haskell Int (C: ptrdiff_t) | +| `column` | Haskell Int (C: ptrdiff_t) | + +Returns a scalar. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_at_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out); +``` + +```c +hmath_status hmath_dense_at_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out); +``` + +## `slice_matrix_checked` + +`matrix.slice_matrix_checked(start_row, start_column, rows, columns, matrix)` + +Original contract: [`HMath.Matrix.sliceMatrixChecked`](haskell/HMath-Matrix.md#v:sliceMatrixChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `start_row` | Haskell Int (C: ptrdiff_t) | +| `start_column` | Haskell Int (C: ptrdiff_t) | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_slice_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_slice_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +``` + +## `reshape_checked` + +`matrix.reshape_checked(rows, columns, matrix)` + +Original contract: [`HMath.Matrix.reshapeChecked`](haskell/HMath-Matrix.md#v:reshapeChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `rows` | Haskell Int (C: ptrdiff_t) | +| `columns` | Haskell Int (C: ptrdiff_t) | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_reshape_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_reshape_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + +## `add_matrix_checked` + +`matrix.add_matrix_checked(matrix, right)` + +Original contract: [`HMath.Matrix.addMatrixChecked`](haskell/HMath-Matrix.md#v:addMatrixChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_add_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_add_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `subtract_matrix_checked` + +`matrix.subtract_matrix_checked(matrix, right)` + +Original contract: [`HMath.Matrix.subtractMatrixChecked`](haskell/HMath-Matrix.md#v:subtractMatrixChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_subtract_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_subtract_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `hadamard_checked` + +`matrix.hadamard_checked(matrix, right)` + +Original contract: [`HMath.Matrix.hadamardChecked`](haskell/HMath-Matrix.md#v:hadamardChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_hadamard_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_hadamard_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `multiply_checked` + +`matrix.multiply_checked(matrix, right)` + +Original contract: [`HMath.Matrix.multiplyChecked`](haskell/HMath-Matrix.md#v:multiplyChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `right` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_multiply_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_multiply_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `identity_checked` + +`matrix.identity_checked(order, *, dtype="float64")` + +Original contract: [`HMath.Matrix.identityChecked`](haskell/HMath-Matrix.md#v:identityChecked). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `order` | Haskell Int (C: ptrdiff_t) | +| `dtype` | float32 or float64; default float64 | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_identity_checked_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_identity_checked_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +``` + +## `scale_matrix` + +`matrix.scale_matrix(scalar, matrix)` + +Original contract: [`HMath.Matrix.scaleMatrix`](haskell/HMath-Matrix.md#v:scaleMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `scalar` | scalar of matching dtype | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_scale_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_scale_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `transpose_matrix` + +`matrix.transpose_matrix(matrix)` + +Original contract: [`HMath.Matrix.transposeMatrix`](haskell/HMath-Matrix.md#v:transposeMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_transpose_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_transpose_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +``` + +## `lu_decompose` + +`matrix.lu_decompose(matrix)` + +Original contract: [`HMath.Matrix.LU.luDecompose`](haskell/HMath-Matrix-LU.md#v:luDecompose). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | + +Returns independently owned LU factors. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_lu_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out); +``` + +```c +hmath_status hmath_dense_lu_lu_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out); +``` + +## `lu_decompose_with_tolerance` + +`matrix.lu_decompose_with_tolerance(tolerance, matrix)` + +Original contract: [`HMath.Matrix.LU.luDecomposeWithTolerance`](haskell/HMath-Matrix-LU.md#v:luDecomposeWithTolerance). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `tolerance` | scalar of matching dtype | +| `matrix` | Matrix of matching dtype | + +Returns independently owned LU factors. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_lu **out); +``` + +```c +hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_lu **out); +``` + +## `lu_lower` + +`matrix.lu_lower(factors)` + +Original contract: [`HMath.Matrix.LU.luLower`](haskell/HMath-Matrix-LU.md#v:luLower). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_lu_lu_lower_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_lu_lu_lower_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +``` + +## `lu_upper` + +`matrix.lu_upper(factors)` + +Original contract: [`HMath.Matrix.LU.luUpper`](haskell/HMath-Matrix-LU.md#v:luUpper). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_lu_lu_upper_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_lu_lu_upper_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +``` + +## `lu_permutation` + +`matrix.lu_permutation(factors)` + +Original contract: [`HMath.Matrix.LU.luPermutation`](haskell/HMath-Matrix-LU.md#v:luPermutation). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | + +Returns the original list of zero-based permutation indices. + +```c +hmath_status hmath_dense_lu_lu_permutation_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out); +``` + +```c +hmath_status hmath_dense_lu_lu_permutation_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out); +``` + +## `solve_lu` + +`matrix.solve_lu(factors, rhs)` + +Original contract: [`HMath.Matrix.LU.solveLU`](haskell/HMath-Matrix-LU.md#v:solveLU). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | +| `rhs` | finite-length sequence of elements (C: typed pointer + count) | + +Returns the original list of solution elements. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_solve_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +``` + +```c +hmath_status hmath_dense_lu_solve_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +``` + +## `solve_matrix_lu` + +`matrix.solve_matrix_lu(factors, rhs)` + +Original contract: [`HMath.Matrix.LU.solveMatrixLU`](haskell/HMath-Matrix-LU.md#v:solveMatrixLU). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_solve_matrix_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_lu_solve_matrix_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `solve` + +`matrix.solve(matrix, rhs)` + +Original contract: [`HMath.Matrix.LU.solve`](haskell/HMath-Matrix-LU.md#v:solve). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `rhs` | finite-length sequence of elements (C: typed pointer + count) | + +Returns the original list of solution elements. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_solve_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +``` + +```c +hmath_status hmath_dense_lu_solve_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +``` + +## `solve_matrix` + +`matrix.solve_matrix(matrix, rhs)` + +Original contract: [`HMath.Matrix.LU.solveMatrix`](haskell/HMath-Matrix-LU.md#v:solveMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_solve_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_lu_solve_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `determinant_lu` + +`matrix.determinant_lu(factors)` + +Original contract: [`HMath.Matrix.LU.determinantLU`](haskell/HMath-Matrix-LU.md#v:determinantLU). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | LU factors of matching dtype | + +Returns a scalar. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_determinant_lu_f32(hmath_context *context, const hmath_dense_lu *a0, float *out); +``` + +```c +hmath_status hmath_dense_lu_determinant_lu_f64(hmath_context *context, const hmath_dense_lu *a0, double *out); +``` + +## `determinant` + +`matrix.determinant(matrix)` + +Original contract: [`HMath.Matrix.LU.determinant`](haskell/HMath-Matrix-LU.md#v:determinant). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | + +Returns a scalar. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_determinant_f32(hmath_context *context, const hmath_dense_matrix *a0, float *out); +``` + +```c +hmath_status hmath_dense_lu_determinant_f64(hmath_context *context, const hmath_dense_matrix *a0, double *out); +``` + +## `inverse` + +`matrix.inverse(matrix)` + +Original contract: [`HMath.Matrix.LU.inverse`](haskell/HMath-Matrix-LU.md#v:inverse). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_lu_inverse_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_lu_inverse_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +``` + +## `qr_decompose` + +`matrix.qr_decompose(matrix)` + +Original contract: [`HMath.Matrix.QR.qrDecompose`](haskell/HMath-Matrix-QR.md#v:qrDecompose). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | + +Returns independently owned QR factors. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_qr_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out); +``` + +```c +hmath_status hmath_dense_qr_qr_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out); +``` + +## `qr_decompose_with_tolerance` + +`matrix.qr_decompose_with_tolerance(tolerance, matrix)` + +Original contract: [`HMath.Matrix.QR.qrDecomposeWithTolerance`](haskell/HMath-Matrix-QR.md#v:qrDecomposeWithTolerance). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `tolerance` | scalar of matching dtype | +| `matrix` | Matrix of matching dtype | + +Returns independently owned QR factors. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_qr **out); +``` + +```c +hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_qr **out); +``` + +## `qr_q` + +`matrix.qr_q(factors)` + +Original contract: [`HMath.Matrix.QR.qrQ`](haskell/HMath-Matrix-QR.md#v:qrQ). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_qr_qr_q_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_qr_q_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +``` + +## `qr_r` + +`matrix.qr_r(factors)` + +Original contract: [`HMath.Matrix.QR.qrR`](haskell/HMath-Matrix-QR.md#v:qrR). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | + +Returns an independently owned Matrix. + +```c +hmath_status hmath_dense_qr_qr_r_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_qr_r_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +``` + +## `qr_permutation` + +`matrix.qr_permutation(factors)` + +Original contract: [`HMath.Matrix.QR.qrPermutation`](haskell/HMath-Matrix-QR.md#v:qrPermutation). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | + +Returns the original list of zero-based permutation indices. + +```c +hmath_status hmath_dense_qr_qr_permutation_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out); +``` + +```c +hmath_status hmath_dense_qr_qr_permutation_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out); +``` + +## `qr_rank` + +`matrix.qr_rank(factors)` + +Original contract: [`HMath.Matrix.QR.qrRank`](haskell/HMath-Matrix-QR.md#v:qrRank). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | + +Returns an integer. + +```c +hmath_status hmath_dense_qr_qr_rank_f32(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out); +``` + +```c +hmath_status hmath_dense_qr_qr_rank_f64(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out); +``` + +## `apply_q` + +`matrix.apply_q(factors, rhs)` + +Original contract: [`HMath.Matrix.QR.applyQ`](haskell/HMath-Matrix-QR.md#v:applyQ). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_apply_q_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_apply_q_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `apply_qt` + +`matrix.apply_qt(factors, rhs)` + +Original contract: [`HMath.Matrix.QR.applyQT`](haskell/HMath-Matrix-QR.md#v:applyQT). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_apply_qt_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_apply_qt_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `solve_matrix_qr` + +`matrix.solve_matrix_qr(factors, rhs)` + +Original contract: [`HMath.Matrix.QR.solveMatrixQR`](haskell/HMath-Matrix-QR.md#v:solveMatrixQR). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_solve_matrix_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_solve_matrix_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `solve_qr` + +`matrix.solve_qr(factors, rhs)` + +Original contract: [`HMath.Matrix.QR.solveQR`](haskell/HMath-Matrix-QR.md#v:solveQR). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `factors` | QR factors of matching dtype | +| `rhs` | finite-length sequence of elements (C: typed pointer + count) | + +Returns the original list of solution elements. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_solve_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +``` + +```c +hmath_status hmath_dense_qr_solve_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +``` + +## `least_squares` + +`matrix.least_squares(matrix, rhs)` + +Original contract: [`HMath.Matrix.QR.leastSquares`](haskell/HMath-Matrix-QR.md#v:leastSquares). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `rhs` | finite-length sequence of elements (C: typed pointer + count) | + +Returns the original list of solution elements. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_least_squares_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +``` + +```c +hmath_status hmath_dense_qr_least_squares_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +``` + +## `least_squares_matrix` + +`matrix.least_squares_matrix(matrix, rhs)` + +Original contract: [`HMath.Matrix.QR.leastSquaresMatrix`](haskell/HMath-Matrix-QR.md#v:leastSquaresMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `matrix` | Matrix of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_least_squares_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_least_squares_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +``` + +## `ridge_solve` + +`matrix.ridge_solve(lambda_, matrix, rhs)` + +Original contract: [`HMath.Matrix.QR.ridgeSolve`](haskell/HMath-Matrix-QR.md#v:ridgeSolve). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `lambda_` | scalar of matching dtype | +| `matrix` | Matrix of matching dtype | +| `rhs` | finite-length sequence of elements (C: typed pointer + count) | + +Returns the original list of solution elements. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_ridge_solve_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const float *a2, size_t a2_count, hmath_dense_vector **out); +``` + +```c +hmath_status hmath_dense_qr_ridge_solve_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const double *a2, size_t a2_count, hmath_dense_vector **out); +``` + +## `ridge_solve_matrix` + +`matrix.ridge_solve_matrix(lambda_, matrix, rhs)` + +Original contract: [`HMath.Matrix.QR.ridgeSolveMatrix`](haskell/HMath-Matrix-QR.md#v:ridgeSolveMatrix). This defines the computation, boundary conditions, failure order and numerical policy. + +| Parameter | Type | +| --- | --- | +| `lambda_` | scalar of matching dtype | +| `matrix` | Matrix of matching dtype | +| `rhs` | Matrix of matching dtype | + +Returns an independently owned Matrix. A Left MathError raises/returns the original error. + +```c +hmath_status hmath_dense_qr_ridge_solve_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + +```c +hmath_status hmath_dense_qr_ridge_solve_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +``` + diff --git a/docs/reference/matrix-values.md b/docs/reference/matrix-values.md new file mode 100644 index 0000000..ea462d0 --- /dev/null +++ b/docs/reference/matrix-values.md @@ -0,0 +1,65 @@ +# Exact and complex matrices + +The `hmath.matrix` core supports Float, Double, arbitrary Integer, exact Rational, Complex Float, Complex Double, and the standard bounded integral types. Constructors select the coefficient type with `dtype`; binary operations require matching types. Arithmetic calls the original Haskell `HMath.Matrix` functions with that coefficient instance. Bounded integral arithmetic therefore retains the original Haskell wrapping behavior, while constructing an out-of-range scalar reports a representation error. + +```python +from fractions import Fraction +from hmath import matrix +from hmath import polynomial + +p = polynomial.polynomial([1, Fraction(1, 3), 2], dtype="rational") +a = polynomial.companion_matrix(p) +p.close() +b = matrix.multiply_checked(a, a) +assert a.dtype == "rational" +assert all(isinstance(x, Fraction) for x in b.to_list()) +a.close() +b.close() +``` + +Companion matrices keep their coefficient type and are ordinary `matrix.Matrix` instances. Exact and complex matrices support the same core constructors, shape/list inspection, indexing, slicing, reshape, addition, subtraction, Hadamard product, scalar multiplication, matrix multiplication, transpose and identity functions described in [Matrix bindings](matrix-bindings.md). `Maybe` functions return `None` on their original failures; `Checked` functions raise the original `MathError`. The original zero-dimension shapes, exact size-overflow checks, arithmetic order and behavior for NaN/Inf remain unchanged. No fixed tensor element or operation cap is added to the pure Matrix API. + +LU and QR require the original `RealFloat` coefficient instance. Their supported coefficient types remain Float and Double. Calling those decompositions on an exact or complex Matrix is rejected before entering an unsupported specialization. + +## C representation + +Include `hmath_matrix_value.h` and `hmath_value.h`. The generic functions use owned immutable `hmath_value` matrices with `kind == 9`; `hmath_value_info` reports the coefficient dtype and element count. Use common scalar/list/tuple constructors for arguments. Constructors take a typed scalar `prototype` first to preserve the type of an empty matrix. Every returned handle must be released with `hmath_value_release`; inputs are borrowed only for the call. A successful output owns an independent reference, including after all input handles are closed. Failure leaves the output pointer untouched. + +`hmath_dense_to_value` exports an existing Float/Double `hmath_dense_matrix` without copying its mathematical storage or changing its type. `hmath_dense_from_value` imports a Float/Double Value matrix into an existing typed Matrix owner. Exact and complex matrices stay in the generic representation and use `hmath_matrix_value_*`. These representation bridges retain the original Haskell immutable matrix; they do not serialize/reparse coefficients or convert through FP64. + +The C function suffixes correspond directly to the Python functions and source operations: + +| Source operation | Generic C entry point | Result Value | +| --- | --- | --- | +| `fromList`, `fromListChecked` | `hmath_matrix_value_from_list[_checked]` | Matrix or None / Matrix or original error | +| `zeroMatrix`, `zeroMatrixChecked` | `hmath_matrix_value_zero_matrix[_checked]` | Matrix or None / Matrix or original error | +| `diagonal`, `diagonalChecked` | `hmath_matrix_value_diagonal[_checked]` | Matrix or None / Matrix or original error | +| `at`, `atChecked` | `hmath_matrix_value_at[_checked]` | coefficient or None / coefficient or original error | +| `sliceMatrix`, `sliceMatrixChecked` | `hmath_matrix_value_slice_matrix[_checked]` | Matrix or None / Matrix or original error | +| `reshape`, `reshapeChecked` | `hmath_matrix_value_reshape[_checked]` | Matrix or None / Matrix or original error | +| `addMatrix`, `addMatrixChecked` | `hmath_matrix_value_add_matrix[_checked]` | Matrix or None / Matrix or original error | +| `subtractMatrix`, `subtractMatrixChecked` | `hmath_matrix_value_subtract_matrix[_checked]` | Matrix or None / Matrix or original error | +| `hadamard`, `hadamardChecked` | `hmath_matrix_value_hadamard[_checked]` | Matrix or None / Matrix or original error | +| `multiply`, `multiplyChecked` | `hmath_matrix_value_multiply[_checked]` | Matrix or None / Matrix or original error | +| `identity`, `identityChecked` | `hmath_matrix_value_identity[_checked]` | Matrix or None / Matrix or original error | +| `scaleMatrix` | `hmath_matrix_value_scale_matrix` | Matrix | +| `transposeMatrix` | `hmath_matrix_value_transpose_matrix` | Matrix | +| `toList` | `hmath_matrix_value_to_list` | scalar list | +| `shape` | `hmath_matrix_value_shape` | (rows, columns) Index tuple | + +Every original argument appears in source order after `context`; constructor `prototype` precedes those arguments and an owned `hmath_value **out` follows them. Slice origin and extent pairs are flattened to `start_row, start_column, rows, columns`, matching the existing typed C binding. The header declares each exact signature. + +## Bool and String structure + +`dtype="bool"` and `dtype="string"` create actual Haskell `Matrix Bool` and `Matrix String` values. `from_list`, `from_list_checked`, `at`, `at_checked`, slicing, reshape, transpose, shape and list inspection keep their original values and error conventions. Strings preserve Unicode codepoints, embedded NUL and surrogate Char values. Bool/String matrices report dtype codes 16/17, matching the typed Tensor element codes. + +```python +from hmath import matrix +with matrix.from_list_checked(1, 2, [True, False], dtype="bool") as flags: + column = matrix.transpose_matrix(flags) +assert column.shape == (2, 1) +assert column.to_list() == [True, False] +column.close() +``` + +These element types have no original `Num` instance. Zero/identity/diagonal construction and arithmetic therefore return `HMATH_UNSUPPORTED`; the binding does not invent Boolean addition/multiplication or String numeric conversions. C structural constructors use a Boolean/Text prototype with ordinary Boolean/Text element Values. The internal structural codec also lets other non-Num domains retain their original Matrix element type without converting through a numeric dtype. diff --git a/docs/reference/numeric-bindings.md b/docs/reference/numeric-bindings.md new file mode 100644 index 0000000..e5ccc90 --- /dev/null +++ b/docs/reference/numeric-bindings.md @@ -0,0 +1,10804 @@ +# Numeric bindings + +These bindings call the original Haskell functions. They do not replace their algorithms or change domain checks. This is an incremental subset, **not full Haskell API coverage**. + +Include `hmath_numeric.h` in C/C++; in Python use `from hmath import scalar, basic, trigonometry, statistics, constants`. Floating functions accept keyword-only `dtype="float64"` or `dtype="float32"`; these select Haskell `Double` and `Float`, respectively. Functions whose original signature fixes `Double` accept only `float64`; `float32` is rejected rather than silently promoted. Generic functions may have other Haskell type instances which are not yet bound. Python returns ordinary floats, complex numbers, tuples, lists, arbitrary-precision integers and `fractions.Fraction` values. + +Original argument order is preserved. C flattens coordinate pairs and complex values into two real arguments, lists into a pointer and count, and tuple results into separate output pointers. Haskell `Int` uses `ptrdiff_t`; `Integer` uses signed ASCII decimal strings without a fixed precision limit. Rationals use separate exact numerator and denominator strings. Free each returned string with `hmath_numeric_string_free`. Python owns and releases this transport automatically. + +Generic Basic, Scalar, Linear and Statistics functions list their supported `dtype` instances below. `integer` uses unbounded Haskell `Integer`; `rational` uses exact `Rational` and Python `fractions.Fraction`. `int8`/`int16`/`int32`/`int64` and unsigned `uint*` select the corresponding bounded Haskell types. `intp`/`uintp` select native-width Haskell `Int`/`Word`. `complex64` and `complex128` select `Complex Float` and `Complex Double`. Only instances permitted by the original constraints are offered. [Typed generic Value adapters](numeric-objects.md) additionally preserve bound Numeric.Dual/Quaternion, original AD.Dual/Expr and supported native Ord labels through their actual dictionaries. These finite instance sets do not claim support for every user-defined Haskell typeclass instance. + +Ordinary bounded arithmetic keeps the original wrapping behavior; the dedicated checked and saturating functions keep their original error/clamping behavior. Python rejects values outside the selected bounded input type with `OverflowError`. Use explicit `dtype='integer'`/`'rational'` for exact arithmetic; existing floating defaults remain unchanged. Rational input arrays use alternating decimal numerator/denominator strings; complex arrays use alternating real/imaginary components. Array counts are logical values, not component counts. + +A Haskell `Left MathError` becomes `HMATH_MATH_ERROR` (11) in C and `HMathError(status=11)` in Python; the original constructor and payload are retained in the error message. Pure exceptions use status 6. Unchecked functions still allow their original NaN/Inf behavior. No finite-value check is added. + +Input buffers live for the call. Output buffers must not overlap inputs or each other, and list outputs must hold the input count (plus one for prefixSum); C output capacity is checked. Outputs remain untouched on failure. Initialize the runtime before numerical calls. Cancellation is checked before the call. Independent calls can run concurrently. + +## `basic.factorial` + +`basic.factorial(n)` + +Original: [`HMath.Basic.factorial`](haskell/HMath-Basic.md#v:factorial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_basic_factorial( + hmath_context *context, + const char *n, + char **out0); +``` + +## `basic.fibonacci` + +`basic.fibonacci(n)` + +Original: [`HMath.Basic.fibonacci`](haskell/HMath-Basic.md#v:fibonacci). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_basic_fibonacci( + hmath_context *context, + const char *n, + char **out0); +``` + +## `basic.is_prime` + +`basic.is_prime(n)` + +Original: [`HMath.Basic.isPrime`](haskell/HMath-Basic.md#v:isPrime). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_basic_is_prime( + hmath_context *context, + const char *n, + int *out0); +``` + +## `basic.clamp` + +`basic.clamp(low, high, value, *, dtype='float64')` + +Original: [`HMath.Basic.clamp`](haskell/HMath-Basic.md#v:clamp). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_basic_clamp_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0); +``` + +```c +hmath_status hmath_basic_clamp_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0); +``` + +```c +hmath_status hmath_basic_clamp_rational( + hmath_context *context, + const char *low_numerator, + const char *low_denominator, + const char *high_numerator, + const char *high_denominator, + const char *value_numerator, + const char *value_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_basic_clamp_integer( + hmath_context *context, + const char *low, + const char *high, + const char *value, + char **out0); +``` + +```c +hmath_status hmath_basic_clamp_i8( + hmath_context *context, + int8_t low, + int8_t high, + int8_t value, + int8_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_i16( + hmath_context *context, + int16_t low, + int16_t high, + int16_t value, + int16_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_i32( + hmath_context *context, + int32_t low, + int32_t high, + int32_t value, + int32_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_i64( + hmath_context *context, + int64_t low, + int64_t high, + int64_t value, + int64_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_u8( + hmath_context *context, + uint8_t low, + uint8_t high, + uint8_t value, + uint8_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_u16( + hmath_context *context, + uint16_t low, + uint16_t high, + uint16_t value, + uint16_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_u32( + hmath_context *context, + uint32_t low, + uint32_t high, + uint32_t value, + uint32_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_u64( + hmath_context *context, + uint64_t low, + uint64_t high, + uint64_t value, + uint64_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_int( + hmath_context *context, + ptrdiff_t low, + ptrdiff_t high, + ptrdiff_t value, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_basic_clamp_word( + hmath_context *context, + size_t low, + size_t high, + size_t value, + size_t *out0); +``` + +## `basic.lerp` + +`basic.lerp(a, b, t, *, dtype='float64')` + +Original: [`HMath.Basic.lerp`](haskell/HMath-Basic.md#v:lerp). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `complex64`, `complex128`. + +```c +hmath_status hmath_basic_lerp_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0); +``` + +```c +hmath_status hmath_basic_lerp_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0); +``` + +```c +hmath_status hmath_basic_lerp_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + const char *t_numerator, + const char *t_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_basic_lerp_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float t_0, + float t_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_basic_lerp_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double t_0, + double t_1, + double *out0, + double *out1); +``` + +## `scalar.add` + +`scalar.add(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.add`](haskell/HMath-Scalar.md#v:add). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_add_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_add_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +```c +hmath_status hmath_scalar_add_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_add_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +``` + +```c +hmath_status hmath_scalar_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_add_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_add_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `scalar.subtract_scalar` + +`scalar.subtract_scalar(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.subtractScalar`](haskell/HMath-Scalar.md#v:subtractScalar). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_subtract_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_subtract_scalar_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `scalar.multiply` + +`scalar.multiply(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.multiply`](haskell/HMath-Scalar.md#v:multiply). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +```c +hmath_status hmath_scalar_multiply_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_multiply_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +``` + +```c +hmath_status hmath_scalar_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_multiply_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_multiply_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `scalar.minimum_scalar` + +`scalar.minimum_scalar(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.minimumScalar`](haskell/HMath-Scalar.md#v:minimumScalar). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_minimum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_minimum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.maximum_scalar` + +`scalar.maximum_scalar(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.maximumScalar`](haskell/HMath-Scalar.md#v:maximumScalar). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_maximum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_maximum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.absolute` + +`scalar.absolute(x, *, dtype='float64')` + +Original: [`HMath.Scalar.absolute`](haskell/HMath-Scalar.md#v:absolute). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_absolute_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_absolute_f64( + hmath_context *context, + double x, + double *out0); +``` + +```c +hmath_status hmath_scalar_absolute_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_absolute_integer( + hmath_context *context, + const char *x, + char **out0); +``` + +```c +hmath_status hmath_scalar_absolute_i8( + hmath_context *context, + int8_t x, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_i16( + hmath_context *context, + int16_t x, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_i32( + hmath_context *context, + int32_t x, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_i64( + hmath_context *context, + int64_t x, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_word( + hmath_context *context, + size_t x, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_absolute_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_absolute_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1); +``` + +## `scalar.sign` + +`scalar.sign(x, *, dtype='float64')` + +Original: [`HMath.Scalar.sign`](haskell/HMath-Scalar.md#v:sign). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_sign_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_sign_f64( + hmath_context *context, + double x, + double *out0); +``` + +```c +hmath_status hmath_scalar_sign_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_scalar_sign_integer( + hmath_context *context, + const char *x, + char **out0); +``` + +```c +hmath_status hmath_scalar_sign_i8( + hmath_context *context, + int8_t x, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_i16( + hmath_context *context, + int16_t x, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_i32( + hmath_context *context, + int32_t x, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_i64( + hmath_context *context, + int64_t x, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_word( + hmath_context *context, + size_t x, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_sign_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_sign_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1); +``` + +## `scalar.divide` + +`scalar.divide(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.divide`](haskell/HMath-Scalar.md#v:divide). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_divide_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_divide_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `scalar.power` + +`scalar.power(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.power`](haskell/HMath-Scalar.md#v:power). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_power_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_power_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `scalar.hypot` + +`scalar.hypot(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.hypot`](haskell/HMath-Scalar.md#v:hypot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_hypot_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_hypot_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `scalar.clamp_checked` + +`scalar.clamp_checked(low, high, value, *, dtype='float64')` + +Original: [`HMath.Scalar.clampChecked`](haskell/HMath-Scalar.md#v:clampChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_clamp_checked_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0); +``` + +```c +hmath_status hmath_scalar_clamp_checked_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0); +``` + +## `scalar.lerp_checked` + +`scalar.lerp_checked(a, b, t, *, dtype='float64')` + +Original: [`HMath.Scalar.lerpChecked`](haskell/HMath-Scalar.md#v:lerpChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_lerp_checked_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0); +``` + +```c +hmath_status hmath_scalar_lerp_checked_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0); +``` + +## `scalar.inverse_lerp` + +`scalar.inverse_lerp(a, b, x, *, dtype='float64')` + +Original: [`HMath.Scalar.inverseLerp`](haskell/HMath-Scalar.md#v:inverseLerp). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_inverse_lerp_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_inverse_lerp_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +``` + +## `scalar.smoothstep` + +`scalar.smoothstep(a, b, x, *, dtype='float64')` + +Original: [`HMath.Scalar.smoothstep`](haskell/HMath-Scalar.md#v:smoothstep). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_smoothstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_smoothstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +``` + +## `scalar.smootherstep` + +`scalar.smootherstep(a, b, x, *, dtype='float64')` + +Original: [`HMath.Scalar.smootherstep`](haskell/HMath-Scalar.md#v:smootherstep). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_smootherstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_smootherstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +``` + +## `scalar.remap` + +`scalar.remap(a, b, c, d, x, *, dtype='float64')` + +Original: [`HMath.Scalar.remap`](haskell/HMath-Scalar.md#v:remap). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_remap_f32( + hmath_context *context, + float a, + float b, + float c, + float d, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_remap_f64( + hmath_context *context, + double a, + double b, + double c, + double d, + double x, + double *out0); +``` + +## `scalar.step` + +`scalar.step(edge, x, *, dtype='float64')` + +Original: [`HMath.Scalar.step`](haskell/HMath-Scalar.md#v:step). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_step_f32( + hmath_context *context, + float edge, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_step_f64( + hmath_context *context, + double edge, + double x, + double *out0); +``` + +## `scalar.sqrt_checked` + +`scalar.sqrt_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.sqrtChecked`](haskell/HMath-Scalar.md#v:sqrtChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_sqrt_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_sqrt_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.cube_root` + +`scalar.cube_root(x, *, dtype='float64')` + +Original: [`HMath.Scalar.cubeRoot`](haskell/HMath-Scalar.md#v:cubeRoot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_cube_root_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_cube_root_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.reciprocal_sqrt` + +`scalar.reciprocal_sqrt(x, *, dtype='float64')` + +Original: [`HMath.Scalar.reciprocalSqrt`](haskell/HMath-Scalar.md#v:reciprocalSqrt). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_reciprocal_sqrt_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_reciprocal_sqrt_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.exp_checked` + +`scalar.exp_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.expChecked`](haskell/HMath-Scalar.md#v:expChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_exp_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_exp_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.log_checked` + +`scalar.log_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.logChecked`](haskell/HMath-Scalar.md#v:logChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_log_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_log_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.expm1` + +`scalar.expm1(x, *, dtype='float64')` + +Original: [`HMath.Scalar.expm1`](haskell/HMath-Scalar.md#v:expm1). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_expm1_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_expm1_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.log1p` + +`scalar.log1p(x, *, dtype='float64')` + +Original: [`HMath.Scalar.log1p`](haskell/HMath-Scalar.md#v:log1p). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_log1p_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_log1p_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.integer_power` + +`scalar.integer_power(a, n, *, dtype='float64')` + +Original: [`HMath.Scalar.integerPower`](haskell/HMath-Scalar.md#v:integerPower). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_integer_power_f32( + hmath_context *context, + float a, + const char *n, + float *out0); +``` + +```c +hmath_status hmath_scalar_integer_power_f64( + hmath_context *context, + double a, + const char *n, + double *out0); +``` + +## `scalar.nth_root` + +`scalar.nth_root(n, x, *, dtype='float64')` + +Original: [`HMath.Scalar.nthRoot`](haskell/HMath-Scalar.md#v:nthRoot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_nth_root_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_nth_root_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `scalar.round_digits` + +`scalar.round_digits(n, x, *, dtype='float64')` + +Original: [`HMath.Scalar.roundDigits`](haskell/HMath-Scalar.md#v:roundDigits). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_round_digits_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0); +``` + +```c +hmath_status hmath_scalar_round_digits_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `scalar.absolute_error` + +`scalar.absolute_error(actual, expected, *, dtype='float64')` + +Original: [`HMath.Scalar.absoluteError`](haskell/HMath-Scalar.md#v:absoluteError). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_absolute_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0); +``` + +```c +hmath_status hmath_scalar_absolute_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0); +``` + +## `scalar.relative_error` + +`scalar.relative_error(actual, expected, *, dtype='float64')` + +Original: [`HMath.Scalar.relativeError`](haskell/HMath-Scalar.md#v:relativeError). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_relative_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0); +``` + +```c +hmath_status hmath_scalar_relative_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0); +``` + +## `scalar.fused_multiply_add` + +`scalar.fused_multiply_add(a, b, c, *, dtype='float64')` + +Original: [`HMath.Scalar.fusedMultiplyAdd`](haskell/HMath-Scalar.md#v:fusedMultiplyAdd). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_fused_multiply_add_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0); +``` + +```c +hmath_status hmath_scalar_fused_multiply_add_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0); +``` + +## `scalar.checked_float_multiply` + +`scalar.checked_float_multiply(a, b, *, dtype='float64')` + +Original: [`HMath.Scalar.checkedFloatMultiply`](haskell/HMath-Scalar.md#v:checkedFloatMultiply). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_checked_float_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_scalar_checked_float_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `scalar.floor_checked` + +`scalar.floor_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.floorChecked`](haskell/HMath-Scalar.md#v:floorChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_floor_checked_f32( + hmath_context *context, + float x, + char **out0); +``` + +```c +hmath_status hmath_scalar_floor_checked_f64( + hmath_context *context, + double x, + char **out0); +``` + +## `scalar.ceil_checked` + +`scalar.ceil_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.ceilChecked`](haskell/HMath-Scalar.md#v:ceilChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_ceil_checked_f32( + hmath_context *context, + float x, + char **out0); +``` + +```c +hmath_status hmath_scalar_ceil_checked_f64( + hmath_context *context, + double x, + char **out0); +``` + +## `scalar.round_checked` + +`scalar.round_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.roundChecked`](haskell/HMath-Scalar.md#v:roundChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_round_checked_f32( + hmath_context *context, + float x, + char **out0); +``` + +```c +hmath_status hmath_scalar_round_checked_f64( + hmath_context *context, + double x, + char **out0); +``` + +## `scalar.truncate_checked` + +`scalar.truncate_checked(x, *, dtype='float64')` + +Original: [`HMath.Scalar.truncateChecked`](haskell/HMath-Scalar.md#v:truncateChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_truncate_checked_f32( + hmath_context *context, + float x, + char **out0); +``` + +```c +hmath_status hmath_scalar_truncate_checked_f64( + hmath_context *context, + double x, + char **out0); +``` + +## `scalar.bankers_round` + +`scalar.bankers_round(x, *, dtype='float64')` + +Original: [`HMath.Scalar.bankersRound`](haskell/HMath-Scalar.md#v:bankersRound). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_bankers_round_f32( + hmath_context *context, + float x, + char **out0); +``` + +```c +hmath_status hmath_scalar_bankers_round_f64( + hmath_context *context, + double x, + char **out0); +``` + +## `scalar.integer_fraction` + +`scalar.integer_fraction(x, *, dtype='float64')` + +Original: [`HMath.Scalar.integerFraction`](haskell/HMath-Scalar.md#v:integerFraction). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_integer_fraction_f32( + hmath_context *context, + float x, + char **out0, + float *out1); +``` + +```c +hmath_status hmath_scalar_integer_fraction_f64( + hmath_context *context, + double x, + char **out0, + double *out1); +``` + +## `scalar.quotient_remainder` + +`scalar.quotient_remainder(a, b)` + +Original: [`HMath.Scalar.quotientRemainder`](haskell/HMath-Scalar.md#v:quotientRemainder). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_quotient_remainder( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +``` + +## `scalar.euclidean_division` + +`scalar.euclidean_division(a, b)` + +Original: [`HMath.Scalar.euclideanDivision`](haskell/HMath-Scalar.md#v:euclideanDivision). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_euclidean_division( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +``` + +## `scalar.positive_modulo` + +`scalar.positive_modulo(a, modulus, *, dtype='integer')` + +Original: [`HMath.Scalar.positiveModulo`](haskell/HMath-Scalar.md#v:positiveModulo). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_positive_modulo_integer( + hmath_context *context, + const char *a, + const char *modulus, + char **out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_i8( + hmath_context *context, + int8_t a, + int8_t modulus, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_i16( + hmath_context *context, + int16_t a, + int16_t modulus, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_i32( + hmath_context *context, + int32_t a, + int32_t modulus, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_i64( + hmath_context *context, + int64_t a, + int64_t modulus, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_u8( + hmath_context *context, + uint8_t a, + uint8_t modulus, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_u16( + hmath_context *context, + uint16_t a, + uint16_t modulus, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_u32( + hmath_context *context, + uint32_t a, + uint32_t modulus, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_u64( + hmath_context *context, + uint64_t a, + uint64_t modulus, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t modulus, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo_word( + hmath_context *context, + size_t a, + size_t modulus, + size_t *out0); +``` + +```c +hmath_status hmath_scalar_positive_modulo( + hmath_context *context, + const char *a, + const char *modulus, + char **out0); +``` + +## `scalar.modular_power` + +`scalar.modular_power(a, n, modulus)` + +Original: [`HMath.Scalar.modularPower`](haskell/HMath-Scalar.md#v:modularPower). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_modular_power( + hmath_context *context, + const char *a, + const char *n, + const char *modulus, + char **out0); +``` + +## `scalar.factorial_checked` + +`scalar.factorial_checked(n)` + +Original: [`HMath.Scalar.factorialChecked`](haskell/HMath-Scalar.md#v:factorialChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_factorial_checked( + hmath_context *context, + const char *n, + char **out0); +``` + +## `scalar.double_factorial` + +`scalar.double_factorial(n)` + +Original: [`HMath.Scalar.doubleFactorial`](haskell/HMath-Scalar.md#v:doubleFactorial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_double_factorial( + hmath_context *context, + const char *n, + char **out0); +``` + +## `scalar.fibonacci_checked` + +`scalar.fibonacci_checked(n)` + +Original: [`HMath.Scalar.fibonacciChecked`](haskell/HMath-Scalar.md#v:fibonacciChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_fibonacci_checked( + hmath_context *context, + const char *n, + char **out0); +``` + +## `scalar.lucas` + +`scalar.lucas(n)` + +Original: [`HMath.Scalar.lucas`](haskell/HMath-Scalar.md#v:lucas). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_lucas( + hmath_context *context, + const char *n, + char **out0); +``` + +## `scalar.catalan` + +`scalar.catalan(n)` + +Original: [`HMath.Scalar.catalan`](haskell/HMath-Scalar.md#v:catalan). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_catalan( + hmath_context *context, + const char *n, + char **out0); +``` + +## `scalar.rising_factorial` + +`scalar.rising_factorial(x, n)` + +Original: [`HMath.Scalar.risingFactorial`](haskell/HMath-Scalar.md#v:risingFactorial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_rising_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0); +``` + +## `scalar.falling_factorial` + +`scalar.falling_factorial(x, n)` + +Original: [`HMath.Scalar.fallingFactorial`](haskell/HMath-Scalar.md#v:fallingFactorial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_falling_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0); +``` + +## `scalar.permutations` + +`scalar.permutations(n, k)` + +Original: [`HMath.Scalar.permutations`](haskell/HMath-Scalar.md#v:permutations). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_permutations( + hmath_context *context, + const char *n, + const char *k, + char **out0); +``` + +## `scalar.combinations` + +`scalar.combinations(n, k)` + +Original: [`HMath.Scalar.combinations`](haskell/HMath-Scalar.md#v:combinations). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_combinations( + hmath_context *context, + const char *n, + const char *k, + char **out0); +``` + +## `scalar.bernoulli` + +`scalar.bernoulli(n)` + +Original: [`HMath.Scalar.bernoulli`](haskell/HMath-Scalar.md#v:bernoulli). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_bernoulli( + hmath_context *context, + ptrdiff_t n, + char **out0, + char **out1); +``` + +## `scalar.harmonic` + +`scalar.harmonic(n)` + +Original: [`HMath.Scalar.harmonic`](haskell/HMath-Scalar.md#v:harmonic). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_harmonic( + hmath_context *context, + const char *n, + char **out0, + char **out1); +``` + +## `scalar.cumulative_sum` + +`scalar.cumulative_sum(values, *, dtype='float64')` + +Original: [`HMath.Scalar.cumulativeSum`](haskell/HMath-Scalar.md#v:cumulativeSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_cumulative_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +``` + +## `scalar.cumulative_product` + +`scalar.cumulative_product(values, *, dtype='float64')` + +Original: [`HMath.Scalar.cumulativeProduct`](haskell/HMath-Scalar.md#v:cumulativeProduct). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_cumulative_product_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_cumulative_product_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_cumulative_product_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_cumulative_product_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +``` + +## `scalar.prefix_sum` + +`scalar.prefix_sum(values, *, dtype='float64')` + +Original: [`HMath.Scalar.prefixSum`](haskell/HMath-Scalar.md#v:prefixSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_scalar_prefix_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_prefix_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +``` + +```c +hmath_status hmath_scalar_prefix_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_scalar_prefix_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +``` + +## `trigonometry.sin_checked` + +`trigonometry.sin_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sinChecked`](haskell/HMath-Trigonometry.md#v:sinChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sin_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_sin_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.cos_checked` + +`trigonometry.cos_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.cosChecked`](haskell/HMath-Trigonometry.md#v:cosChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_cos_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_cos_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.tan_checked` + +`trigonometry.tan_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.tanChecked`](haskell/HMath-Trigonometry.md#v:tanChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_tan_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_tan_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.asin_checked` + +`trigonometry.asin_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.asinChecked`](haskell/HMath-Trigonometry.md#v:asinChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_asin_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_asin_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acos_checked` + +`trigonometry.acos_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acosChecked`](haskell/HMath-Trigonometry.md#v:acosChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acos_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acos_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.atan_checked` + +`trigonometry.atan_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.atanChecked`](haskell/HMath-Trigonometry.md#v:atanChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_atan_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_atan_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.sec` + +`trigonometry.sec(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sec`](haskell/HMath-Trigonometry.md#v:sec). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sec_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_sec_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.csc` + +`trigonometry.csc(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.csc`](haskell/HMath-Trigonometry.md#v:csc). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_csc_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_csc_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.cot` + +`trigonometry.cot(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.cot`](haskell/HMath-Trigonometry.md#v:cot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_cot_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_cot_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.asec` + +`trigonometry.asec(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.asec`](haskell/HMath-Trigonometry.md#v:asec). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_asec_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_asec_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acsc` + +`trigonometry.acsc(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acsc`](haskell/HMath-Trigonometry.md#v:acsc). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acsc_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acsc_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acot` + +`trigonometry.acot(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acot`](haskell/HMath-Trigonometry.md#v:acot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acot_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acot_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.sinh_checked` + +`trigonometry.sinh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sinhChecked`](haskell/HMath-Trigonometry.md#v:sinhChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sinh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_sinh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.cosh_checked` + +`trigonometry.cosh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.coshChecked`](haskell/HMath-Trigonometry.md#v:coshChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_cosh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_cosh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.tanh_checked` + +`trigonometry.tanh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.tanhChecked`](haskell/HMath-Trigonometry.md#v:tanhChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_tanh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_tanh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.asinh_checked` + +`trigonometry.asinh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.asinhChecked`](haskell/HMath-Trigonometry.md#v:asinhChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_asinh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_asinh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acosh_checked` + +`trigonometry.acosh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acoshChecked`](haskell/HMath-Trigonometry.md#v:acoshChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acosh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acosh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.atanh_checked` + +`trigonometry.atanh_checked(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.atanhChecked`](haskell/HMath-Trigonometry.md#v:atanhChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_atanh_checked_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_atanh_checked_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.sech` + +`trigonometry.sech(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sech`](haskell/HMath-Trigonometry.md#v:sech). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sech_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_sech_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.csch` + +`trigonometry.csch(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.csch`](haskell/HMath-Trigonometry.md#v:csch). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_csch_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_csch_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.coth` + +`trigonometry.coth(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.coth`](haskell/HMath-Trigonometry.md#v:coth). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_coth_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_coth_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.asech` + +`trigonometry.asech(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.asech`](haskell/HMath-Trigonometry.md#v:asech). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_asech_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_asech_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acsch` + +`trigonometry.acsch(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acsch`](haskell/HMath-Trigonometry.md#v:acsch). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acsch_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acsch_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.acoth` + +`trigonometry.acoth(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.acoth`](haskell/HMath-Trigonometry.md#v:acoth). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_acoth_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_acoth_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.normalize_angle` + +`trigonometry.normalize_angle(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.normalizeAngle`](haskell/HMath-Trigonometry.md#v:normalizeAngle). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_normalize_angle_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_normalize_angle_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.normalize_signed_angle` + +`trigonometry.normalize_signed_angle(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.normalizeSignedAngle`](haskell/HMath-Trigonometry.md#v:normalizeSignedAngle). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_normalize_signed_angle_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_normalize_signed_angle_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.versine` + +`trigonometry.versine(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.versine`](haskell/HMath-Trigonometry.md#v:versine). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_versine_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_versine_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.haversine` + +`trigonometry.haversine(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.haversine`](haskell/HMath-Trigonometry.md#v:haversine). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_haversine_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_haversine_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.sinc` + +`trigonometry.sinc(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sinc`](haskell/HMath-Trigonometry.md#v:sinc). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sinc_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_sinc_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.cosc` + +`trigonometry.cosc(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.cosc`](haskell/HMath-Trigonometry.md#v:cosc). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_cosc_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_cosc_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `trigonometry.atan2_checked` + +`trigonometry.atan2_checked(y, x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.atan2Checked`](haskell/HMath-Trigonometry.md#v:atan2Checked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_atan2_checked_f32( + hmath_context *context, + float y, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_atan2_checked_f64( + hmath_context *context, + double y, + double x, + double *out0); +``` + +## `trigonometry.sincos` + +`trigonometry.sincos(x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sincos`](haskell/HMath-Trigonometry.md#v:sincos). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_sincos_f32( + hmath_context *context, + float x, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_sincos_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `trigonometry.wrap` + +`trigonometry.wrap(low, high, x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.wrap`](haskell/HMath-Trigonometry.md#v:wrap). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_wrap_f32( + hmath_context *context, + float low, + float high, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_wrap_f64( + hmath_context *context, + double low, + double high, + double x, + double *out0); +``` + +## `trigonometry.angle_difference` + +`trigonometry.angle_difference(a, b, *, dtype='float64')` + +Original: [`HMath.Trigonometry.angleDifference`](haskell/HMath-Trigonometry.md#v:angleDifference). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_angle_difference_f32( + hmath_context *context, + float a, + float b, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_angle_difference_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `trigonometry.great_circle_angle` + +`trigonometry.great_circle_angle(a, b, *, dtype='float64')` + +Original: [`HMath.Trigonometry.greatCircleAngle`](haskell/HMath-Trigonometry.md#v:greatCircleAngle). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_great_circle_angle_f32( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_great_circle_angle_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +``` + +## `trigonometry.great_circle_distance` + +`trigonometry.great_circle_distance(radius, a, b, *, dtype='float64')` + +Original: [`HMath.Trigonometry.greatCircleDistance`](haskell/HMath-Trigonometry.md#v:greatCircleDistance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_great_circle_distance_f32( + hmath_context *context, + float radius, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_great_circle_distance_f64( + hmath_context *context, + double radius, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +``` + +## `trigonometry.spherical_side` + +`trigonometry.spherical_side(a, b, included, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sphericalSide`](haskell/HMath-Trigonometry.md#v:sphericalSide). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_spherical_side_f32( + hmath_context *context, + float a, + float b, + float included, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_spherical_side_f64( + hmath_context *context, + double a, + double b, + double included, + double *out0); +``` + +## `trigonometry.spherical_angles` + +`trigonometry.spherical_angles(a, b, c, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sphericalAngles`](haskell/HMath-Trigonometry.md#v:sphericalAngles). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_spherical_angles_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0, + float *out1, + float *out2); +``` + +```c +hmath_status hmath_trigonometry_spherical_angles_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0, + double *out1, + double *out2); +``` + +## `trigonometry.spherical_excess` + +`trigonometry.spherical_excess(a, b, c, *, dtype='float64')` + +Original: [`HMath.Trigonometry.sphericalExcess`](haskell/HMath-Trigonometry.md#v:sphericalExcess). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_spherical_excess_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_spherical_excess_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0); +``` + +## `trigonometry.complex_sin` + +`trigonometry.complex_sin(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexSin`](haskell/HMath-Trigonometry.md#v:complexSin). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_sin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_sin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_cos` + +`trigonometry.complex_cos(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexCos`](haskell/HMath-Trigonometry.md#v:complexCos). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_cos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_cos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_tan` + +`trigonometry.complex_tan(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexTan`](haskell/HMath-Trigonometry.md#v:complexTan). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_tan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_tan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_asin` + +`trigonometry.complex_asin(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAsin`](haskell/HMath-Trigonometry.md#v:complexAsin). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_asin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_asin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_acos` + +`trigonometry.complex_acos(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAcos`](haskell/HMath-Trigonometry.md#v:complexAcos). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_acos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_acos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_atan` + +`trigonometry.complex_atan(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAtan`](haskell/HMath-Trigonometry.md#v:complexAtan). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_atan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_atan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_sinh` + +`trigonometry.complex_sinh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexSinh`](haskell/HMath-Trigonometry.md#v:complexSinh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_sinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_sinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_cosh` + +`trigonometry.complex_cosh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexCosh`](haskell/HMath-Trigonometry.md#v:complexCosh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_cosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_cosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_tanh` + +`trigonometry.complex_tanh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexTanh`](haskell/HMath-Trigonometry.md#v:complexTanh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_tanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_tanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_asinh` + +`trigonometry.complex_asinh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAsinh`](haskell/HMath-Trigonometry.md#v:complexAsinh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_asinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_asinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_acosh` + +`trigonometry.complex_acosh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAcosh`](haskell/HMath-Trigonometry.md#v:complexAcosh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_acosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_acosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.complex_atanh` + +`trigonometry.complex_atanh(z, *, dtype='float64')` + +Original: [`HMath.Trigonometry.complexAtanh`](haskell/HMath-Trigonometry.md#v:complexAtanh). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_complex_atanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_trigonometry_complex_atanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `trigonometry.periodic_sawtooth` + +`trigonometry.periodic_sawtooth(period, x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.periodicSawtooth`](haskell/HMath-Trigonometry.md#v:periodicSawtooth). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_periodic_sawtooth_f32( + hmath_context *context, + float period, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_periodic_sawtooth_f64( + hmath_context *context, + double period, + double x, + double *out0); +``` + +## `trigonometry.periodic_triangle` + +`trigonometry.periodic_triangle(period, x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.periodicTriangle`](haskell/HMath-Trigonometry.md#v:periodicTriangle). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_periodic_triangle_f32( + hmath_context *context, + float period, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_periodic_triangle_f64( + hmath_context *context, + double period, + double x, + double *out0); +``` + +## `trigonometry.periodic_square` + +`trigonometry.periodic_square(period, x, *, dtype='float64')` + +Original: [`HMath.Trigonometry.periodicSquare`](haskell/HMath-Trigonometry.md#v:periodicSquare). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_trigonometry_periodic_square_f32( + hmath_context *context, + float period, + float x, + float *out0); +``` + +```c +hmath_status hmath_trigonometry_periodic_square_f64( + hmath_context *context, + double period, + double x, + double *out0); +``` + +## `statistics.mean` + +`statistics.mean(values, *, dtype='float64')` + +Original: [`HMath.Statistics.mean`](haskell/HMath-Statistics.md#v:mean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `complex64`, `complex128`. + +```c +hmath_status hmath_statistics_mean_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +``` + +```c +hmath_status hmath_statistics_mean_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +``` + +```c +hmath_status hmath_statistics_mean_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_statistics_mean_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_statistics_mean_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +``` + +## `statistics.variance` + +`statistics.variance(values, *, dtype='float64')` + +Original: [`HMath.Statistics.variance`](haskell/HMath-Statistics.md#v:variance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `complex64`, `complex128`. + +```c +hmath_status hmath_statistics_variance_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +``` + +```c +hmath_status hmath_statistics_variance_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +``` + +```c +hmath_status hmath_statistics_variance_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_statistics_variance_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_statistics_variance_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +``` + +## `statistics.standard_deviation` + +`statistics.standard_deviation(values, *, dtype='float64')` + +Original: [`HMath.Statistics.standardDeviation`](haskell/HMath-Statistics.md#v:standardDeviation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `complex64`, `complex128`. + +```c +hmath_status hmath_statistics_standard_deviation_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +``` + +```c +hmath_status hmath_statistics_standard_deviation_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +``` + +```c +hmath_status hmath_statistics_standard_deviation_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_statistics_standard_deviation_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +``` + +## `statistics.median` + +`statistics.median(values, *, dtype='float64')` + +Original: [`HMath.Statistics.median`](haskell/HMath-Statistics.md#v:median). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`. + +```c +hmath_status hmath_statistics_median_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +``` + +```c +hmath_status hmath_statistics_median_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +``` + +```c +hmath_status hmath_statistics_median_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +``` + +## `constants.pi_constant` + +`constants.pi_constant(*, dtype='float64')` + +Original: [`HMath.Constants.piConstant`](haskell/HMath-Constants.md#v:piConstant). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_pi_constant_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_pi_constant_f64( + hmath_context *context, + double *out0); +``` + +## `constants.e_constant` + +`constants.e_constant(*, dtype='float64')` + +Original: [`HMath.Constants.eConstant`](haskell/HMath-Constants.md#v:eConstant). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_e_constant_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_e_constant_f64( + hmath_context *context, + double *out0); +``` + +## `constants.tau` + +`constants.tau(*, dtype='float64')` + +Original: [`HMath.Constants.tau`](haskell/HMath-Constants.md#v:tau). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_tau_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_tau_f64( + hmath_context *context, + double *out0); +``` + +## `constants.golden_ratio` + +`constants.golden_ratio(*, dtype='float64')` + +Original: [`HMath.Constants.goldenRatio`](haskell/HMath-Constants.md#v:goldenRatio). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_golden_ratio_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_golden_ratio_f64( + hmath_context *context, + double *out0); +``` + +## `constants.euler_mascheroni` + +`constants.euler_mascheroni(*, dtype='float64')` + +Original: [`HMath.Constants.eulerMascheroni`](haskell/HMath-Constants.md#v:eulerMascheroni). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_euler_mascheroni_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_euler_mascheroni_f64( + hmath_context *context, + double *out0); +``` + +## `constants.catalan_constant` + +`constants.catalan_constant(*, dtype='float64')` + +Original: [`HMath.Constants.catalanConstant`](haskell/HMath-Constants.md#v:catalanConstant). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_catalan_constant_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_catalan_constant_f64( + hmath_context *context, + double *out0); +``` + +## `constants.apery_constant` + +`constants.apery_constant(*, dtype='float64')` + +Original: [`HMath.Constants.aperyConstant`](haskell/HMath-Constants.md#v:aperyConstant). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_apery_constant_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_apery_constant_f64( + hmath_context *context, + double *out0); +``` + +## `constants.sqrt2` + +`constants.sqrt2(*, dtype='float64')` + +Original: [`HMath.Constants.sqrt2`](haskell/HMath-Constants.md#v:sqrt2). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_sqrt2_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_sqrt2_f64( + hmath_context *context, + double *out0); +``` + +## `constants.sqrt3` + +`constants.sqrt3(*, dtype='float64')` + +Original: [`HMath.Constants.sqrt3`](haskell/HMath-Constants.md#v:sqrt3). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_sqrt3_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_sqrt3_f64( + hmath_context *context, + double *out0); +``` + +## `constants.ln2` + +`constants.ln2(*, dtype='float64')` + +Original: [`HMath.Constants.ln2`](haskell/HMath-Constants.md#v:ln2). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_ln2_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_ln2_f64( + hmath_context *context, + double *out0); +``` + +## `constants.ln10` + +`constants.ln10(*, dtype='float64')` + +Original: [`HMath.Constants.ln10`](haskell/HMath-Constants.md#v:ln10). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_ln10_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_ln10_f64( + hmath_context *context, + double *out0); +``` + +## `constants.infinity` + +`constants.infinity(*, dtype='float64')` + +Original: [`HMath.Constants.infinity`](haskell/HMath-Constants.md#v:infinity). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_infinity_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_infinity_f64( + hmath_context *context, + double *out0); +``` + +## `constants.nan` + +`constants.nan(*, dtype='float64')` + +Original: [`HMath.Constants.nan`](haskell/HMath-Constants.md#v:nan). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_constants_nan_f32( + hmath_context *context, + float *out0); +``` + +```c +hmath_status hmath_constants_nan_f64( + hmath_context *context, + double *out0); +``` + +## `scalar.multinomial` + +`scalar.multinomial(ks)` + +Original: [`HMath.Scalar.multinomial`](haskell/HMath-Scalar.md#v:multinomial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_scalar_multinomial( + hmath_context *context, + const char * const *ks, + size_t ks_count, + char **out0); +``` + +## `numbertheory.gcd_integer` + +`numbertheory.gcd_integer(argument1, argument2)` + +Original: [`HMath.NumberTheory.gcdInteger`](haskell/HMath-NumberTheory.md#v:gcdInteger). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_gcd_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0); +``` + +## `numbertheory.lcm_integer` + +`numbertheory.lcm_integer(argument1, argument2)` + +Original: [`HMath.NumberTheory.lcmInteger`](haskell/HMath-NumberTheory.md#v:lcmInteger). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_lcm_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0); +``` + +## `numbertheory.extended_g_c_d` + +`numbertheory.extended_g_c_d(a, b)` + +Original: [`HMath.NumberTheory.extendedGCD`](haskell/HMath-NumberTheory.md#v:extendedGCD). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_extended_g_c_d( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1, + char **out2); +``` + +## `numbertheory.bezout` + +`numbertheory.bezout(a, b)` + +Original: [`HMath.NumberTheory.bezout`](haskell/HMath-NumberTheory.md#v:bezout). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_bezout( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +``` + +## `numbertheory.mod_pow` + +`numbertheory.mod_pow(a, e, m)` + +Original: [`HMath.NumberTheory.modPow`](haskell/HMath-NumberTheory.md#v:modPow). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_mod_pow( + hmath_context *context, + const char *a, + const char *e, + const char *m, + char **out0); +``` + +## `numbertheory.mod_inverse` + +`numbertheory.mod_inverse(a, m)` + +Original: [`HMath.NumberTheory.modInverse`](haskell/HMath-NumberTheory.md#v:modInverse). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_mod_inverse( + hmath_context *context, + const char *a, + const char *m, + char **out0); +``` + +## `numbertheory.integer_square_root` + +`numbertheory.integer_square_root(n)` + +Original: [`HMath.NumberTheory.integerSquareRoot`](haskell/HMath-NumberTheory.md#v:integerSquareRoot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_integer_square_root( + hmath_context *context, + const char *n, + char **out0); +``` + +## `numbertheory.is_prime_exact` + +`numbertheory.is_prime_exact(budget, n)` + +Original: [`HMath.NumberTheory.isPrimeExact`](haskell/HMath-NumberTheory.md#v:isPrimeExact). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_is_prime_exact( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0); +``` + +## `numbertheory.next_prime` + +`numbertheory.next_prime(budget, n)` + +Original: [`HMath.NumberTheory.nextPrime`](haskell/HMath-NumberTheory.md#v:nextPrime). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_next_prime( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.miller_rabin` + +`numbertheory.miller_rabin(bases, n)` + +Original: [`HMath.NumberTheory.millerRabin`](haskell/HMath-NumberTheory.md#v:millerRabin). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_miller_rabin( + hmath_context *context, + const char * const *bases, + size_t bases_count, + const char *n, + int *out0); +``` + +## `numbertheory.baillie_p_s_w` + +`numbertheory.baillie_p_s_w(n)` + +Original: [`HMath.NumberTheory.bailliePSW`](haskell/HMath-NumberTheory.md#v:bailliePSW). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_baillie_p_s_w( + hmath_context *context, + const char *n, + int *out0); +``` + +## `numbertheory.sieve_eratosthenes` + +`numbertheory.sieve_eratosthenes(bound)` + +Original: [`HMath.NumberTheory.sieveEratosthenes`](haskell/HMath-NumberTheory.md#v:sieveEratosthenes). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_sieve_eratosthenes( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.sieve_atkin` + +`numbertheory.sieve_atkin(bound)` + +Original: [`HMath.NumberTheory.sieveAtkin`](haskell/HMath-NumberTheory.md#v:sieveAtkin). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_sieve_atkin( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.segmented_sieve` + +`numbertheory.segmented_sieve(lo, hi)` + +Original: [`HMath.NumberTheory.segmentedSieve`](haskell/HMath-NumberTheory.md#v:segmentedSieve). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_segmented_sieve( + hmath_context *context, + const char *lo, + const char *hi, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.pollard_rho` + +`numbertheory.pollard_rho(budget, seed, n)` + +Original: [`HMath.NumberTheory.pollardRho`](haskell/HMath-NumberTheory.md#v:pollardRho). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_pollard_rho( + hmath_context *context, + ptrdiff_t budget, + const char *seed, + const char *n, + char **out0); +``` + +## `numbertheory.pollard_p_minus_one` + +`numbertheory.pollard_p_minus_one(bound, base, n)` + +Original: [`HMath.NumberTheory.pollardPMinusOne`](haskell/HMath-NumberTheory.md#v:pollardPMinusOne). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_pollard_p_minus_one( + hmath_context *context, + ptrdiff_t bound, + const char *base, + const char *n, + char **out0); +``` + +## `numbertheory.fermat_factor` + +`numbertheory.fermat_factor(budget, n)` + +Original: [`HMath.NumberTheory.fermatFactor`](haskell/HMath-NumberTheory.md#v:fermatFactor). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_fermat_factor( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.divisors` + +`numbertheory.divisors(budget, n)` + +Original: [`HMath.NumberTheory.divisors`](haskell/HMath-NumberTheory.md#v:divisors). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_divisors( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.divisor_sum` + +`numbertheory.divisor_sum(budget, n)` + +Original: [`HMath.NumberTheory.divisorSum`](haskell/HMath-NumberTheory.md#v:divisorSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_divisor_sum( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.divisor_count` + +`numbertheory.divisor_count(budget, n)` + +Original: [`HMath.NumberTheory.divisorCount`](haskell/HMath-NumberTheory.md#v:divisorCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_divisor_count( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.euler_totient` + +`numbertheory.euler_totient(budget, n)` + +Original: [`HMath.NumberTheory.eulerTotient`](haskell/HMath-NumberTheory.md#v:eulerTotient). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_euler_totient( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.carmichael` + +`numbertheory.carmichael(budget, n)` + +Original: [`HMath.NumberTheory.carmichael`](haskell/HMath-NumberTheory.md#v:carmichael). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_carmichael( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.mobius` + +`numbertheory.mobius(budget, n)` + +Original: [`HMath.NumberTheory.mobius`](haskell/HMath-NumberTheory.md#v:mobius). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_mobius( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.liouville` + +`numbertheory.liouville(budget, n)` + +Original: [`HMath.NumberTheory.liouville`](haskell/HMath-NumberTheory.md#v:liouville). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_liouville( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +``` + +## `numbertheory.multiplicative_order` + +`numbertheory.multiplicative_order(budget, a, m)` + +Original: [`HMath.NumberTheory.multiplicativeOrder`](haskell/HMath-NumberTheory.md#v:multiplicativeOrder). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_multiplicative_order( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *m, + char **out0); +``` + +## `numbertheory.primitive_root` + +`numbertheory.primitive_root(budget, m)` + +Original: [`HMath.NumberTheory.primitiveRoot`](haskell/HMath-NumberTheory.md#v:primitiveRoot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_primitive_root( + hmath_context *context, + ptrdiff_t budget, + const char *m, + char **out0); +``` + +## `numbertheory.discrete_log` + +`numbertheory.discrete_log(budget, a, b, m)` + +Original: [`HMath.NumberTheory.discreteLog`](haskell/HMath-NumberTheory.md#v:discreteLog). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_discrete_log( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + const char *m, + char **out0); +``` + +## `numbertheory.legendre_symbol` + +`numbertheory.legendre_symbol(budget, a, p)` + +Original: [`HMath.NumberTheory.legendreSymbol`](haskell/HMath-NumberTheory.md#v:legendreSymbol). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_legendre_symbol( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +``` + +## `numbertheory.jacobi_symbol` + +`numbertheory.jacobi_symbol(a, n)` + +Original: [`HMath.NumberTheory.jacobiSymbol`](haskell/HMath-NumberTheory.md#v:jacobiSymbol). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_jacobi_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0); +``` + +## `numbertheory.kronecker_symbol` + +`numbertheory.kronecker_symbol(a, n)` + +Original: [`HMath.NumberTheory.kroneckerSymbol`](haskell/HMath-NumberTheory.md#v:kroneckerSymbol). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_kronecker_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0); +``` + +## `numbertheory.tonelli_shanks` + +`numbertheory.tonelli_shanks(budget, a, p)` + +Original: [`HMath.NumberTheory.tonelliShanks`](haskell/HMath-NumberTheory.md#v:tonelliShanks). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_tonelli_shanks( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +``` + +## `numbertheory.continued_fraction` + +`numbertheory.continued_fraction(r)` + +Original: [`HMath.NumberTheory.continuedFraction`](haskell/HMath-NumberTheory.md#v:continuedFraction). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_continued_fraction( + hmath_context *context, + const char *r_numerator, + const char *r_denominator, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.from_continued_fraction` + +`numbertheory.from_continued_fraction(argument1)` + +Original: [`HMath.NumberTheory.fromContinuedFraction`](haskell/HMath-NumberTheory.md#v:fromContinuedFraction). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_from_continued_fraction( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char **out0, + char **out1); +``` + +## `numbertheory.convergents` + +`numbertheory.convergents(xs)` + +Original: [`HMath.NumberTheory.convergents`](haskell/HMath-NumberTheory.md#v:convergents). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_convergents( + hmath_context *context, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.farey` + +`numbertheory.farey(n)` + +Original: [`HMath.NumberTheory.farey`](haskell/HMath-NumberTheory.md#v:farey). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_farey( + hmath_context *context, + const char *n, + char * **out_data, + size_t *out_count); +``` + +## `numbertheory.pell_fundamental` + +`numbertheory.pell_fundamental(budget, d)` + +Original: [`HMath.NumberTheory.pellFundamental`](haskell/HMath-NumberTheory.md#v:pellFundamental). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_pell_fundamental( + hmath_context *context, + ptrdiff_t budget, + const char *d, + char **out0, + char **out1); +``` + +## `numbertheory.is_perfect_number` + +`numbertheory.is_perfect_number(budget, n)` + +Original: [`HMath.NumberTheory.isPerfectNumber`](haskell/HMath-NumberTheory.md#v:isPerfectNumber). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_is_perfect_number( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0); +``` + +## `numbertheory.are_amicable` + +`numbertheory.are_amicable(budget, a, b)` + +Original: [`HMath.NumberTheory.areAmicable`](haskell/HMath-NumberTheory.md#v:areAmicable). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_are_amicable( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + int *out0); +``` + +## `numbertheory.partition_count` + +`numbertheory.partition_count(n)` + +Original: [`HMath.NumberTheory.partitionCount`](haskell/HMath-NumberTheory.md#v:partitionCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_partition_count( + hmath_context *context, + ptrdiff_t n, + char **out0); +``` + +## `numbertheory.fibonacci_fast` + +`numbertheory.fibonacci_fast(n)` + +Original: [`HMath.NumberTheory.fibonacciFast`](haskell/HMath-NumberTheory.md#v:fibonacciFast). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numbertheory_fibonacci_fast( + hmath_context *context, + const char *n, + char **out0); +``` + +## `combinatorics.permutations_count` + +`combinatorics.permutations_count(n, k)` + +Original: [`HMath.Combinatorics.permutationsCount`](haskell/HMath-Combinatorics.md#v:permutationsCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_permutations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +``` + +## `combinatorics.combinations_count` + +`combinatorics.combinations_count(n, k)` + +Original: [`HMath.Combinatorics.combinationsCount`](haskell/HMath-Combinatorics.md#v:combinationsCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_combinations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +``` + +## `combinatorics.multinomial` + +`combinatorics.multinomial(argument1)` + +Original: [`HMath.Combinatorics.multinomial`](haskell/HMath-Combinatorics.md#v:multinomial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_multinomial( + hmath_context *context, + ptrdiff_t const *argument1, + size_t argument1_count, + char **out0); +``` + +## `combinatorics.rank_permutation` + +`combinatorics.rank_permutation(p)` + +Original: [`HMath.Combinatorics.rankPermutation`](haskell/HMath-Combinatorics.md#v:rankPermutation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_rank_permutation( + hmath_context *context, + ptrdiff_t const *p, + size_t p_count, + char **out0); +``` + +## `combinatorics.unrank_permutation` + +`combinatorics.unrank_permutation(n, r)` + +Original: [`HMath.Combinatorics.unrankPermutation`](haskell/HMath-Combinatorics.md#v:unrankPermutation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_unrank_permutation( + hmath_context *context, + ptrdiff_t n, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `combinatorics.rank_combination` + +`combinatorics.rank_combination(n, xs)` + +Original: [`HMath.Combinatorics.rankCombination`](haskell/HMath-Combinatorics.md#v:rankCombination). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_rank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t const *xs, + size_t xs_count, + char **out0); +``` + +## `combinatorics.unrank_combination` + +`combinatorics.unrank_combination(n, k, r)` + +Original: [`HMath.Combinatorics.unrankCombination`](haskell/HMath-Combinatorics.md#v:unrankCombination). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_unrank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `combinatorics.derangement_count` + +`combinatorics.derangement_count(n)` + +Original: [`HMath.Combinatorics.derangementCount`](haskell/HMath-Combinatorics.md#v:derangementCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_derangement_count( + hmath_context *context, + ptrdiff_t n, + char **out0); +``` + +## `combinatorics.stirling_first` + +`combinatorics.stirling_first(argument1, argument2)` + +Original: [`HMath.Combinatorics.stirlingFirst`](haskell/HMath-Combinatorics.md#v:stirlingFirst). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_stirling_first( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +``` + +## `combinatorics.stirling_second` + +`combinatorics.stirling_second(argument1, argument2)` + +Original: [`HMath.Combinatorics.stirlingSecond`](haskell/HMath-Combinatorics.md#v:stirlingSecond). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_stirling_second( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +``` + +## `combinatorics.bell_number` + +`combinatorics.bell_number(n)` + +Original: [`HMath.Combinatorics.bellNumber`](haskell/HMath-Combinatorics.md#v:bellNumber). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_bell_number( + hmath_context *context, + ptrdiff_t n, + char **out0); +``` + +## `combinatorics.eulerian_number` + +`combinatorics.eulerian_number(argument1, argument2)` + +Original: [`HMath.Combinatorics.eulerianNumber`](haskell/HMath-Combinatorics.md#v:eulerianNumber). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_eulerian_number( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +``` + +## `combinatorics.lah_number` + +`combinatorics.lah_number(n, k)` + +Original: [`HMath.Combinatorics.lahNumber`](haskell/HMath-Combinatorics.md#v:lahNumber). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_lah_number( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +``` + +## `combinatorics.catalan_number` + +`combinatorics.catalan_number(argument1)` + +Original: [`HMath.Combinatorics.catalanNumber`](haskell/HMath-Combinatorics.md#v:catalanNumber). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_catalan_number( + hmath_context *context, + ptrdiff_t argument1, + char **out0); +``` + +## `combinatorics.fibonacci` + +`combinatorics.fibonacci(n)` + +Original: [`HMath.Combinatorics.fibonacci`](haskell/HMath-Combinatorics.md#v:fibonacci). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_fibonacci( + hmath_context *context, + ptrdiff_t n, + char **out0); +``` + +## `combinatorics.lucas` + +`combinatorics.lucas(n)` + +Original: [`HMath.Combinatorics.lucas`](haskell/HMath-Combinatorics.md#v:lucas). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_lucas( + hmath_context *context, + ptrdiff_t n, + char **out0); +``` + +## `combinatorics.inclusion_exclusion` + +`combinatorics.inclusion_exclusion(n, sizes)` + +Original: [`HMath.Combinatorics.inclusionExclusion`](haskell/HMath-Combinatorics.md#v:inclusionExclusion). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_inclusion_exclusion( + hmath_context *context, + ptrdiff_t n, + const char * const *sizes, + size_t sizes_count, + char **out0); +``` + +## `combinatorics.multiset_count` + +`combinatorics.multiset_count(argument1, *, dtype='float64')` + +Original: [`HMath.Combinatorics.multisetCount`](haskell/HMath-Combinatorics.md#v:multisetCount). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_multiset_count_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + char **out0); +``` + +```c +hmath_status hmath_combinatorics_multiset_count_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + char **out0); +``` + +## `combinatorics.linear_recurrence` + +`combinatorics.linear_recurrence(n, cs, initial)` + +Original: [`HMath.Combinatorics.linearRecurrence`](haskell/HMath-Combinatorics.md#v:linearRecurrence). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_linear_recurrence( + hmath_context *context, + ptrdiff_t n, + const char * const *cs, + size_t cs_count, + const char * const *initial, + size_t initial_count, + char * **out_data, + size_t *out_count); +``` + +## `combinatorics.convolve_series` + +`combinatorics.convolve_series(n, a, b)` + +Original: [`HMath.Combinatorics.convolveSeries`](haskell/HMath-Combinatorics.md#v:convolveSeries). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_convolve_series( + hmath_context *context, + ptrdiff_t n, + const char * const *a, + size_t a_count, + const char * const *b, + size_t b_count, + char * **out_data, + size_t *out_count); +``` + +## `combinatorics.finite_sum` + +`combinatorics.finite_sum(argument1, *, dtype='float64')` + +Original: [`HMath.Combinatorics.finiteSum`](haskell/HMath-Combinatorics.md#v:finiteSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_combinatorics_finite_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_combinatorics_finite_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `linear.dot` + +`linear.dot(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.dot`](haskell/HMath-Linear.md#v:dot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_dot_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +``` + +```c +hmath_status hmath_linear_dot_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +``` + +```c +hmath_status hmath_linear_dot_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_linear_dot_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +``` + +```c +hmath_status hmath_linear_dot_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +``` + +```c +hmath_status hmath_linear_dot_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +``` + +```c +hmath_status hmath_linear_dot_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +``` + +```c +hmath_status hmath_linear_dot_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +``` + +```c +hmath_status hmath_linear_dot_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +``` + +```c +hmath_status hmath_linear_dot_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +``` + +```c +hmath_status hmath_linear_dot_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +``` + +```c +hmath_status hmath_linear_dot_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +``` + +```c +hmath_status hmath_linear_dot_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_linear_dot_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +``` + +```c +hmath_status hmath_linear_dot_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_linear_dot_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +``` + +## `linear.dot_checked` + +`linear.dot_checked(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.dotChecked`](haskell/HMath-Linear.md#v:dotChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_dot_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +``` + +```c +hmath_status hmath_linear_dot_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +``` + +```c +hmath_status hmath_linear_dot_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +``` + +```c +hmath_status hmath_linear_dot_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_linear_dot_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +``` + +## `linear.magnitude` + +`linear.magnitude(argument1, *, dtype='float64')` + +Original: [`HMath.Linear.magnitude`](haskell/HMath-Linear.md#v:magnitude). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_magnitude_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_linear_magnitude_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +```c +hmath_status hmath_linear_magnitude_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float *out0, + float *out1); +``` + +```c +hmath_status hmath_linear_magnitude_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double *out0, + double *out1); +``` + +## `linear.normalize` + +`linear.normalize(argument1, *, dtype='float64')` + +Original: [`HMath.Linear.normalize`](haskell/HMath-Linear.md#v:normalize). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_normalize_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_normalize_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_normalize_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_normalize_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `linear.add` + +`linear.add(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.add`](haskell/HMath-Linear.md#v:add). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_add_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `linear.add_checked` + +`linear.add_checked(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.addChecked`](haskell/HMath-Linear.md#v:addChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_add_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_add_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `linear.subtract_checked` + +`linear.subtract_checked(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.subtractChecked`](haskell/HMath-Linear.md#v:subtractChecked). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_subtract_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_subtract_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `linear.scale` + +`linear.scale(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Linear.scale`](haskell/HMath-Linear.md#v:scale). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `float32`, `float64`, `rational`, `integer`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`, `complex64`, `complex128`. + +```c +hmath_status hmath_linear_scale_f32( + hmath_context *context, + float argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_rational( + hmath_context *context, + const char *argument1_numerator, + const char *argument1_denominator, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_integer( + hmath_context *context, + const char *argument1, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_i8( + hmath_context *context, + int8_t argument1, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_i16( + hmath_context *context, + int16_t argument1, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_i32( + hmath_context *context, + int32_t argument1, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_i64( + hmath_context *context, + int64_t argument1, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_u8( + hmath_context *context, + uint8_t argument1, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_u16( + hmath_context *context, + uint16_t argument1, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_u32( + hmath_context *context, + uint32_t argument1, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_u64( + hmath_context *context, + uint64_t argument1, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_int( + hmath_context *context, + ptrdiff_t argument1, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_word( + hmath_context *context, + size_t argument1, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_c64( + hmath_context *context, + float argument1_0, + float argument1_1, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_linear_scale_c128( + hmath_context *context, + double argument1_0, + double argument1_1, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `special.gamma` + +`special.gamma(x, *, dtype='float64')` + +Original: [`HMath.Special.gamma`](haskell/HMath-Special.md#v:gamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_gamma_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.log_gamma` + +`special.log_gamma(x, *, dtype='float64')` + +Original: [`HMath.Special.logGamma`](haskell/HMath-Special.md#v:logGamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_log_gamma_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.log_beta` + +`special.log_beta(a, b, *, dtype='float64')` + +Original: [`HMath.Special.logBeta`](haskell/HMath-Special.md#v:logBeta). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_log_beta_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `special.beta` + +`special.beta(a, b, *, dtype='float64')` + +Original: [`HMath.Special.beta`](haskell/HMath-Special.md#v:beta). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_beta_f64( + hmath_context *context, + double a, + double b, + double *out0); +``` + +## `special.gamma_p` + +`special.gamma_p(a, x, *, dtype='float64')` + +Original: [`HMath.Special.gammaP`](haskell/HMath-Special.md#v:gammaP). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_gamma_p_f64( + hmath_context *context, + double a, + double x, + double *out0); +``` + +## `special.gamma_q` + +`special.gamma_q(a, x, *, dtype='float64')` + +Original: [`HMath.Special.gammaQ`](haskell/HMath-Special.md#v:gammaQ). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_gamma_q_f64( + hmath_context *context, + double a, + double x, + double *out0); +``` + +## `special.incomplete_gamma` + +`special.incomplete_gamma(a, x, *, dtype='float64')` + +Original: [`HMath.Special.incompleteGamma`](haskell/HMath-Special.md#v:incompleteGamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_incomplete_gamma_f64( + hmath_context *context, + double a, + double x, + double *out0); +``` + +## `special.beta_i` + +`special.beta_i(a, b, x, *, dtype='float64')` + +Original: [`HMath.Special.betaI`](haskell/HMath-Special.md#v:betaI). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_beta_i_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +``` + +## `special.incomplete_beta` + +`special.incomplete_beta(a, b, x, *, dtype='float64')` + +Original: [`HMath.Special.incompleteBeta`](haskell/HMath-Special.md#v:incompleteBeta). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_incomplete_beta_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +``` + +## `special.digamma` + +`special.digamma(x, *, dtype='float64')` + +Original: [`HMath.Special.digamma`](haskell/HMath-Special.md#v:digamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_digamma_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.trigamma` + +`special.trigamma(argument1, *, dtype='float64')` + +Original: [`HMath.Special.trigamma`](haskell/HMath-Special.md#v:trigamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_trigamma_f64( + hmath_context *context, + double argument1, + double *out0); +``` + +## `special.polygamma` + +`special.polygamma(n, x, *, dtype='float64')` + +Original: [`HMath.Special.polygamma`](haskell/HMath-Special.md#v:polygamma). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_polygamma_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.erf` + +`special.erf(x, *, dtype='float64')` + +Original: [`HMath.Special.erf`](haskell/HMath-Special.md#v:erf). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_erf_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.erfc` + +`special.erfc(x, *, dtype='float64')` + +Original: [`HMath.Special.erfc`](haskell/HMath-Special.md#v:erfc). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_erfc_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.erfcx` + +`special.erfcx(x, *, dtype='float64')` + +Original: [`HMath.Special.erfcx`](haskell/HMath-Special.md#v:erfcx). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_erfcx_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.normal_c_d_f` + +`special.normal_c_d_f(x, *, dtype='float64')` + +Original: [`HMath.Special.normalCDF`](haskell/HMath-Special.md#v:normalCDF). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_normal_c_d_f_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.normal_quantile` + +`special.normal_quantile(p, *, dtype='float64')` + +Original: [`HMath.Special.normalQuantile`](haskell/HMath-Special.md#v:normalQuantile). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_normal_quantile_f64( + hmath_context *context, + double p, + double *out0); +``` + +## `special.inverse_erf` + +`special.inverse_erf(x, *, dtype='float64')` + +Original: [`HMath.Special.inverseErf`](haskell/HMath-Special.md#v:inverseErf). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_inverse_erf_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `special.dawson` + +`special.dawson(x, *, dtype='float64')` + +Original: [`HMath.Special.dawson`](haskell/HMath-Special.md#v:dawson). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_dawson_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.exponential_integral` + +`special.exponential_integral(n, x, *, dtype='float64')` + +Original: [`HMath.Special.exponentialIntegral`](haskell/HMath-Special.md#v:exponentialIntegral). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_exponential_integral_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.logarithmic_integral` + +`special.logarithmic_integral(x, *, dtype='float64')` + +Original: [`HMath.Special.logarithmicIntegral`](haskell/HMath-Special.md#v:logarithmicIntegral). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_logarithmic_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.sine_integral` + +`special.sine_integral(x, *, dtype='float64')` + +Original: [`HMath.Special.sineIntegral`](haskell/HMath-Special.md#v:sineIntegral). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_sine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.cosine_integral` + +`special.cosine_integral(x, *, dtype='float64')` + +Original: [`HMath.Special.cosineIntegral`](haskell/HMath-Special.md#v:cosineIntegral). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_cosine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.fresnel` + +`special.fresnel(x, *, dtype='float64')` + +Original: [`HMath.Special.fresnel`](haskell/HMath-Special.md#v:fresnel). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_fresnel_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3); +``` + +## `special.elliptic_f` + +`special.elliptic_f(phi, m, *, dtype='float64')` + +Original: [`HMath.Special.ellipticF`](haskell/HMath-Special.md#v:ellipticF). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_elliptic_f_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1); +``` + +## `special.elliptic_e` + +`special.elliptic_e(phi, m, *, dtype='float64')` + +Original: [`HMath.Special.ellipticE`](haskell/HMath-Special.md#v:ellipticE). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_elliptic_e_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1); +``` + +## `special.elliptic_pi` + +`special.elliptic_pi(n, phi, m, *, dtype='float64')` + +Original: [`HMath.Special.ellipticPi`](haskell/HMath-Special.md#v:ellipticPi). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_elliptic_pi_f64( + hmath_context *context, + double n, + double phi, + double m, + double *out0, + double *out1); +``` + +## `special.jacobi_elliptic` + +`special.jacobi_elliptic(u, m, *, dtype='float64')` + +Original: [`HMath.Special.jacobiElliptic`](haskell/HMath-Special.md#v:jacobiElliptic). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_jacobi_elliptic_f64( + hmath_context *context, + double u, + double m, + double *out0, + double *out1, + double *out2); +``` + +## `special.bessel_j` + +`special.bessel_j(n, x, *, dtype='float64')` + +Original: [`HMath.Special.besselJ`](haskell/HMath-Special.md#v:besselJ). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.bessel_y` + +`special.bessel_y(n, x, *, dtype='float64')` + +Original: [`HMath.Special.besselY`](haskell/HMath-Special.md#v:besselY). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.bessel_i` + +`special.bessel_i(n, x, *, dtype='float64')` + +Original: [`HMath.Special.besselI`](haskell/HMath-Special.md#v:besselI). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.scaled_bessel_i` + +`special.scaled_bessel_i(n, x, *, dtype='float64')` + +Original: [`HMath.Special.scaledBesselI`](haskell/HMath-Special.md#v:scaledBesselI). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_scaled_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.bessel_k` + +`special.bessel_k(n, x, *, dtype='float64')` + +Original: [`HMath.Special.besselK`](haskell/HMath-Special.md#v:besselK). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.scaled_bessel_k` + +`special.scaled_bessel_k(n, x, *, dtype='float64')` + +Original: [`HMath.Special.scaledBesselK`](haskell/HMath-Special.md#v:scaledBesselK). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_scaled_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.spherical_bessel_j` + +`special.spherical_bessel_j(n, x, *, dtype='float64')` + +Original: [`HMath.Special.sphericalBesselJ`](haskell/HMath-Special.md#v:sphericalBesselJ). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_spherical_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.spherical_bessel_y` + +`special.spherical_bessel_y(n, x, *, dtype='float64')` + +Original: [`HMath.Special.sphericalBesselY`](haskell/HMath-Special.md#v:sphericalBesselY). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_spherical_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.airy` + +`special.airy(x, *, dtype='float64')` + +Original: [`HMath.Special.airy`](haskell/HMath-Special.md#v:airy). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_airy_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3, + double *out4, + double *out5, + double *out6, + double *out7); +``` + +## `special.struve` + +`special.struve(nu, x, *, dtype='float64')` + +Original: [`HMath.Special.struve`](haskell/HMath-Special.md#v:struve). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_struve_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1); +``` + +## `special.hypergeometric` + +`special.hypergeometric(as_, bs, z, *, dtype='float64')` + +Original: [`HMath.Special.hypergeometric`](haskell/HMath-Special.md#v:hypergeometric). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_hypergeometric_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *bs, + size_t bs_count, + double z, + double *out0, + double *out1); +``` + +## `special.hypergeometric1_f1` + +`special.hypergeometric1_f1(a, b, z, *, dtype='float64')` + +Original: [`HMath.Special.hypergeometric1F1`](haskell/HMath-Special.md#v:hypergeometric1F1). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_hypergeometric1_f1_f64( + hmath_context *context, + double a, + double b, + double z, + double *out0, + double *out1); +``` + +## `special.hypergeometric2_f1` + +`special.hypergeometric2_f1(a, b, c, z, *, dtype='float64')` + +Original: [`HMath.Special.hypergeometric2F1`](haskell/HMath-Special.md#v:hypergeometric2F1). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_hypergeometric2_f1_f64( + hmath_context *context, + double a, + double b, + double c, + double z, + double *out0, + double *out1); +``` + +## `special.legendre` + +`special.legendre(n, x, *, dtype='float64')` + +Original: [`HMath.Special.legendre`](haskell/HMath-Special.md#v:legendre). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_legendre_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.associated_legendre` + +`special.associated_legendre(l, m, x, *, dtype='float64')` + +Original: [`HMath.Special.associatedLegendre`](haskell/HMath-Special.md#v:associatedLegendre). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_associated_legendre_f64( + hmath_context *context, + ptrdiff_t l, + ptrdiff_t m, + double x, + double *out0); +``` + +## `special.hurwitz_zeta` + +`special.hurwitz_zeta(s, q, *, dtype='float64')` + +Original: [`HMath.Special.hurwitzZeta`](haskell/HMath-Special.md#v:hurwitzZeta). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_hurwitz_zeta_f64( + hmath_context *context, + double s, + double q, + double *out0, + double *out1); +``` + +## `special.riemann_zeta` + +`special.riemann_zeta(s, *, dtype='float64')` + +Original: [`HMath.Special.riemannZeta`](haskell/HMath-Special.md#v:riemannZeta). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_riemann_zeta_f64( + hmath_context *context, + double s, + double *out0, + double *out1); +``` + +## `special.polylogarithm` + +`special.polylogarithm(s, z, *, dtype='float64')` + +Original: [`HMath.Special.polylogarithm`](haskell/HMath-Special.md#v:polylogarithm). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_polylogarithm_f64( + hmath_context *context, + double s, + double z, + double *out0, + double *out1); +``` + +## `special.dilogarithm` + +`special.dilogarithm(x, *, dtype='float64')` + +Original: [`HMath.Special.dilogarithm`](haskell/HMath-Special.md#v:dilogarithm). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_dilogarithm_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +``` + +## `special.lambert_w` + +`special.lambert_w(branch, x, *, dtype='float64')` + +Original: [`HMath.Special.lambertW`](haskell/HMath-Special.md#v:lambertW). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_lambert_w_f64( + hmath_context *context, + ptrdiff_t branch, + double x, + double *out0, + double *out1); +``` + +## `special.debye` + +`special.debye(n, x, *, dtype='float64')` + +Original: [`HMath.Special.debye`](haskell/HMath-Special.md#v:debye). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_debye_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +``` + +## `special.clausen` + +`special.clausen(theta, *, dtype='float64')` + +Original: [`HMath.Special.clausen`](haskell/HMath-Special.md#v:clausen). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_clausen_f64( + hmath_context *context, + double theta, + double *out0, + double *out1); +``` + +## `special.fermi_dirac` + +`special.fermi_dirac(order, eta, *, dtype='float64')` + +Original: [`HMath.Special.fermiDirac`](haskell/HMath-Special.md#v:fermiDirac). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_fermi_dirac_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1); +``` + +## `special.bose_einstein` + +`special.bose_einstein(order, eta, *, dtype='float64')` + +Original: [`HMath.Special.boseEinstein`](haskell/HMath-Special.md#v:boseEinstein). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bose_einstein_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1); +``` + +## `special.coulomb_wave` + +`special.coulomb_wave(l, eta, rho, *, dtype='float64')` + +Original: [`HMath.Special.coulombWave`](haskell/HMath-Special.md#v:coulombWave). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_coulomb_wave_f64( + hmath_context *context, + ptrdiff_t l, + double eta, + double rho, + double *out0, + double *out1, + double *out2, + double *out3); +``` + +## `special.gegenbauer` + +`special.gegenbauer(n, a, x, *, dtype='float64')` + +Original: [`HMath.Special.gegenbauer`](haskell/HMath-Special.md#v:gegenbauer). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_gegenbauer_f64( + hmath_context *context, + ptrdiff_t n, + double a, + double x, + double *out0); +``` + +## `special.parabolic_cylinder` + +`special.parabolic_cylinder(nu, x, *, dtype='float64')` + +Original: [`HMath.Special.parabolicCylinder`](haskell/HMath-Special.md#v:parabolicCylinder). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_parabolic_cylinder_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1); +``` + +## `special.mathieu` + +`special.mathieu(evenMode, n, q, x, *, dtype='float64')` + +Original: [`HMath.Special.mathieu`](haskell/HMath-Special.md#v:mathieu). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_mathieu_f64( + hmath_context *context, + int evenMode, + ptrdiff_t n, + double q, + double x, + double *out0, + double *out1, + double *out2); +``` + +## `special.bernoulli_polynomial` + +`special.bernoulli_polynomial(n, x, *, dtype='float64')` + +Original: [`HMath.Special.bernoulliPolynomial`](haskell/HMath-Special.md#v:bernoulliPolynomial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_bernoulli_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.euler_polynomial` + +`special.euler_polynomial(n, x, *, dtype='float64')` + +Original: [`HMath.Special.eulerPolynomial`](haskell/HMath-Special.md#v:eulerPolynomial). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_euler_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +``` + +## `special.wigner3j` + +`special.wigner3j(j1, j2, j3, m1, m2, m3, *, dtype='float64')` + +Original: [`HMath.Special.wigner3j`](haskell/HMath-Special.md#v:wigner3j). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_wigner3j_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t j2, + ptrdiff_t j3, + ptrdiff_t m1, + ptrdiff_t m2, + ptrdiff_t m3, + double *out0); +``` + +## `special.wigner6j` + +`special.wigner6j(a, b, c, d, e, f, *, dtype='float64')` + +Original: [`HMath.Special.wigner6j`](haskell/HMath-Special.md#v:wigner6j). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_wigner6j_f64( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t c, + ptrdiff_t d, + ptrdiff_t e, + ptrdiff_t f, + double *out0); +``` + +## `special.wigner9j` + +`special.wigner9j(js, *, dtype='float64')` + +Original: [`HMath.Special.wigner9j`](haskell/HMath-Special.md#v:wigner9j). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_wigner9j_f64( + hmath_context *context, + ptrdiff_t const *js, + size_t js_count, + double *out0); +``` + +## `special.clebsch_gordan` + +`special.clebsch_gordan(j1, m1, j2, m2, j, m, *, dtype='float64')` + +Original: [`HMath.Special.clebschGordan`](haskell/HMath-Special.md#v:clebschGordan). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_clebsch_gordan_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t m1, + ptrdiff_t j2, + ptrdiff_t m2, + ptrdiff_t j, + ptrdiff_t m, + double *out0); +``` + +## `complex.to_polar` + +`complex.to_polar(z, *, dtype='float64')` + +Original: [`HMath.Complex.toPolar`](haskell/HMath-Complex.md#v:toPolar). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_to_polar_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `probability.gamma_poisson_update` + +`probability.gamma_poisson_update(shapePrior, ratePrior, xs, *, dtype='float64')` + +Original: [`HMath.Probability.gammaPoissonUpdate`](haskell/HMath-Probability.md#v:gammaPoissonUpdate). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_gamma_poisson_update_f64( + hmath_context *context, + double shapePrior, + double ratePrior, + ptrdiff_t const *xs, + size_t xs_count, + double *out0, + double *out1); +``` + +## `probability.normal_normal_update` + +`probability.normal_normal_update(mu, priorVariance, observationVariance, xs, *, dtype='float64')` + +Original: [`HMath.Probability.normalNormalUpdate`](haskell/HMath-Probability.md#v:normalNormalUpdate). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_normal_normal_update_f64( + hmath_context *context, + double mu, + double priorVariance, + double observationVariance, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +``` + +## `probability.conditional_probability` + +`probability.conditional_probability(joint, given, *, dtype='float64')` + +Original: [`HMath.Probability.conditionalProbability`](haskell/HMath-Probability.md#v:conditionalProbability). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_conditional_probability_f64( + hmath_context *context, + double joint, + double given, + double *out0); +``` + +## `probability.bayes` + +`probability.bayes(priors, likelihoods, *, dtype='float64')` + +Original: [`HMath.Probability.bayes`](haskell/HMath-Probability.md#v:bayes). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_bayes_f64( + hmath_context *context, + const double *priors, + size_t priors_count, + const double *likelihoods, + size_t likelihoods_count, + double **out_data, + size_t *out_count); +``` + +## `probability.multinomial_p_m_f` + +`probability.multinomial_p_m_f(ps, counts, *, dtype='float64')` + +Original: [`HMath.Probability.multinomialPMF`](haskell/HMath-Probability.md#v:multinomialPMF). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_multinomial_p_m_f_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + ptrdiff_t const *counts, + size_t counts_count, + double *out0); +``` + +## `probability.dirichlet_density` + +`probability.dirichlet_density(as_, xs, *, dtype='float64')` + +Original: [`HMath.Probability.dirichletDensity`](haskell/HMath-Probability.md#v:dirichletDensity). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_probability_dirichlet_density_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `complex.complex` + +`complex.complex(real, imaginary, *, dtype='float64')` + +Original: [`HMath.Complex.complex`](haskell/HMath-Complex.md#v:complex). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_complex_f64( + hmath_context *context, + double real, + double imaginary, + double *out0, + double *out1); +``` + +## `complex.reciprocal` + +`complex.reciprocal(z, *, dtype='float64')` + +Original: [`HMath.Complex.reciprocal`](haskell/HMath-Complex.md#v:reciprocal). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_reciprocal_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `complex.add` + +`complex.add(a, b, *, dtype='float64')` + +Original: [`HMath.Complex.add`](haskell/HMath-Complex.md#v:add). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_add_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `complex.subtract_complex` + +`complex.subtract_complex(a, b, *, dtype='float64')` + +Original: [`HMath.Complex.subtractComplex`](haskell/HMath-Complex.md#v:subtractComplex). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_subtract_complex_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `complex.multiply` + +`complex.multiply(a, b, *, dtype='float64')` + +Original: [`HMath.Complex.multiply`](haskell/HMath-Complex.md#v:multiply). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_multiply_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `complex.divide` + +`complex.divide(a, b, *, dtype='float64')` + +Original: [`HMath.Complex.divide`](haskell/HMath-Complex.md#v:divide). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_divide_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `complex.power` + +`complex.power(a, b, *, dtype='float64')` + +Original: [`HMath.Complex.power`](haskell/HMath-Complex.md#v:power). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_power_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +``` + +## `complex.from_polar` + +`complex.from_polar(radius, angle, *, dtype='float64')` + +Original: [`HMath.Complex.fromPolar`](haskell/HMath-Complex.md#v:fromPolar). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_from_polar_f64( + hmath_context *context, + double radius, + double angle, + double *out0, + double *out1); +``` + +## `complex.rotate` + +`complex.rotate(angle, z, *, dtype='float64')` + +Original: [`HMath.Complex.rotate`](haskell/HMath-Complex.md#v:rotate). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_complex_rotate_f64( + hmath_context *context, + double angle, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `special.hankel` + +`special.hankel(kind, order, x, *, dtype='float64')` + +Original: [`HMath.Special.hankel`](haskell/HMath-Special.md#v:hankel). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_hankel_f64( + hmath_context *context, + ptrdiff_t kind, + ptrdiff_t order, + double x, + double *out0, + double *out1); +``` + +## `special.spherical_harmonic` + +`special.spherical_harmonic(degree, order, theta, phi, *, dtype='float64')` + +Original: [`HMath.Special.sphericalHarmonic`](haskell/HMath-Special.md#v:sphericalHarmonic). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_spherical_harmonic_f64( + hmath_context *context, + ptrdiff_t degree, + ptrdiff_t order, + double theta, + double phi, + double *out0, + double *out1); +``` + +## `special.complex1_f1` + +`special.complex1_f1(a, b, z, *, dtype='float64')` + +Original: [`HMath.Special.complex1F1`](haskell/HMath-Special.md#v:complex1F1). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_special_complex1_f1_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double z_0, + double z_1, + double *out0, + double *out1); +``` + +## `api_algebra.inner_product` + +`api_algebra.inner_product(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.API.Algebra.innerProduct`](haskell/HMath-API-Algebra.md#v:innerProduct). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_api_algebra_inner_product_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +``` + +```c +hmath_status hmath_api_algebra_inner_product_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +``` + +## `algorithms.lower_bound` + +`algorithms.lower_bound(x, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.lowerBound`](haskell/HMath-Algorithms.md#v:lowerBound). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_lower_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_algorithms_lower_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +``` + +## `algorithms.upper_bound` + +`algorithms.upper_bound(x, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.upperBound`](haskell/HMath-Algorithms.md#v:upperBound). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_upper_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_algorithms_upper_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +``` + +## `algorithms.quickselect` + +`algorithms.quickselect(k, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.quickselect`](haskell/HMath-Algorithms.md#v:quickselect). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_quickselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +``` + +```c +hmath_status hmath_algorithms_quickselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `algorithms.introselect` + +`algorithms.introselect(k, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.introselect`](haskell/HMath-Algorithms.md#v:introselect). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_introselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +``` + +```c +hmath_status hmath_algorithms_introselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `algorithms.partial_sort` + +`algorithms.partial_sort(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Algorithms.partialSort`](haskell/HMath-Algorithms.md#v:partialSort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_partial_sort_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_partial_sort_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.merge_sort` + +`algorithms.merge_sort(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.mergeSort`](haskell/HMath-Algorithms.md#v:mergeSort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_merge_sort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_merge_sort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.quicksort` + +`algorithms.quicksort(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.quicksort`](haskell/HMath-Algorithms.md#v:quicksort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_quicksort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_quicksort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.heapsort` + +`algorithms.heapsort(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.heapsort`](haskell/HMath-Algorithms.md#v:heapsort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_heapsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_heapsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.introsort` + +`algorithms.introsort(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.introsort`](haskell/HMath-Algorithms.md#v:introsort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_introsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_introsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.counting_sort` + +`algorithms.counting_sort(budget, xs)` + +Original: [`HMath.Algorithms.countingSort`](haskell/HMath-Algorithms.md#v:countingSort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_counting_sort( + hmath_context *context, + ptrdiff_t budget, + ptrdiff_t const *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `algorithms.radix_sort` + +`algorithms.radix_sort(argument1)` + +Original: [`HMath.Algorithms.radixSort`](haskell/HMath-Algorithms.md#v:radixSort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_radix_sort( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char * **out_data, + size_t *out_count); +``` + +## `algorithms.bucket_sort` + +`algorithms.bucket_sort(buckets, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.bucketSort`](haskell/HMath-Algorithms.md#v:bucketSort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_bucket_sort_f64( + hmath_context *context, + ptrdiff_t buckets, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.argsort` + +`algorithms.argsort(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.argsort`](haskell/HMath-Algorithms.md#v:argsort). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_argsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_argsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `algorithms.top_k` + +`algorithms.top_k(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Algorithms.topK`](haskell/HMath-Algorithms.md#v:topK). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_top_k_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_top_k_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.quantile_select` + +`algorithms.quantile_select(q, xs, *, dtype='float64')` + +Original: [`HMath.Algorithms.quantileSelect`](haskell/HMath-Algorithms.md#v:quantileSelect). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_quantile_select_f64( + hmath_context *context, + double q, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `algorithms.deduplicate` + +`algorithms.deduplicate(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.deduplicate`](haskell/HMath-Algorithms.md#v:deduplicate). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_deduplicate_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_deduplicate_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.prefix_sums` + +`algorithms.prefix_sums(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.prefixSums`](haskell/HMath-Algorithms.md#v:prefixSums). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_prefix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_prefix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.suffix_sums` + +`algorithms.suffix_sums(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.suffixSums`](haskell/HMath-Algorithms.md#v:suffixSums). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_suffix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_suffix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.difference_array` + +`algorithms.difference_array(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.differenceArray`](haskell/HMath-Algorithms.md#v:differenceArray). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_difference_array_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_difference_array_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.apply_differences` + +`algorithms.apply_differences(argument1, *, dtype='float64')` + +Original: [`HMath.Algorithms.applyDifferences`](haskell/HMath-Algorithms.md#v:applyDifferences). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_apply_differences_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_algorithms_apply_differences_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `algorithms.binary_lift` + +`algorithms.binary_lift(next, steps, start)` + +Original: [`HMath.Algorithms.binaryLift`](haskell/HMath-Algorithms.md#v:binaryLift). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_binary_lift( + hmath_context *context, + ptrdiff_t const *next, + size_t next_count, + const char *steps, + ptrdiff_t start, + ptrdiff_t *out0); +``` + +## `algorithms.polynomial_hash` + +`algorithms.polynomial_hash(base, modulus, xs)` + +Original: [`HMath.Algorithms.polynomialHash`](haskell/HMath-Algorithms.md#v:polynomialHash). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_polynomial_hash( + hmath_context *context, + const char *base, + const char *modulus, + const char * const *xs, + size_t xs_count, + char **out0); +``` + +## `algorithms.rolling_hashes` + +`algorithms.rolling_hashes(base, modulus, width, xs)` + +Original: [`HMath.Algorithms.rollingHashes`](haskell/HMath-Algorithms.md#v:rollingHashes). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_algorithms_rolling_hashes( + hmath_context *context, + const char *base, + const char *modulus, + ptrdiff_t width, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +``` + +## `datastructure.monotonic_minima` + +`datastructure.monotonic_minima(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.DataStructure.monotonicMinima`](haskell/HMath-DataStructure.md#v:monotonicMinima). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_datastructure_monotonic_minima_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_datastructure_monotonic_minima_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `deeplearning_core.log_softmax` + +`deeplearning_core.log_softmax(argument1, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.logSoftmax`](haskell/HMath-DeepLearning-Core.md#v:logSoftmax). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_log_softmax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `deeplearning_core.softmax` + +`deeplearning_core.softmax(xs, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.softmax`](haskell/HMath-DeepLearning-Core.md#v:softmax). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_softmax_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `deeplearning_core.sparsemax` + +`deeplearning_core.sparsemax(argument1, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.sparsemax`](haskell/HMath-DeepLearning-Core.md#v:sparsemax). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_sparsemax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +``` + +## `deeplearning_core.gated_linear_unit` + +`deeplearning_core.gated_linear_unit(values, gate, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.gatedLinearUnit`](haskell/HMath-DeepLearning-Core.md#v:gatedLinearUnit). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_gated_linear_unit_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *gate, + size_t gate_count, + double **out_data, + size_t *out_count); +``` + +## `deeplearning_core.categorical_cross_entropy_logits` + +`deeplearning_core.categorical_cross_entropy_logits(target, logits, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.categoricalCrossEntropyLogits`](haskell/HMath-DeepLearning-Core.md#v:categoricalCrossEntropyLogits). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_categorical_cross_entropy_logits_f64( + hmath_context *context, + const double *target, + size_t target_count, + const double *logits, + size_t logits_count, + double *out0); +``` + +## `deeplearning_core.regularization` + +`deeplearning_core.regularization(l1, l2, weights, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.regularization`](haskell/HMath-DeepLearning-Core.md#v:regularization). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_regularization_f64( + hmath_context *context, + double l1, + double l2, + const double *weights, + size_t weights_count, + double *out0); +``` + +## `deeplearning_core.contrastive_loss` + +`deeplearning_core.contrastive_loss(margin, similar, a, b, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.contrastiveLoss`](haskell/HMath-DeepLearning-Core.md#v:contrastiveLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_contrastive_loss_f64( + hmath_context *context, + double margin, + int similar, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +``` + +## `deeplearning_core.triplet_loss` + +`deeplearning_core.triplet_loss(margin, anchor, positive, negative, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.tripletLoss`](haskell/HMath-DeepLearning-Core.md#v:tripletLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_triplet_loss_f64( + hmath_context *context, + double margin, + const double *anchor, + size_t anchor_count, + const double *positive, + size_t positive_count, + const double *negative, + size_t negative_count, + double *out0); +``` + +## `deeplearning_core.focal_loss` + +`deeplearning_core.focal_loss(alpha, gamma, target, prediction, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.focalLoss`](haskell/HMath-DeepLearning-Core.md#v:focalLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_focal_loss_f64( + hmath_context *context, + double alpha, + double gamma, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +``` + +## `deeplearning_core.dice_loss` + +`deeplearning_core.dice_loss(smooth, target, prediction, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.diceLoss`](haskell/HMath-DeepLearning-Core.md#v:diceLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_dice_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +``` + +## `deeplearning_core.iou_loss` + +`deeplearning_core.iou_loss(smooth, target, prediction, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Core.iouLoss`](haskell/HMath-DeepLearning-Core.md#v:iouLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_core_iou_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +``` + +## `deeplearning_metrics.perplexity` + +`deeplearning_metrics.perplexity(logs, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Metrics.perplexity`](haskell/HMath-DeepLearning-Metrics.md#v:perplexity). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_metrics_perplexity_f64( + hmath_context *context, + const double *logs, + size_t logs_count, + double *out0); +``` + +## `deeplearning_metrics.margin_ranking_loss` + +`deeplearning_metrics.margin_ranking_loss(margin, labels, left, right, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Metrics.marginRankingLoss`](haskell/HMath-DeepLearning-Metrics.md#v:marginRankingLoss). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_metrics_margin_ranking_loss_f64( + hmath_context *context, + double margin, + const double *labels, + size_t labels_count, + const double *left, + size_t left_count, + const double *right, + size_t right_count, + double *out0); +``` + +## `deeplearning_precision.gradient_norm` + +`deeplearning_precision.gradient_norm(xs, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Precision.gradientNorm`](haskell/HMath-DeepLearning-Precision.md#v:gradientNorm). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_precision_gradient_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `deeplearning_precision.clip_gradients` + +`deeplearning_precision.clip_gradients(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.DeepLearning.Precision.clipGradients`](haskell/HMath-DeepLearning-Precision.md#v:clipGradients). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_deeplearning_precision_clip_gradients_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `discrete.set_union` + +`discrete.set_union(a, b, *, dtype='float64')` + +Original: [`HMath.Discrete.setUnion`](haskell/HMath-Discrete.md#v:setUnion). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_discrete_set_union_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_discrete_set_union_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +``` + +## `discrete.set_intersection` + +`discrete.set_intersection(a, b, *, dtype='float64')` + +Original: [`HMath.Discrete.setIntersection`](haskell/HMath-Discrete.md#v:setIntersection). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_discrete_set_intersection_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_discrete_set_intersection_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +``` + +## `discrete.set_difference` + +`discrete.set_difference(a, b, *, dtype='float64')` + +Original: [`HMath.Discrete.setDifference`](haskell/HMath-Discrete.md#v:setDifference). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_discrete_set_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_discrete_set_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +``` + +## `discrete.symmetric_difference` + +`discrete.symmetric_difference(a, b, *, dtype='float64')` + +Original: [`HMath.Discrete.symmetricDifference`](haskell/HMath-Discrete.md#v:symmetricDifference). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_discrete_symmetric_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +``` + +```c +hmath_status hmath_discrete_symmetric_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.frequencies` + +`fourier.frequencies(n, spacing, *, dtype='float64')` + +Original: [`HMath.Fourier.frequencies`](haskell/HMath-Fourier.md#v:frequencies). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_frequencies_f64( + hmath_context *context, + ptrdiff_t n, + double spacing, + double **out_data, + size_t *out_count); +``` + +## `fourier.fft_shift` + +`fourier.fft_shift(xs, *, dtype='float64')` + +Original: [`HMath.Fourier.fftShift`](haskell/HMath-Fourier.md#v:fftShift). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_fft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.ifft_shift` + +`fourier.ifft_shift(xs, *, dtype='float64')` + +Original: [`HMath.Fourier.ifftShift`](haskell/HMath-Fourier.md#v:ifftShift). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_ifft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.hartley` + +`fourier.hartley(xs, *, dtype='float64')` + +Original: [`HMath.Fourier.hartley`](haskell/HMath-Fourier.md#v:hartley). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_hartley_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.periodogram` + +`fourier.periodogram(rate, window, xs, *, dtype='float64')` + +Original: [`HMath.Fourier.periodogram`](haskell/HMath-Fourier.md#v:periodogram). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_periodogram_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.welch` + +`fourier.welch(rate, window, hop, xs, *, dtype='float64')` + +Original: [`HMath.Fourier.welch`](haskell/HMath-Fourier.md#v:welch). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_welch_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + ptrdiff_t hop, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.cepstrum` + +`fourier.cepstrum(floorValue, xs, *, dtype='float64')` + +Original: [`HMath.Fourier.cepstrum`](haskell/HMath-Fourier.md#v:cepstrum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_cepstrum_f64( + hmath_context *context, + double floorValue, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `fourier.hilbert` + +`fourier.hilbert(xs, *, dtype='float64')` + +Original: [`HMath.Fourier.hilbert`](haskell/HMath-Fourier.md#v:hilbert). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_fourier_hilbert_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `geometry_primitives.hamming_distance` + +`geometry_primitives.hamming_distance(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Geometry.Primitives.hammingDistance`](haskell/HMath-Geometry-Primitives.md#v:hammingDistance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_geometry_primitives_hamming_distance_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_geometry_primitives_hamming_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + ptrdiff_t *out0); +``` + +## `geometry_primitives.jaccard_distance` + +`geometry_primitives.jaccard_distance(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Geometry.Primitives.jaccardDistance`](haskell/HMath-Geometry-Primitives.md#v:jaccardDistance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_geometry_primitives_jaccard_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +``` + +## `graph_core.finite` + +`graph_core.finite(x, *, dtype='float64')` + +Original: [`HMath.Graph.Core.finite`](haskell/HMath-Graph-Core.md#v:finite). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_graph_core_finite_f64( + hmath_context *context, + double x, + int *out0); +``` + +## `image_color.srgb_to_linear` + +`image_color.srgb_to_linear(x, *, dtype='float64')` + +Original: [`HMath.Image.Color.srgbToLinear`](haskell/HMath-Image-Color.md#v:srgbToLinear). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_image_color_srgb_to_linear_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `image_color.linear_to_srgb` + +`image_color.linear_to_srgb(x, *, dtype='float64')` + +Original: [`HMath.Image.Color.linearToSrgb`](haskell/HMath-Image-Color.md#v:linearToSrgb). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_image_color_linear_to_srgb_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `interpolation.evaluate_chebyshev` + +`interpolation.evaluate_chebyshev(cs, a, b, x, *, dtype='float64')` + +Original: [`HMath.Interpolation.evaluateChebyshev`](haskell/HMath-Interpolation.md#v:evaluateChebyshev). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_interpolation_evaluate_chebyshev_f64( + hmath_context *context, + const double *cs, + size_t cs_count, + double a, + double b, + double x, + double *out0); +``` + +## `numeric.next_after` + +`numeric.next_after(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Numeric.nextAfter`](haskell/HMath-Numeric.md#v:nextAfter). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_next_after_f32( + hmath_context *context, + float argument1, + float argument2, + float *out0); +``` + +```c +hmath_status hmath_numeric_next_after_f64( + hmath_context *context, + double argument1, + double argument2, + double *out0); +``` + +## `numeric.ldexp` + +`numeric.ldexp(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Numeric.ldexp`](haskell/HMath-Numeric.md#v:ldexp). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_ldexp_f32( + hmath_context *context, + float argument1, + ptrdiff_t argument2, + float *out0); +``` + +```c +hmath_status hmath_numeric_ldexp_f64( + hmath_context *context, + double argument1, + ptrdiff_t argument2, + double *out0); +``` + +## `numeric.ulp_distance` + +`numeric.ulp_distance(a, b, *, dtype='float64')` + +Original: [`HMath.Numeric.ulpDistance`](haskell/HMath-Numeric.md#v:ulpDistance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_ulp_distance_f64( + hmath_context *context, + double a, + double b, + char **out0); +``` + +## `numeric.within_u_l_ps` + +`numeric.within_u_l_ps(n, a, b, *, dtype='float64')` + +Original: [`HMath.Numeric.withinULPs`](haskell/HMath-Numeric.md#v:withinULPs). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_within_u_l_ps_f64( + hmath_context *context, + const char *n, + double a, + double b, + int *out0); +``` + +## `numeric.kahan_sum` + +`numeric.kahan_sum(argument1, *, dtype='float64')` + +Original: [`HMath.Numeric.kahanSum`](haskell/HMath-Numeric.md#v:kahanSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_kahan_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_numeric_kahan_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `numeric.neumaier_sum` + +`numeric.neumaier_sum(argument1, *, dtype='float64')` + +Original: [`HMath.Numeric.neumaierSum`](haskell/HMath-Numeric.md#v:neumaierSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_neumaier_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_numeric_neumaier_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `numeric.pairwise_sum` + +`numeric.pairwise_sum(argument1, *, dtype='float64')` + +Original: [`HMath.Numeric.pairwiseSum`](haskell/HMath-Numeric.md#v:pairwiseSum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_pairwise_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_numeric_pairwise_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `numeric.logsumexp` + +`numeric.logsumexp(argument1, *, dtype='float64')` + +Original: [`HMath.Numeric.logsumexp`](haskell/HMath-Numeric.md#v:logsumexp). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_logsumexp_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_numeric_logsumexp_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `numeric.sum_error_bound` + +`numeric.sum_error_bound(argument1, *, dtype='float64')` + +Original: [`HMath.Numeric.sumErrorBound`](haskell/HMath-Numeric.md#v:sumErrorBound). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_numeric_sum_error_bound_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +``` + +```c +hmath_status hmath_numeric_sum_error_bound_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `optimization_common.dot` + +`optimization_common.dot(a, b, *, dtype='float64')` + +Original: [`HMath.Optimization.Common.dot`](haskell/HMath-Optimization-Common.md#v:dot). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_optimization_common_dot_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +``` + +## `optimization_common.norm` + +`optimization_common.norm(xs, *, dtype='float64')` + +Original: [`HMath.Optimization.Common.norm`](haskell/HMath-Optimization-Common.md#v:norm). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_optimization_common_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `optimization_common.add` + +`optimization_common.add(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Optimization.Common.add`](haskell/HMath-Optimization-Common.md#v:add). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_optimization_common_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `optimization_common.sub` + +`optimization_common.sub(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Optimization.Common.sub`](haskell/HMath-Optimization-Common.md#v:sub). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_optimization_common_sub_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `optimization_common.scale` + +`optimization_common.scale(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Optimization.Common.scale`](haskell/HMath-Optimization-Common.md#v:scale). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_optimization_common_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `random.importance` + +`random.importance(values, weights, *, dtype='float64')` + +Original: [`HMath.Random.importance`](haskell/HMath-Random.md#v:importance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_random_importance_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *weights, + size_t weights_count, + double *out0); +``` + +## `random.halton` + +`random.halton(dimension, index, *, dtype='float64')` + +Original: [`HMath.Random.halton`](haskell/HMath-Random.md#v:halton). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_random_halton_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +``` + +## `random.sobol` + +`random.sobol(dimension, index, *, dtype='float64')` + +Original: [`HMath.Random.sobol`](haskell/HMath-Random.md#v:sobol). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_random_sobol_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +``` + +## `random.faure` + +`random.faure(d, ix, *, dtype='float64')` + +Original: [`HMath.Random.faure`](haskell/HMath-Random.md#v:faure). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_random_faure_f64( + hmath_context *context, + ptrdiff_t d, + ptrdiff_t ix, + double **out_data, + size_t *out_count); +``` + +## `signal.convolution` + +`signal.convolution(xs, ys, *, dtype='float64')` + +Original: [`HMath.Signal.convolution`](haskell/HMath-Signal.md#v:convolution). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_convolution_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double **out_data, + size_t *out_count); +``` + +## `signal.circular_convolution` + +`signal.circular_convolution(x, y, *, dtype='float64')` + +Original: [`HMath.Signal.circularConvolution`](haskell/HMath-Signal.md#v:circularConvolution). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_circular_convolution_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +``` + +## `signal.correlation` + +`signal.correlation(x, y, *, dtype='float64')` + +Original: [`HMath.Signal.correlation`](haskell/HMath-Signal.md#v:correlation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_correlation_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +``` + +## `signal.autocorrelation` + +`signal.autocorrelation(x, *, dtype='float64')` + +Original: [`HMath.Signal.autocorrelation`](haskell/HMath-Signal.md#v:autocorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_autocorrelation_f64( + hmath_context *context, + const double *x, + size_t x_count, + double **out_data, + size_t *out_count); +``` + +## `signal.overlap_add` + +`signal.overlap_add(block, kernel, xs, *, dtype='float64')` + +Original: [`HMath.Signal.overlapAdd`](haskell/HMath-Signal.md#v:overlapAdd). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_overlap_add_f64( + hmath_context *context, + ptrdiff_t block, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.overlap_save` + +`signal.overlap_save(fftLength, kernel, xs, *, dtype='float64')` + +Original: [`HMath.Signal.overlapSave`](haskell/HMath-Signal.md#v:overlapSave). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_overlap_save_f64( + hmath_context *context, + ptrdiff_t fftLength, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.moving_average` + +`signal.moving_average(count, xs, *, dtype='float64')` + +Original: [`HMath.Signal.movingAverage`](haskell/HMath-Signal.md#v:movingAverage). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_moving_average_f64( + hmath_context *context, + ptrdiff_t count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.median_filter` + +`signal.median_filter(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Signal.medianFilter`](haskell/HMath-Signal.md#v:medianFilter). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_median_filter_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `signal.gaussian_filter` + +`signal.gaussian_filter(width, sigma, xs, *, dtype='float64')` + +Original: [`HMath.Signal.gaussianFilter`](haskell/HMath-Signal.md#v:gaussianFilter). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_gaussian_filter_f64( + hmath_context *context, + ptrdiff_t width, + double sigma, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.savitzky_golay` + +`signal.savitzky_golay(width, degree, derivative, spacing, xs, *, dtype='float64')` + +Original: [`HMath.Signal.savitzkyGolay`](haskell/HMath-Signal.md#v:savitzkyGolay). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_savitzky_golay_f64( + hmath_context *context, + ptrdiff_t width, + ptrdiff_t degree, + ptrdiff_t derivative, + double spacing, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.downsample` + +`signal.downsample(factor, offset, xs, *, dtype='float64')` + +Original: [`HMath.Signal.downsample`](haskell/HMath-Signal.md#v:downsample). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_downsample_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t offset, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.upsample` + +`signal.upsample(factor, xs, *, dtype='float64')` + +Original: [`HMath.Signal.upsample`](haskell/HMath-Signal.md#v:upsample). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_upsample_f64( + hmath_context *context, + ptrdiff_t factor, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.resample_polyphase` + +`signal.resample_polyphase(up, down, kernel, xs, *, dtype='float64')` + +Original: [`HMath.Signal.resamplePolyphase`](haskell/HMath-Signal.md#v:resamplePolyphase). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_resample_polyphase_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.resample` + +`signal.resample(up, down, taps, xs, *, dtype='float64')` + +Original: [`HMath.Signal.resample`](haskell/HMath-Signal.md#v:resample). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_resample_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.anti_alias` + +`signal.anti_alias(factor, taps, xs, *, dtype='float64')` + +Original: [`HMath.Signal.antiAlias`](haskell/HMath-Signal.md#v:antiAlias). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_anti_alias_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.zero_crossings` + +`signal.zero_crossings(xs, *, dtype='float64')` + +Original: [`HMath.Signal.zeroCrossings`](haskell/HMath-Signal.md#v:zeroCrossings). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_zero_crossings_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.envelope` + +`signal.envelope(xs, *, dtype='float64')` + +Original: [`HMath.Signal.envelope`](haskell/HMath-Signal.md#v:envelope). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_envelope_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.unwrap_phase` + +`signal.unwrap_phase(xs, *, dtype='float64')` + +Original: [`HMath.Signal.unwrapPhase`](haskell/HMath-Signal.md#v:unwrapPhase). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_unwrap_phase_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.detrend` + +`signal.detrend(linear, xs, *, dtype='float64')` + +Original: [`HMath.Signal.detrend`](haskell/HMath-Signal.md#v:detrend). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_detrend_f64( + hmath_context *context, + int linear, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.normalize` + +`signal.normalize(xs, *, dtype='float64')` + +Original: [`HMath.Signal.normalize`](haskell/HMath-Signal.md#v:normalize). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_normalize_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `signal.smooth` + +`signal.smooth(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Signal.smooth`](haskell/HMath-Signal.md#v:smooth). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_smooth_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +``` + +## `signal.noise_estimate` + +`signal.noise_estimate(xs, *, dtype='float64')` + +Original: [`HMath.Signal.noiseEstimate`](haskell/HMath-Signal.md#v:noiseEstimate). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_noise_estimate_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `signal.signal_to_noise` + +`signal.signal_to_noise(signal, noise, *, dtype='float64')` + +Original: [`HMath.Signal.signalToNoise`](haskell/HMath-Signal.md#v:signalToNoise). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_signal_to_noise_f64( + hmath_context *context, + const double *signal, + size_t signal_count, + const double *noise, + size_t noise_count, + double *out0); +``` + +## `signal.rms` + +`signal.rms(xs, *, dtype='float64')` + +Original: [`HMath.Signal.rms`](haskell/HMath-Signal.md#v:rms). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_signal_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.arithmetic_mean` + +`statistics_advanced.arithmetic_mean(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.arithmeticMean`](haskell/HMath-Statistics-Advanced.md#v:arithmeticMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_arithmetic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.weighted_mean` + +`statistics_advanced.weighted_mean(xs, ws, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.weightedMean`](haskell/HMath-Statistics-Advanced.md#v:weightedMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_weighted_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ws, + size_t ws_count, + double *out0); +``` + +## `statistics_advanced.geometric_mean` + +`statistics_advanced.geometric_mean(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.geometricMean`](haskell/HMath-Statistics-Advanced.md#v:geometricMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_geometric_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.harmonic_mean` + +`statistics_advanced.harmonic_mean(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.harmonicMean`](haskell/HMath-Statistics-Advanced.md#v:harmonicMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_harmonic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.rms` + +`statistics_advanced.rms(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.rms`](haskell/HMath-Statistics-Advanced.md#v:rms). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.trimmed_mean` + +`statistics_advanced.trimmed_mean(fraction, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.trimmedMean`](haskell/HMath-Statistics-Advanced.md#v:trimmedMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_trimmed_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.winsorized_mean` + +`statistics_advanced.winsorized_mean(fraction, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.winsorizedMean`](haskell/HMath-Statistics-Advanced.md#v:winsorizedMean). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_winsorized_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.quantile` + +`statistics_advanced.quantile(p, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.quantile`](haskell/HMath-Statistics-Advanced.md#v:quantile). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_quantile_f64( + hmath_context *context, + double p, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.median` + +`statistics_advanced.median(argument1, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.median`](haskell/HMath-Statistics-Advanced.md#v:median). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_median_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `statistics_advanced.percentile` + +`statistics_advanced.percentile(argument1, argument2, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.percentile`](haskell/HMath-Statistics-Advanced.md#v:percentile). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_percentile_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double *out0); +``` + +## `statistics_advanced.modes` + +`statistics_advanced.modes(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.modes`](haskell/HMath-Statistics-Advanced.md#v:modes). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_modes_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.interquartile_range` + +`statistics_advanced.interquartile_range(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.interquartileRange`](haskell/HMath-Statistics-Advanced.md#v:interquartileRange). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_interquartile_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.median_absolute_deviation` + +`statistics_advanced.median_absolute_deviation(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.medianAbsoluteDeviation`](haskell/HMath-Statistics-Advanced.md#v:medianAbsoluteDeviation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_median_absolute_deviation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.data_range` + +`statistics_advanced.data_range(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.dataRange`](haskell/HMath-Statistics-Advanced.md#v:dataRange). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_data_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.central_moment` + +`statistics_advanced.central_moment(k, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.centralMoment`](haskell/HMath-Statistics-Advanced.md#v:centralMoment). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_central_moment_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.population_variance` + +`statistics_advanced.population_variance(argument1, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.populationVariance`](haskell/HMath-Statistics-Advanced.md#v:populationVariance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_population_variance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `statistics_advanced.sample_variance` + +`statistics_advanced.sample_variance(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.sampleVariance`](haskell/HMath-Statistics-Advanced.md#v:sampleVariance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_sample_variance_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.population_s_d` + +`statistics_advanced.population_s_d(argument1, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.populationSD`](haskell/HMath-Statistics-Advanced.md#v:populationSD). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_population_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `statistics_advanced.sample_s_d` + +`statistics_advanced.sample_s_d(argument1, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.sampleSD`](haskell/HMath-Statistics-Advanced.md#v:sampleSD). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_sample_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +``` + +## `statistics_advanced.coefficient_of_variation` + +`statistics_advanced.coefficient_of_variation(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.coefficientOfVariation`](haskell/HMath-Statistics-Advanced.md#v:coefficientOfVariation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_coefficient_of_variation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.skewness` + +`statistics_advanced.skewness(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.skewness`](haskell/HMath-Statistics-Advanced.md#v:skewness). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_skewness_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.kurtosis` + +`statistics_advanced.kurtosis(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.kurtosis`](haskell/HMath-Statistics-Advanced.md#v:kurtosis). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_kurtosis_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.covariance` + +`statistics_advanced.covariance(sampleCorrection, xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.covariance`](haskell/HMath-Statistics-Advanced.md#v:covariance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_covariance_f64( + hmath_context *context, + int sampleCorrection, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.correlation` + +`statistics_advanced.correlation(xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.correlation`](haskell/HMath-Statistics-Advanced.md#v:correlation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_correlation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.spearman` + +`statistics_advanced.spearman(xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.spearman`](haskell/HMath-Statistics-Advanced.md#v:spearman). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_spearman_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.kendall` + +`statistics_advanced.kendall(xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.kendall`](haskell/HMath-Statistics-Advanced.md#v:kendall). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_kendall_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.autocorrelation` + +`statistics_advanced.autocorrelation(lag, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.autocorrelation`](haskell/HMath-Statistics-Advanced.md#v:autocorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.cross_correlation` + +`statistics_advanced.cross_correlation(lag, xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.crossCorrelation`](haskell/HMath-Statistics-Advanced.md#v:crossCorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.moving_average` + +`statistics_advanced.moving_average(window, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.movingAverage`](haskell/HMath-Statistics-Advanced.md#v:movingAverage). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_moving_average_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.moving_variance` + +`statistics_advanced.moving_variance(window, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.movingVariance`](haskell/HMath-Statistics-Advanced.md#v:movingVariance). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_moving_variance_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.exponential_moving_average` + +`statistics_advanced.exponential_moving_average(alpha, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.exponentialMovingAverage`](haskell/HMath-Statistics-Advanced.md#v:exponentialMovingAverage). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_exponential_moving_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.entropy` + +`statistics_advanced.entropy(ps, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.entropy`](haskell/HMath-Statistics-Advanced.md#v:entropy). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_entropy_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double *out0); +``` + +## `statistics_advanced.kl_divergence` + +`statistics_advanced.kl_divergence(p, q, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.klDivergence`](haskell/HMath-Statistics-Advanced.md#v:klDivergence). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_kl_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +``` + +## `statistics_advanced.js_divergence` + +`statistics_advanced.js_divergence(p, q, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.jsDivergence`](haskell/HMath-Statistics-Advanced.md#v:jsDivergence). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_js_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +``` + +## `statistics_advanced.z_scores` + +`statistics_advanced.z_scores(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.zScores`](haskell/HMath-Statistics-Advanced.md#v:zScores). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_z_scores_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.standard_error` + +`statistics_advanced.standard_error(xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.standardError`](haskell/HMath-Statistics-Advanced.md#v:standardError). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_standard_error_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `statistics_advanced.confidence_interval` + +`statistics_advanced.confidence_interval(level, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.confidenceInterval`](haskell/HMath-Statistics-Advanced.md#v:confidenceInterval). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_confidence_interval_f64( + hmath_context *context, + double level, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +``` + +## `statistics_advanced.bonferroni` + +`statistics_advanced.bonferroni(ps, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.bonferroni`](haskell/HMath-Statistics-Advanced.md#v:bonferroni). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_bonferroni_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.benjamini_hochberg` + +`statistics_advanced.benjamini_hochberg(ps, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.benjaminiHochberg`](haskell/HMath-Statistics-Advanced.md#v:benjaminiHochberg). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_benjamini_hochberg_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +``` + +## `statistics_advanced.cohens_d` + +`statistics_advanced.cohens_d(xs, ys, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.cohensD`](haskell/HMath-Statistics-Advanced.md#v:cohensD). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_cohens_d_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `statistics_advanced.normal_test_power` + +`statistics_advanced.normal_test_power(alpha, standardizedEffect, n, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.normalTestPower`](haskell/HMath-Statistics-Advanced.md#v:normalTestPower). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_normal_test_power_f64( + hmath_context *context, + double alpha, + double standardizedEffect, + ptrdiff_t n, + double *out0); +``` + +## `statistics_advanced.normal_sample_size` + +`statistics_advanced.normal_sample_size(alpha, power, effect, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.normalSampleSize`](haskell/HMath-Statistics-Advanced.md#v:normalSampleSize). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_normal_sample_size_f64( + hmath_context *context, + double alpha, + double power, + double effect, + ptrdiff_t *out0); +``` + +## `statistics_advanced.tukey_outliers` + +`statistics_advanced.tukey_outliers(multiplier, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.tukeyOutliers`](haskell/HMath-Statistics-Advanced.md#v:tukeyOutliers). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_tukey_outliers_f64( + hmath_context *context, + double multiplier, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `statistics_advanced.huber_location` + +`statistics_advanced.huber_location(tuning, xs, *, dtype='float64')` + +Original: [`HMath.Statistics.Advanced.huberLocation`](haskell/HMath-Statistics-Advanced.md#v:huberLocation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_statistics_advanced_huber_location_f64( + hmath_context *context, + double tuning, + const double *xs, + size_t xs_count, + double *out0); +``` + +## `tensor.shape_size` + +`tensor.shape_size(dims)` + +Original: [`HMath.Tensor.shapeSize`](haskell/HMath-Tensor.md#v:shapeSize). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_tensor_shape_size( + hmath_context *context, + ptrdiff_t const *dims, + size_t dims_count, + ptrdiff_t *out0); +``` + +## `tensor.infer_broadcast` + +`tensor.infer_broadcast(as_, bs)` + +Original: [`HMath.Tensor.inferBroadcast`](haskell/HMath-Tensor.md#v:inferBroadcast). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_tensor_infer_broadcast( + hmath_context *context, + ptrdiff_t const *as, + size_t as_count, + ptrdiff_t const *bs, + size_t bs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `timeseries_core.exponential_average` + +`timeseries_core.exponential_average(alpha, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.exponentialAverage`](haskell/HMath-TimeSeries-Core.md#v:exponentialAverage). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_exponential_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.weighted_average` + +`timeseries_core.weighted_average(ws, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.weightedAverage`](haskell/HMath-TimeSeries-Core.md#v:weightedAverage). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_weighted_average_f64( + hmath_context *context, + const double *ws, + size_t ws_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.cumulative_returns` + +`timeseries_core.cumulative_returns(xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.cumulativeReturns`](haskell/HMath-TimeSeries-Core.md#v:cumulativeReturns). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_cumulative_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.logarithmic_returns` + +`timeseries_core.logarithmic_returns(xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.logarithmicReturns`](haskell/HMath-TimeSeries-Core.md#v:logarithmicReturns). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_logarithmic_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.difference` + +`timeseries_core.difference(order, lag, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.difference`](haskell/HMath-TimeSeries-Core.md#v:difference). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_difference_f64( + hmath_context *context, + ptrdiff_t order, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.autocorrelation` + +`timeseries_core.autocorrelation(lags, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.autocorrelation`](haskell/HMath-TimeSeries-Core.md#v:autocorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lags, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_core.cross_correlation` + +`timeseries_core.cross_correlation(lag, xs, ys, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.crossCorrelation`](haskell/HMath-TimeSeries-Core.md#v:crossCorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +``` + +## `timeseries_core.partial_autocorrelation` + +`timeseries_core.partial_autocorrelation(order, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Core.partialAutocorrelation`](haskell/HMath-TimeSeries-Core.md#v:partialAutocorrelation). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_core_partial_autocorrelation_f64( + hmath_context *context, + ptrdiff_t order, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +``` + +## `timeseries_diagnostics.change_points` + +`timeseries_diagnostics.change_points(penalty, minSegment, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Diagnostics.changePoints`](haskell/HMath-TimeSeries-Diagnostics.md#v:changePoints). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_diagnostics_change_points_f64( + hmath_context *context, + double penalty, + ptrdiff_t minSegment, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `timeseries_diagnostics.cusum` + +`timeseries_diagnostics.cusum(mean, sd, drift, threshold, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Diagnostics.cusum`](haskell/HMath-TimeSeries-Diagnostics.md#v:cusum). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_diagnostics_cusum_f64( + hmath_context *context, + double mean, + double sd, + double drift, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `timeseries_diagnostics.anomalies` + +`timeseries_diagnostics.anomalies(threshold, xs, *, dtype='float64')` + +Original: [`HMath.TimeSeries.Diagnostics.anomalies`](haskell/HMath-TimeSeries-Diagnostics.md#v:anomalies). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_timeseries_diagnostics_anomalies_f64( + hmath_context *context, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +``` + +## `units.radians_to_degrees` + +`units.radians_to_degrees(x, *, dtype='float64')` + +Original: [`HMath.Units.radiansToDegrees`](haskell/HMath-Units.md#v:radiansToDegrees). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_units_radians_to_degrees_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_units_radians_to_degrees_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `units.degrees_to_radians` + +`units.degrees_to_radians(x, *, dtype='float64')` + +Original: [`HMath.Units.degreesToRadians`](haskell/HMath-Units.md#v:degreesToRadians). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_units_degrees_to_radians_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_units_degrees_to_radians_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `units.radians_to_gradians` + +`units.radians_to_gradians(x, *, dtype='float64')` + +Original: [`HMath.Units.radiansToGradians`](haskell/HMath-Units.md#v:radiansToGradians). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_units_radians_to_gradians_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_units_radians_to_gradians_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `units.gradians_to_radians` + +`units.gradians_to_radians(x, *, dtype='float64')` + +Original: [`HMath.Units.gradiansToRadians`](haskell/HMath-Units.md#v:gradiansToRadians). The linked contract defines the operation, valid inputs, result and mathematical errors. + +```c +hmath_status hmath_units_gradians_to_radians_f32( + hmath_context *context, + float x, + float *out0); +``` + +```c +hmath_status hmath_units_gradians_to_radians_f64( + hmath_context *context, + double x, + double *out0); +``` + +## `scalar.saturating_add` + +`scalar.saturating_add(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.saturatingAdd`](haskell/HMath-Scalar.md#v:saturatingAdd). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_saturating_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.saturating_subtract` + +`scalar.saturating_subtract(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.saturatingSubtract`](haskell/HMath-Scalar.md#v:saturatingSubtract). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_saturating_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.saturating_multiply` + +`scalar.saturating_multiply(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.saturatingMultiply`](haskell/HMath-Scalar.md#v:saturatingMultiply). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_saturating_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_saturating_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.checked_add` + +`scalar.checked_add(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.checkedAdd`](haskell/HMath-Scalar.md#v:checkedAdd). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_checked_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.checked_subtract` + +`scalar.checked_subtract(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.checkedSubtract`](haskell/HMath-Scalar.md#v:checkedSubtract). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_checked_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + +## `scalar.checked_multiply` + +`scalar.checked_multiply(a, b, *, dtype='intp')` + +Original: [`HMath.Scalar.checkedMultiply`](haskell/HMath-Scalar.md#v:checkedMultiply). The linked contract defines the operation, valid inputs, result and mathematical errors. + +Supported `dtype`: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `intp`, `uintp`. + +```c +hmath_status hmath_scalar_checked_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +``` + +```c +hmath_status hmath_scalar_checked_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +``` + diff --git a/docs/reference/numeric-objects.md b/docs/reference/numeric-objects.md new file mode 100644 index 0000000..78e9b04 --- /dev/null +++ b/docs/reference/numeric-objects.md @@ -0,0 +1,284 @@ +# Typed generic numeric APIs + +These are additional type instances of the same Basic, Scalar, Linear, Statistics and Geometry equality functions, not additional source functions. Existing flat C APIs and Python dtype defaults remain unchanged. C includes `hmath_numeric_objects.h`; each original prefix gains `_value` and an explicit borrowed typed prototype, with owned Value outputs. + +Python automatically selects this path when an argument contains a native numeric owner (recursively through lists), including `Numeric.Dual`, `Numeric.Quaternion`, original `Autodiff.Dual` and symbolic `Autodiff.Expr`. Use `dtype=prototype` for empty vectors, or `dtype="value"` for ordinary values using their exact encoded type, such as unbounded integers or ordered strings/Booleans/tuples/lists. All numeric operands must have the same actual Haskell type; no implicit widening or conversion between the two distinct Dual types occurs. + +The actual Coefficient dictionaries preserve all existing standard primitive numeric instances, recursively nested Numeric.Dual and Quaternion where permitted. Original AD.Dual dictionaries preserve its primal-only ordering and full-field equality. Symbolic AD.Expr has Num/Fractional/Floating but no Eq/Ord: normalization and median therefore reject it. Numeric.Quaternion has Num only, so fractional/floating statistics reject it; Numeric.Dual has no Ord. Integral/Bounded operations keep their actual bounded instances and reject nonintegral objects. Ord-only clamp/min/max use the shared resolver for supported native public labels, lists, tuples and optional values, calling the actual original Ord dictionary. Geometry hamming/jaccard Value paths retain the shared native Eq dictionaries: exact coefficients, Numeric.Dual/Quaternion, supported original AD.Dual, structural values and supported domain owners. They do not substitute an ordering comparison for equality. Arbitrary user-defined Haskell instances require a compiled bridge; these finite adapters do not claim universal typeclass coverage. + +```python +from hmath import scalar, statistics, numeric_types + +with numeric_types.dual(2.0, 1.0) as x, numeric_types.dual(3.0, 0.0) as y: + with scalar.add(x, y) as z: + assert numeric_types.primal(z) == 5.0 + with statistics.mean([x, y]) as mean: + assert numeric_types.primal(mean) == 2.5 + +assert scalar.minimum_scalar("alpha", "beta", dtype="value") == "alpha" +``` + +## `hmath.basic.clamp` + +Additional Value specialization for the [same original function](haskell/HMath-Basic.md#v:clamp). + +```c +hmath_status hmath_basic_clamp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *low, const hmath_value *high, const hmath_value *value, hmath_value **out); +``` + +## `hmath.basic.lerp` + +Additional Value specialization for the [same original function](haskell/HMath-Basic.md#v:lerp). + +```c +hmath_status hmath_basic_lerp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, const hmath_value *t, hmath_value **out); +``` + +## `hmath.scalar.add` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:add). + +```c +hmath_status hmath_scalar_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.subtract_scalar` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:subtractScalar). + +```c +hmath_status hmath_scalar_subtract_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.multiply` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:multiply). + +```c +hmath_status hmath_scalar_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.minimum_scalar` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:minimumScalar). + +```c +hmath_status hmath_scalar_minimum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.maximum_scalar` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:maximumScalar). + +```c +hmath_status hmath_scalar_maximum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.absolute` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:absolute). + +```c +hmath_status hmath_scalar_absolute_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out); +``` + +## `hmath.scalar.sign` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:sign). + +```c +hmath_status hmath_scalar_sign_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out); +``` + +## `hmath.scalar.positive_modulo` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:positiveModulo). + +```c +hmath_status hmath_scalar_positive_modulo_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *modulus, hmath_value **out); +``` + +## `hmath.scalar.cumulative_sum` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:cumulativeSum). + +```c +hmath_status hmath_scalar_cumulative_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.scalar.cumulative_product` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:cumulativeProduct). + +```c +hmath_status hmath_scalar_cumulative_product_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.scalar.prefix_sum` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:prefixSum). + +```c +hmath_status hmath_scalar_prefix_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.statistics.mean` + +Additional Value specialization for the [same original function](haskell/HMath-Statistics.md#v:mean). + +```c +hmath_status hmath_statistics_mean_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.statistics.variance` + +Additional Value specialization for the [same original function](haskell/HMath-Statistics.md#v:variance). + +```c +hmath_status hmath_statistics_variance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.statistics.standard_deviation` + +Additional Value specialization for the [same original function](haskell/HMath-Statistics.md#v:standardDeviation). + +```c +hmath_status hmath_statistics_standard_deviation_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.statistics.median` + +Additional Value specialization for the [same original function](haskell/HMath-Statistics.md#v:median). + +```c +hmath_status hmath_statistics_median_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +``` + +## `hmath.linear.dot` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:dot). + +```c +hmath_status hmath_linear_dot_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.linear.dot_checked` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:dotChecked). + +```c +hmath_status hmath_linear_dot_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.linear.magnitude` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:magnitude). + +```c +hmath_status hmath_linear_magnitude_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out); +``` + +## `hmath.linear.normalize` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:normalize). + +```c +hmath_status hmath_linear_normalize_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out); +``` + +## `hmath.linear.add` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:add). + +```c +hmath_status hmath_linear_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.linear.add_checked` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:addChecked). + +```c +hmath_status hmath_linear_add_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.linear.subtract_checked` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:subtractChecked). + +```c +hmath_status hmath_linear_subtract_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.linear.scale` + +Additional Value specialization for the [same original function](haskell/HMath-Linear.md#v:scale). + +```c +hmath_status hmath_linear_scale_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.scalar.saturating_add` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:saturatingAdd). + +```c +hmath_status hmath_scalar_saturating_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.saturating_subtract` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:saturatingSubtract). + +```c +hmath_status hmath_scalar_saturating_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.saturating_multiply` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:saturatingMultiply). + +```c +hmath_status hmath_scalar_saturating_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.checked_add` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:checkedAdd). + +```c +hmath_status hmath_scalar_checked_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.checked_subtract` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:checkedSubtract). + +```c +hmath_status hmath_scalar_checked_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.scalar.checked_multiply` + +Additional Value specialization for the [same original function](haskell/HMath-Scalar.md#v:checkedMultiply). + +```c +hmath_status hmath_scalar_checked_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `hmath.geometry_primitives.hamming_distance` + +Additional Value specialization for the [same original function](haskell/HMath-Geometry-Primitives.md#v:hammingDistance). + +```c +hmath_status hmath_geometry_primitives_hamming_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + +## `hmath.geometry_primitives.jaccard_distance` + +Additional Value specialization for the [same original function](haskell/HMath-Geometry-Primitives.md#v:jaccardDistance). + +```c +hmath_status hmath_geometry_primitives_jaccard_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +``` + diff --git a/docs/reference/numeric-type-functions.md b/docs/reference/numeric-type-functions.md new file mode 100644 index 0000000..e86ba26 --- /dev/null +++ b/docs/reference/numeric-type-functions.md @@ -0,0 +1,108 @@ +# Numeric type functions +All entries below call the corresponding original Haskell function or constructor. +The [representation and ownership contract](numeric-types.md) applies to every entry. +Python functions additionally accept `boxed=True` to retain an output scalar dtype. + +| Python signature | Original symbol | C function | +| --- | --- | --- | +| `round_rational(mode, value)` | `HMath.Numeric.roundRational` | `hmath_numeric_types_round_rational` | +| `classify(value)` | `HMath.Numeric.classify` | `hmath_numeric_types_classify` | +| `frexp(value)` | `HMath.Numeric.frexp` | `hmath_numeric_types_frexp` | +| `numeric_limits(value)` | `HMath.Numeric.numericLimits` | `hmath_numeric_types_numeric_limits` | +| `integer_limits(value)` | `HMath.Numeric.integerLimits` | `hmath_numeric_types_integer_limits` | +| `float16_limits()` | `HMath.Numeric.float16Limits` | `hmath_numeric_types_float16_limits` | +| `bfloat16_limits()` | `HMath.Numeric.bfloat16Limits` | `hmath_numeric_types_bfloat16_limits` | +| `numeric_limits_record(normal, subnormal, maximum_value, epsilon, digits, low, high)` | `HMath.Numeric.NumericLimits` | `hmath_numeric_types_numeric_limits_record` | +| `minimum_normal(value)` | `HMath.Numeric.minimumNormal` | `hmath_numeric_types_minimum_normal` | +| `minimum_subnormal(value)` | `HMath.Numeric.minimumSubnormal` | `hmath_numeric_types_minimum_subnormal` | +| `maximum_finite(value)` | `HMath.Numeric.maximumFinite` | `hmath_numeric_types_maximum_finite` | +| `machine_epsilon(value)` | `HMath.Numeric.machineEpsilon` | `hmath_numeric_types_machine_epsilon` | +| `significand_digits(value)` | `HMath.Numeric.significandDigits` | `hmath_numeric_types_significand_digits` | +| `minimum_exponent(value)` | `HMath.Numeric.minimumExponent` | `hmath_numeric_types_minimum_exponent` | +| `maximum_exponent(value)` | `HMath.Numeric.maximumExponent` | `hmath_numeric_types_maximum_exponent` | +| `safe_integral_cast(value, dtype)` | `HMath.Numeric.safeIntegralCast` | `hmath_numeric_types_safe_integral_cast` | +| `saturating_cast(value, dtype)` | `HMath.Numeric.saturatingCast` | `hmath_numeric_types_saturating_cast` | +| `real_to_integral(mode, value, dtype)` | `HMath.Numeric.realToIntegral` | `hmath_numeric_types_real_to_integral` | +| `narrow_float(value, dtype)` | `HMath.Numeric.narrowFloat` | `hmath_numeric_types_narrow_float` | +| `float16(mode, value)` | `HMath.Numeric.float16` | `hmath_numeric_types_float16` | +| `bfloat16(mode, value)` | `HMath.Numeric.bfloat16` | `hmath_numeric_types_bfloat16` | +| `float16_from_bits(bits)` | `HMath.Numeric.float16FromBits` | `hmath_numeric_types_float16_from_bits` | +| `bfloat16_from_bits(bits)` | `HMath.Numeric.bfloat16FromBits` | `hmath_numeric_types_bfloat16_from_bits` | +| `float16_bits(value)` | `HMath.Numeric.float16Bits` | `hmath_numeric_types_float16_bits` | +| `bfloat16_bits(value)` | `HMath.Numeric.bfloat16Bits` | `hmath_numeric_types_bfloat16_bits` | +| `from_float16(value)` | `HMath.Numeric.fromFloat16` | `hmath_numeric_types_from_float16` | +| `from_bfloat16(value)` | `HMath.Numeric.fromBFloat16` | `hmath_numeric_types_from_bfloat16` | +| `rounded(value, flags)` | `HMath.Numeric.Rounded` | `hmath_numeric_types_rounded` | +| `rounded_value(value)` | `HMath.Numeric.roundedValue` | `hmath_numeric_types_rounded_value` | +| `numerical_exceptions(value)` | `HMath.Numeric.numericalExceptions` | `hmath_numeric_types_numerical_exceptions` | +| `big_float(precision, mode, value)` | `HMath.Numeric.bigFloat` | `hmath_numeric_types_big_float` | +| `extended(value)` | `HMath.Numeric.extended` | `hmath_numeric_types_extended` | +| `big_precision(value)` | `HMath.Numeric.bigPrecision` | `hmath_numeric_types_big_precision` | +| `big_rational(value)` | `HMath.Numeric.bigRational` | `hmath_numeric_types_big_rational` | +| `big_to_double(value)` | `HMath.Numeric.bigToDouble` | `hmath_numeric_types_big_to_double` | +| `big_add(a, b)` | `HMath.Numeric.bigAdd` | `hmath_numeric_types_big_add` | +| `big_subtract(a, b)` | `HMath.Numeric.bigSubtract` | `hmath_numeric_types_big_subtract` | +| `big_multiply(a, b)` | `HMath.Numeric.bigMultiply` | `hmath_numeric_types_big_multiply` | +| `big_divide(a, b)` | `HMath.Numeric.bigDivide` | `hmath_numeric_types_big_divide` | +| `big_sqrt(value)` | `HMath.Numeric.bigSqrt` | `hmath_numeric_types_big_sqrt` | +| `big_exp(value)` | `HMath.Numeric.bigExp` | `hmath_numeric_types_big_exp` | +| `big_log(value)` | `HMath.Numeric.bigLog` | `hmath_numeric_types_big_log` | +| `mixed_add(a, b)` | `HMath.Numeric.mixedAdd` | `hmath_numeric_types_mixed_add` | +| `mixed_multiply(a, b)` | `HMath.Numeric.mixedMultiply` | `hmath_numeric_types_mixed_multiply` | +| `fixed(scale, mode, value)` | `HMath.Numeric.fixed` | `hmath_numeric_types_fixed` | +| `fixed_rational(value)` | `HMath.Numeric.fixedRational` | `hmath_numeric_types_fixed_rational` | +| `fixed_add(a, b)` | `HMath.Numeric.fixedAdd` | `hmath_numeric_types_fixed_add` | +| `fixed_multiply(mode, a, b)` | `HMath.Numeric.fixedMultiply` | `hmath_numeric_types_fixed_multiply` | +| `fixed_divide(mode, a, b)` | `HMath.Numeric.fixedDivide` | `hmath_numeric_types_fixed_divide` | +| `decimal(scale, mode, value)` | `HMath.Numeric.decimal` | `hmath_numeric_types_decimal` | +| `decimal_rational(value)` | `HMath.Numeric.decimalRational` | `hmath_numeric_types_decimal_rational` | +| `decimal_add(a, b)` | `HMath.Numeric.decimalAdd` | `hmath_numeric_types_decimal_add` | +| `decimal_multiply(mode, a, b)` | `HMath.Numeric.decimalMultiply` | `hmath_numeric_types_decimal_multiply` | +| `decimal_divide(mode, a, b)` | `HMath.Numeric.decimalDivide` | `hmath_numeric_types_decimal_divide` | +| `fixed_scale(value)` | `HMath.Numeric.fixedScale` | `hmath_numeric_types_fixed_scale` | +| `fixed_coefficient(value)` | `HMath.Numeric.fixedCoefficient` | `hmath_numeric_types_fixed_coefficient` | +| `interval(low, high)` | `HMath.Numeric.interval` | `hmath_numeric_types_interval` | +| `interval_bounds(value)` | `HMath.Numeric.intervalBounds` | `hmath_numeric_types_interval_bounds` | +| `interval_contains(value, point)` | `HMath.Numeric.intervalContains` | `hmath_numeric_types_interval_contains` | +| `interval_add(a, b)` | `HMath.Numeric.intervalAdd` | `hmath_numeric_types_interval_add` | +| `interval_subtract(a, b)` | `HMath.Numeric.intervalSubtract` | `hmath_numeric_types_interval_subtract` | +| `interval_multiply(a, b)` | `HMath.Numeric.intervalMultiply` | `hmath_numeric_types_interval_multiply` | +| `interval_divide(a, b)` | `HMath.Numeric.intervalDivide` | `hmath_numeric_types_interval_divide` | +| `dual(primal_value, tangent_value)` | `HMath.Numeric.Dual` | `hmath_numeric_types_dual` | +| `primal(value)` | `HMath.Numeric.primal` | `hmath_numeric_types_primal` | +| `tangent(value)` | `HMath.Numeric.tangent` | `hmath_numeric_types_tangent` | +| `derivative(function, value)` | `HMath.Numeric.derivative` | `hmath_numeric_types_derivative` | +| `quaternion(real, i, j, k)` | `HMath.Numeric.Quaternion` | `hmath_numeric_types_quaternion` | +| `quaternion_conjugate(value)` | `HMath.Numeric.quaternionConjugate` | `hmath_numeric_types_quaternion_conjugate` | +| `quaternion_norm(value)` | `HMath.Numeric.quaternionNorm` | `hmath_numeric_types_quaternion_norm` | +| `quaternion_inverse(value)` | `HMath.Numeric.quaternionInverse` | `hmath_numeric_types_quaternion_inverse` | +| `dual_quaternion(real, dual)` | `HMath.Numeric.DualQuaternion` | `hmath_numeric_types_dual_quaternion` | +| `dual_quaternion_multiply(a, b)` | `HMath.Numeric.dualQuaternionMultiply` | `hmath_numeric_types_dual_quaternion_multiply` | +| `dual_quaternion_inverse(value)` | `HMath.Numeric.dualQuaternionInverse` | `hmath_numeric_types_dual_quaternion_inverse` | +| `rotate_vector(value, x, y, z)` | `HMath.Numeric.rotateVector` | `hmath_numeric_types_rotate_vector` | +| `rigid_transform(value, x, y, z)` | `HMath.Numeric.rigidTransform` | `hmath_numeric_types_rigid_transform` | +| `transform_point(value, x, y, z)` | `HMath.Numeric.transformPoint` | `hmath_numeric_types_transform_point` | +| `constant(name, value, uncertainty, approximation, unit, source)` | `HMath.Constants.Constant` | `hmath_numeric_types_constant` | +| `constant_name(value)` | `HMath.Constants.constantName` | `hmath_numeric_types_constant_name` | +| `constant_value(value)` | `HMath.Constants.constantValue` | `hmath_numeric_types_constant_value` | +| `standard_uncertainty(value)` | `HMath.Constants.standardUncertainty` | `hmath_numeric_types_standard_uncertainty` | +| `approximation_bound(value)` | `HMath.Constants.approximationBound` | `hmath_numeric_types_approximation_bound` | +| `constant_unit(value)` | `HMath.Constants.constantUnit` | `hmath_numeric_types_constant_unit` | +| `constant_source(value)` | `HMath.Constants.constantSource` | `hmath_numeric_types_constant_source` | +| `constant_as(value, dtype)` | `HMath.Constants.constantAs` | `hmath_numeric_types_constant_as` | +| `mathematical_constants()` | `HMath.Constants.mathematicalConstants` | `hmath_numeric_types_mathematical_constants` | +| `physical_constants()` | `HMath.Constants.physicalConstants` | `hmath_numeric_types_physical_constants` | +| `speed_of_light()` | `HMath.Constants.speedOfLight` | `hmath_numeric_types_speed_of_light` | +| `planck_constant()` | `HMath.Constants.planckConstant` | `hmath_numeric_types_planck_constant` | +| `elementary_charge()` | `HMath.Constants.elementaryCharge` | `hmath_numeric_types_elementary_charge` | +| `boltzmann_constant()` | `HMath.Constants.boltzmannConstant` | `hmath_numeric_types_boltzmann_constant` | +| `avogadro_constant()` | `HMath.Constants.avogadroConstant` | `hmath_numeric_types_avogadro_constant` | +| `gravitational_constant()` | `HMath.Constants.gravitationalConstant` | `hmath_numeric_types_gravitational_constant` | +| `electron_mass()` | `HMath.Constants.electronMass` | `hmath_numeric_types_electron_mass` | +| `astronomical_unit()` | `HMath.Constants.astronomicalUnit` | `hmath_numeric_types_astronomical_unit` | + +All handle parameters preserve their original type. `mode` is a `RoundingMode`; +`dtype` selects a shared scalar code. Precision, scale, digits and exponent fields +use native Haskell `Int` width. Rational parameters accept `Fraction` in Python +and exact numerator/denominator decimal strings in C. The `constant_as_like` +helper uses a typed prototype instead of a fixed scalar code. diff --git a/docs/reference/numeric-types.md b/docs/reference/numeric-types.md new file mode 100644 index 0000000..0f463f6 --- /dev/null +++ b/docs/reference/numeric-types.md @@ -0,0 +1,153 @@ +# Numeric representations and constants + +`hmath.numeric_types` exposes the original `HMath.Numeric` representations and +`HMath.Constants.Constant` records. Numerical operations run in Haskell. Values +retain their precision, scale, software exception flags and constant metadata. +The C declarations are in `hmath_numeric_types.h`; scalar/container transport is +shared with the matrix and polynomial APIs through `hmath_value.h`. + +## Python values + +```python +from fractions import Fraction +from hmath import numeric_types as n + +result = n.big_float(200, n.RoundingMode.NEAREST_EVEN, Fraction(1, 3)) +with result, result.rounded_value as value: + print(n.big_precision(value)) # 200 + print(n.big_rational(value)) # exact stored Rational + print(result.numerical_exceptions) # software rounding flags + +with n.number(-2, "float32") as point: + print(n.derivative(lambda x: x**3 + 2*x, point)) + +with n.speed_of_light() as constant: + print(n.constant_value(constant)) # Fraction(299792458, 1) + print(n.constant_unit(constant)) + print(n.constant_source(constant)) +``` + +Factories for structured types return immutable `NumericValue` owners. Close them +explicitly, or use `with`. A returned child owns its data independently of its +parent. Every live owner keeps the Haskell runtime alive. Final runtime shutdown +reports `BUSY` while a native reference is live. + +Standard scalar results normally become Python `int`, `float`, `complex` or +`fractions.Fraction`. Pass `boxed=True` to any numerical function to keep its +native coefficient type for another typed operation. `n.number(value, dtype)` +constructs a typed scalar. The `.value` property explicitly decodes a boxed +standard scalar; `.primal`, `.tangent`, `.rounded_value` and `.components` retain +boxed children and their exact types. + +Supported scalar dtype names are `float32`, `float64`, `integer`, `rational`, +`complex64`, `complex128`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, +`uint32`, `uint64`, `intp` and `uintp`. Integer and Rational inputs have no binary +floating conversion. Bounded input constructors reject values outside their +representation. `safe_integral_cast` and `saturating_cast` instead execute the +original Haskell checked/saturating conversion functions. + +`NumericValue` arithmetic invokes the original `Num`, `Fractional` or `Floating` +instance. Python integer/rational literals are lifted into that same instance. +Two explicitly boxed operands must have identical Haskell coefficient types; +there is no implicit promotion. Integer exponents use Haskell `(^)` and, for a +negative exponent, `(^^)`. Other exponents use `(**)`. Methods `sin`, `cos`, `exp`, +`log`, `sqrt`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `asinh`, +`acosh`, `atanh`, `signum` and `recip` invoke those original instance methods. +Unavailable instances produce `UNSUPPORTED` rather than a replacement algorithm. + +## Rounding, representations and records + +- `RoundingMode`: `NEAREST_EVEN`, `TOWARD_ZERO`, `TOWARD_POSITIVE`, + `TOWARD_NEGATIVE`. The host CPU rounding environment is unchanged. +- `NumericException`: `INVALID_OPERATION`, `DIVISION_BY_ZERO`, + `NUMERIC_OVERFLOW`, `NUMERIC_UNDERFLOW`, `INEXACT`. `Rounded` retains flag order + and duplicates; the public record constructor applies no extra filtering. +- `IEEEClass`: `NOT_A_NUMBER`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, + `POSITIVE_ZERO`, `NEGATIVE_ZERO`, `SUBNORMAL`, `NORMAL`. +- `Float16` and `BFloat16`: constructors take the original `Double` input and + explicit rounding mode. Bit constructors/accessors preserve all 16 input bits, + including signed zeros, infinities and NaN representations. +- `BigFloat`: precision is retained with the stored exact Rational. + `big_add`, `big_subtract`, `big_multiply`, `big_divide`, `big_sqrt`, `big_exp`, + `big_log`, `mixed_add` and `mixed_multiply` use the original implementations and + precision selection. Inspect `big_precision` and `big_rational` to avoid a + lossy `big_to_double` conversion. +- `Fixed`: the stored decimal scale and unbounded integer coefficient remain + available through `fixed_scale` and `fixed_coefficient`. `Decimal` retains its + original representation; both expose exact Rational getters. The original + larger-scale and explicit-rounding rules apply to their arithmetic results. +- `Interval`: bounds remain `Double`, with the original outward-rounded + operations and original division-by-zero interval checks. `interval_contains` + has the original inclusive membership behavior. +- `NumericLimits`: `numeric_limits` requires an actual `RealFloat` witness, + currently `Float`/`Double`; `integer_limits` requires a bounded integral + witness. Dedicated 16-bit limit functions preserve their original `Double` + metadata fields. `numeric_limits_record` constructs the original record from + its four value fields and three integer metadata fields. Field accessors do + not recompute or normalize those values. + +## Duals, quaternions and callbacks + +`dual(primal_value, tangent_value)` constructs `HMath.Numeric.Dual`, a distinct +source type from the reverse/forward automatic differentiation APIs. Both fields +must have the same coefficient type. Nested Duals preserve that nesting. +`derivative(function, value)` evaluates the original `Numeric.derivative` with a +synchronous Python/C callback over the actual `Numeric.Dual` argument. The +callback must be deterministic. Python exceptions propagate back to the caller; +C callbacks return a status and transfer one owned output reference. + +Dual coefficients support the standard scalar types and recursive Duals where +the original instance exists. `Quaternion` can retain standard coefficient +components; its `Num` instance requires `RealFloat` components, so arithmetic is +available for Float/Double components. Norm, inverse, rotation and rigid +transforms enforce their original constraints. A `Dual` of such a Quaternion can +use the original `Num` instance. `DualQuaternion` retains two actual Quaternion +values and provides the original multiplication, inverse and point transform. +No `Ord`, `RealFloat` or `Fractional` instance is invented for Quaternion or Dual. + +## Constant metadata + +`constant(name, value, uncertainty, approximation, unit, source)` retains all six +original record fields. Values, standard uncertainty and approximation bounds +are exact Rationals, including user-provided signs. Strings preserve every +Haskell `Char`, embedded NUL and surrogate code points without normalization. +`mathematical_constants` and `physical_constants` return the original record +lists in source order. Physical values retain their CODATA/definition provenance +instead of promising an unversioned latest adjustment. + +`constant_as(record, dtype)` invokes the original `constantAs` for standard +Fractional types. `constant_as_like(record, prototype)` selects the actual native +Fractional type of a boxed prototype, including a supported nested Numeric.Dual. +These conversions omit metadata by the original contract; retain the record +when reporting uncertainty or provenance. + +## C ownership and errors + +Every function accepts an optional `hmath_context *` and writes a new owned +`hmath_numeric_value *` through its final output argument. The typedef aliases +the common `hmath_value` owner. Inputs are borrowed for the synchronous call; +hold an owned reference throughout the call and on each participating thread. +Outputs stay untouched on failure. Release each reference with +`hmath_numeric_types_release`; releasing `NULL` is a no-op. Scalar and container +accessors in `hmath_value.h` accept these same handles. + +Distinct handles are immutable and can be shared by independent calls. Callbacks +may reenter the checked API. Retain a borrowed callback input before returning +it as the callback's owned result. A callback must not unwind through C. Its +transferred output is consumed on success and failure. Cancellation is checked +before entering a numerical operation, with the same granularity as other +checked native adapters. + +Exact integers are signed ASCII decimal strings. Rationals use separate +numerator and nonzero denominator strings. Text is an explicit array of 32-bit +Unicode code points plus its length; each code point must be at most `0x10ffff`. +Flags are explicit integer enum arrays and lengths. Array spans and overflow are +checked before reading input memory. Original `Left MathError` results use +`HMATH_MATH_ERROR`; `hmath_last_math_error` exposes the complete source +constructor, fields and message. Callback errors preserve that same payload. +There is no process-wide floating environment change or silent dtype promotion. + +The function-by-function generated table is in +[Numeric type functions](numeric-type-functions.md). The bindings support the +listed concrete standard types and recursive Numeric.Dual/Quaternion witnesses; +arbitrary user-defined Haskell typeclass instances are outside this C ABI. diff --git a/docs/reference/numerical-solvers.md b/docs/reference/numerical-solvers.md new file mode 100644 index 0000000..0c3c391 --- /dev/null +++ b/docs/reference/numerical-solvers.md @@ -0,0 +1,2970 @@ +# Numerical solvers + +Python exposes `hmath.calculus`, `hmath.root`, `hmath.ode` and `hmath.pde`. C includes `hmath_numerical.h`. Every named operation invokes the original Haskell function with its original argument order, defaults, budgets, diagnostic fields, finite checks and errors. + +Inputs are borrowed, successful outputs own a [structured value](values.md), and failure leaves output pointers untouched. Immutable handles can be shared by concurrent readers retaining their own references. Source `Left MathError` returns status11 with its full structured payload. Cancellation is checked before entry; source evaluation/step limits govern the solver. + +Function arguments are kind101 objects constructed with `hmath_linear_callback`. Their input is a tuple of the source's curried arguments flattened into positional order; their output transfers one owned value. Callbacks may reenter checked APIs and must not unwind through C. Python accepts normal callables and re-raises their original exceptions after cleanup. An actual source `Either MathError` callback may return a recoverable mathematical error; pure callbacks propagate it to the outer boundary. Callback function/userdata must remain valid for all objects retaining them. Python propagates these owners automatically. + +`Estimate` retains an arbitrary structured payload; its value is never implicitly converted to binary64. Numerical estimates produced by these solvers have their original binary64 payload. `Matrix Double`, sparse operators and exact polynomial inputs interoperate with their existing typed binding owners. + +## `calculus.estimate` + +`calculus.estimate(value, error, evaluations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Estimate`](haskell/HMath-Calculus.md#v:Estimate). + +```haskell +a -> Double -> Int -> Estimate a +``` + +```c +hmath_status hmath_calculus_estimate(hmath_context *context, const hmath_value *value, const hmath_value *error, const hmath_value *evaluations, hmath_value **out); +``` + +## `calculus.estimate_value` + +`calculus.estimate_value(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.estimateValue`](haskell/HMath-Calculus.md#v:estimateValue). + +```haskell +Estimate a -> a +``` + +```c +hmath_status hmath_calculus_estimate_value(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.estimate_error` + +`calculus.estimate_error(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.estimateError`](haskell/HMath-Calculus.md#v:estimateError). + +```haskell +Estimate a -> Double +``` + +```c +hmath_status hmath_calculus_estimate_error(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.evaluations` + +`calculus.evaluations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.evaluations`](haskell/HMath-Calculus.md#v:evaluations). + +```haskell +Estimate a -> Int +``` + +```c +hmath_status hmath_calculus_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.tolerance` + +`calculus.tolerance(absolute_tolerance, relative_tolerance, maximum_evaluations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Tolerance`](haskell/HMath-Calculus.md#v:Tolerance). + +```haskell +Double -> Double -> Int -> Tolerance +``` + +```c +hmath_status hmath_calculus_tolerance(hmath_context *context, const hmath_value *absolute_tolerance, const hmath_value *relative_tolerance, const hmath_value *maximum_evaluations, hmath_value **out); +``` + +## `calculus.absolute_tolerance` + +`calculus.absolute_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.absoluteTolerance`](haskell/HMath-Calculus.md#v:absoluteTolerance). + +```haskell +Tolerance -> Double +``` + +```c +hmath_status hmath_calculus_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.relative_tolerance` + +`calculus.relative_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.relativeTolerance`](haskell/HMath-Calculus.md#v:relativeTolerance). + +```haskell +Tolerance -> Double +``` + +```c +hmath_status hmath_calculus_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.maximum_evaluations` + +`calculus.maximum_evaluations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.maximumEvaluations`](haskell/HMath-Calculus.md#v:maximumEvaluations). + +```haskell +Tolerance -> Int +``` + +```c +hmath_status hmath_calculus_maximum_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.default_tolerance` + +`calculus.default_tolerance()` + +Default adaptive tolerance: 1e-10 absolute, 1e-8 relative, 100000 evaluations. + +Original: [`HMath.Calculus.defaultTolerance`](haskell/HMath-Calculus.md#v:defaultTolerance). + +```haskell +Tolerance +``` + +```c +hmath_status hmath_calculus_default_tolerance(hmath_context *context, hmath_value **out); +``` + +## `calculus.forward` + +`calculus.forward()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Forward`](haskell/HMath-Calculus.md#v:Forward). + +```haskell +Difference +``` + +```c +hmath_status hmath_calculus_forward(hmath_context *context, hmath_value **out); +``` + +## `calculus.backward` + +`calculus.backward()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Backward`](haskell/HMath-Calculus.md#v:Backward). + +```haskell +Difference +``` + +```c +hmath_status hmath_calculus_backward(hmath_context *context, hmath_value **out); +``` + +## `calculus.central` + +`calculus.central()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Central`](haskell/HMath-Calculus.md#v:Central). + +```haskell +Difference +``` + +```c +hmath_status hmath_calculus_central(hmath_context *context, hmath_value **out); +``` + +## `calculus.trapezoidal` + +`calculus.trapezoidal()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Trapezoidal`](haskell/HMath-Calculus.md#v:Trapezoidal). + +```haskell +Quadrature +``` + +```c +hmath_status hmath_calculus_trapezoidal(hmath_context *context, hmath_value **out); +``` + +## `calculus.simpson` + +`calculus.simpson()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.Simpson`](haskell/HMath-Calculus.md#v:Simpson). + +```haskell +Quadrature +``` + +```c +hmath_status hmath_calculus_simpson(hmath_context *context, hmath_value **out); +``` + +## `calculus.three_eighths` + +`calculus.three_eighths()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Calculus.ThreeEighths`](haskell/HMath-Calculus.md#v:ThreeEighths). + +```haskell +Quadrature +``` + +```c +hmath_status hmath_calculus_three_eighths(hmath_context *context, hmath_value **out); +``` + +## `calculus.derivative` + +`calculus.derivative(method, h, f, x)` + +First derivative with explicit positive finite step; rounded-away steps fail. + +Original: [`HMath.Calculus.derivative`](haskell/HMath-Calculus.md#v:derivative). + +```haskell +Difference -> Double -> (Double -> Double) -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_derivative(hmath_context *context, const hmath_value *method, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.derivative_n` + +`calculus.derivative_n(order, h, f, x)` + + Arbitrary nonnegative derivative order by recursively centered differences. Work grows exponentially with the requested order; orders are limited to 12. + +Original: [`HMath.Calculus.derivativeN`](haskell/HMath-Calculus.md#v:derivativeN). + +```haskell +Int -> Double -> (Double -> Double) -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_derivative_n(hmath_context *context, const hmath_value *order, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.complex_derivative` + +`calculus.complex_derivative(h, f, x)` + + Complex-step first derivative. The callback must have a holomorphic extension and be real on the real axis. + +Original: [`HMath.Calculus.complexDerivative`](haskell/HMath-Calculus.md#v:complexDerivative). + +```haskell +Double -> (Complex Double -> Complex Double) -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_complex_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.richardson` + +`calculus.richardson(tol, initial, f, x)` + + Richardson extrapolation of a central first difference. Each row halves the step. Evaluation budget is 2 per row; convergence uses consecutive diagonals. + +Original: [`HMath.Calculus.richardson`](haskell/HMath-Calculus.md#v:richardson). + +```haskell +Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_richardson(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.ridders` + +`calculus.ridders(tol, initial, f, x)` + +Ridders extrapolation with factor 1.4 and a best-error stopping criterion. + +Original: [`HMath.Calculus.ridders`](haskell/HMath-Calculus.md#v:ridders). + +```haskell +Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_ridders(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.limit` + +`calculus.limit(side, tol, initial, f, x)` + + One-sided numerical limit, approaching geometrically from the requested side. Central compares the average of both sides; it cannot prove continuity. + +Original: [`HMath.Calculus.limit`](haskell/HMath-Calculus.md#v:limit). + +```haskell +Difference -> Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_limit(hmath_context *context, const hmath_value *side, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.partial_derivative` + +`calculus.partial_derivative(i, h, f, xs)` + +Partial derivative at a zero-based coordinate. + +Original: [`HMath.Calculus.partialDerivative`](haskell/HMath-Calculus.md#v:partialDerivative). + +```haskell +Int -> Double -> ([Double] -> Double) -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_partial_derivative(hmath_context *context, const hmath_value *i, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +``` + +## `calculus.gradient` + +`calculus.gradient(h, f, xs)` + +Gradient using one central difference per coordinate. + +Original: [`HMath.Calculus.gradient`](haskell/HMath-Calculus.md#v:gradient). + +```haskell +Double -> ([Double] -> Double) -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_gradient(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +``` + +## `calculus.jacobian` + +`calculus.jacobian(h, f, xs)` + +Row-major Jacobian; callback output dimensions must remain constant. + +Original: [`HMath.Calculus.jacobian`](haskell/HMath-Calculus.md#v:jacobian). + +```haskell +Double -> ([Double] -> [Double]) -> [Double] -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_calculus_jacobian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +``` + +## `calculus.hessian` + +`calculus.hessian(h, f, xs)` + +Hessian with centered diagonal and mixed differences. + +Original: [`HMath.Calculus.hessian`](haskell/HMath-Calculus.md#v:hessian). + +```haskell +Double -> ([Double] -> Double) -> [Double] -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_calculus_hessian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +``` + +## `calculus.directional_derivative` + +`calculus.directional_derivative(h, f, x, v)` + +Directional derivative; the direction is used as supplied, without normalization. + +Original: [`HMath.Calculus.directionalDerivative`](haskell/HMath-Calculus.md#v:directionalDerivative). + +```haskell +Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_directional_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +``` + +## `calculus.jvp` + +`calculus.jvp(h, f, x, v)` + +Jacobian-vector product by directional central differences. + +Original: [`HMath.Calculus.jvp`](haskell/HMath-Calculus.md#v:jvp). + +```haskell +Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_jvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +``` + +## `calculus.vjp` + +`calculus.vjp(h, f, x, v)` + +Vector-Jacobian product as the gradient of a scalar contraction. + +Original: [`HMath.Calculus.vjp`](haskell/HMath-Calculus.md#v:vjp). + +```haskell +Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_vjp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +``` + +## `calculus.hvp` + +`calculus.hvp(h, f, x, v)` + +Hessian-vector product with four directional/coordinate samples per component. + +Original: [`HMath.Calculus.hvp`](haskell/HMath-Calculus.md#v:hvp). + +```haskell +Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_hvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +``` + +## `calculus.divergence` + +`calculus.divergence(h, f, x)` + +Divergence of a vector field with equal input and output dimensions. + +Original: [`HMath.Calculus.divergence`](haskell/HMath-Calculus.md#v:divergence). + +```haskell +Double -> ([Double] -> [Double]) -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_divergence(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.curl` + +`calculus.curl(h, f, x)` + +Curl of a three-dimensional vector field. + +Original: [`HMath.Calculus.curl`](haskell/HMath-Calculus.md#v:curl). + +```haskell +Double -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_curl(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.laplacian` + +`calculus.laplacian(h, f, x)` + +Laplacian as the sum of centered second coordinate differences. + +Original: [`HMath.Calculus.laplacian`](haskell/HMath-Calculus.md#v:laplacian). + +```haskell +Double -> ([Double] -> Double) -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_laplacian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +``` + +## `calculus.integrate_composite` + +`calculus.integrate_composite(method, n, f, a, b)` + +Composite finite-interval integration with exact panel constraints. + +Original: [`HMath.Calculus.integrateComposite`](haskell/HMath-Calculus.md#v:integrateComposite). + +```haskell +Quadrature -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_integrate_composite(hmath_context *context, const hmath_value *method, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.romberg` + +`calculus.romberg(tol, f, a, b)` + +Romberg integration using trapezoidal refinement and Richardson diagonals. + +Original: [`HMath.Calculus.romberg`](haskell/HMath-Calculus.md#v:romberg). + +```haskell +Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_romberg(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.gauss_legendre` + +`calculus.gauss_legendre(n, f, a, b)` + +n-point Gauss-Legendre quadrature; nodes are refined by Newton iteration. + +Original: [`HMath.Calculus.gaussLegendre`](haskell/HMath-Calculus.md#v:gaussLegendre). + +```haskell +Int -> (Double -> Double) -> Double -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_gauss_legendre(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.gauss_hermite` + +`calculus.gauss_hermite(value, value2)` + + Weighted Gaussian quadrature on the real line for weight exp(-x^2). Uses the symmetric Jacobi recurrence and a checked implicit QL eigensystem. + +Original: [`HMath.Calculus.gaussHermite`](haskell/HMath-Calculus.md#v:gaussHermite). + +```haskell +Int -> (Double -> Double) -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_gauss_hermite(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `calculus.gauss_laguerre` + +`calculus.gauss_laguerre(value, value2)` + +Weighted Gaussian quadrature on [0,infinity) for weight exp(-x). + +Original: [`HMath.Calculus.gaussLaguerre`](haskell/HMath-Calculus.md#v:gaussLaguerre). + +```haskell +Int -> (Double -> Double) -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_gauss_laguerre(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `calculus.gauss_chebyshev` + +`calculus.gauss_chebyshev(n, f)` + +Weighted first-kind Chebyshev rule on [-1,1], weight 1/sqrt(1-x^2). + +Original: [`HMath.Calculus.gaussChebyshev`](haskell/HMath-Calculus.md#v:gaussChebyshev). + +```haskell +Int -> (Double -> Double) -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_gauss_chebyshev(hmath_context *context, const hmath_value *n, const hmath_value *f, hmath_value **out); +``` + +## `calculus.gauss_kronrod` + +`calculus.gauss_kronrod(f, a, b)` + + Embedded 7-point Gauss / 15-point Kronrod estimate. Nodes and weights are the standard Gauss-Kronrod pair used by QUADPACK dqk15 (Netlib). + +Original: [`HMath.Calculus.gaussKronrod`](haskell/HMath-Calculus.md#v:gaussKronrod). + +```haskell +(Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_gauss_kronrod(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.adaptive_integrate` + +`calculus.adaptive_integrate(tol, f, a, b)` + + Adaptive Gauss-Kronrod with global summed error and a strict evaluation budget. The interval with the largest estimated error is bisected first. + +Original: [`HMath.Calculus.adaptiveIntegrate`](haskell/HMath-Calculus.md#v:adaptiveIntegrate). + +```haskell +Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_adaptive_integrate(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.clenshaw_curtis` + +`calculus.clenshaw_curtis(n, f, a, b)` + + Clenshaw-Curtis quadrature on n cosine-spaced panels using exact moments of the cosine interpolant. n must be positive and at most 4096. + +Original: [`HMath.Calculus.clenshawCurtis`](haskell/HMath-Calculus.md#v:clenshawCurtis). + +```haskell +Int -> (Double -> Double) -> Double -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_clenshaw_curtis(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.tanh_sinh` + +`calculus.tanh_sinh(tol, f, a, b)` + + Tanh-sinh quadrature with geometric step refinement on a finite interval. Rounded-to-endpoint nodes are omitted, supporting integrable endpoint poles. + +Original: [`HMath.Calculus.tanhSinh`](haskell/HMath-Calculus.md#v:tanhSinh). + +```haskell +Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_tanh_sinh(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.integrate_infinite` + +`calculus.integrate_infinite(tol, f, a, b)` + + Integrate on finite, half-infinite or doubly-infinite intervals by an open coordinate transform followed by adaptive Gauss-Kronrod. Reversed bounds change the sign. Divergent integrals have no guaranteed detection criterion. + +Original: [`HMath.Calculus.integrateInfinite`](haskell/HMath-Calculus.md#v:integrateInfinite). + +```haskell +Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_integrate_infinite(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.integrate_oscillatory` + +`calculus.integrate_oscillatory(sine, omega, tol, f, a, b)` + + Integrate f(x)*cos(omega*x) or f(x)*sin(omega*x), splitting at least once per half-period to avoid accepting an aliased embedded quadrature estimate. + +Original: [`HMath.Calculus.integrateOscillatory`](haskell/HMath-Calculus.md#v:integrateOscillatory). + +```haskell +Bool -> Double -> Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_integrate_oscillatory(hmath_context *context, const hmath_value *sine, const hmath_value *omega, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.integrate_nd` + +`calculus.integrate_nd(panels, budget, f, bounds)` + + Tensor-product midpoint integration over a box. The product of panel counts is checked against the explicit budget before callback evaluation. + +Original: [`HMath.Calculus.integrateND`](haskell/HMath-Calculus.md#v:integrateND). + +```haskell +Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_integrate_nd(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +``` + +## `calculus.monte_carlo` + +`calculus.monte_carlo(seed, n, f, bounds)` + + Reproducible Monte Carlo box integral with an explicit 64-bit seed. Error is one estimated standard error from Welford's sample variance. + +Original: [`HMath.Calculus.monteCarlo`](haskell/HMath-Calculus.md#v:monteCarlo). + +```haskell +Integer -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_monte_carlo(hmath_context *context, const hmath_value *seed, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +``` + +## `calculus.quasi_monte_carlo` + +`calculus.quasi_monte_carlo(n, f, bounds)` + + Deterministic Halton-box quadrature, up to 16 dimensions. No probabilistic error bound is claimed; estimateError is the difference of the two halves. + +Original: [`HMath.Calculus.quasiMonteCarlo`](haskell/HMath-Calculus.md#v:quasiMonteCarlo). + +```haskell +Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_quasi_monte_carlo(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +``` + +## `calculus.cumulative_integral` + +`calculus.cumulative_integral(value)` + +Cumulative trapezoidal integrals at strictly increasing sample coordinates. + +Original: [`HMath.Calculus.cumulativeIntegral`](haskell/HMath-Calculus.md#v:cumulativeIntegral). + +```haskell +[(Double, Double)] -> Either MathError [Double] +``` + +```c +hmath_status hmath_calculus_cumulative_integral(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `calculus.path_integral` + +`calculus.path_integral(tol, curve, tangent, f, a, b)` + +Scalar line integral f(r(t))*|r'(t)| along an explicitly parameterized path. + +Original: [`HMath.Calculus.pathIntegral`](haskell/HMath-Calculus.md#v:pathIntegral). + +```haskell +Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> Double) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_path_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.line_integral` + +`calculus.line_integral(tol, curve, tangent, field, a, b)` + +Oriented vector-field line integral along a parameterized path. + +Original: [`HMath.Calculus.lineIntegral`](haskell/HMath-Calculus.md#v:lineIntegral). + +```haskell +Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> Either MathError (Estimate Double) +``` + +```c +hmath_status hmath_calculus_line_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *field, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `calculus.surface_integral` + +`calculus.surface_integral(panels, budget, surface, du, dv, f, bounds)` + +Scalar surface integral over a rectangular parameter domain in R3. + +Original: [`HMath.Calculus.surfaceIntegral`](haskell/HMath-Calculus.md#v:surfaceIntegral). + +```haskell +Int -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_surface_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *surface, const hmath_value *du, const hmath_value *dv, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +``` + +## `calculus.volume_integral` + +`calculus.volume_integral(panels, budget, f, bounds)` + +Volume integral over a three-dimensional rectangular box. + +Original: [`HMath.Calculus.volumeIntegral`](haskell/HMath-Calculus.md#v:volumeIntegral). + +```haskell +Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double +``` + +```c +hmath_status hmath_calculus_volume_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +``` + +## `root.root_options` + +`root.root_options(root_max_iterations, root_max_evaluations, root_tolerance, root_step_tolerance)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.RootOptions`](haskell/HMath-Root.md#v:RootOptions). + +```haskell +Int -> Int -> Double -> Double -> RootOptions +``` + +```c +hmath_status hmath_root_root_options(hmath_context *context, const hmath_value *root_max_iterations, const hmath_value *root_max_evaluations, const hmath_value *root_tolerance, const hmath_value *root_step_tolerance, hmath_value **out); +``` + +## `root.root_max_iterations` + +`root.root_max_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootMaxIterations`](haskell/HMath-Root.md#v:rootMaxIterations). + +```haskell +RootOptions -> Int +``` + +```c +hmath_status hmath_root_root_max_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_max_evaluations` + +`root.root_max_evaluations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootMaxEvaluations`](haskell/HMath-Root.md#v:rootMaxEvaluations). + +```haskell +RootOptions -> Int +``` + +```c +hmath_status hmath_root_root_max_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_tolerance` + +`root.root_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootTolerance`](haskell/HMath-Root.md#v:rootTolerance). + +```haskell +RootOptions -> Double +``` + +```c +hmath_status hmath_root_root_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_step_tolerance` + +`root.root_step_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootStepTolerance`](haskell/HMath-Root.md#v:rootStepTolerance). + +```haskell +RootOptions -> Double +``` + +```c +hmath_status hmath_root_root_step_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.default_root_options` + +`root.default_root_options()` + + Default root-solving limits: 200 iterations, 4000 evaluations, residual tolerance 1e-10 and step tolerance 1e-12. Solvers validate options and report their own convergence diagnostics. + +Original: [`HMath.Root.defaultRootOptions`](haskell/HMath-Root.md#v:defaultRootOptions). + +```haskell +RootOptions +``` + +```c +hmath_status hmath_root_default_root_options(hmath_context *context, hmath_value **out); +``` + +## `root.root_result` + +`root.root_result(root_value, root_residual, root_error_bound, root_iterations, root_evaluations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.RootResult`](haskell/HMath-Root.md#v:RootResult). + +```haskell +Double -> Double -> Maybe Double -> Int -> Int -> RootResult +``` + +```c +hmath_status hmath_root_root_result(hmath_context *context, const hmath_value *root_value, const hmath_value *root_residual, const hmath_value *root_error_bound, const hmath_value *root_iterations, const hmath_value *root_evaluations, hmath_value **out); +``` + +## `root.root_value` + +`root.root_value(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootValue`](haskell/HMath-Root.md#v:rootValue). + +```haskell +RootResult -> Double +``` + +```c +hmath_status hmath_root_root_value(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_residual` + +`root.root_residual(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootResidual`](haskell/HMath-Root.md#v:rootResidual). + +```haskell +RootResult -> Double +``` + +```c +hmath_status hmath_root_root_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_error_bound` + +`root.root_error_bound(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootErrorBound`](haskell/HMath-Root.md#v:rootErrorBound). + +```haskell +RootResult -> Maybe Double +``` + +```c +hmath_status hmath_root_root_error_bound(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_iterations` + +`root.root_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootIterations`](haskell/HMath-Root.md#v:rootIterations). + +```haskell +RootResult -> Int +``` + +```c +hmath_status hmath_root_root_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.root_evaluations` + +`root.root_evaluations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.rootEvaluations`](haskell/HMath-Root.md#v:rootEvaluations). + +```haskell +RootResult -> Int +``` + +```c +hmath_status hmath_root_root_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.bisection` + +`root.bisection()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Bisection`](haskell/HMath-Root.md#v:Bisection). + +```haskell +BracketMethod +``` + +```c +hmath_status hmath_root_bisection(hmath_context *context, hmath_value **out); +``` + +## `root.regula_falsi` + +`root.regula_falsi()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.RegulaFalsi`](haskell/HMath-Root.md#v:RegulaFalsi). + +```haskell +BracketMethod +``` + +```c +hmath_status hmath_root_regula_falsi(hmath_context *context, hmath_value **out); +``` + +## `root.illinois` + +`root.illinois()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Illinois`](haskell/HMath-Root.md#v:Illinois). + +```haskell +BracketMethod +``` + +```c +hmath_status hmath_root_illinois(hmath_context *context, hmath_value **out); +``` + +## `root.brent` + +`root.brent()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Brent`](haskell/HMath-Root.md#v:Brent). + +```haskell +BracketMethod +``` + +```c +hmath_status hmath_root_brent(hmath_context *context, hmath_value **out); +``` + +## `root.ridder` + +`root.ridder()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Ridder`](haskell/HMath-Root.md#v:Ridder). + +```haskell +BracketMethod +``` + +```c +hmath_status hmath_root_ridder(hmath_context *context, hmath_value **out); +``` + +## `root.newton` + +`root.newton()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Newton`](haskell/HMath-Root.md#v:Newton). + +```haskell +DerivativeMethod +``` + +```c +hmath_status hmath_root_newton(hmath_context *context, hmath_value **out); +``` + +## `root.halley` + +`root.halley()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Halley`](haskell/HMath-Root.md#v:Halley). + +```haskell +DerivativeMethod +``` + +```c +hmath_status hmath_root_halley(hmath_context *context, hmath_value **out); +``` + +## `root.householder3` + +`root.householder3()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Householder3`](haskell/HMath-Root.md#v:Householder3). + +```haskell +DerivativeMethod +``` + +```c +hmath_status hmath_root_householder3(hmath_context *context, hmath_value **out); +``` + +## `root.picard` + +`root.picard()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Picard`](haskell/HMath-Root.md#v:Picard). + +```haskell +FixedPointMethod +``` + +```c +hmath_status hmath_root_picard(hmath_context *context, hmath_value **out); +``` + +## `root.aitken` + +`root.aitken()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Aitken`](haskell/HMath-Root.md#v:Aitken). + +```haskell +FixedPointMethod +``` + +```c +hmath_status hmath_root_aitken(hmath_context *context, hmath_value **out); +``` + +## `root.steffensen_fixed` + +`root.steffensen_fixed()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.SteffensenFixed`](haskell/HMath-Root.md#v:SteffensenFixed). + +```haskell +FixedPointMethod +``` + +```c +hmath_status hmath_root_steffensen_fixed(hmath_context *context, hmath_value **out); +``` + +## `root.multivariate_newton` + +`root.multivariate_newton()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.MultivariateNewton`](haskell/HMath-Root.md#v:MultivariateNewton). + +```haskell +SystemMethod +``` + +```c +hmath_status hmath_root_multivariate_newton(hmath_context *context, hmath_value **out); +``` + +## `root.newton_trust_region` + +`root.newton_trust_region(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.NewtonTrustRegion`](haskell/HMath-Root.md#v:NewtonTrustRegion). + +```haskell +Double -> SystemMethod +``` + +```c +hmath_status hmath_root_newton_trust_region(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.broyden` + +`root.broyden()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.Broyden`](haskell/HMath-Root.md#v:Broyden). + +```haskell +SystemMethod +``` + +```c +hmath_status hmath_root_broyden(hmath_context *context, hmath_value **out); +``` + +## `root.system_root_result` + +`root.system_root_result(system_root, system_residual, system_iterations, system_evaluations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.SystemRootResult`](haskell/HMath-Root.md#v:SystemRootResult). + +```haskell +[Double] -> Double -> Int -> Int -> SystemRootResult +``` + +```c +hmath_status hmath_root_system_root_result(hmath_context *context, const hmath_value *system_root, const hmath_value *system_residual, const hmath_value *system_iterations, const hmath_value *system_evaluations, hmath_value **out); +``` + +## `root.system_root` + +`root.system_root(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.systemRoot`](haskell/HMath-Root.md#v:systemRoot). + +```haskell +SystemRootResult -> [Double] +``` + +```c +hmath_status hmath_root_system_root(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.system_residual` + +`root.system_residual(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.systemResidual`](haskell/HMath-Root.md#v:systemResidual). + +```haskell +SystemRootResult -> Double +``` + +```c +hmath_status hmath_root_system_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.system_iterations` + +`root.system_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.systemIterations`](haskell/HMath-Root.md#v:systemIterations). + +```haskell +SystemRootResult -> Int +``` + +```c +hmath_status hmath_root_system_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.system_evaluations` + +`root.system_evaluations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Root.systemEvaluations`](haskell/HMath-Root.md#v:systemEvaluations). + +```haskell +SystemRootResult -> Int +``` + +```c +hmath_status hmath_root_system_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `root.bracket` + +`root.bracket(f, a, b)` + +Validate finite a Double) -> Double -> Double -> Either MathError Bracket +``` + +```c +hmath_status hmath_root_bracket(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `root.solve_bracket` + +`root.solve_bracket(value, value2, value3, value4)` + + Brackets are re-evaluated with the supplied function, preventing stale or mismatched endpoint caches from certifying a different function's root. + +Original: [`HMath.Root.solveBracket`](haskell/HMath-Root.md#v:solveBracket). + +```haskell +BracketMethod -> RootOptions -> (Double -> Double) -> Bracket -> Either MathError RootResult +``` + +```c +hmath_status hmath_root_solve_bracket(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `root.bracket_scan` + +`root.bracket_scan(o, f, a, b, cells)` + +Evaluate a uniform finite grid under the evaluation budget and return every endpoint/sign-change bracket. + +Original: [`HMath.Root.bracketScan`](haskell/HMath-Root.md#v:bracketScan). + +```haskell +RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [Bracket] +``` + +```c +hmath_status hmath_root_bracket_scan(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out); +``` + +## `root.isolate_intervals` + +`root.isolate_intervals(o, f, a, b, cells)` + +Refine sign-change scan brackets and deduplicate endpoint roots. Even roots require polynomial isolation. + +Original: [`HMath.Root.isolateIntervals`](haskell/HMath-Root.md#v:isolateIntervals). + +```haskell +RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [RootResult] +``` + +```c +hmath_status hmath_root_isolate_intervals(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out); +``` + +## `root.solve_derivative` + +`root.solve_derivative(method, o, f, derivatives, x0)` + + Derivatives [f', f'', f'''] are required through order 1, 2, or 3. Householder3 is the order-four rational Householder update. + +Original: [`HMath.Root.solveDerivative`](haskell/HMath-Root.md#v:solveDerivative). + +```haskell +DerivativeMethod -> RootOptions -> (Double -> Double) -> [Double -> Double] -> Double -> Either MathError RootResult +``` + +```c +hmath_status hmath_root_solve_derivative(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *derivatives, const hmath_value *x0, hmath_value **out); +``` + +## `root.secant` + +`root.secant(o, f, a, b)` + +Unbracketed two-point secant iteration; zero slopes, stagnation, and exhausted budgets fail explicitly. + +Original: [`HMath.Root.secant`](haskell/HMath-Root.md#v:secant). + +```haskell +RootOptions -> (Double -> Double) -> Double -> Double -> Either MathError RootResult +``` + +```c +hmath_status hmath_root_secant(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `root.steffensen` + +`root.steffensen(o, f, x0)` + +Derivative-free Steffensen root update using f(x+f(x)); termination checks the original residual. + +Original: [`HMath.Root.steffensen`](haskell/HMath-Root.md#v:steffensen). + +```haskell +RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult +``` + +```c +hmath_status hmath_root_steffensen(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *x0, hmath_value **out); +``` + +## `root.fixed_point` + +`root.fixed_point(method, o, g, x0)` + +Picard iteration, non-restarted Aitken sequence acceleration, or restarted Steffensen acceleration. + +Original: [`HMath.Root.fixedPoint`](haskell/HMath-Root.md#v:fixedPoint). + +```haskell +FixedPointMethod -> RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult +``` + +```c +hmath_status hmath_root_fixed_point(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out); +``` + +## `root.anderson` + +`root.anderson(depth, regularization, o, g, x0)` + + Anderson mixing with depth m and Tikhonov regularization. Residuals are g(x)-x. Solving the constrained residual Gram system is a bounded reference implementation; it does not pretend to use a low-storage QR update. + +Original: [`HMath.Root.anderson`](haskell/HMath-Root.md#v:anderson). + +```haskell +Int -> Double -> RootOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError SystemRootResult +``` + +```c +hmath_status hmath_root_anderson(hmath_context *context, const hmath_value *depth, const hmath_value *regularization, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out); +``` + +## `root.solve_system` + +`root.solve_system(method, o, f, jac, x0)` + +Solve a square analytic-Jacobian system using Newton, trust-radius Newton, or rank-one Broyden updates. + +Original: [`HMath.Root.solveSystem`](haskell/HMath-Root.md#v:solveSystem). + +```haskell +SystemMethod -> RootOptions -> ([Double] -> [Double]) -> ([Double] -> [[Double]]) -> [Double] -> Either MathError SystemRootResult +``` + +```c +hmath_status hmath_root_solve_system(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *jac, const hmath_value *x0, hmath_value **out); +``` + +## `root.polynomial_roots` + +`root.polynomial_roots(o, p)` + +Reuse the checked Aberth-Ehrlich simultaneous complex solver for an ascending-coefficient polynomial. + +Original: [`HMath.Root.polynomialRoots`](haskell/HMath-Root.md#v:polynomialRoots). + +```haskell +RootOptions -> P.Polynomial (Complex Double) -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_root_polynomial_roots(hmath_context *context, const hmath_value *o, const hmath_value *p, hmath_value **out); +``` + +## `root.real_polynomial_roots` + +`root.real_polynomial_roots(budget, tolerance, p)` + +Use exact square-free factorization and Sturm isolation; return rational intervals and integer multiplicities. + +Original: [`HMath.Root.realPolynomialRoots`](haskell/HMath-Root.md#v:realPolynomialRoots). + +```haskell +Int -> Rational -> P.Polynomial Rational -> Either MathError [(Rational, Rational, Int)] +``` + +```c +hmath_status hmath_root_real_polynomial_roots(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *p, hmath_value **out); +``` + +## `ode.euler` + +`ode.euler()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Euler`](haskell/HMath-ODE.md#v:Euler). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_euler(hmath_context *context, hmath_value **out); +``` + +## `ode.heun` + +`ode.heun()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Heun`](haskell/HMath-ODE.md#v:Heun). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_heun(hmath_context *context, hmath_value **out); +``` + +## `ode.midpoint` + +`ode.midpoint()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Midpoint`](haskell/HMath-ODE.md#v:Midpoint). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_midpoint(hmath_context *context, hmath_value **out); +``` + +## `ode.rk2` + +`ode.rk2()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.RK2`](haskell/HMath-ODE.md#v:RK2). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_rk2(hmath_context *context, hmath_value **out); +``` + +## `ode.rk4` + +`ode.rk4()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.RK4`](haskell/HMath-ODE.md#v:RK4). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_rk4(hmath_context *context, hmath_value **out); +``` + +## `ode.rk23` + +`ode.rk23()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.RK23`](haskell/HMath-ODE.md#v:RK23). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_rk23(hmath_context *context, hmath_value **out); +``` + +## `ode.rk45` + +`ode.rk45()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.RK45`](haskell/HMath-ODE.md#v:RK45). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_rk45(hmath_context *context, hmath_value **out); +``` + +## `ode.dormand_prince` + +`ode.dormand_prince()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.DormandPrince`](haskell/HMath-ODE.md#v:DormandPrince). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_dormand_prince(hmath_context *context, hmath_value **out); +``` + +## `ode.dop853` + +`ode.dop853()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.DOP853`](haskell/HMath-ODE.md#v:DOP853). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_dop853(hmath_context *context, hmath_value **out); +``` + +## `ode.adams_bashforth` + +`ode.adams_bashforth()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.AdamsBashforth`](haskell/HMath-ODE.md#v:AdamsBashforth). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_adams_bashforth(hmath_context *context, hmath_value **out); +``` + +## `ode.adams_moulton` + +`ode.adams_moulton()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.AdamsMoulton`](haskell/HMath-ODE.md#v:AdamsMoulton). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_adams_moulton(hmath_context *context, hmath_value **out); +``` + +## `ode.predictor_corrector` + +`ode.predictor_corrector()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.PredictorCorrector`](haskell/HMath-ODE.md#v:PredictorCorrector). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_predictor_corrector(hmath_context *context, hmath_value **out); +``` + +## `ode.backward_euler` + +`ode.backward_euler()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.BackwardEuler`](haskell/HMath-ODE.md#v:BackwardEuler). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_backward_euler(hmath_context *context, hmath_value **out); +``` + +## `ode.bdf` + +`ode.bdf()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.BDF`](haskell/HMath-ODE.md#v:BDF). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_bdf(hmath_context *context, hmath_value **out); +``` + +## `ode.radau` + +`ode.radau()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Radau`](haskell/HMath-ODE.md#v:Radau). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_radau(hmath_context *context, hmath_value **out); +``` + +## `ode.rosenbrock` + +`ode.rosenbrock()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Rosenbrock`](haskell/HMath-ODE.md#v:Rosenbrock). + +```haskell +Method +``` + +```c +hmath_status hmath_ode_rosenbrock(hmath_context *context, hmath_value **out); +``` + +## `ode.ode_options` + +`ode.ode_options(ode_absolute_tolerance, ode_relative_tolerance, initial_step, minimum_step, maximum_step, maximum_steps, newton_iterations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.ODEOptions`](haskell/HMath-ODE.md#v:ODEOptions). + +```haskell +Double -> Double -> Double -> Double -> Double -> Int -> Int -> ODEOptions +``` + +```c +hmath_status hmath_ode_ode_options(hmath_context *context, const hmath_value *ode_absolute_tolerance, const hmath_value *ode_relative_tolerance, const hmath_value *initial_step, const hmath_value *minimum_step, const hmath_value *maximum_step, const hmath_value *maximum_steps, const hmath_value *newton_iterations, hmath_value **out); +``` + +## `ode.ode_absolute_tolerance` + +`ode.ode_absolute_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.odeAbsoluteTolerance`](haskell/HMath-ODE.md#v:odeAbsoluteTolerance). + +```haskell +ODEOptions -> Double +``` + +```c +hmath_status hmath_ode_ode_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.ode_relative_tolerance` + +`ode.ode_relative_tolerance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.odeRelativeTolerance`](haskell/HMath-ODE.md#v:odeRelativeTolerance). + +```haskell +ODEOptions -> Double +``` + +```c +hmath_status hmath_ode_ode_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.initial_step` + +`ode.initial_step(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.initialStep`](haskell/HMath-ODE.md#v:initialStep). + +```haskell +ODEOptions -> Double +``` + +```c +hmath_status hmath_ode_initial_step(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.minimum_step` + +`ode.minimum_step(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.minimumStep`](haskell/HMath-ODE.md#v:minimumStep). + +```haskell +ODEOptions -> Double +``` + +```c +hmath_status hmath_ode_minimum_step(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.maximum_step` + +`ode.maximum_step(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.maximumStep`](haskell/HMath-ODE.md#v:maximumStep). + +```haskell +ODEOptions -> Double +``` + +```c +hmath_status hmath_ode_maximum_step(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.maximum_steps` + +`ode.maximum_steps(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.maximumSteps`](haskell/HMath-ODE.md#v:maximumSteps). + +```haskell +ODEOptions -> Int +``` + +```c +hmath_status hmath_ode_maximum_steps(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.newton_iterations` + +`ode.newton_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.newtonIterations`](haskell/HMath-ODE.md#v:newtonIterations). + +```haskell +ODEOptions -> Int +``` + +```c +hmath_status hmath_ode_newton_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.default_ode_options` + +`ode.default_ode_options()` + +Conservative default adaptive settings for Double callbacks. + +Original: [`HMath.ODE.defaultODEOptions`](haskell/HMath-ODE.md#v:defaultODEOptions). + +```haskell +ODEOptions +``` + +```c +hmath_status hmath_ode_default_ode_options(hmath_context *context, hmath_value **out); +``` + +## `ode.trajectory` + +`ode.trajectory(trajectory_times, trajectory_states, trajectory_derivatives)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Trajectory`](haskell/HMath-ODE.md#v:Trajectory). + +```haskell +[Double] -> [[Double]] -> [[Double]] -> Trajectory +``` + +```c +hmath_status hmath_ode_trajectory(hmath_context *context, const hmath_value *trajectory_times, const hmath_value *trajectory_states, const hmath_value *trajectory_derivatives, hmath_value **out); +``` + +## `ode.trajectory_times` + +`ode.trajectory_times(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.trajectoryTimes`](haskell/HMath-ODE.md#v:trajectoryTimes). + +```haskell +Trajectory -> [Double] +``` + +```c +hmath_status hmath_ode_trajectory_times(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.trajectory_states` + +`ode.trajectory_states(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.trajectoryStates`](haskell/HMath-ODE.md#v:trajectoryStates). + +```haskell +Trajectory -> [[Double]] +``` + +```c +hmath_status hmath_ode_trajectory_states(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.trajectory_derivatives` + +`ode.trajectory_derivatives(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.trajectoryDerivatives`](haskell/HMath-ODE.md#v:trajectoryDerivatives). + +```haskell +Trajectory -> [[Double]] +``` + +```c +hmath_status hmath_ode_trajectory_derivatives(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.solve_ivp` + +`ode.solve_ivp(method, options, panels, f, start, end, initial)` + + Integrate on n equal panels. Multistep methods use genuine derivative history; implicit methods use checked finite-difference Newton iterations. + +Original: [`HMath.ODE.solveIVP`](haskell/HMath-ODE.md#v:solveIVP). + +```haskell +Method -> ODEOptions -> Int -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_ivp(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +``` + +## `ode.solve_adaptive` + +`ode.solve_adaptive(method, options, f, start, end, initial)` + + Adaptive explicit RK integration. Euler/Heun/Midpoint/RK4 use step-doubling error estimates. RK23/RK45/DormandPrince/DOP853 use their embedded estimates. Multistep and implicit methods require 'solveIVP' to preserve their grid/history. + +Original: [`HMath.ODE.solveAdaptive`](haskell/HMath-ODE.md#v:solveAdaptive). + +```haskell +Method -> ODEOptions -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_adaptive(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +``` + +## `ode.interpolate_trajectory` + +`ode.interpolate_trajectory(trajectory, t)` + + Cubic Hermite interpolation inside the trajectory's closed time range. Extrapolation, malformed public trajectories and repeated sample times fail. + +Original: [`HMath.ODE.interpolateTrajectory`](haskell/HMath-ODE.md#v:interpolateTrajectory). + +```haskell +Trajectory -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_ode_interpolate_trajectory(hmath_context *context, const hmath_value *trajectory, const hmath_value *t, hmath_value **out); +``` + +## `ode.any_direction` + +`ode.any_direction()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.AnyDirection`](haskell/HMath-ODE.md#v:AnyDirection). + +```haskell +EventDirection +``` + +```c +hmath_status hmath_ode_any_direction(hmath_context *context, hmath_value **out); +``` + +## `ode.rising` + +`ode.rising()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Rising`](haskell/HMath-ODE.md#v:Rising). + +```haskell +EventDirection +``` + +```c +hmath_status hmath_ode_rising(hmath_context *context, hmath_value **out); +``` + +## `ode.falling` + +`ode.falling()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Falling`](haskell/HMath-ODE.md#v:Falling). + +```haskell +EventDirection +``` + +```c +hmath_status hmath_ode_falling(hmath_context *context, hmath_value **out); +``` + +## `ode.event` + +`ode.event(event_time, event_state)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Event`](haskell/HMath-ODE.md#v:Event). + +```haskell +Double -> [Double] -> Event +``` + +```c +hmath_status hmath_ode_event(hmath_context *context, const hmath_value *event_time, const hmath_value *event_state, hmath_value **out); +``` + +## `ode.event_time` + +`ode.event_time(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.eventTime`](haskell/HMath-ODE.md#v:eventTime). + +```haskell +Event -> Double +``` + +```c +hmath_status hmath_ode_event_time(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.event_state` + +`ode.event_state(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.eventState`](haskell/HMath-ODE.md#v:eventState). + +```haskell +Event -> [Double] +``` + +```c +hmath_status hmath_ode_event_state(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ode.locate_events` + +`ode.locate_events(direction, tolerance, function, trajectory)` + + Locate bracketed sign-changing events by dense-output bisection. Tangential roots and multiple roots inside one sample interval are not guaranteed. + +Original: [`HMath.ODE.locateEvents`](haskell/HMath-ODE.md#v:locateEvents). + +```haskell +EventDirection -> Double -> (Double -> [Double] -> Double) -> Trajectory -> Either MathError [Event] +``` + +```c +hmath_status hmath_ode_locate_events(hmath_context *context, const hmath_value *direction, const hmath_value *tolerance, const hmath_value *function, const hmath_value *trajectory, hmath_value **out); +``` + +## `ode.solve_boundary` + +`ode.solve_boundary(method, options, panels, f, boundary, start, end, guess)` + + Shooting boundary-value solver: all initial-state components are unknown. The boundary callback takes initial/final states and returns n residuals. Returns the trajectory matching a locally converged shooting root; convergence is local and depends on the supplied initial guess. + +Original: [`HMath.ODE.solveBoundary`](haskell/HMath-ODE.md#v:solveBoundary). + +```haskell +Method -> ODEOptions -> Int -> ODE -> ([Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_boundary(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *boundary, const hmath_value *start, const hmath_value *end, const hmath_value *guess, hmath_value **out); +``` + +## `ode.solve_dae` + +`ode.solve_dae(options, panels, residual, start, end, initial, initial_derivative)` + + Index-one implicit DAE driver F(t,y,y')=0 with backward differences. Initial y and y' must be consistent to the configured tolerance. Each subsequent state is obtained by a full residual Newton solve. + +Original: [`HMath.ODE.solveDAE`](haskell/HMath-ODE.md#v:solveDAE). + +```haskell +ODEOptions -> Int -> (Double -> [Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_dae(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *residual, const hmath_value *start, const hmath_value *end, const hmath_value *initial, const hmath_value *initial_derivative, hmath_value **out); +``` + +## `ode.symplectic_euler` + +`ode.symplectic_euler()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.SymplecticEuler`](haskell/HMath-ODE.md#v:SymplecticEuler). + +```haskell +HamiltonianMethod +``` + +```c +hmath_status hmath_ode_symplectic_euler(hmath_context *context, hmath_value **out); +``` + +## `ode.verlet` + +`ode.verlet()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Verlet`](haskell/HMath-ODE.md#v:Verlet). + +```haskell +HamiltonianMethod +``` + +```c +hmath_status hmath_ode_verlet(hmath_context *context, hmath_value **out); +``` + +## `ode.leapfrog` + +`ode.leapfrog()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.ODE.Leapfrog`](haskell/HMath-ODE.md#v:Leapfrog). + +```haskell +HamiltonianMethod +``` + +```c +hmath_status hmath_ode_leapfrog(hmath_context *context, hmath_value **out); +``` + +## `ode.solve_hamiltonian` + +`ode.solve_hamiltonian(method, panels, velocity, force, start, end, q0, p0)` + + Fixed-step symplectic integration; output states concatenate q then p. Verlet is kick-drift-kick; Leapfrog is drift-kick-drift with integer-time output momenta. These equivalent second-order splittings have distinct order. + +Original: [`HMath.ODE.solveHamiltonian`](haskell/HMath-ODE.md#v:solveHamiltonian). + +```haskell +HamiltonianMethod -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_hamiltonian(hmath_context *context, const hmath_value *method, const hmath_value *panels, const hmath_value *velocity, const hmath_value *force, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *p0, hmath_value **out); +``` + +## `ode.solve_nystrom` + +`ode.solve_nystrom(panels, acceleration, start, end, q0, v0)` + + Fourth-order explicit Runge-Kutta-Nystrom method for q''=a(t,q), with acceleration independent of velocity. State output concatenates q and q'. + +Original: [`HMath.ODE.solveNystrom`](haskell/HMath-ODE.md#v:solveNystrom). + +```haskell +Int -> (Double -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory +``` + +```c +hmath_status hmath_ode_solve_nystrom(hmath_context *context, const hmath_value *panels, const hmath_value *acceleration, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *v0, hmath_value **out); +``` + +## `ode.sensitivities` + +`ode.sensitivities(method, options, panels, h, family, parameters, start, end, initial)` + + Terminal-state parameter sensitivities by centered perturbation of the complete IVP solve. Parameters use the same explicit finite-difference step. + +Original: [`HMath.ODE.sensitivities`](haskell/HMath-ODE.md#v:sensitivities). + +```haskell +Method -> ODEOptions -> Int -> Double -> ([Double] -> ODE) -> [Double] -> Double -> Double -> [Double] -> Either MathError (Matrix Double) +``` + +```c +hmath_status hmath_ode_sensitivities(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *h, const hmath_value *family, const hmath_value *parameters, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +``` + +## `ode.equilibrium` + +`ode.equilibrium(options, field, guess)` + +Find an autonomous equilibrium by a locally convergent Newton solve. + +Original: [`HMath.ODE.equilibrium`](haskell/HMath-ODE.md#v:equilibrium). + +```haskell +ODEOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_ode_equilibrium(hmath_context *context, const hmath_value *options, const hmath_value *field, const hmath_value *guess, hmath_value **out); +``` + +## `ode.phase_trajectories` + +`ode.phase_trajectories(value, value2, value3, value4, value5, value6, value7)` + +Compute autonomous phase-space trajectories for independently supplied starts. + +Original: [`HMath.ODE.phaseTrajectories`](haskell/HMath-ODE.md#v:phaseTrajectories). + +```haskell +Method -> ODEOptions -> Int -> ([Double] -> [Double]) -> Double -> Double -> [[Double]] -> Either MathError [Trajectory] +``` + +```c +hmath_status hmath_ode_phase_trajectories(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, const hmath_value *value7, hmath_value **out); +``` + +## `ode.lyapunov_exponents` + +`ode.lyapunov_exponents(options, panels, difference_step, f, start, end, initial)` + + Full Lyapunov spectrum by the Benettin tangent-space method: integrate variational equations with RK4, then modified Gram-Schmidt at each sample. Finite-difference Jacobians are used; results are finite-time estimates. + +Original: [`HMath.ODE.lyapunovExponents`](haskell/HMath-ODE.md#v:lyapunovExponents). + +```haskell +ODEOptions -> Int -> Double -> ODE -> Double -> Double -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_ode_lyapunov_exponents(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *difference_step, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +``` + +## `pde.dirichlet` + +`pde.dirichlet(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.Dirichlet`](haskell/HMath-PDE.md#v:Dirichlet). + +```haskell +Double -> Boundary +``` + +```c +hmath_status hmath_pde_dirichlet(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.neumann` + +`pde.neumann(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.Neumann`](haskell/HMath-PDE.md#v:Neumann). + +```haskell +Double -> Boundary +``` + +```c +hmath_status hmath_pde_neumann(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.robin` + +`pde.robin(value, value2, value3)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.Robin`](haskell/HMath-PDE.md#v:Robin). + +```haskell +Double -> Double -> Double -> Boundary +``` + +```c +hmath_status hmath_pde_robin(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `pde.periodic` + +`pde.periodic()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.Periodic`](haskell/HMath-PDE.md#v:Periodic). + +```haskell +Boundary +``` + +```c +hmath_status hmath_pde_periodic(hmath_context *context, hmath_value **out); +``` + +## `pde.finite_difference` + +`pde.finite_difference()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.FiniteDifference`](haskell/HMath-PDE.md#v:FiniteDifference). + +```haskell +Discretization +``` + +```c +hmath_status hmath_pde_finite_difference(hmath_context *context, hmath_value **out); +``` + +## `pde.finite_volume` + +`pde.finite_volume()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.FiniteVolume`](haskell/HMath-PDE.md#v:FiniteVolume). + +```haskell +Discretization +``` + +```c +hmath_status hmath_pde_finite_volume(hmath_context *context, hmath_value **out); +``` + +## `pde.finite_element` + +`pde.finite_element()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.FiniteElement`](haskell/HMath-PDE.md#v:FiniteElement). + +```haskell +Discretization +``` + +```c +hmath_status hmath_pde_finite_element(hmath_context *context, hmath_value **out); +``` + +## `pde.pde_result` + +`pde.pde_result(pde_values, pde_residual, pde_error_estimate)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.PDEResult`](haskell/HMath-PDE.md#v:PDEResult). + +```haskell +[Double] -> Double -> Double -> PDEResult +``` + +```c +hmath_status hmath_pde_pde_result(hmath_context *context, const hmath_value *pde_values, const hmath_value *pde_residual, const hmath_value *pde_error_estimate, hmath_value **out); +``` + +## `pde.pde_values` + +`pde.pde_values(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.pdeValues`](haskell/HMath-PDE.md#v:pdeValues). + +```haskell +PDEResult -> [Double] +``` + +```c +hmath_status hmath_pde_pde_values(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.pde_residual` + +`pde.pde_residual(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.pdeResidual`](haskell/HMath-PDE.md#v:pdeResidual). + +```haskell +PDEResult -> Double +``` + +```c +hmath_status hmath_pde_pde_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.pde_error_estimate` + +`pde.pde_error_estimate(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.pdeErrorEstimate`](haskell/HMath-PDE.md#v:pdeErrorEstimate). + +```haskell +PDEResult -> Double +``` + +```c +hmath_status hmath_pde_pde_error_estimate(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.grid` + +`pde.grid(dims, bounds, periodic)` + +Construct a grid with >=3 nodes per axis; reject overflowing counts and rounded-away duplicate coordinates. + +Original: [`HMath.PDE.grid`](haskell/HMath-PDE.md#v:grid). + +```haskell +[Int] -> [(Double, Double)] -> [Bool] -> Either MathError Grid +``` + +```c +hmath_status hmath_pde_grid(hmath_context *context, const hmath_value *dims, const hmath_value *bounds, const hmath_value *periodic, hmath_value **out); +``` + +## `pde.grid_shape` + +`pde.grid_shape(value)` + +Number of nodes along each axis, preserving last-axis-fastest storage order. + +Original: [`HMath.PDE.gridShape`](haskell/HMath-PDE.md#v:gridShape). + +```haskell +Grid -> [Int] +``` + +```c +hmath_status hmath_pde_grid_shape(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.grid_spacing` + +`pde.grid_spacing(value)` + +Positive uniform distance between adjacent nodes on each axis. + +Original: [`HMath.PDE.gridSpacing`](haskell/HMath-PDE.md#v:gridSpacing). + +```haskell +Grid -> [Double] +``` + +```c +hmath_status hmath_pde_grid_spacing(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.flatten_index` + +`pde.flatten_index(value, value2)` + +Checked conversion of zero-based multidimensional node coordinates to a row-major flat index. + +Original: [`HMath.PDE.flattenIndex`](haskell/HMath-PDE.md#v:flattenIndex). + +```haskell +Grid -> [Int] -> Either MathError Int +``` + +```c +hmath_status hmath_pde_flatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `pde.unflatten_index` + +`pde.unflatten_index(value, value2)` + +Inverse checked row-major index conversion. + +Original: [`HMath.PDE.unflattenIndex`](haskell/HMath-PDE.md#v:unflattenIndex). + +```haskell +Grid -> Int -> Either MathError [Int] +``` + +```c +hmath_status hmath_pde_unflatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `pde.grid_coordinates` + +`pde.grid_coordinates(value)` + +Physical coordinates in flat storage order; periodic upper endpoints are omitted. + +Original: [`HMath.PDE.gridCoordinates`](haskell/HMath-PDE.md#v:gridCoordinates). + +```haskell +Grid -> [[Double]] +``` + +```c +hmath_status hmath_pde_grid_coordinates(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.assemble_pde` + +`pde.assemble_pde(value, value2, value3, value4, value5)` + +Assemble -kappa*Laplacian (FD) or -div(kappa grad) (FV/FEM) plus constant reaction; coefficient field is positive at every node. + +Original: [`HMath.PDE.assemblePDE`](haskell/HMath-PDE.md#v:assemblePDE). + +```haskell +Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Double -> Either MathError PDEOperator +``` + +```c +hmath_status hmath_pde_assemble_pde(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `pde.pde_stiffness` + +`pde.pde_stiffness(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.pdeStiffness`](haskell/HMath-PDE.md#v:pdeStiffness). + +```haskell +PDEOperator -> S.Sparse Double +``` + +```c +hmath_status hmath_pde_pde_stiffness(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.pde_mass` + +`pde.pde_mass(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.PDE.pdeMass`](haskell/HMath-PDE.md#v:pdeMass). + +```haskell +PDEOperator -> S.Sparse Double +``` + +```c +hmath_status hmath_pde_pde_mass(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.pde_boundary_load` + +`pde.pde_boundary_load(value)` + +Read boundary contributions, including prescribed values at essential rows. + +Original: [`HMath.PDE.pdeBoundaryLoad`](haskell/HMath-PDE.md#v:pdeBoundaryLoad). + +```haskell +PDEOperator -> [Double] +``` + +```c +hmath_status hmath_pde_pde_boundary_load(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `pde.solve_elliptic` + +`pde.solve_elliptic(value, value2)` + + Dense pivoted reference solve and independently recomputed infinity residual. The error estimate is backward residual, not continuum error. + +Original: [`HMath.PDE.solveElliptic`](haskell/HMath-PDE.md#v:solveElliptic). + +```haskell +PDEOperator -> [Double] -> Either MathError PDEResult +``` + +```c +hmath_status hmath_pde_solve_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `pde.poisson` + +`pde.poisson(method, g, bc, forcing)` + +Solve a unit-diffusivity zero-reaction Poisson problem with the selected spatial discretization. + +Original: [`HMath.PDE.poisson`](haskell/HMath-PDE.md#v:poisson). + +```haskell +Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError PDEResult +``` + +```c +hmath_status hmath_pde_poisson(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *forcing, hmath_value **out); +``` + +## `pde.laplace` + +`pde.laplace(method, g, bc)` + +Solve the corresponding homogeneous-source boundary-value problem. + +Original: [`HMath.PDE.laplace`](haskell/HMath-PDE.md#v:laplace). + +```haskell +Discretization -> Grid -> [(Boundary, Boundary)] -> Either MathError PDEResult +``` + +```c +hmath_status hmath_pde_laplace(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, hmath_value **out); +``` + +## `pde.helmholtz` + +`pde.helmholtz(method, g, bc, k, forcing)` + +Solve -Laplacian(u)-k²u=f; resonances/singular systems fail. + +Original: [`HMath.PDE.helmholtz`](haskell/HMath-PDE.md#v:helmholtz). + +```haskell +Discretization -> Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> Either MathError PDEResult +``` + +```c +hmath_status hmath_pde_helmholtz(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *k, const hmath_value *forcing, hmath_value **out); +``` + +## `pde.spatial_gradient` + +`pde.spatial_gradient(value, value2)` + +Second-order central spatial gradients; physical endpoints use second-order one-sided stencils. + +Original: [`HMath.PDE.spatialGradient`](haskell/HMath-PDE.md#v:spatialGradient). + +```haskell +Grid -> [Double] -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_pde_spatial_gradient(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `pde.laplacian_stencil` + +`pde.laplacian_stencil(g, bc, values)` + +Apply the FD Laplacian with ghost normal/Robin boundary data. Essential rows return prescribed-value minus current-value residuals. + +Original: [`HMath.PDE.laplacianStencil`](haskell/HMath-PDE.md#v:laplacianStencil). + +```haskell +Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_pde_laplacian_stencil(hmath_context *context, const hmath_value *g, const hmath_value *bc, const hmath_value *values, hmath_value **out); +``` + +## `pde.spectral_derivative` + +`pde.spectral_derivative(value, value2, value3, value4)` + +Periodic Fourier collocation derivative of order 0..8 along one axis; odd real Nyquist derivatives are zero. + +Original: [`HMath.PDE.spectralDerivative`](haskell/HMath-PDE.md#v:spectralDerivative). + +```haskell +Grid -> Int -> Int -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_pde_spectral_derivative(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `pde.spectral_laplacian` + +`pde.spectral_laplacian(g, values)` + +Sum periodic second Fourier derivatives over all spatial axes. + +Original: [`HMath.PDE.spectralLaplacian`](haskell/HMath-PDE.md#v:spectralLaplacian). + +```haskell +Grid -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_pde_spectral_laplacian(hmath_context *context, const hmath_value *g, const hmath_value *values, hmath_value **out); +``` + +## `pde.spectral_poisson` + +`pde.spectral_poisson(value, value2, value3)` + +Solve (-Laplacian+reaction)u=f spectrally; reaction>=0, and zero reaction requires a mean-free source with zero-mean solution gauge. + +Original: [`HMath.PDE.spectralPoisson`](haskell/HMath-PDE.md#v:spectralPoisson). + +```haskell +Grid -> Double -> [Double] -> Either MathError PDEResult +``` + +```c +hmath_status hmath_pde_spectral_poisson(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `pde.pseudo_spectral_diffusion` + +`pde.pseudo_spectral_diffusion(g, kappas, values)` + + Pseudospectral divergence(kappa*gradient u). Products are evaluated at collocation nodes; no implicit de-aliasing, so caller must resolve coefficients. + +Original: [`HMath.PDE.pseudoSpectralDiffusion`](haskell/HMath-PDE.md#v:pseudoSpectralDiffusion). + +```haskell +Grid -> [Double] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_pde_pseudo_spectral_diffusion(hmath_context *context, const hmath_value *g, const hmath_value *kappas, const hmath_value *values, hmath_value **out); +``` + +## `pde.method_of_lines` + +`pde.method_of_lines(value, value2, value3, value4, value5)` + + Method of lines with a constant assembled operator and checked time-source callback. Essential Dirichlet values remain constant in time; initial state must satisfy them. Consistent FEM mass is inverted on unconstrained rows. + +Original: [`HMath.PDE.methodOfLines`](haskell/HMath-PDE.md#v:methodOfLines). + +```haskell +O.Method -> PDEOperator -> (Double -> [Double]) -> [Double] -> [Double] -> Either MathError O.Trajectory +``` + +```c +hmath_status hmath_pde_method_of_lines(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `pde.heat` + +`pde.heat(value, value2, value3, value4, value5)` + + Explicit heat/diffusion uses RK4, with a conservative forward-Euler CFL check (therefore valid for RK4 too). Positive diffusivity and ordered times. + +Original: [`HMath.PDE.heat`](haskell/HMath-PDE.md#v:heat). + +```haskell +Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> [Double] -> Either MathError O.Trajectory +``` + +```c +hmath_status hmath_pde_heat(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `pde.diffusion` + +`pde.diffusion(method, g, bc, kappas, times, initial)` + +Variable positive nodal diffusivity, chosen spatial method and increasing output times; FEM uses a stricter consistent-mass CFL bound. + +Original: [`HMath.PDE.diffusion`](haskell/HMath-PDE.md#v:diffusion). + +```haskell +Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> [Double] -> [Double] -> Either MathError O.Trajectory +``` + +```c +hmath_status hmath_pde_diffusion(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *kappas, const hmath_value *times, const hmath_value *initial, hmath_value **out); +``` + +## `pde.wave` + +`pde.wave(g, speed, times, initial, velocity)` + + Periodic velocity-Verlet wave equation u_tt=c² Laplacian(u); returns u at requested equally or unequally spaced increasing times. Spectral Laplacian. + +Original: [`HMath.PDE.wave`](haskell/HMath-PDE.md#v:wave). + +```haskell +Grid -> Double -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_pde_wave(hmath_context *context, const hmath_value *g, const hmath_value *speed, const hmath_value *times, const hmath_value *initial, const hmath_value *velocity, hmath_value **out); +``` + +## `pde.advection` + +`pde.advection(value, value2, value3, value4)` + + Conservative first-order upwind periodic advection, central conservative variable-coefficient diffusion. Explicit Euler preserves constants and total mass for periodic data when the combined positivity CFL is satisfied. + +Original: [`HMath.PDE.advection`](haskell/HMath-PDE.md#v:advection). + +```haskell +Grid -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_pde_advection(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `pde.advection_diffusion` + +`pde.advection_diffusion(value, value2, value3, value4, value5)` + +Periodic upwind advection plus central diffusion using explicit Euler and the combined positivity CFL bound. + +Original: [`HMath.PDE.advectionDiffusion`](haskell/HMath-PDE.md#v:advectionDiffusion). + +```haskell +Grid -> [Double] -> Double -> [Double] -> [Double] -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_pde_advection_diffusion(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `pde.stability_limit` + +`pde.stability_limit(g, diffusivity, velocity)` + +Conservative explicit positivity bound 1/sum(|v|/h+2*kappa/h^2); infinity denotes a zero spatial operator. + +Original: [`HMath.PDE.stabilityLimit`](haskell/HMath-PDE.md#v:stabilityLimit). + +```haskell +Grid -> Double -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_pde_stability_limit(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, hmath_value **out); +``` + +## `pde.cfl_number` + +`pde.cfl_number(g, diffusivity, velocity, dt)` + +Requested nonnegative timestep divided by the conservative combined stability limit. + +Original: [`HMath.PDE.cflNumber`](haskell/HMath-PDE.md#v:cflNumber). + +```haskell +Grid -> Double -> [Double] -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_pde_cfl_number(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, const hmath_value *dt, hmath_value **out); +``` + +## `pde.manufactured_error` + +`pde.manufactured_error(g, exact, values)` + +Maximum absolute nodal difference from a finite exact-solution callback; this measures continuum error when an exact solution is known. + +Original: [`HMath.PDE.manufacturedError`](haskell/HMath-PDE.md#v:manufacturedError). + +```haskell +Grid -> ([Double] -> Double) -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_pde_manufactured_error(hmath_context *context, const hmath_value *g, const hmath_value *exact, const hmath_value *values, hmath_value **out); +``` + diff --git a/docs/reference/optimization-bindings.md b/docs/reference/optimization-bindings.md new file mode 100644 index 0000000..abe1a9c --- /dev/null +++ b/docs/reference/optimization-bindings.md @@ -0,0 +1,460 @@ +# Optimizer bindings + +The C and Python APIs call the original functions in `Optimization.Common`, +`FirstOrder`, `Local`, `Constrained` and `Global`. They preserve method +constructors, callbacks, result diagnostics, default options, evaluation budgets +and explicit stochastic seeds. The low-level optimizer-state ABI below remains +available alongside the structured solver API. + +Include `hmath_optimization.h` in C or C++. In Python, use +`from hmath import optimization`. These operations use binary64, matching the +original `Double` functions. There is no implicit FP32 optimizer implementation. + +## GradientMethod + +The mathematical methods and enumeration order are unchanged: + +| Haskell | C | Python `optimization.GradientMethod` | +| --- | --- | --- | +| `GradientDescent` | `HMATH_GRADIENT_DESCENT` | `GRADIENT_DESCENT` | +| `Momentum` | `HMATH_MOMENTUM` | `MOMENTUM` | +| `Nesterov` | `HMATH_NESTEROV` | `NESTEROV` | +| `AdaGrad` | `HMATH_ADAGRAD` | `ADAGRAD` | +| `RMSProp` | `HMATH_RMSPROP` | `RMSPROP` | +| `AdaDelta` | `HMATH_ADADELTA` | `ADADELTA` | +| `Adam` | `HMATH_ADAM` | `ADAM` | +| `AdamW` | `HMATH_ADAMW` | `ADAMW` | +| `AMSGrad` | `HMATH_AMSGRAD` | `AMSGRAD` | +| `AdaMax` | `HMATH_ADAMAX` | `ADAMAX` | +| `Nadam` | `HMATH_NADAM` | `NADAM` | +| `RAdam` | `HMATH_RADAM` | `RADAM` | + +## initialize_optimizer / hmath_initialize_optimizer + +Original: [initializeOptimizer](haskell/HMath-Optimization-FirstOrder.md#v:initializeOptimizer). + +```c +hmath_status hmath_initialize_optimizer( + hmath_context *context, ptrdiff_t dimension, hmath_optimizer_state **out); +``` + +`optimization.initialize_optimizer(dimension)` and +`optimization.OptimizerState(dimension)` construct the same state. + +| Parameter | Meaning | +| --- | --- | +| `dimension` | Number of parameters, represented as Haskell `Int`. Negative values retain the original `InvalidArgument "negative optimizer dimension"` error. Zero is valid. | +| `context` | C cancellation context, or `NULL`. Checked before entry. | +| `out` | C address receiving one owned state reference on success; untouched on failure. | + +The result is an immutable state with zero initial moments/history. A state holds +the Haskell runtime alive. `hmath_runtime_shutdown` returns `HMATH_BUSY` while any +state remains alive. + +## optimizer_step / hmath_optimizer_step + +Original: [optimizerStep](haskell/HMath-Optimization-FirstOrder.md#v:optimizerStep). + +```c +hmath_status hmath_optimizer_step( + hmath_context *context, hmath_gradient_method method, double rate, + const hmath_optimizer_state *state, + const double *parameters, size_t parameter_count, + const double *gradient, size_t gradient_count, + double *out_parameters, size_t out_capacity, + hmath_optimizer_state **out_state); +``` + +Python: `optimization.optimizer_step(method, rate, state, parameters, gradient)`. + +| Parameter | Meaning | +| --- | --- | +| `method` | Original `GradientMethod` constructor; see the table above. | +| `rate` | Positive finite learning rate. No default is introduced. | +| `state` | Live state returned by initialization or a previous step. | +| `parameters` | Current parameters, in parameter order. | +| `gradient` | Gradient components in the same order. The binding does not compute or modify the gradient. | +| `parameter_count`, `gradient_count` | C lengths of the corresponding readable buffers. | +| `context` | C cancellation context, or `NULL`; checked before entry. | +| `out_parameters`, `out_capacity` | C writable result buffer and its capacity in doubles. Capacity must be at least `parameter_count`. | +| `out_state` | C address receiving one owned reference to the new state. | + +Python returns `(new_parameters, new_state)`; C writes those same two results. +The original state is unchanged and may be reused to branch a computation. +All output memory must be disjoint from the inputs and other outputs. On failure +both C outputs remain untouched. Inputs are borrowed only for the call; each +thread must retain a state reference while using it. Independent calls can share +an immutable state, but must use separate output buffers. + +Original constants remain unchanged: β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸; +RMSProp/AdaDelta use ρ = 0.9, and AdamW uses weight decay 0.01. +`Nesterov` in this function applies the original corrected momentum direction; +it does not perform the look-ahead objective evaluation of `minimizeGradient`. + +Non-finite parameters, gradients, state or results return the original +`NonFiniteResult`. Nonpositive rates or mismatched dimensions return the original +`InvalidArgument "optimizer rate or state shape"`. A Haskell `MathError` is status +11 in C and `HMathError` with `status == 11` in Python; the error message retains +the constructor and payload. Invalid C pointers/enum representations, insufficient +buffer capacity and allocation failures are separate binding errors. + +## State ownership + +`hmath_optimizer_state_retain(state)` adds a reference; +`hmath_optimizer_state_release(state)` releases one. Both accept `NULL` as a no-op. +Final release frees the Haskell state and its runtime reservation. Never use a +released state or release the last reference concurrently with a call using it. + +Python `state.close()` is idempotent. A `with state:` block closes that reference +on exit; the destructor is a fallback. A closed state rejects further steps with +`ValueError`. Each returned state is independently owned. + +```python +from hmath import optimization + +with optimization.initialize_optimizer(2) as initial: + parameters, updated = optimization.optimizer_step( + optimization.GradientMethod.ADAM, + 0.01, + initial, + [1.0, -2.0], + [2.0, -4.0], + ) + with updated: + assert len(parameters) == 2 + assert parameters[0] < 1.0 + assert parameters[1] > -2.0 +``` + +See also: [original Haskell optimizer API](haskell/HMath-Optimization-FirstOrder.md), +[C runtime and errors](c.md#runtime), [numeric bindings](numeric-bindings.md). + +## Solver records and options + +```python +from hmath import optimization as opt + +options = opt.OptimizeOptions( + max_iterations=1000, + max_evaluations=20000, + tolerance=1e-8, + learning_rate=0.01, +) +result = opt.minimize_quasi_newton( + opt.BFGS, + options, + lambda point: sum(x*x for x in point), + lambda point: [2*x for x in point], + [1.0, -2.0], +) +print(result.point, result.value, result.converged) +``` + +`default_optimize_options()` returns the original defaults shown above. Options +are immutable Python records; create another `OptimizeOptions` to change them. +The source validates options inside the relevant operation. Constructor calls +do not invent stricter validation. + +| Record | Fields, in constructor order | +| --- | --- | +| `OptimizeOptions` | `max_iterations`: iteration budget; `max_evaluations`: evaluation budget; `tolerance`: stopping tolerance; `learning_rate`: positive update rate | +| `OptimizeResult` | `point`: final parameter vector; `value`: objective; `gradient_norm`: original solver's residual diagnostic; `iterations`: source iteration count; `evaluations`: source evaluation count; `converged`: original stopping flag | +| `LPResult` | `point`: primal variables; `value`: objective; `basis`: retained zero-based basis indices; `iterations`: source pivot count | +| `EarlyStopping` | `best_score`: `None` or best score; `stale_steps`: stale observation count; `stopped`: stop flag | + +The `opt_*`, `lp_*`, `best_score`, `stale_steps` and `stopped` functions expose +original record selectors as well. They are equivalent to reading the matching +record field. A result's diagnostic is solver specific: scalar minimization +reports bracket width, projected/proximal methods report a mapping residual, +and global methods report spread or step size. A global convergence flag does +not certify global optimality. Some algorithms return their incumbent with +`converged=False` on exhaustion; others return `NonConvergence`. Those original +choices and evaluation-accounting rules remain unchanged. + +## Callbacks and returned functions + +| Source/Python type | Python arguments | Successful result | +| --- | --- | --- | +| `Objective` | `point` | scalar `float` | +| `Gradient` | `point` | vector | +| `Hessian` | `point` | rows of a matrix | +| `ResidualFunction` | `point` | residual vector | +| `JacobianFunction` | `point` | Jacobian rows | +| Projection | `point` | projected vector | +| Proximal operator | `rate, point` | vector | +| Iterate monitor | `OptimizeResult` | `bool`; `False` stops the original monitor-based minimizer | + +`minimize_scalar` alone passes a scalar to its objective. Python callbacks return +ordinary values or raise [a structured MathError](errors.md#checked-callbacks) +to return the original `Left` branch. Such failures remain recoverable by the +original solver; for example, feasible barrier backtracking retries a rejected +`DomainError`. Unexpected Python exceptions abort the call and are re-raised +after temporary native values are cleaned up. + +`mini_batch_gradient(gradients)` returns a callable original gradient; +`weighted_objective(weights, objectives)` returns a callable original objective. +They evaluate lazily when called. Use the returned function as a context manager +or call `.close()`; its callback references remain alive transitively. Empty +batches, wrong gradient lengths and invalid weights retain original errors. +A callback may call other HMath operations reentrantly. It must not request +final runtime shutdown. + +All these original solvers operate on `Double`. Supplying Python or C float32 +values does not select an FP32 solver. Vectors/matrices are lists of binary64 +values at this API, with no added rectangularization, truncation or finite-value +checks. Exact generic `transpose` accepts shared Value elements (including +integers, rationals, strings and structured native values) and preserves the +original ragged-list behavior. + +## Methods and solver contracts + +Learning schedules are `ConstantRate(rate)`, +`StepDecay(initial_rate, period, decay)`, +`ExponentialDecay(initial_rate, decay)`, +`CosineAnnealing(maximum, minimum, period)` and `Warmup(steps, base)`. +`learning_rate(schedule, step)` calls the original schedule validation and +formula, including nesting. `early_stopping(patience, min_delta, value, state)` +minimizes the observed score and returns the next immutable state. + +Scalar methods are `GoldenSection`, `TernarySearch`, `BrentSearch`; the finite +bracket must satisfy `lower < upper`. Quasi-Newton methods are `BFGS`, +`LBFGS(memory)`, `DFP`, `SR1`. Newton methods are `Newton`, `NewtonCG`, +`TrustRegion(radius)`, `Dogleg(radius)`; Hessians are supplied explicitly. +Least-squares losses are `SquaredLoss`, `HuberLoss(scale)`, `CauchyLoss(scale)`, +`SoftL1(scale)`; `least_squares` also takes the original positive damping value. +`nelder_mead` and `powell` need only an objective. `nonlinear_cg` takes an +objective and gradient. + +`stochastic_gradient` makes one pass over the explicit gradients in order, +returning `(point, OptimizerState)`; ordering/shuffling remain caller owned. +`projected_gradient` projects each update. `proximal_gradient` and `fista` call +the supplied proximal operator. `coordinate_descent` requires nonempty blocks +that partition the zero-based parameter indices exactly once. No additional +momentum constants or tuning parameters are introduced by the binding. + +Constraints are `Equality(objective, gradient)` for `g(x) = 0` and +`LessEqual(objective, gradient)` for `g(x) <= 0`. `feasibility` returns the maximum +absolute equality or positive inequality violation. `constrained_minimize` +accepts `QuadraticPenalty`, `LogBarrier`, `InteriorPoint`, +`AugmentedLagrangian`; barrier methods require strictly feasible inequality-only +initial points. `slsqp` takes explicit Hessians; `cobyla` takes constraint +objectives without derivative callbacks and an initial radius. + +`linear_programming` minimizes `cost·x` with `A x <= rhs` and `x >= 0`, including +phase I for negative right-hand sides. `revised_simplex` instead uses its +original equality-form feasible-basis contract: provide a full row-rank matrix +and a valid feasible basis, with indices into its columns. +`quadratic_programming` minimizes `0.5*xᵀ*H*x + costᵀ*x` under `A x <= rhs`; +its budget bounds dense active-set enumeration. These are the original bounded +dense reference algorithms. `pareto_front` returns zero-based indices of +nondominated minimization vectors. `weighted_objective` keeps each supplied +objective and its original weight validation. + +Global methods are `SimulatedAnnealing`, `DifferentialEvolution`, +`GeneticAlgorithm`, `ParticleSwarm`, `CMAES`. `global_minimize` requires a +population size of at least four and finite `(lower, upper)` bounds with +`lower < upper`. Its seed is the exact original unsigned 64-bit seed, including +values above 2⁵³. `basin_hopping` additionally takes temperature, hop count and +an in-bounds initial vector; it performs original local Nelder–Mead descents. +No global RNG, system entropy or replacement stochastic implementation is used. + +## Structured C and C++ solver API + +Include `hmath_optimization.h` (which includes `hmath_optimization_all.h`). Every +named structured wrapper follows the source argument order in the tables below: + +```c +hmath_status hmath_optimization_minimize_quasi_newton( + hmath_context *context, + const hmath_value *method, + const hmath_value *options, + const hmath_value *objective, + const hmath_value *gradient, + const hmath_value *initial, + hmath_value **out); +``` + +Arguments use [shared immutable Values](values.md): scalar `Double`, `Int` +index, exact `Word64` scalar seed, lists/tuples, or opaque original records and +method constructors. Constructor wrappers end in `_create`. Selectors return +copied Values; numerical solvers return an `OptimizeResult` or `LPResult` Value. +Release every owned output with `hmath_value_release`. Inputs are borrowed for +the call; immutable sharing across threads is allowed when each user retains +its own live reference. Final release must not race a call using the same last +reference. Output pointer storage must be disjoint from inputs and remains +untouched on failure. + +Create function Values with `hmath_optimization_callback(context, role, +function, userdata, out)`. Roles are 0 objective, 1 gradient/projection, +2 Hessian/Jacobian, 3 proximal operator, 4 monitor. The C callback receives one +borrowed Value: a parameter list, a `(rate, point)` tuple for role 3, or a result +record for role 4. A scalar-minimization objective receives `[x]` in C. Return +one owned Value reference on success (retain a borrowed input before returning +it). On `HMATH_MATH_ERROR`, fill the `hmath_math_error` wire; other failures +abort the operation. Function pointers, userdata and borrowed error buffers +must remain valid until consumed; pointers/userdata used in a derived function +or constraint remain live until its final release. Calls are synchronous and +may reenter HMath; callback/thread safety remains the caller's responsibility. + +`hmath_optimization_function_apply` invokes a returned function Value with an +array of argument Values. `hmath_optimization_state_import` and `_state_export` +convert between a structured state Value and the compatible low-level +`hmath_optimizer_state` handle; each conversion returns independent ownership. +All live native Values and optimizer states reserve the Haskell runtime. + +## Named function mapping + +The following signatures give the exact argument order. Python `None` denotes +a source `Nothing`/unit as appropriate; all source checked errors use the +structured error contract above. For full mathematical formulas and source +validation conditions, follow the defining Haskell module for each group. + +### Common + +[Original Haskell reference](haskell/HMath-Optimization-Common.md). + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `OptimizeOptions(max_iterations, max_evaluations, tolerance, learning_rate)` | `OptimizeOptions` | `hmath_optimization_optimize_options_create` | +| `default_optimize_options()` | `OptimizeOptions` | `hmath_optimization_default_optimize_options` | +| `OptimizeResult(point, value, gradient_norm, iterations, evaluations, converged)` | `OptimizeResult` | `hmath_optimization_optimize_result_create` | +| `EarlyStopping(best_score, stale_steps, stopped)` | `EarlyStopping` | `hmath_optimization_early_stopping_create` | +| `ConstantRate(rate)` | `LearningRate` | `hmath_optimization_constant_rate_create` | +| `StepDecay(initial_rate, period, decay)` | `LearningRate` | `hmath_optimization_step_decay_create` | +| `ExponentialDecay(initial_rate, decay)` | `LearningRate` | `hmath_optimization_exponential_decay_create` | +| `CosineAnnealing(maximum, minimum, period)` | `LearningRate` | `hmath_optimization_cosine_annealing_create` | +| `Warmup(steps, base)` | `LearningRate` | `hmath_optimization_warmup_create` | +| `Armijo` | `LineSearch` | `hmath_optimization_armijo_create` | +| `StrongWolfe` | `LineSearch` | `hmath_optimization_strong_wolfe_create` | +| `checked_options(options)` | `None` | `hmath_optimization_checked_options` | +| `checked_point(point)` | `None` | `hmath_optimization_checked_point` | +| `checked_value(objective, point)` | `Double` | `hmath_optimization_checked_value` | +| `checked_gradient(gradient, point)` | `Vector` | `hmath_optimization_checked_gradient` | +| `check_budget(options, evaluations)` | `None` | `hmath_optimization_check_budget` | +| `dot(left, right)` | `original field/helper value` | `hmath_optimization_dot` | +| `add(left, right)` | `original field/helper value` | `hmath_optimization_add` | +| `sub(left, right)` | `original field/helper value` | `hmath_optimization_sub` | +| `outer(left, right)` | `original field/helper value` | `hmath_optimization_outer` | +| `norm(values)` | `Double` | `hmath_optimization_norm` | +| `scale(factor, values)` | `Vector` | `hmath_optimization_scale` | +| `identity(dimension)` | `Matrix` | `hmath_optimization_identity` | +| `mat_vec(matrix, vector)` | `Vector` | `hmath_optimization_mat_vec` | +| `mat_mul(left, right)` | `Matrix` | `hmath_optimization_mat_mul` | +| `transpose(rows)` | `GenericMatrix` | `hmath_optimization_transpose` | +| `solve_dense(matrix, rhs)` | `Vector` | `hmath_optimization_solve_dense` | +| `result(iterations, evaluations, converged, objective, gradient, point)` | `OptimizeResult` | `hmath_optimization_result` | +| `learning_rate(schedule, step)` | `Double` | `hmath_optimization_learning_rate` | +| `early_stopping(patience, min_delta, value, state)` | `EarlyStopping` | `hmath_optimization_early_stopping` | +| `line_search(method, budget, objective, gradient, point, direction, value, point_gradient)` | `original tuple` | `hmath_optimization_line_search` | +| `opt_max_iterations(value)` | `original field/helper value` | `hmath_optimization_opt_max_iterations` | +| `opt_max_evaluations(value)` | `original field/helper value` | `hmath_optimization_opt_max_evaluations` | +| `opt_tolerance(value)` | `original field/helper value` | `hmath_optimization_opt_tolerance` | +| `opt_learning_rate(value)` | `original field/helper value` | `hmath_optimization_opt_learning_rate` | +| `opt_point(value)` | `original field/helper value` | `hmath_optimization_opt_point` | +| `opt_value(value)` | `original field/helper value` | `hmath_optimization_opt_value` | +| `opt_gradient_norm(value)` | `original field/helper value` | `hmath_optimization_opt_gradient_norm` | +| `opt_iterations(value)` | `original field/helper value` | `hmath_optimization_opt_iterations` | +| `opt_evaluations(value)` | `original field/helper value` | `hmath_optimization_opt_evaluations` | +| `opt_converged(value)` | `original field/helper value` | `hmath_optimization_opt_converged` | +| `best_score(value)` | `original field/helper value` | `hmath_optimization_best_score` | +| `stale_steps(value)` | `original field/helper value` | `hmath_optimization_stale_steps` | +| `stopped(value)` | `original field/helper value` | `hmath_optimization_stopped` | + +### FirstOrder + +[Original Haskell reference](haskell/HMath-Optimization-FirstOrder.md). + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `GradientMethod.GRADIENT_DESCENT` | `GradientMethod` | `hmath_optimization_gradient_descent_create` | +| `GradientMethod.MOMENTUM` | `GradientMethod` | `hmath_optimization_momentum_create` | +| `GradientMethod.NESTEROV` | `GradientMethod` | `hmath_optimization_nesterov_create` | +| `GradientMethod.ADAGRAD` | `GradientMethod` | `hmath_optimization_ada_grad_create` | +| `GradientMethod.RMSPROP` | `GradientMethod` | `hmath_optimization_rms_prop_create` | +| `GradientMethod.ADADELTA` | `GradientMethod` | `hmath_optimization_ada_delta_create` | +| `GradientMethod.ADAM` | `GradientMethod` | `hmath_optimization_adam_create` | +| `GradientMethod.ADAMW` | `GradientMethod` | `hmath_optimization_adam_w_create` | +| `GradientMethod.AMSGRAD` | `GradientMethod` | `hmath_optimization_ams_grad_create` | +| `GradientMethod.ADAMAX` | `GradientMethod` | `hmath_optimization_ada_max_create` | +| `GradientMethod.NADAM` | `GradientMethod` | `hmath_optimization_nadam_create` | +| `GradientMethod.RADAM` | `GradientMethod` | `hmath_optimization_r_adam_create` | +| `initialize_optimizer(dimension)` | `OptimizerState` | `hmath_optimization_initialize_optimizer` | +| `optimizer_step(method, rate, state, parameters, gradient)` | `original tuple` | `hmath_optimization_optimizer_step` | +| `minimize_gradient(method, options, objective, gradient, initial)` | `OptimizeResult` | `hmath_optimization_minimize_gradient` | +| `minimize_gradient_with_callback(monitor, method, options, objective, gradient, initial)` | `OptimizeResult` | `hmath_optimization_minimize_gradient_with_callback` | +| `stochastic_gradient(method, rate, gradients, initial)` | `original tuple` | `hmath_optimization_stochastic_gradient` | +| `mini_batch_gradient(gradients)` | `owned callable` | `hmath_optimization_mini_batch_gradient` | +| `projected_gradient(options, objective, gradient, project, initial)` | `OptimizeResult` | `hmath_optimization_projected_gradient` | +| `proximal_gradient(options, objective, gradient, prox, initial)` | `OptimizeResult` | `hmath_optimization_proximal_gradient` | +| `fista(options, objective, gradient, prox, initial)` | `OptimizeResult` | `hmath_optimization_fista` | +| `coordinate_descent(blocks, options, objective, gradient, initial)` | `OptimizeResult` | `hmath_optimization_coordinate_descent` | + +### Local + +[Original Haskell reference](haskell/HMath-Optimization-Local.md). + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `GoldenSection` | `ScalarMethod` | `hmath_optimization_golden_section_create` | +| `TernarySearch` | `ScalarMethod` | `hmath_optimization_ternary_search_create` | +| `BrentSearch` | `ScalarMethod` | `hmath_optimization_brent_search_create` | +| `minimize_scalar(method, options, objective, lower, upper)` | `OptimizeResult` | `hmath_optimization_minimize_scalar` | +| `BFGS` | `QuasiNewton` | `hmath_optimization_bfgs_create` | +| `DFP` | `QuasiNewton` | `hmath_optimization_dfp_create` | +| `SR1` | `QuasiNewton` | `hmath_optimization_sr1_create` | +| `LBFGS(memory)` | `QuasiNewton` | `hmath_optimization_lbfgs_create` | +| `minimize_quasi_newton(method, options, objective, gradient, initial)` | `OptimizeResult` | `hmath_optimization_minimize_quasi_newton` | +| `Newton` | `NewtonMethod` | `hmath_optimization_newton_create` | +| `NewtonCG` | `NewtonMethod` | `hmath_optimization_newton_cg_create` | +| `TrustRegion(radius)` | `NewtonMethod` | `hmath_optimization_trust_region_create` | +| `Dogleg(radius)` | `NewtonMethod` | `hmath_optimization_dogleg_create` | +| `minimize_newton(method, options, objective, gradient, hessian, initial)` | `OptimizeResult` | `hmath_optimization_minimize_newton` | +| `nonlinear_cg(options, objective, gradient, initial)` | `OptimizeResult` | `hmath_optimization_nonlinear_cg` | +| `SquaredLoss` | `Loss` | `hmath_optimization_squared_loss_create` | +| `HuberLoss(scale)` | `Loss` | `hmath_optimization_huber_loss_create` | +| `CauchyLoss(scale)` | `Loss` | `hmath_optimization_cauchy_loss_create` | +| `SoftL1(scale)` | `Loss` | `hmath_optimization_soft_l1_create` | +| `least_squares(loss, damping, options, residual, jacobian, initial)` | `OptimizeResult` | `hmath_optimization_least_squares` | +| `nelder_mead(options, objective, initial)` | `OptimizeResult` | `hmath_optimization_nelder_mead` | +| `powell(initial_step, options, objective, initial)` | `OptimizeResult` | `hmath_optimization_powell` | + +### Constrained + +[Original Haskell reference](haskell/HMath-Optimization-Constrained.md). + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `Equality(objective, gradient)` | `Constraint` | `hmath_optimization_equality_create` | +| `LessEqual(objective, gradient)` | `Constraint` | `hmath_optimization_less_equal_create` | +| `feasibility(constraints, point)` | `Double` | `hmath_optimization_feasibility` | +| `QuadraticPenalty` | `PenaltyMethod` | `hmath_optimization_quadratic_penalty_create` | +| `LogBarrier` | `PenaltyMethod` | `hmath_optimization_log_barrier_create` | +| `InteriorPoint` | `PenaltyMethod` | `hmath_optimization_interior_point_create` | +| `AugmentedLagrangian` | `PenaltyMethod` | `hmath_optimization_augmented_lagrangian_create` | +| `constrained_minimize(method, options, objective, gradient, constraints, initial)` | `OptimizeResult` | `hmath_optimization_constrained_minimize` | +| `LPResult(point, value, basis, iterations)` | `LPResult` | `hmath_optimization_lp_result_create` | +| `linear_programming(budget, tolerance, cost, matrix, rhs)` | `LPResult` | `hmath_optimization_linear_programming` | +| `revised_simplex(budget, tolerance, cost, matrix, rhs, basis)` | `LPResult` | `hmath_optimization_revised_simplex` | +| `quadratic_programming(budget, tolerance, hessian, cost, matrix, rhs)` | `OptimizeResult` | `hmath_optimization_quadratic_programming` | +| `slsqp(options, objective, gradient, hessian, constraints, initial)` | `OptimizeResult` | `hmath_optimization_slsqp` | +| `cobyla(initial_radius, options, objective, constraints, initial)` | `OptimizeResult` | `hmath_optimization_cobyla` | +| `weighted_objective(weights, objectives)` | `owned callable` | `hmath_optimization_weighted_objective` | +| `pareto_front(points)` | `list[int]` | `hmath_optimization_pareto_front` | +| `lp_point(value)` | `original field/helper value` | `hmath_optimization_lp_point` | +| `lp_value(value)` | `original field/helper value` | `hmath_optimization_lp_value` | +| `lp_basis(value)` | `original field/helper value` | `hmath_optimization_lp_basis` | +| `lp_iterations(value)` | `original field/helper value` | `hmath_optimization_lp_iterations` | + +### Global + +[Original Haskell reference](haskell/HMath-Optimization-Global.md). + +| Python callable or constructor | Result | C wrapper | +| --- | --- | --- | +| `SimulatedAnnealing` | `GlobalMethod` | `hmath_optimization_simulated_annealing_create` | +| `DifferentialEvolution` | `GlobalMethod` | `hmath_optimization_differential_evolution_create` | +| `GeneticAlgorithm` | `GlobalMethod` | `hmath_optimization_genetic_algorithm_create` | +| `ParticleSwarm` | `GlobalMethod` | `hmath_optimization_particle_swarm_create` | +| `CMAES` | `GlobalMethod` | `hmath_optimization_cmaes_create` | +| `global_minimize(method, population_size, seed, options, bounds, objective)` | `OptimizeResult` | `hmath_optimization_global_minimize` | +| `basin_hopping(seed, temperature, hops, options, bounds, objective, initial)` | `OptimizeResult` | `hmath_optimization_basin_hopping` | diff --git a/docs/reference/polynomial.md b/docs/reference/polynomial.md new file mode 100644 index 0000000..23ffa75 --- /dev/null +++ b/docs/reference/polynomial.md @@ -0,0 +1,547 @@ +# Polynomial and power series + +These bindings call the original Haskell functions. Coefficients are ascending: `[a0,a1,...]` represents `a0+a1*x+...`. Polynomial construction removes trailing exact zeros; the zero polynomial has `degree is None`. Power series retain their full finite coefficient sequence, including trailing zeros. They use the source truncation rules. No tolerance, budget or arithmetic algorithm is substituted. + +Use `from hmath import polynomial as p`. Constructors accept `dtype="float64"` by default; choose `"float32"`, `"integer"`, `"rational"`, `"complex64"` or `"complex128"` explicitly. Bounded integral types are also available for Num operations. Rational results use `fractions.Fraction` and integers have no FP intermediary. Binary operations require matching coefficient types. A missing original typeclass instance returns `HMATH_UNSUPPORTED`; for example, polynomial division requires Fractional, and logarithmic series require ordered Floating coefficients. + +```python +from fractions import Fraction +from hmath import polynomial as p +f = p.polynomial([1, 0, -2], dtype="rational") +g = p.differentiate_polynomial(f) +assert p.evaluate_polynomial(g, Fraction(3, 2)) == -6 +f.close() +g.close() +``` + +C functions borrow inputs for the duration of the call and return independently owned `hmath_value` handles. Construct typed scalar/list/tuple values with `hmath_value.h`; release each owned handle once. `prototype` selects the coefficient type, including for empty lists. Outputs remain untouched on failure. Original `Left MathError` values return status 11 and retain constructor/fields/message through `hmath_last_math_error`. Python raises `HMathError` with `.math_error`. Opaque owners support `close()` and context management. All returned data are immutable; concurrent independent calls may share inputs. + +## `polynomial` + +Construct a polynomial, deleting trailing exact zeros (no floating tolerance). + +`polynomial(coefficients, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `coefficients`. + +```c +hmath_status hmath_polynomial_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out); +``` + +## `coefficients` + +Ascending coefficients, with no trailing zero; zero gives an empty list. + +`coefficients(polynomial)` returns ascending coefficient list. Parameters follow the original source order: `polynomial`. + +```c +hmath_status hmath_polynomial_coefficients(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `polynomial_degree` + +Degree of a nonzero polynomial; zero has no degree. + +`polynomial_degree(polynomial)` returns integer degree, or None for the zero polynomial. Parameters follow the original source order: `polynomial`. + +```c +hmath_status hmath_polynomial_polynomial_degree(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `evaluate_polynomial` + +Horner evaluation, with the constant coefficient first in storage. + +`evaluate_polynomial(polynomial, x)` returns coefficient scalar. Parameters follow the original source order: `polynomial`, `x`. + +```c +hmath_status hmath_polynomial_evaluate_polynomial(hmath_context *context, const hmath_value *polynomial, const hmath_value *x, hmath_value **out); +``` + +## `add_polynomial` + +Coefficientwise addition with canonical exact-zero normalization. + +`add_polynomial(left, right)` returns Polynomial. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_add_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `subtract_polynomial` + +Coefficientwise subtraction. + +`subtract_polynomial(left, right)` returns Polynomial. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_subtract_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `scale_polynomial` + +Multiply every coefficient by a scalar. + +`scale_polynomial(scalar, polynomial)` returns Polynomial. Parameters follow the original source order: `scalar`, `polynomial`. + +```c +hmath_status hmath_polynomial_scale_polynomial(hmath_context *context, const hmath_value *scalar, const hmath_value *polynomial, hmath_value **out); +``` + +## `multiply_polynomial` + +Exact schoolbook convolution, including zero polynomials. + +`multiply_polynomial(left, right)` returns Polynomial. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_multiply_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `compose_polynomial` + +Composition `p(q(x))` by polynomial Horner evaluation. + +`compose_polynomial(outer, inner)` returns Polynomial. Parameters follow the original source order: `outer`, `inner`. + +```c +hmath_status hmath_polynomial_compose_polynomial(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out); +``` + +## `divide_polynomial` + +Long division over a field. Exact coefficient equality controls termination; numerical cancellation is truncated at the eliminated leading coefficient. Zero denominator is rejected. + +`divide_polynomial(numerator, denominator)` returns (quotient, remainder). Parameters follow the original source order: `numerator`, `denominator`. + +```c +hmath_status hmath_polynomial_divide_polynomial(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `monic_polynomial` + +Normalize a nonzero polynomial to leading coefficient one; zero remains zero. + +`monic_polynomial(polynomial)` returns Polynomial. Parameters follow the original source order: `polynomial`. + +```c +hmath_status hmath_polynomial_monic_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `gcd_polynomial` + +Monic Euclidean GCD over an exact field; `gcd(0,0)=0`. + +`gcd_polynomial(left, right)` returns Polynomial. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_gcd_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `differentiate_polynomial` + +Formal derivative. + +`differentiate_polynomial(polynomial)` returns Polynomial. Parameters follow the original source order: `polynomial`. + +```c +hmath_status hmath_polynomial_differentiate_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `integrate_polynomial` + +Formal integral with the supplied integration constant. + +`integrate_polynomial(constant, polynomial)` returns Polynomial. Parameters follow the original source order: `constant`, `polynomial`. + +```c +hmath_status hmath_polynomial_integrate_polynomial(hmath_context *context, const hmath_value *constant, const hmath_value *polynomial, hmath_value **out); +``` + +## `square_free_factors` + +Monic square-free factors with positive multiplicities over Rational. The leading coefficient is omitted; constant polynomials have no factors. + +`square_free_factors(polynomial)` returns list of (monic factor, multiplicity). Parameters follow the original source order: `polynomial`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_square_free_factors(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `rational_roots` + +Rational roots with exact multiplicities using the rational-root theorem. Budget applies to integer factorization of numerator and leading coefficient. + +`rational_roots(budget, polynomial)` returns list of (exact Rational root, multiplicity). Parameters follow the original source order: `budget`, `polynomial`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_rational_roots(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out); +``` + +## `factor_rational_polynomial` + +Complete rational factorization by bounded Kronecker interpolation. Returns the original leading scalar and monic irreducible factors with multiplicity. Every candidate is divided exactly. Exhausting the candidate budget reports failure, never an unsupported claim of irreducibility. Intended for small exact polynomials; coefficient divisor enumeration also uses this budget. + +`factor_rational_polynomial(budget, polynomial)` returns (leading scalar, [(monic factor, multiplicity)]). Parameters follow the original source order: `budget`, `polynomial`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_factor_rational_polynomial(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out); +``` + +## `sturm_sequence` + +Sturm chain over exact rationals, after removing the derivative GCD. Zero polynomial is invalid. Square-free normalization ensures a repeated root cannot make every chain member vanish and destroy one-sided variation counts. + +`sturm_sequence(polynomial)` returns list of exact Rational polynomials. Parameters follow the original source order: `polynomial`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_sturm_sequence(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `count_real_roots` + +Number of distinct real roots in `(a,b]`. Endpoints that are roots of the polynomial are rejected to make the interval convention unambiguous. + +`count_real_roots(polynomial, left, right)` returns integer number of roots. Parameters follow the original source order: `polynomial`, `left`, `right`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_count_real_roots(hmath_context *context, const hmath_value *polynomial, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `isolate_real_roots` + +Isolate every distinct real root in rational intervals with disjoint interiors and width at most tolerance. Intervals have the root-count convention (a,b]; shared endpoints belong to the interval on their left. Bisection budget bounds visited intervals; all arithmetic is exact. + +`isolate_real_roots(depth, width, polynomial)` returns list of exact Rational endpoint pairs. Parameters follow the original source order: `depth`, `width`, `polynomial`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_isolate_real_roots(hmath_context *context, const hmath_value *depth, const hmath_value *width, const hmath_value *polynomial, hmath_value **out); +``` + +## `durand_kerner` + +DurandKerner simultaneous complex root iteration. Distinct initial roots are placed on a Cauchy-bound circle; repeated roots may converge slowly. + +`durand_kerner(iterations, tolerance, polynomial)` returns list of Complex Double roots. Parameters follow the original source order: `iterations`, `tolerance`, `polynomial`. + +```c +hmath_status hmath_polynomial_durand_kerner(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out); +``` + +## `aberth_ehrlich` + +AberthEhrlich simultaneous iteration, combining Newton corrections with mutual-root repulsion. All roots are verified against a scaled residual. + +`aberth_ehrlich(iterations, tolerance, polynomial)` returns list of Complex Double roots. Parameters follow the original source order: `iterations`, `tolerance`, `polynomial`. + +```c +hmath_status hmath_polynomial_aberth_ehrlich(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out); +``` + +## `companion_matrix` + +Frobenius companion matrix of a nonconstant polynomial, with ones on the subdiagonal and negated monic coefficients in the last column. + +`companion_matrix(polynomial)` returns interoperable Matrix with the same coefficient type. Parameters follow the original source order: `polynomial`. + +```c +hmath_status hmath_polynomial_companion_matrix(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +``` + +## `lagrange_interpolation` + +Exact Lagrange interpolating polynomial. Duplicate nodes are rejected. + +`lagrange_interpolation(points, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `points`. + +```c +hmath_status hmath_polynomial_lagrange_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out); +``` + +## `newton_interpolation` + +Newton divided differences, returned in the standard power basis. + +`newton_interpolation(points, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `points`. + +```c +hmath_status hmath_polynomial_newton_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out); +``` + +## `chebyshev_polynomial` + +Chebyshev T_n, normalized by T_0=1, T_1=x. + +`chebyshev_polynomial(degree, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`. + +```c +hmath_status hmath_polynomial_chebyshev_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +``` + +## `legendre_polynomial` + +Legendre P_n, normalized by P_n(1)=1. + +`legendre_polynomial(degree, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`. + +```c +hmath_status hmath_polynomial_legendre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +``` + +## `hermite_polynomial` + +Physicists' Hermite H_n: H_0=1, H_1=2x. + +`hermite_polynomial(degree, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`. + +```c +hmath_status hmath_polynomial_hermite_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +``` + +## `laguerre_polynomial` + +Ordinary Laguerre L_n with alpha=0 and L_n(0)=1. + +`laguerre_polynomial(degree, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`. + +```c +hmath_status hmath_polynomial_laguerre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +``` + +## `bernstein_polynomial` + +Bernstein basis `binomial(n,k)*x^k*(1-x)^(n-k)` for 0<=k<=n. + +`bernstein_polynomial(degree, index, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`, `index`. + +```c +hmath_status hmath_polynomial_bernstein_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *index, hmath_value **out); +``` + +## `polynomial_regression` + +Least-squares power-basis regression using column-pivoted Householder QR. Degree must be nonnegative; undersampling, nonfinite data and rank deficiency are reported by the checked design-matrix solver. + +`polynomial_regression(degree, points, *, dtype="float64")` returns Polynomial. Parameters follow the original source order: `prototype`, `degree`, `points`. + +```c +hmath_status hmath_polynomial_polynomial_regression(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *points, hmath_value **out); +``` + +## `power_series` + +Construct a jet with explicit coefficients, including trailing zeros. + +`power_series(coefficients, *, dtype="float64")` returns PowerSeries. Parameters follow the original source order: `prototype`, `coefficients`. + +```c +hmath_status hmath_polynomial_power_series(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out); +``` + +## `series_coefficients` + +Stored Taylor coefficients; coefficient n multiplies x^n, not x^n/n!. + +`series_coefficients(series)` returns coefficient list, including trailing zeros. Parameters follow the original source order: `series`. + +```c +hmath_status hmath_polynomial_series_coefficients(hmath_context *context, const hmath_value *series, hmath_value **out); +``` + +## `add_series` + +Add jets to their common truncation order. + +`add_series(left, right)` returns PowerSeries. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_add_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `multiply_series` + +Multiply jets by truncated convolution. + +`multiply_series(left, right)` returns PowerSeries. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_multiply_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `reciprocal_series` + +Reciprocal jet from coefficient recurrence; constant term must be nonzero. + +`reciprocal_series(series)` returns PowerSeries. Parameters follow the original source order: `series`. + +```c +hmath_status hmath_polynomial_reciprocal_series(hmath_context *context, const hmath_value *series, hmath_value **out); +``` + +## `divide_series` + +Divide jets to their common order; denominator constant must be nonzero. + +`divide_series(numerator, denominator)` returns PowerSeries. Parameters follow the original source order: `numerator`, `denominator`. + +```c +hmath_status hmath_polynomial_divide_series(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `compose_series` + +Formal composition to the inner jet's order. Inner constant must be zero, so unknown higher outer coefficients cannot affect the returned jet. + +`compose_series(outer, inner)` returns PowerSeries. Parameters follow the original source order: `outer`, `inner`. + +```c +hmath_status hmath_polynomial_compose_series(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out); +``` + +## `differentiate_series` + +Derivative jet has one fewer coefficient. + +`differentiate_series(series)` returns PowerSeries. Parameters follow the original source order: `series`. + +```c +hmath_status hmath_polynomial_differentiate_series(hmath_context *context, const hmath_value *series, hmath_value **out); +``` + +## `integrate_series` + +Integral jet with supplied constant, one coefficient longer. + +`integrate_series(constant, series)` returns PowerSeries. Parameters follow the original source order: `constant`, `series`. + +```c +hmath_status hmath_polynomial_integrate_series(hmath_context *context, const hmath_value *constant, const hmath_value *series, hmath_value **out); +``` + +## `exp_series` + +Exponential of a finite jet from b'=a'b; constant uses the coefficient type's exp. The output has the same truncation order. + +`exp_series(series)` returns PowerSeries. Parameters follow the original source order: `series`. + +```c +hmath_status hmath_polynomial_exp_series(hmath_context *context, const hmath_value *series, hmath_value **out); +``` + +## `log_series` + +Formal log through derivative/division/integration. Requires positive real constant term, with exact truncation matching the input jet. + +`log_series(series)` returns PowerSeries. Parameters follow the original source order: `series`. + +```c +hmath_status hmath_polynomial_log_series(hmath_context *context, const hmath_value *series, hmath_value **out); +``` + +## `rational_function` + +Normalize by polynomial GCD and reject a zero denominator. + +`rational_function(numerator, denominator)` returns RationalFunction. Parameters follow the original source order: `numerator`, `denominator`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_rational_function(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `rational_numerator` + +Reduced numerator. + +`rational_numerator(function)` returns Polynomial. Parameters follow the original source order: `function`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_rational_numerator(hmath_context *context, const hmath_value *function, hmath_value **out); +``` + +## `rational_denominator` + +Monic reduced denominator. + +`rational_denominator(function)` returns Polynomial. Parameters follow the original source order: `function`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_rational_denominator(hmath_context *context, const hmath_value *function, hmath_value **out); +``` + +## `evaluate_rational_function` + +Exact evaluation, rejecting poles. + +`evaluate_rational_function(function, x)` returns exact Rational scalar. Parameters follow the original source order: `function`, `x`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_evaluate_rational_function(hmath_context *context, const hmath_value *function, const hmath_value *x, hmath_value **out); +``` + +## `add_rational_function` + +Exact rational-function addition with cancellation. + +`add_rational_function(left, right)` returns RationalFunction. Parameters follow the original source order: `left`, `right`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_add_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `multiply_rational_function` + +Exact rational-function multiplication with cancellation. + +`multiply_rational_function(left, right)` returns RationalFunction. Parameters follow the original source order: `left`, `right`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_multiply_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `partial_fractions` + +Exact partial fractions over Q. Each term is `(numerator,monic irreducible denominator,power)` and numerator degree is smaller than denominator degree. Supports repeated and nonlinear factors. Kronecker factorization and linear elimination are bounded by the supplied candidate budget. + +`partial_fractions(budget, function)` returns (polynomial part, [(numerator, denominator, power)]). Parameters follow the original source order: `budget`, `function`. This operation requires exact Rational coefficients. + +```c +hmath_status hmath_polynomial_partial_fractions(hmath_context *context, const hmath_value *budget, const hmath_value *function, hmath_value **out); +``` + +## `polynomial_equal` + +Original derived Eq comparison; coefficient types must match. + +`polynomial_equal(left, right)` returns Boolean. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_polynomial_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `series_equal` + +Original derived Eq comparison; coefficient types must match. + +`series_equal(left, right)` returns Boolean. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_series_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `rational_function_equal` + +Original derived Eq comparison; coefficient types must match. + +`rational_function_equal(left, right)` returns Boolean. Parameters follow the original source order: `left`, `right`. + +```c +hmath_status hmath_polynomial_rational_function_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `chebyshev_approximation` + +Truncated Chebyshev interpolation at first-kind nodes on [-1,1], returned in power basis. Uses degree+1 evaluations; nonfinite values are rejected. + +`chebyshev_approximation(degree, function)` returns a Double Polynomial. The callback is synchronous and sampled only by the original algorithm. It receives one Python float and returns one float. An original MathError raised by the callback is preserved; other Python exceptions are re-raised after native cleanup. No native callback or userdata outlives the call. + +```c +hmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context, ptrdiff_t degree, hmath_polynomial_callback callback, void *userdata, hmath_value **out); +``` diff --git a/docs/reference/python.md b/docs/reference/python.md index 0ec29e8..b48989a 100644 --- a/docs/reference/python.md +++ b/docs/reference/python.md @@ -1,11 +1,38 @@ # Python API -`hmath` is the primary interface. Calculations use finite IEEE 754 binary64 -values. Tensors are immutable and do not broadcast implicitly. NumPy is needed -only for the conversion methods. Python code blocks run in documentation checks; -the final-shutdown example is displayed separately. +`hmath` exposes the native library through Python functions and owned objects. +The `Tensor` class below is the original finite binary64 storage interface. +The typed namespaces also expose FP32, exact integers and rationals, complex +values, algorithms, models and mutable tensors with their original contracts. +NumPy is optional except for array interoperability and borrowed execution. -## Function index +## Domain namespaces + +Import a namespace with `from hmath import matrix`, then call its functions. +Each reference lists Python signatures, C entry points, source semantics, +precision, errors and ownership. A function's documented dtype selects an +original concrete Haskell instance; it does not change the algorithm. + +| Task | Reference | +| --- | --- | +| Scalar arithmetic and elementary functions | [Numeric functions](numeric-bindings.md), [complex and special functions](scalar-extras.md) | +| Exact and lower-precision representations | [Numeric types](numeric-types.md), [type functions](numeric-type-functions.md), [units](units-values.md) | +| Matrices, vectors and linear systems | [Matrix](matrix-bindings.md), [generic matrix](matrix-values.md), [extended linear algebra](linear-bindings.md) | +| Polynomial and symbolic calculation | [Polynomials](polynomial.md), [expressions and symbolic algebra](expression-bindings.md) | +| Differentiation, integration and differential equations | [Numerical solvers](numerical-solvers.md) | +| Automatic differentiation and optimization | [Autodiff](autodiff-bindings.md), [optimizers](optimization-bindings.md) | +| General typed tensors and neural layers | [Tensors](tensor-bindings.md), [deep learning](deeplearning-bindings.md) | +| Model fitting, preprocessing and neighbors | [Machine learning](machinelearning-bindings.md) | +| Randomness, probability and time series | [Random and probability](stochastic.md), [time series](timeseries-bindings.md) | +| Signals, transforms and interpolation | [Signal/Fourier/interpolation](spectral-bindings.md) | +| Graphs, geometry, rotations and images | [Graphs](graph-bindings.md), [geometry](geometry-bindings.md), [rotations](rotations.md), [images](image-bindings.md) | +| Collections, algebra and static shapes | [Foundation](foundation.md), [algebra](algebra-values.md), [shape](shapes.md) | +| Binary/text/NumPy formats, streaming and mapped files | [Interchange](interchange-bindings.md) | +| Borrowed FP32/FP64 execution | [Buffer execution](execution.md) | +| Immutable, scoped ST and synchronized IO storage | [Typed buffers](buffer-bindings.md) | +| Shared object and callback contracts | [Structured values](values.md), [errors](errors.md) | + +## Binary64 tensor function index | API | Purpose | | --- | --- | @@ -42,7 +69,7 @@ the final-shutdown example is displayed separately. | [hmath_cffi.Tensor.__enter__](#hmath_cffitensor__enter__) | Enter a context that owns this tensor handle. | | [hmath_cffi.Tensor.__exit__](#hmath_cffitensor__exit__args) | Close the tensor when leaving a context. | -## Common contracts +## Binary64 tensor contracts - Shapes contain at most **8** nonnegative Python integers (not booleans). Each dimension and the total size are bounded by **1,048,576**. Empty diff --git a/docs/reference/rotations.md b/docs/reference/rotations.md new file mode 100644 index 0000000..63aeea4 --- /dev/null +++ b/docs/reference/rotations.md @@ -0,0 +1,126 @@ +# Quaternions and rigid transforms + +`hmath.quaternion` and `hmath.rotation` expose every public function of +`HMath.Quaternion` and `HMath.Rotation`. They use the actual immutable Haskell +objects and original checked algorithms. These finite, normalized rotation APIs +have distinct types from the generic algebraic values in `hmath.numeric_types`. + +```python +from hmath import quaternion as q, rotation as r + +with q.from_euler(0.1, 0.2, 0.3) as orientation: + print(q.components(orientation)) # scalar-first [w, x, y, z] + with r.so3(orientation) as rotation: + with r.se3(rotation, [1, 2, 3]) as transform: + print(r.transform_point(transform, [0, 0, 0])) + with r.to_homogeneous(transform) as matrix: + print(matrix.shape) # (4, 4) + print(matrix.to_list()) +``` + +All real coefficients are the source `Double`. Python vector inputs become +`[Double]`; nested list/tuple results retain their original structure. Matrix +conversions accept or return the same owned `Matrix Double` used by the dense +matrix API, including its shape and row-major logical values. A Float32 Matrix +is a distinct coefficient type and must be converted explicitly. + +## Mathematical conventions + +Quaternions are Hamilton quaternions in scalar-first `(w,x,y,z)` order. Rotations +are active and right-handed, acting on column vectors. Angles are radians. +`multiply(a,b)` and transform `compose(a,b)` apply `b` first. Euler angles use +intrinsic ZYX, with the Python arguments and returned tuple ordered +`(roll,pitch,yaw)`. The source gimbal-lock convention chooses roll zero. + +The `quaternion` constructor checks finite components. Normalization and inverse +reject a zero quaternion. SO(3) construction normalizes a nonzero quaternion. +Quaternion interpolation chooses the original shortest sign-equivalent arc; +`nlerp`, `slerp`, `squad` and dual-quaternion interpolation retain their source +parameter bounds and normalization behavior. SO(3) logarithms use the principal +angle in `[0,pi]`. SE(3) twists are a tuple `(omega,v)` of two three-vectors. The +source left-Jacobian formulas and their series near identity are unchanged. +Rigid dual-quaternion interpolation remains ScLERP through SE(3), including its +pure-translation limit. + +`SO3`, `SE3` and `rotation.DualQuaternion` retain the source normalized and rigid +constraints. They do not represent arbitrary scale or shear. `from_matrix` and +`from_homogeneous` keep the original shape, orthogonality, handedness and bottom +row checks. No adapter sanitizes nonfinite data or substitutes a transform. + +## Ownership and C interface + +Use context managers or `close()` for native objects. Every returned child owns +its value independently of its parent. Equality uses the actual Haskell `Eq` +instance, so a sign-equivalent rotation does not automatically imply object +equality. Independent calls may share immutable objects while holding an owned +reference on each participating thread. + +`hmath_rotations.h` declares the C interface. Arguments and outputs use shared +`hmath_value` owners. Scalar arguments must be common Double scalar values; +vector arguments are lists of Double scalar values. A twist is a tuple of two +such lists. Matrix arguments are shared Dense `Matrix Double` values. Opaque +kinds are 72 Quaternion, 73 SO3, 74 SE3 and 75 Rotation.DualQuaternion. These tags +are distinct from the generic Numeric quaternion types. + +Each input is borrowed throughout its synchronous call. Success transfers one +owned output reference; failure leaves the output pointer untouched. Release +references with `hmath_value_release`. A live value keeps the Haskell runtime +alive and final shutdown reports `BUSY`. The original `Left MathError` becomes +status `HMATH_MATH_ERROR`, with complete constructor and payload available through +`hmath_last_math_error`. Cancellation is checked before a call enters Haskell. + +## Functions + +The table below lists every public function, its arguments and result shape. +Names use Python snake case; the original numerical function is unchanged. + +| Python function | Argument types, in order | Result | Original function | +| --- | --- | --- | --- | +| `quaternion.quaternion(w, x, y, z)` | `float`, `float`, `float`, `float` | `Quaternion` | `HMath.Quaternion.quaternion` | +| `quaternion.components(value)` | `Quaternion` | `list[float]` | `HMath.Quaternion.components` | +| `quaternion.norm(value)` | `Quaternion` | `float` | `HMath.Quaternion.norm` | +| `quaternion.normalize(value)` | `Quaternion` | `Quaternion` | `HMath.Quaternion.normalize` | +| `quaternion.inverse(value)` | `Quaternion` | `Quaternion` | `HMath.Quaternion.inverse` | +| `quaternion.conjugate(value)` | `Quaternion` | `Quaternion` | `HMath.Quaternion.conjugate` | +| `quaternion.multiply(a, b)` | `Quaternion`, `Quaternion` | `Quaternion` | `HMath.Quaternion.multiply` | +| `quaternion.add(a, b)` | `Quaternion`, `Quaternion` | `Quaternion` | `HMath.Quaternion.add` | +| `quaternion.scale(factor, value)` | `float`, `Quaternion` | `Quaternion` | `HMath.Quaternion.scale` | +| `quaternion.rotate_vector(value, vector)` | `Quaternion`, `list[float]` | `list[float]` | `HMath.Quaternion.rotateVector` | +| `quaternion.axis_angle(axis, angle)` | `list[float]`, `float` | `Quaternion` | `HMath.Quaternion.axisAngle` | +| `quaternion.to_axis_angle(value)` | `Quaternion` | `(list[float], float)` | `HMath.Quaternion.toAxisAngle` | +| `quaternion.from_euler(roll, pitch, yaw)` | `float`, `float`, `float` | `Quaternion` | `HMath.Quaternion.fromEuler` | +| `quaternion.to_euler(value)` | `Quaternion` | `(float, float, float)` | `HMath.Quaternion.toEuler` | +| `quaternion.to_matrix(value)` | `Quaternion` | `Matrix Double` | `HMath.Quaternion.toMatrix` | +| `quaternion.from_matrix(matrix)` | `Matrix Double` | `Quaternion` | `HMath.Quaternion.fromMatrix` | +| `quaternion.nlerp(fraction, a, b)` | `float`, `Quaternion`, `Quaternion` | `Quaternion` | `HMath.Quaternion.nlerp` | +| `quaternion.slerp(fraction, a, b)` | `float`, `Quaternion`, `Quaternion` | `Quaternion` | `HMath.Quaternion.slerp` | +| `quaternion.squad(fraction, q0, q1, q2, q3)` | `float`, `Quaternion`, `Quaternion`, `Quaternion`, `Quaternion` | `Quaternion` | `HMath.Quaternion.squad` | +| `quaternion.exponential(value)` | `Quaternion` | `Quaternion` | `HMath.Quaternion.exponential` | +| `quaternion.logarithm(value)` | `Quaternion` | `Quaternion` | `HMath.Quaternion.logarithm` | +| `quaternion.swing_twist(axis, value)` | `list[float]`, `Quaternion` | `(Quaternion, Quaternion)` | `HMath.Quaternion.swingTwist` | +| `rotation.so3(value)` | `Quaternion` | `SO3` | `HMath.Rotation.so3` | +| `rotation.rotation_quaternion(value)` | `SO3` | `Quaternion` | `HMath.Rotation.rotationQuaternion` | +| `rotation.identity_rotation()` | | `SO3` | `HMath.Rotation.identityRotation` | +| `rotation.compose_rotation(a, b)` | `SO3`, `SO3` | `SO3` | `HMath.Rotation.composeRotation` | +| `rotation.inverse_rotation(value)` | `SO3` | `SO3` | `HMath.Rotation.inverseRotation` | +| `rotation.rotate(value, vector)` | `SO3`, `list[float]` | `list[float]` | `HMath.Rotation.rotate` | +| `rotation.exp_so3(omega)` | `list[float]` | `SO3` | `HMath.Rotation.expSO3` | +| `rotation.log_so3(value)` | `SO3` | `list[float]` | `HMath.Rotation.logSO3` | +| `rotation.se3(rotation, translation)` | `SO3`, `list[float]` | `SE3` | `HMath.Rotation.se3` | +| `rotation.rotation_part(value)` | `SE3` | `SO3` | `HMath.Rotation.rotationPart` | +| `rotation.translation_part(value)` | `SE3` | `list[float]` | `HMath.Rotation.translationPart` | +| `rotation.identity_transform()` | | `SE3` | `HMath.Rotation.identityTransform` | +| `rotation.compose(a, b)` | `SE3`, `SE3` | `SE3` | `HMath.Rotation.compose` | +| `rotation.inverse(value)` | `SE3` | `SE3` | `HMath.Rotation.inverse` | +| `rotation.transform_point(value, point)` | `SE3`, `list[float]` | `list[float]` | `HMath.Rotation.transformPoint` | +| `rotation.exp_se3(twist)` | `(list[float], list[float])` | `SE3` | `HMath.Rotation.expSE3` | +| `rotation.log_se3(value)` | `SE3` | `(list[float], list[float])` | `HMath.Rotation.logSE3` | +| `rotation.to_homogeneous(value)` | `SE3` | `Matrix Double` | `HMath.Rotation.toHomogeneous` | +| `rotation.from_homogeneous(matrix)` | `Matrix Double` | `SE3` | `HMath.Rotation.fromHomogeneous` | +| `rotation.dual_quaternion(real, dual)` | `Quaternion`, `Quaternion` | `DualQuaternion` | `HMath.Rotation.dualQuaternion` | +| `rotation.dual_parts(value)` | `DualQuaternion` | `(Quaternion, Quaternion)` | `HMath.Rotation.dualParts` | +| `rotation.to_dual_quaternion(value)` | `SE3` | `DualQuaternion` | `HMath.Rotation.toDualQuaternion` | +| `rotation.from_dual_quaternion(value)` | `DualQuaternion` | `SE3` | `HMath.Rotation.fromDualQuaternion` | +| `rotation.multiply_dual(a, b)` | `DualQuaternion`, `DualQuaternion` | `DualQuaternion` | `HMath.Rotation.multiplyDual` | +| `rotation.inverse_dual(value)` | `DualQuaternion` | `DualQuaternion` | `HMath.Rotation.inverseDual` | +| `rotation.interpolate_dual(fraction, a, b)` | `float`, `DualQuaternion`, `DualQuaternion` | `DualQuaternion` | `HMath.Rotation.interpolateDual` | diff --git a/docs/reference/scalar-extras.md b/docs/reference/scalar-extras.md new file mode 100644 index 0000000..afb39e3 --- /dev/null +++ b/docs/reference/scalar-extras.md @@ -0,0 +1,582 @@ +# Complete scalar-domain adapters + +These functions call the original Complex, Trigonometry, NumberTheory and Special APIs. C includes `hmath_scalar_extras.h`; Python namespaces extend existing modules without replacing earlier numerical functions. Complex selectors are owned immutable original objects, constructed with `complex.exp()`/`trigonometry.c_sin()` etc. The `complex_function` adapter accepts `dtype="float32"` or `"float64"`; actual typed Complex Float inputs remain Float through the original RealFloat algorithm. Other complex operations/SFResult retain original Double precision. No principal-branch, pole/nonfinite, error-estimate or integer-budget policy is changed. + +Values use the [owned structured protocol](values.md): inputs borrowed, outputs owned/untouched on failure, each reference pins the runtime. Exact integers have no fixed precision or floating conversion. Variable-length/nested lists and tuples keep their original order/shape; Maybe uses None. Checked source errors retain complete MathError/status11. Selectors use kinds352/353. SFResult uses a tuple of two Doubles, interoperable with existing SFResult(value,error) named tuples; its raw constructor does not normalize or certify the error field. + +## `complex.exp` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_exp(hmath_context *context, hmath_value **out); +``` + +## `complex.log` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_log(hmath_context *context, hmath_value **out); +``` + +## `complex.sqrt` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_sqrt(hmath_context *context, hmath_value **out); +``` + +## `complex.sin` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_sin(hmath_context *context, hmath_value **out); +``` + +## `complex.cos` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_cos(hmath_context *context, hmath_value **out); +``` + +## `complex.tan` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_tan(hmath_context *context, hmath_value **out); +``` + +## `complex.sinh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_sinh(hmath_context *context, hmath_value **out); +``` + +## `complex.cosh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_cosh(hmath_context *context, hmath_value **out); +``` + +## `complex.tanh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_tanh(hmath_context *context, hmath_value **out); +``` + +## `complex.asin` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_asin(hmath_context *context, hmath_value **out); +``` + +## `complex.acos` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_acos(hmath_context *context, hmath_value **out); +``` + +## `complex.atan` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_atan(hmath_context *context, hmath_value **out); +``` + +## `complex.asinh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_asinh(hmath_context *context, hmath_value **out); +``` + +## `complex.acosh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_acosh(hmath_context *context, hmath_value **out); +``` + +## `complex.atanh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Elementary +``` + +```c +hmath_status hmath_complex_atanh(hmath_context *context, hmath_value **out); +``` + +## `complex.elementary` + +Apply an elementary function, rejecting poles and nonfinite results. + +```haskell +Elementary -> Complex Double -> Either MathError (Complex Double) +``` + +```c +hmath_status hmath_complex_elementary(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out); +``` + +## `complex.complex_matrix` + +Checked finite complex matrix, at most 256 rows and columns. + +```haskell +Int -> Int -> [Complex Double] -> Either MathError (Matrix (Complex Double)) +``` + +```c +hmath_status hmath_complex_complex_matrix(hmath_context *context, const hmath_value *rows, const hmath_value *columns, const hmath_value *values, hmath_value **out); +``` + +## `complex.multiply_matrices` + +Matrix multiplication with finite-result validation. + +```haskell +Matrix (Complex Double) -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)) +``` + +```c +hmath_status hmath_complex_multiply_matrices(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `complex.conjugate_transpose` + +Hermitian transpose with finite-input validation. + +```haskell +Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)) +``` + +```c +hmath_status hmath_complex_conjugate_transpose(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `complex.complex_fft` + +Existing checked mixed-radix/Bluestein forward FFT. + +```haskell +[Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_complex_complex_fft(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `complex.complex_ifft` + +Existing checked inverse FFT, normalized by sample count. + +```haskell +[Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_complex_complex_ifft(hmath_context *context, const hmath_value *values, hmath_value **out); +``` + +## `trigonometry.c_sin` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_sin(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_cos` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_cos(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_tan` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_tan(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_asin` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_asin(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_acos` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_acos(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_atan` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_atan(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_sinh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_sinh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_cosh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_cosh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_tanh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_tanh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_asinh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_asinh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_acosh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_acosh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_atanh` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_atanh(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_sec` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_sec(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_csc` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_csc(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_cot` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_cot(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_sech` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_sech(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_csch` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_csch(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.c_coth` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +ComplexFunction +``` + +```c +hmath_status hmath_trigonometry_c_coth(hmath_context *context, hmath_value **out); +``` + +## `trigonometry.complex_function` + + Given a ComplexFunction selector then complex input, compute the selected principal-branch Data.Complex function or reciprocal. Reject non-finite components and non-finite results/poles with Left DomainError. + +```haskell +RealFloat a => ComplexFunction -> Complex a -> Either MathError (Complex a) +``` + +```c +hmath_status hmath_trigonometry_complex_function(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out); +``` + +## `numbertheory.chinese_remainder` + + Generalized CRT for @(residue,positive modulus)@ pairs. Compatible noncoprime moduli are supported. Returns canonical residue and lcm modulus. + +```haskell +[(Integer,Integer)] -> Either MathError (Integer,Integer) +``` + +```c +hmath_status hmath_numbertheory_chinese_remainder(hmath_context *context, const hmath_value *congruences, hmath_value **out); +``` + +## `numbertheory.linear_diophantine` + + One solution and a direction: @(x,y,dx,dy)@ represents every solution @(x+k*dx,y+k*dy)@ of @a*x+b*y=c@. The all-zero equation has a two-dimensional solution set and is rejected instead of returning a misleading direction. + +```haskell +Integer -> Integer -> Integer -> Either MathError (Integer,Integer,Integer,Integer) +``` + +```c +hmath_status hmath_numbertheory_linear_diophantine(hmath_context *context, const hmath_value *a, const hmath_value *b, const hmath_value *c, hmath_value **out); +``` + +## `numbertheory.perfect_power` + + Find a representation @n = base^exponent@ with exponent greater than one. Zero, one, and minus one use exponent 2, 2, and 3 respectively. + +```haskell +Integer -> Maybe (Integer,Int) +``` + +```c +hmath_status hmath_numbertheory_perfect_power(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `numbertheory.prime_factorization` + + Exact trial factorization of a positive integer. The budget counts attempted divisors (including repeated factors). One has an empty factorization. + +```haskell +Int -> Integer -> Either MathError [(Integer,Int)] +``` + +```c +hmath_status hmath_numbertheory_prime_factorization(hmath_context *context, const hmath_value *budget, const hmath_value *value, hmath_value **out); +``` + +## `numbertheory.partitions` + +Integer partitions in descending part order. Zero has one empty partition. + +```haskell +Int -> Either MathError [[Int]] +``` + +```c +hmath_status hmath_numbertheory_partitions(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `special.sf_result` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +Double -> Double -> SFResult +``` + +```c +hmath_status hmath_special_sf_result(hmath_context *context, const hmath_value *value, const hmath_value *error, hmath_value **out); +``` + +## `special.sf_value` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SFResult -> Double +``` + +```c +hmath_status hmath_special_sf_value(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `special.sf_error` + +Construct or inspect the original immutable record; field order follows the source signature. + +```haskell +SFResult -> Double +``` + +```c +hmath_status hmath_special_sf_error(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + diff --git a/docs/reference/shapes.md b/docs/reference/shapes.md new file mode 100644 index 0000000..a0006ea --- /dev/null +++ b/docs/reference/shapes.md @@ -0,0 +1,83 @@ +# Runtime and type-indexed shapes + +These APIs call the original `HMath.API.Shape` operations. Haskell type-level +natural dimensions become explicit Python integers/C Integer Values. The adapter +reifies actual `KnownNat` and recursive `KnownShape` dictionaries; it never +coerces a matrix/tensor to an unrelated shape. `reflected_shape` retains exact +Integer dimensions, even above Int. The original constructors decide Int +overflow and dynamic shape errors. Static multiplication also requires equal +nominal inner dimensions and identical element types. + +`scalar_shape`, `vector_shape`, and `matrix_shape` are read-only source pattern +views: Boolean match, optional length, and optional `(rows, columns)`. +`make_shape` performs checked construction. `coordinates(length, values, +dtype=...)` retains the original lazy list element type; numeric, Bool, String +and Exact elements remain lossless. Vector conversion uses the original source +conversion and produces an ordinary interoperable Vector owner. Static wrappers +own independent references. Dynamic conversion retains the original element +type and does not copy or coerce mathematical values. Close each owned result. + +## `shape.shape_dimensions` + +Calls `HMath.API.Shape.shapeDimensions`. C parameters: `shape`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.shape_elements` + +Calls `HMath.API.Shape.shapeElements`. C parameters: `shape`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.make_shape` + +Calls `HMath.API.Shape.makeShape`. C parameters: `dimensions`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.scalar_shape` + +Calls `HMath.API.Shape.ScalarShape`. C parameters: `shape`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.vector_shape` + +Calls `HMath.API.Shape.VectorShape`. C parameters: `shape`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.matrix_shape` + +Calls `HMath.API.Shape.MatrixShape`. C parameters: `shape`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.static_matrix` + +Calls `HMath.API.Shape.staticMatrix`. C parameters: `rows, columns, matrix`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.dynamic_matrix` + +Calls `HMath.API.Shape.dynamicMatrix`. C parameters: `matrix`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.static_multiply` + +Calls `HMath.API.Shape.staticMultiply`. C parameters: `left, right`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.static_transpose` + +Calls `HMath.API.Shape.staticTranspose`. C parameters: `matrix`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.reflected_shape` + +Calls `HMath.API.Shape.reflectedShape`. C parameters: `dimensions`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.static_tensor` + +Calls `HMath.API.Shape.staticTensor`. C parameters: `dimensions, tensor`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.dynamic_tensor` + +Calls `HMath.API.Shape.dynamicTensor`. C parameters: `tensor`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.coordinates` + +Calls `HMath.API.Shape.coordinates`. C parameters: `prototype, length, values`, each a borrowed Value; the output owns one reference. The prototype selects the original element type, including empty coordinates. Failures leave the output pointer untouched. + +## `shape.coordinate_values` + +Calls `HMath.API.Shape.coordinateValues`. C parameters: `coordinates`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + +## `shape.coordinates_to_vector` + +Calls `HMath.API.Shape.coordinatesToVector`. C parameters: `coordinates`, each a borrowed Value; the output owns one reference. Failures leave the output pointer untouched. + diff --git a/docs/reference/spectral-bindings.md b/docs/reference/spectral-bindings.md new file mode 100644 index 0000000..f3322c7 --- /dev/null +++ b/docs/reference/spectral-bindings.md @@ -0,0 +1,2485 @@ +# Signal, Fourier and interpolation bindings + +Python uses `hmath.signal`, `hmath.fourier` and `hmath.interpolation`. C includes `hmath_spectral.h` and uses immutable owned [structured values](values.md). Existing scalar entry points remain available. Every operation calls the original implementation. + +Forward Fourier exponents are negative; inverse transforms divide by N. DCT/DST retain the original orthonormal type I–IV definitions. Plans retain the original bounded reference algorithms and are reusable immutable objects. They do not substitute a different transform provider. + +Interpolation preserves strictly increasing unique finite samples, exact extrapolation choices and ascending local polynomial coefficients. Error values remain the source's sampled estimates. Signal filters preserve state continuation, window definitions, boundary conventions, Kalman updates and wavelet coefficient ordering. Source work/shape/iteration limits remain in force. + +Inputs are borrowed for a synchronous call and successful C outputs own one reference. Output pointers remain untouched on failure. Immutable objects support concurrent readers retaining references and using independent output addresses. Function arguments use kind101 callbacks from `hmath_linear_callback`, with a tuple of flattened positional arguments. Python accepts ordinary callables and retains their owners; exceptions are re-raised after native cleanup. Source MathError returns status11 with a lossless payload. Cancellation is checked before entry. + +## `signal.iir` + +`signal.iir(numerator, denominator)` + +Normalize finite ascending z^-1 coefficients by nonzero a0 and initialize a zero transposed-direct-form-II state. + +Original: [`HMath.Signal.iir`](haskell/HMath-Signal.md#v:iir). + +```haskell +[Double] -> [Double] -> Either MathError Filter +``` + +```c +hmath_status hmath_signal_value_iir(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `signal.fir` + +`signal.fir(b)` + +Construct a causal zero-state finite-impulse-response filter; maximum 257 taps. + +Original: [`HMath.Signal.fir`](haskell/HMath-Signal.md#v:fir). + +```haskell +[Double] -> Either MathError Filter +``` + +```c +hmath_status hmath_signal_value_fir(hmath_context *context, const hmath_value *b, hmath_value **out); +``` + +## `signal.filter_coefficients` + +`signal.filter_coefficients(value)` + +Read normalized padded (numerator,denominator) coefficients in increasing delay order. + +Original: [`HMath.Signal.filterCoefficients`](haskell/HMath-Signal.md#v:filterCoefficients). + +```haskell +Filter -> ([Double], [Double]) +``` + +```c +hmath_status hmath_signal_value_filter_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.filter_state` + +`signal.filter_state(value)` + +Read explicit delay state after a block; the list is immutable and independently reusable. + +Original: [`HMath.Signal.filterState`](haskell/HMath-Signal.md#v:filterState). + +```haskell +Filter -> [Double] +``` + +```c +hmath_status hmath_signal_value_filter_state(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.reset_filter` + +`signal.reset_filter(value)` + +Preserve coefficients while replacing every delay with zero. + +Original: [`HMath.Signal.resetFilter`](haskell/HMath-Signal.md#v:resetFilter). + +```haskell +Filter -> Filter +``` + +```c +hmath_status hmath_signal_value_reset_filter(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.filter_signal` + +`signal.filter_signal(value, value2)` + +Process a finite input block, returning both its output and the filter state for the next block. + +Original: [`HMath.Signal.filterSignal`](haskell/HMath-Signal.md#v:filterSignal). + +```haskell +Filter -> [Double] -> Either MathError ([Double], Filter) +``` + +```c +hmath_status hmath_signal_value_filter_signal(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `signal.frequency_response` + +`signal.frequency_response(value, value2)` + +Complex unit-circle response at omega radians/sample; reject poles and nonfinite arithmetic. + +Original: [`HMath.Signal.frequencyResponse`](haskell/HMath-Signal.md#v:frequencyResponse). + +```haskell +Filter -> Double -> Either MathError (Complex Double) +``` + +```c +hmath_status hmath_signal_value_frequency_response(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `signal.butterworth` + +`signal.butterworth()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Butterworth`](haskell/HMath-Signal.md#v:Butterworth). + +```haskell +FilterFamily +``` + +```c +hmath_status hmath_signal_value_butterworth(hmath_context *context, hmath_value **out); +``` + +## `signal.chebyshev_i` + +`signal.chebyshev_i(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.ChebyshevI`](haskell/HMath-Signal.md#v:ChebyshevI). + +```haskell +Double -> FilterFamily +``` + +```c +hmath_status hmath_signal_value_chebyshev_i(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.chebyshev_ii` + +`signal.chebyshev_ii(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.ChebyshevII`](haskell/HMath-Signal.md#v:ChebyshevII). + +```haskell +Double -> FilterFamily +``` + +```c +hmath_status hmath_signal_value_chebyshev_ii(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.elliptic` + +`signal.elliptic(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Elliptic`](haskell/HMath-Signal.md#v:Elliptic). + +```haskell +Double -> Double -> FilterFamily +``` + +```c +hmath_status hmath_signal_value_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `signal.bessel` + +`signal.bessel()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Bessel`](haskell/HMath-Signal.md#v:Bessel). + +```haskell +FilterFamily +``` + +```c +hmath_status hmath_signal_value_bessel(hmath_context *context, hmath_value **out); +``` + +## `signal.lowpass` + +`signal.lowpass(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Lowpass`](haskell/HMath-Signal.md#v:Lowpass). + +```haskell +Double -> FilterBand +``` + +```c +hmath_status hmath_signal_value_lowpass(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.highpass` + +`signal.highpass(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Highpass`](haskell/HMath-Signal.md#v:Highpass). + +```haskell +Double -> FilterBand +``` + +```c +hmath_status hmath_signal_value_highpass(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.bandpass` + +`signal.bandpass(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Bandpass`](haskell/HMath-Signal.md#v:Bandpass). + +```haskell +Double -> Double -> FilterBand +``` + +```c +hmath_status hmath_signal_value_bandpass(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `signal.bandstop` + +`signal.bandstop(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Bandstop`](haskell/HMath-Signal.md#v:Bandstop). + +```haskell +Double -> Double -> FilterBand +``` + +```c +hmath_status hmath_signal_value_bandstop(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `signal.design_iir` + +`signal.design_iir(family, band, order, rate)` + + Orders 1..8; ripple/attenuation in dB; all edges strictly inside (0, fs/2). Expanded coefficients are a bounded reference representation; high orders should use cascaded sections in production applications. + +Original: [`HMath.Signal.designIIR`](haskell/HMath-Signal.md#v:designIIR). + +```haskell +FilterFamily -> FilterBand -> Int -> Double -> Either MathError Filter +``` + +```c +hmath_status hmath_signal_value_design_iir(hmath_context *context, const hmath_value *family, const hmath_value *band, const hmath_value *order, const hmath_value *rate, hmath_value **out); +``` + +## `signal.notch` + +`signal.notch(omega, quality)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.notch`](haskell/HMath-Signal.md#v:notch). + +```haskell +Double -> Double -> Either MathError Filter +``` + +```c +hmath_status hmath_signal_value_notch(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out); +``` + +## `signal.all_pass` + +`signal.all_pass(omega, quality)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.allPass`](haskell/HMath-Signal.md#v:allPass). + +```haskell +Double -> Double -> Either MathError Filter +``` + +```c +hmath_status hmath_signal_value_all_pass(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out); +``` + +## `signal.wiener` + +`signal.wiener(width, noise, xs)` + +Local mean/variance Wiener shrinkage; optional noise variance, otherwise average local variance is estimated. + +Original: [`HMath.Signal.wiener`](haskell/HMath-Signal.md#v:wiener). + +```haskell +Int -> Maybe Double -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_wiener(hmath_context *context, const hmath_value *width, const hmath_value *noise, const hmath_value *xs, hmath_value **out); +``` + +## `signal.hann` + +`signal.hann()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Hann`](haskell/HMath-Signal.md#v:Hann). + +```haskell +Window +``` + +```c +hmath_status hmath_signal_value_hann(hmath_context *context, hmath_value **out); +``` + +## `signal.hamming` + +`signal.hamming()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Hamming`](haskell/HMath-Signal.md#v:Hamming). + +```haskell +Window +``` + +```c +hmath_status hmath_signal_value_hamming(hmath_context *context, hmath_value **out); +``` + +## `signal.blackman` + +`signal.blackman()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Blackman`](haskell/HMath-Signal.md#v:Blackman). + +```haskell +Window +``` + +```c +hmath_status hmath_signal_value_blackman(hmath_context *context, hmath_value **out); +``` + +## `signal.bartlett` + +`signal.bartlett()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Bartlett`](haskell/HMath-Signal.md#v:Bartlett). + +```haskell +Window +``` + +```c +hmath_status hmath_signal_value_bartlett(hmath_context *context, hmath_value **out); +``` + +## `signal.kaiser` + +`signal.kaiser(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Kaiser`](haskell/HMath-Signal.md#v:Kaiser). + +```haskell +Double -> Window +``` + +```c +hmath_status hmath_signal_value_kaiser(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.gaussian` + +`signal.gaussian(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Gaussian`](haskell/HMath-Signal.md#v:Gaussian). + +```haskell +Double -> Window +``` + +```c +hmath_status hmath_signal_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.tukey` + +`signal.tukey(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Tukey`](haskell/HMath-Signal.md#v:Tukey). + +```haskell +Double -> Window +``` + +```c +hmath_status hmath_signal_value_tukey(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.flat_top` + +`signal.flat_top()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.FlatTop`](haskell/HMath-Signal.md#v:FlatTop). + +```haskell +Window +``` + +```c +hmath_status hmath_signal_value_flat_top(hmath_context *context, hmath_value **out); +``` + +## `signal.dolph_chebyshev` + +`signal.dolph_chebyshev(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.DolphChebyshev`](haskell/HMath-Signal.md#v:DolphChebyshev). + +```haskell +Double -> Window +``` + +```c +hmath_status hmath_signal_value_dolph_chebyshev(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.window` + +`signal.window(kind, n)` + +Generate a finite symmetric window. Gaussian sigma is relative to half length; Dolph attenuation is in dB. + +Original: [`HMath.Signal.window`](haskell/HMath-Signal.md#v:window). + +```haskell +Window -> Int -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_window(hmath_context *context, const hmath_value *kind, const hmath_value *n, hmath_value **out); +``` + +## `signal.windowed_sinc` + +`signal.windowed_sinc(kind, taps, cutoff, rate)` + + Given window kind, odd tap count in [1,257], cutoff frequency and positive sample rate, return normalized low-pass FIR coefficients. Require 0\ Int -> Double -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_windowed_sinc(hmath_context *context, const hmath_value *kind, const hmath_value *taps, const hmath_value *cutoff, const hmath_value *rate, hmath_value **out); +``` + +## `signal.peak` + +`signal.peak(peak_index, peak_height, peak_prominence, peak_width)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Peak`](haskell/HMath-Signal.md#v:Peak). + +```haskell +Int -> Double -> Double -> Double -> Peak +``` + +```c +hmath_status hmath_signal_value_peak(hmath_context *context, const hmath_value *peak_index, const hmath_value *peak_height, const hmath_value *peak_prominence, const hmath_value *peak_width, hmath_value **out); +``` + +## `signal.peak_index` + +`signal.peak_index(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.peakIndex`](haskell/HMath-Signal.md#v:peakIndex). + +```haskell +Peak -> Int +``` + +```c +hmath_status hmath_signal_value_peak_index(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.peak_height` + +`signal.peak_height(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.peakHeight`](haskell/HMath-Signal.md#v:peakHeight). + +```haskell +Peak -> Double +``` + +```c +hmath_status hmath_signal_value_peak_height(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.peak_prominence` + +`signal.peak_prominence(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.peakProminence`](haskell/HMath-Signal.md#v:peakProminence). + +```haskell +Peak -> Double +``` + +```c +hmath_status hmath_signal_value_peak_prominence(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.peak_width` + +`signal.peak_width(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.peakWidth`](haskell/HMath-Signal.md#v:peakWidth). + +```haskell +Peak -> Double +``` + +```c +hmath_status hmath_signal_value_peak_width(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.peaks` + +`signal.peaks(minimum_prominence, minimum_distance, xs)` + + Interior local maxima; flat plateaus select the lower middle index. Width is linearly interpolated at half prominence; endpoints are not peaks. + +Original: [`HMath.Signal.peaks`](haskell/HMath-Signal.md#v:peaks). + +```haskell +Double -> Int -> [Double] -> Either MathError [Peak] +``` + +```c +hmath_status hmath_signal_value_peaks(hmath_context *context, const hmath_value *minimum_prominence, const hmath_value *minimum_distance, const hmath_value *xs, hmath_value **out); +``` + +## `signal.kalman` + +`signal.kalman(value, value2, value3, value4, value5, value6)` + + One linear Gaussian prediction+measurement update. Uses Joseph covariance update to preserve positive semidefiniteness under roundoff. + +Original: [`HMath.Signal.kalman`](haskell/HMath-Signal.md#v:kalman). + +```haskell +[[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState +``` + +```c +hmath_status hmath_signal_value_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +``` + +## `signal.extended_kalman` + +`signal.extended_kalman(value, value2, value3, value4, value5, value6)` + +EKF with checked central-difference Jacobians (step 1e-5*max(1,abs x)). + +Original: [`HMath.Signal.extendedKalman`](haskell/HMath-Signal.md#v:extendedKalman). + +```haskell +([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState +``` + +```c +hmath_status hmath_signal_value_extended_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +``` + +## `signal.unscented_kalman` + +`signal.unscented_kalman(alpha, beta, kappa, transition, measurement, q, r, measured, state)` + + Scaled UKF. alpha>0, beta>=0, n+kappa>0, lambda+n>0. Process noise is incorporated before regenerating measurement sigma points. + +Original: [`HMath.Signal.unscentedKalman`](haskell/HMath-Signal.md#v:unscentedKalman). + +```haskell +Double -> Double -> Double -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState +``` + +```c +hmath_status hmath_signal_value_unscented_kalman(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, const hmath_value *kappa, const hmath_value *transition, const hmath_value *measurement, const hmath_value *q, const hmath_value *r, const hmath_value *measured, const hmath_value *state, hmath_value **out); +``` + +## `signal.haar` + +`signal.haar()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Haar`](haskell/HMath-Signal.md#v:Haar). + +```haskell +Wavelet +``` + +```c +hmath_status hmath_signal_value_haar(hmath_context *context, hmath_value **out); +``` + +## `signal.daubechies2` + +`signal.daubechies2()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Daubechies2`](haskell/HMath-Signal.md#v:Daubechies2). + +```haskell +Wavelet +``` + +```c +hmath_status hmath_signal_value_daubechies2(hmath_context *context, hmath_value **out); +``` + +## `signal.daubechies4` + +`signal.daubechies4()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Daubechies4`](haskell/HMath-Signal.md#v:Daubechies4). + +```haskell +Wavelet +``` + +```c +hmath_status hmath_signal_value_daubechies4(hmath_context *context, hmath_value **out); +``` + +## `signal.biorthogonal53` + +`signal.biorthogonal53()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Biorthogonal53`](haskell/HMath-Signal.md#v:Biorthogonal53). + +```haskell +Wavelet +``` + +```c +hmath_status hmath_signal_value_biorthogonal53(hmath_context *context, hmath_value **out); +``` + +## `signal.wavelet_approximation` + +`signal.wavelet_approximation(value)` + +Coarsest approximation coefficients after all requested levels. + +Original: [`HMath.Signal.waveletApproximation`](haskell/HMath-Signal.md#v:waveletApproximation). + +```haskell +WaveletTree -> [Double] +``` + +```c +hmath_status hmath_signal_value_wavelet_approximation(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.wavelet_details` + +`signal.wavelet_details(value)` + +Detail bands ordered from finest first to coarsest last. + +Original: [`HMath.Signal.waveletDetails`](haskell/HMath-Signal.md#v:waveletDetails). + +```haskell +WaveletTree -> [[Double]] +``` + +```c +hmath_status hmath_signal_value_wavelet_details(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.dwt` + +`signal.dwt(family, levels, xs)` + +Periodic multilevel analysis; length must be divisible by 2^levels, with levels 0..20 and length <=1048576. + +Original: [`HMath.Signal.dwt`](haskell/HMath-Signal.md#v:dwt). + +```haskell +Wavelet -> Int -> [Double] -> Either MathError WaveletTree +``` + +```c +hmath_status hmath_signal_value_dwt(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out); +``` + +## `signal.idwt` + +`signal.idwt(value)` + +Invert multilevel analysis using orthogonal synthesis or inverse CDF 5/3 lifting. + +Original: [`HMath.Signal.idwt`](haskell/HMath-Signal.md#v:idwt). + +```haskell +WaveletTree -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_idwt(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.morlet` + +`signal.morlet(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.Morlet`](haskell/HMath-Signal.md#v:Morlet). + +```haskell +Double -> MotherWavelet +``` + +```c +hmath_status hmath_signal_value_morlet(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.mexican_hat` + +`signal.mexican_hat()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.MexicanHat`](haskell/HMath-Signal.md#v:MexicanHat). + +```haskell +MotherWavelet +``` + +```c +hmath_status hmath_signal_value_mexican_hat(hmath_context *context, hmath_value **out); +``` + +## `signal.gaussian_derivative` + +`signal.gaussian_derivative()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Signal.GaussianDerivative`](haskell/HMath-Signal.md#v:GaussianDerivative). + +```haskell +MotherWavelet +``` + +```c +hmath_status hmath_signal_value_gaussian_derivative(hmath_context *context, hmath_value **out); +``` + +## `signal.cwt` + +`signal.cwt(mother, spacing, scales, xs)` + + Direct zero-extended CWT. Scales are in seconds; coefficients use dt/sqrt(s) quadrature. Morlet subtracts its nonzero-mean correction exp(-omega²/2). + +Original: [`HMath.Signal.cwt`](haskell/HMath-Signal.md#v:cwt). + +```haskell +MotherWavelet -> Double -> [Double] -> [Double] -> Either MathError [[Complex Double]] +``` + +```c +hmath_status hmath_signal_value_cwt(hmath_context *context, const hmath_value *mother, const hmath_value *spacing, const hmath_value *scales, const hmath_value *xs, hmath_value **out); +``` + +## `signal.wavelet_packets` + +`signal.wavelet_packets(family, levels, xs)` + +Recursively analyze both approximation and detail branches to the supplied depth. + +Original: [`HMath.Signal.waveletPackets`](haskell/HMath-Signal.md#v:waveletPackets). + +```haskell +Wavelet -> Int -> [Double] -> Either MathError WaveletPacket +``` + +```c +hmath_status hmath_signal_value_wavelet_packets(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out); +``` + +## `signal.inverse_wavelet_packets` + +`signal.inverse_wavelet_packets(value)` + +Reconstruct a complete packet tree exactly up to floating roundoff. + +Original: [`HMath.Signal.inverseWaveletPackets`](haskell/HMath-Signal.md#v:inverseWaveletPackets). + +```haskell +WaveletPacket -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_inverse_wavelet_packets(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.packet_bands` + +`signal.packet_bands(value)` + +Leaf coefficient bands in natural binary low/high tree order. + +Original: [`HMath.Signal.packetBands`](haskell/HMath-Signal.md#v:packetBands). + +```haskell +WaveletPacket -> [[Double]] +``` + +```c +hmath_status hmath_signal_value_packet_bands(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `signal.wavelet_denoise` + +`signal.wavelet_denoise(family, levels, threshold, xs)` + +Soft-threshold detail coefficients; optional explicit threshold, otherwise finest-band MAD universal threshold. + +Original: [`HMath.Signal.waveletDenoise`](haskell/HMath-Signal.md#v:waveletDenoise). + +```haskell +Wavelet -> Int -> Maybe Double -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_signal_value_wavelet_denoise(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +``` + +## `interpolation.reject` + +`interpolation.reject()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Reject`](haskell/HMath-Interpolation.md#v:Reject). + +```haskell +Extrapolation +``` + +```c +hmath_status hmath_interpolation_value_reject(hmath_context *context, hmath_value **out); +``` + +## `interpolation.clamp` + +`interpolation.clamp()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Clamp`](haskell/HMath-Interpolation.md#v:Clamp). + +```haskell +Extrapolation +``` + +```c +hmath_status hmath_interpolation_value_clamp(hmath_context *context, hmath_value **out); +``` + +## `interpolation.extrapolate` + +`interpolation.extrapolate()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Extrapolate`](haskell/HMath-Interpolation.md#v:Extrapolate). + +```haskell +Extrapolation +``` + +```c +hmath_status hmath_interpolation_value_extrapolate(hmath_context *context, hmath_value **out); +``` + +## `interpolation.nearest` + +`interpolation.nearest()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Nearest`](haskell/HMath-Interpolation.md#v:Nearest). + +```haskell +InterpolationMethod +``` + +```c +hmath_status hmath_interpolation_value_nearest(hmath_context *context, hmath_value **out); +``` + +## `interpolation.linear` + +`interpolation.linear()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Linear`](haskell/HMath-Interpolation.md#v:Linear). + +```haskell +InterpolationMethod +``` + +```c +hmath_status hmath_interpolation_value_linear(hmath_context *context, hmath_value **out); +``` + +## `interpolation.lagrange` + +`interpolation.lagrange()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Lagrange`](haskell/HMath-Interpolation.md#v:Lagrange). + +```haskell +InterpolationMethod +``` + +```c +hmath_status hmath_interpolation_value_lagrange(hmath_context *context, hmath_value **out); +``` + +## `interpolation.newton` + +`interpolation.newton()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Newton`](haskell/HMath-Interpolation.md#v:Newton). + +```haskell +InterpolationMethod +``` + +```c +hmath_status hmath_interpolation_value_newton(hmath_context *context, hmath_value **out); +``` + +## `interpolation.barycentric` + +`interpolation.barycentric()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Barycentric`](haskell/HMath-Interpolation.md#v:Barycentric). + +```haskell +InterpolationMethod +``` + +```c +hmath_status hmath_interpolation_value_barycentric(hmath_context *context, hmath_value **out); +``` + +## `interpolation.natural` + +`interpolation.natural()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Natural`](haskell/HMath-Interpolation.md#v:Natural). + +```haskell +SplineBoundary +``` + +```c +hmath_status hmath_interpolation_value_natural(hmath_context *context, hmath_value **out); +``` + +## `interpolation.clamped` + +`interpolation.clamped(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Clamped`](haskell/HMath-Interpolation.md#v:Clamped). + +```haskell +Double -> Double -> SplineBoundary +``` + +```c +hmath_status hmath_interpolation_value_clamped(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `interpolation.periodic` + +`interpolation.periodic()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Periodic`](haskell/HMath-Interpolation.md#v:Periodic). + +```haskell +SplineBoundary +``` + +```c +hmath_status hmath_interpolation_value_periodic(hmath_context *context, hmath_value **out); +``` + +## `interpolation.gaussian` + +`interpolation.gaussian(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Gaussian`](haskell/HMath-Interpolation.md#v:Gaussian). + +```haskell +Double -> RadialKernel +``` + +```c +hmath_status hmath_interpolation_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.multiquadric` + +`interpolation.multiquadric(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Multiquadric`](haskell/HMath-Interpolation.md#v:Multiquadric). + +```haskell +Double -> RadialKernel +``` + +```c +hmath_status hmath_interpolation_value_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.inverse_multiquadric` + +`interpolation.inverse_multiquadric(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.InverseMultiquadric`](haskell/HMath-Interpolation.md#v:InverseMultiquadric). + +```haskell +Double -> RadialKernel +``` + +```c +hmath_status hmath_interpolation_value_inverse_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.thin_plate` + +`interpolation.thin_plate()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.ThinPlate`](haskell/HMath-Interpolation.md#v:ThinPlate). + +```haskell +RadialKernel +``` + +```c +hmath_status hmath_interpolation_value_thin_plate(hmath_context *context, hmath_value **out); +``` + +## `interpolation.cubic` + +`interpolation.cubic()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Cubic`](haskell/HMath-Interpolation.md#v:Cubic). + +```haskell +RadialKernel +``` + +```c +hmath_status hmath_interpolation_value_cubic(hmath_context *context, hmath_value **out); +``` + +## `interpolation.approximation` + +`interpolation.approximation(approximation_coefficients, approximation_error, approximation_iterations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.Approximation`](haskell/HMath-Interpolation.md#v:Approximation). + +```haskell +[Double] -> Double -> Int -> Approximation +``` + +```c +hmath_status hmath_interpolation_value_approximation(hmath_context *context, const hmath_value *approximation_coefficients, const hmath_value *approximation_error, const hmath_value *approximation_iterations, hmath_value **out); +``` + +## `interpolation.approximation_coefficients` + +`interpolation.approximation_coefficients(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.approximationCoefficients`](haskell/HMath-Interpolation.md#v:approximationCoefficients). + +```haskell +Approximation -> [Double] +``` + +```c +hmath_status hmath_interpolation_value_approximation_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.approximation_error` + +`interpolation.approximation_error(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.approximationError`](haskell/HMath-Interpolation.md#v:approximationError). + +```haskell +Approximation -> Double +``` + +```c +hmath_status hmath_interpolation_value_approximation_error(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.approximation_iterations` + +`interpolation.approximation_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Interpolation.approximationIterations`](haskell/HMath-Interpolation.md#v:approximationIterations). + +```haskell +Approximation -> Int +``` + +```c +hmath_status hmath_interpolation_value_approximation_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.interpolate` + +`interpolation.interpolate(method, policy, points, x0)` + +Interpolate ordered (x,y) samples using the selected formula and extrapolation policy; nearest ties choose the earlier node. + +Original: [`HMath.Interpolation.interpolate`](haskell/HMath-Interpolation.md#v:interpolate). + +```haskell +InterpolationMethod -> Extrapolation -> [(Double, Double)] -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *points, const hmath_value *x0, hmath_value **out); +``` + +## `interpolation.hermite` + +`interpolation.hermite(triples, x)` + + Global confluent Hermite polynomial, distinct nodes and supplied first derivatives. Uses the squared Lagrange cardinal functions. + +Original: [`HMath.Interpolation.hermite`](haskell/HMath-Interpolation.md#v:hermite). + +```haskell +[(Double, Double, Double)] -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_hermite(hmath_context *context, const hmath_value *triples, const hmath_value *x, hmath_value **out); +``` + +## `interpolation.piecewise_polynomial` + +`interpolation.piecewise_polynomial(knots, coefficients)` + +Validate breakpoints and nonempty coefficient rows. Each row uses ascending powers of displacement from its left knot. + +Original: [`HMath.Interpolation.piecewisePolynomial`](haskell/HMath-Interpolation.md#v:piecewisePolynomial). + +```haskell +[Double] -> [[Double]] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_piecewise_polynomial(hmath_context *context, const hmath_value *knots, const hmath_value *coefficients, hmath_value **out); +``` + +## `interpolation.piecewise_knots` + +`interpolation.piecewise_knots(value)` + +Return the immutable piecewise breakpoints, including both outer endpoints. + +Original: [`HMath.Interpolation.piecewiseKnots`](haskell/HMath-Interpolation.md#v:piecewiseKnots). + +```haskell +PiecewisePolynomial -> [Double] +``` + +```c +hmath_status hmath_interpolation_value_piecewise_knots(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.evaluate_piecewise` + +`interpolation.evaluate_piecewise(value, value2, value3)` + +Evaluate by Horner rule in the containing interval; use the final interval at the right endpoint. + +Original: [`HMath.Interpolation.evaluatePiecewise`](haskell/HMath-Interpolation.md#v:evaluatePiecewise). + +```haskell +Extrapolation -> PiecewisePolynomial -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_evaluate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `interpolation.differentiate_piecewise` + +`interpolation.differentiate_piecewise(value)` + +Differentiate each local coefficient row without changing the breakpoints. + +Original: [`HMath.Interpolation.differentiatePiecewise`](haskell/HMath-Interpolation.md#v:differentiatePiecewise). + +```haskell +PiecewisePolynomial -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_differentiate_piecewise(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.integrate_piecewise` + +`interpolation.integrate_piecewise(value, value2, value3)` + +Exact polynomial antiderivative across all crossed intervals; both limits must lie inside the domain. + +Original: [`HMath.Interpolation.integratePiecewise`](haskell/HMath-Interpolation.md#v:integratePiecewise). + +```haskell +PiecewisePolynomial -> Double -> Double -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_integrate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `interpolation.cubic_hermite` + +`interpolation.cubic_hermite(triples)` + + Piecewise cubic Hermite interpolation with supplied endpoint derivatives. Triples are (coordinate,value,slope); first derivatives are continuous at shared knots, while second derivatives need not agree. + +Original: [`HMath.Interpolation.cubicHermite`](haskell/HMath-Interpolation.md#v:cubicHermite). + +```haskell +[(Double, Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_cubic_hermite(hmath_context *context, const hmath_value *triples, hmath_value **out); +``` + +## `interpolation.cubic_spline` + +`interpolation.cubic_spline(boundary, points)` + + Cubic C2 interpolation. Periodic requires equal endpoint values and at least three intervals; endpoint first and second derivatives agree. + +Original: [`HMath.Interpolation.cubicSpline`](haskell/HMath-Interpolation.md#v:cubicSpline). + +```haskell +SplineBoundary -> [(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_cubic_spline(hmath_context *context, const hmath_value *boundary, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.pchip` + +`interpolation.pchip(points)` + + Fritsch--Carlson/PCHIP weighted harmonic interior slopes and limited one- sided endpoints preserve monotonicity on monotone data. + +Original: [`HMath.Interpolation.pchip`](haskell/HMath-Interpolation.md#v:pchip). + +```haskell +[(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_pchip(hmath_context *context, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.akima` + +`interpolation.akima(points)` + +Akima cubic interpolation using slope-difference weights and linearly extended endpoint secants; at least three samples. + +Original: [`HMath.Interpolation.akima`](haskell/HMath-Interpolation.md#v:akima). + +```haskell +[(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_akima(hmath_context *context, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.smoothing_spline` + +`interpolation.smoothing_spline(lambda_, points)` + + Natural cubic smoothing spline minimizing sum (y_i-s(x_i))² plus lambda times integral s''². Reinsch Q/R formulation, unit observation weights. + +Original: [`HMath.Interpolation.smoothingSpline`](haskell/HMath-Interpolation.md#v:smoothingSpline). + +```haskell +Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_smoothing_spline(hmath_context *context, const hmath_value *lambda_, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.b_spline` + +`interpolation.b_spline(degree, knots, controls, weights)` + + Nondecreasing full knot vector, degree 0..16, positive rational weights, control points of equal dimension. Evaluation domain [k_p,k_n]. + +Original: [`HMath.Interpolation.bSpline`](haskell/HMath-Interpolation.md#v:bSpline). + +```haskell +Int -> [Double] -> [[Double]] -> [Double] -> Either MathError BSpline +``` + +```c +hmath_status hmath_interpolation_value_b_spline(hmath_context *context, const hmath_value *degree, const hmath_value *knots, const hmath_value *controls, const hmath_value *weights, hmath_value **out); +``` + +## `interpolation.evaluate_b_spline` + +`interpolation.evaluate_b_spline(s, x)` + +Evaluate rational Cox--de Boor basis functions and divide homogeneous coordinates by their positive total weight. + +Original: [`HMath.Interpolation.evaluateBSpline`](haskell/HMath-Interpolation.md#v:evaluateBSpline). + +```haskell +BSpline -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_interpolation_value_evaluate_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out); +``` + +## `interpolation.derivative_b_spline` + +`interpolation.derivative_b_spline(s, x)` + +Analytic first derivative of a rational B-spline using basis derivatives and the homogeneous quotient rule. + +Original: [`HMath.Interpolation.derivativeBSpline`](haskell/HMath-Interpolation.md#v:derivativeBSpline). + +```haskell +BSpline -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_interpolation_value_derivative_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out); +``` + +## `interpolation.insert_knot` + +`interpolation.insert_knot(value, value2)` + +One Boehm knot insertion in homogeneous coordinates; shape is preserved. + +Original: [`HMath.Interpolation.insertKnot`](haskell/HMath-Interpolation.md#v:insertKnot). + +```haskell +BSpline -> Double -> Either MathError BSpline +``` + +```c +hmath_status hmath_interpolation_value_insert_knot(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `interpolation.rational_bezier` + +`interpolation.rational_bezier(controls, ws, t)` + +Positive-weight rational Bezier curve on [0,1], represented exactly as an open clamped B-spline (degree <=16). + +Original: [`HMath.Interpolation.rationalBezier`](haskell/HMath-Interpolation.md#v:rationalBezier). + +```haskell +[[Double]] -> [Double] -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_interpolation_value_rational_bezier(hmath_context *context, const hmath_value *controls, const hmath_value *ws, const hmath_value *t, hmath_value **out); +``` + +## `interpolation.bezier` + +`interpolation.bezier(value, value2)` + +Polynomial Bezier curve with unit weights; controls are vectors with 1..16 coordinates. + +Original: [`HMath.Interpolation.bezier`](haskell/HMath-Interpolation.md#v:bezier). + +```haskell +[[Double]] -> Double -> Either MathError [Double] +``` + +```c +hmath_status hmath_interpolation_value_bezier(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `interpolation.kochanek_bartels` + +`interpolation.kochanek_bartels(tension, continuity, bias, points)` + + Interpolating cubic Hermite segment sequence with Kochanek--Bartels tension, continuity and bias in [-1,1]; endpoint secants are repeated. + +Original: [`HMath.Interpolation.kochanekBartels`](haskell/HMath-Interpolation.md#v:kochanekBartels). + +```haskell +Double -> Double -> Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_kochanek_bartels(hmath_context *context, const hmath_value *tension, const hmath_value *continuity, const hmath_value *bias, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.cardinal_spline` + +`interpolation.cardinal_spline(value, value2)` + +Kochanek--Bartels interpolation with zero continuity/bias and supplied tension in [-1,1]. + +Original: [`HMath.Interpolation.cardinalSpline`](haskell/HMath-Interpolation.md#v:cardinalSpline). + +```haskell +Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_cardinal_spline(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `interpolation.catmull_rom` + +`interpolation.catmull_rom(value)` + +Cardinal cubic interpolation with zero tension and repeated endpoint secants. + +Original: [`HMath.Interpolation.catmullRom`](haskell/HMath-Interpolation.md#v:catmullRom). + +```haskell +[(Double, Double)] -> Either MathError PiecewisePolynomial +``` + +```c +hmath_status hmath_interpolation_value_catmull_rom(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `interpolation.curve_integral` + +`interpolation.curve_integral(value, value2, value3, value4)` + +Componentwise adaptive integral of a B-spline between in-domain limits, with estimated quadrature errors. + +Original: [`HMath.Interpolation.curveIntegral`](haskell/HMath-Interpolation.md#v:curveIntegral). + +```haskell +C.Tolerance -> BSpline -> Double -> Double -> Either MathError [C.Estimate Double] +``` + +```c +hmath_status hmath_interpolation_value_curve_integral(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `interpolation.arc_length` + +`interpolation.arc_length(tolerance, spline, a, b)` + +Adaptive integral of the Euclidean analytic derivative norm; limits must increase and remain in the spline domain. + +Original: [`HMath.Interpolation.arcLength`](haskell/HMath-Interpolation.md#v:arcLength). + +```haskell +C.Tolerance -> BSpline -> Double -> Double -> Either MathError (C.Estimate Double) +``` + +```c +hmath_status hmath_interpolation_value_arc_length(hmath_context *context, const hmath_value *tolerance, const hmath_value *spline, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `interpolation.grid_interpolate` + +`interpolation.grid_interpolate(method, policy, axes, values, point)` + + Rectilinear multilinear interpolation; values are row-major/last axis fast. Nearest uses Euclidean distance to grid nodes; extrapolation policy per axis. + +Original: [`HMath.Interpolation.gridInterpolate`](haskell/HMath-Interpolation.md#v:gridInterpolate). + +```haskell +InterpolationMethod -> Extrapolation -> [[Double]] -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_grid_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *axes, const hmath_value *values, const hmath_value *point, hmath_value **out); +``` + +## `interpolation.fit_rbf` + +`interpolation.fit_rbf(method, smoothing, nodes, ys)` + +Solve the augmented radial/affine system with nonnegative diagonal smoothing; singular or affinely degenerate systems fail. + +Original: [`HMath.Interpolation.fitRBF`](haskell/HMath-Interpolation.md#v:fitRBF). + +```haskell +RadialKernel -> Double -> [[Double]] -> [Double] -> Either MathError RBF +``` + +```c +hmath_status hmath_interpolation_value_fit_rbf(hmath_context *context, const hmath_value *method, const hmath_value *smoothing, const hmath_value *nodes, const hmath_value *ys, hmath_value **out); +``` + +## `interpolation.evaluate_rbf` + +`interpolation.evaluate_rbf(value, value2)` + +Evaluate a fitted scattered model at one finite point with the original coordinate dimension. + +Original: [`HMath.Interpolation.evaluateRBF`](haskell/HMath-Interpolation.md#v:evaluateRBF). + +```haskell +RBF -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_evaluate_rbf(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `interpolation.inverse_distance` + +`interpolation.inverse_distance(power, nodes, ys, point)` + +Normalized inverse-distance interpolation with positive power; coincident queries return the exact observation. + +Original: [`HMath.Interpolation.inverseDistance`](haskell/HMath-Interpolation.md#v:inverseDistance). + +```haskell +Double -> [[Double]] -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_inverse_distance(hmath_context *context, const hmath_value *power, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out); +``` + +## `interpolation.shepard` + +`interpolation.shepard(value, value2, value3)` + +Classical inverse-square Shepard interpolation in the supplied Euclidean coordinates. + +Original: [`HMath.Interpolation.shepard`](haskell/HMath-Interpolation.md#v:shepard). + +```haskell +[[Double]] -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_shepard(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `interpolation.kriging` + +`interpolation.kriging(range, nugget, nodes, ys, point)` + + Ordinary kriging with stationary exponential covariance exp(-distance/range), optional independent nugget, unbiased constant mean. Returns mean and variance. + +Original: [`HMath.Interpolation.kriging`](haskell/HMath-Interpolation.md#v:kriging). + +```haskell +Double -> Double -> [[Double]] -> [Double] -> [Double] -> Either MathError (Double, Double) +``` + +```c +hmath_status hmath_interpolation_value_kriging(hmath_context *context, const hmath_value *range, const hmath_value *nugget, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out); +``` + +## `interpolation.polynomial_fit` + +`interpolation.polynomial_fit(degree, points)` + +Full-column-rank polynomial least squares via pivoted QR, returning ascending coefficients and maximum observation error. + +Original: [`HMath.Interpolation.polynomialFit`](haskell/HMath-Interpolation.md#v:polynomialFit). + +```haskell +Int -> [(Double, Double)] -> Either MathError Approximation +``` + +```c +hmath_status hmath_interpolation_value_polynomial_fit(hmath_context *context, const hmath_value *degree, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.chebyshev_approximate` + +`interpolation.chebyshev_approximate(degree, f, a, b)` + +Chebyshev-root interpolation on a finite interval; report maximum error on a separate 513-point uniform validation grid. + +Original: [`HMath.Interpolation.chebyshevApproximate`](haskell/HMath-Interpolation.md#v:chebyshevApproximate). + +```haskell +Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation +``` + +```c +hmath_status hmath_interpolation_value_chebyshev_approximate(hmath_context *context, const hmath_value *degree, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `interpolation.pade` + +`interpolation.pade(m, n, series)` + +Padé [m/n] from ascending Taylor coefficients, q_0=1. + +Original: [`HMath.Interpolation.pade`](haskell/HMath-Interpolation.md#v:pade). + +```haskell +Int -> Int -> [Double] -> Either MathError ([Double], [Double]) +``` + +```c +hmath_status hmath_interpolation_value_pade(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *series, hmath_value **out); +``` + +## `interpolation.rational_fit` + +`interpolation.rational_fit(m, n, points)` + + Linearized rational least squares y*q(x)-p(x)=0 with q_0=1; poles at observations are rejected. Error is the actual rational residual. + +Original: [`HMath.Interpolation.rationalFit`](haskell/HMath-Interpolation.md#v:rationalFit). + +```haskell +Int -> Int -> [(Double, Double)] -> Either MathError ([Double], [Double], Double) +``` + +```c +hmath_status hmath_interpolation_value_rational_fit(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *points, hmath_value **out); +``` + +## `interpolation.remez` + +`interpolation.remez(degree, grid_count, tolerance, budget, f, a, b)` + + Discrete Remez exchange on an explicit dense grid, 1..64 degree. Success requires alternating extrema and stable equioscillation; returned error is the maximum on this grid only, not a certified continuous minimax bound. + +Original: [`HMath.Interpolation.remez`](haskell/HMath-Interpolation.md#v:remez). + +```haskell +Int -> Int -> Double -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation +``` + +```c +hmath_status hmath_interpolation_value_remez(hmath_context *context, const hmath_value *degree, const hmath_value *grid_count, const hmath_value *tolerance, const hmath_value *budget, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `interpolation.nonlinear_fit` + +`interpolation.nonlinear_fit(budget, tolerance, model, points, initial)` + + Damped Gauss--Newton least squares with central-difference Jacobian, strict residual/step convergence and finite total callbacks; returns fitted parameters. + +Original: [`HMath.Interpolation.nonlinearFit`](haskell/HMath-Interpolation.md#v:nonlinearFit). + +```haskell +Int -> Double -> (Double -> [Double] -> Double) -> [(Double, Double)] -> [Double] -> Either MathError Approximation +``` + +```c +hmath_status hmath_interpolation_value_nonlinear_fit(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *model, const hmath_value *points, const hmath_value *initial, hmath_value **out); +``` + +## `interpolation.interpolation_error` + +`interpolation.interpolation_error(f, points)` + +Maximum absolute discrepancy at the supplied nonempty observations; nonfinite callback results fail. + +Original: [`HMath.Interpolation.interpolationError`](haskell/HMath-Interpolation.md#v:interpolationError). + +```haskell +(Double -> Double) -> [(Double, Double)] -> Either MathError Double +``` + +```c +hmath_status hmath_interpolation_value_interpolation_error(hmath_context *context, const hmath_value *f, const hmath_value *points, hmath_value **out); +``` + +## `fourier.forward` + +`fourier.forward()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Forward`](haskell/HMath-Fourier.md#v:Forward). + +```haskell +Direction +``` + +```c +hmath_status hmath_fourier_value_forward(hmath_context *context, hmath_value **out); +``` + +## `fourier.inverse` + +`fourier.inverse()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Inverse`](haskell/HMath-Fourier.md#v:Inverse). + +```haskell +Direction +``` + +```c +hmath_status hmath_fourier_value_inverse(hmath_context *context, hmath_value **out); +``` + +## `fourier.automatic` + +`fourier.automatic()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Automatic`](haskell/HMath-Fourier.md#v:Automatic). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_automatic(hmath_context *context, hmath_value **out); +``` + +## `fourier.direct` + +`fourier.direct()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Direct`](haskell/HMath-Fourier.md#v:Direct). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_direct(hmath_context *context, hmath_value **out); +``` + +## `fourier.radix2` + +`fourier.radix2()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Radix2`](haskell/HMath-Fourier.md#v:Radix2). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_radix2(hmath_context *context, hmath_value **out); +``` + +## `fourier.radix4` + +`fourier.radix4()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Radix4`](haskell/HMath-Fourier.md#v:Radix4). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_radix4(hmath_context *context, hmath_value **out); +``` + +## `fourier.mixed_radix` + +`fourier.mixed_radix()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.MixedRadix`](haskell/HMath-Fourier.md#v:MixedRadix). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_mixed_radix(hmath_context *context, hmath_value **out); +``` + +## `fourier.split_radix` + +`fourier.split_radix()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.SplitRadix`](haskell/HMath-Fourier.md#v:SplitRadix). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_split_radix(hmath_context *context, hmath_value **out); +``` + +## `fourier.bluestein` + +`fourier.bluestein()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Bluestein`](haskell/HMath-Fourier.md#v:Bluestein). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_bluestein(hmath_context *context, hmath_value **out); +``` + +## `fourier.rader` + +`fourier.rader()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.Rader`](haskell/HMath-Fourier.md#v:Rader). + +```haskell +FFTAlgorithm +``` + +```c +hmath_status hmath_fourier_value_rader(hmath_context *context, hmath_value **out); +``` + +## `fourier.type_i` + +`fourier.type_i()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.TypeI`](haskell/HMath-Fourier.md#v:TypeI). + +```haskell +TransformType +``` + +```c +hmath_status hmath_fourier_value_type_i(hmath_context *context, hmath_value **out); +``` + +## `fourier.type_ii` + +`fourier.type_ii()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.TypeII`](haskell/HMath-Fourier.md#v:TypeII). + +```haskell +TransformType +``` + +```c +hmath_status hmath_fourier_value_type_ii(hmath_context *context, hmath_value **out); +``` + +## `fourier.type_iii` + +`fourier.type_iii()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.TypeIII`](haskell/HMath-Fourier.md#v:TypeIII). + +```haskell +TransformType +``` + +```c +hmath_status hmath_fourier_value_type_iii(hmath_context *context, hmath_value **out); +``` + +## `fourier.type_iv` + +`fourier.type_iv()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.TypeIV`](haskell/HMath-Fourier.md#v:TypeIV). + +```haskell +TransformType +``` + +```c +hmath_status hmath_fourier_value_type_iv(hmath_context *context, hmath_value **out); +``` + +## `fourier.plan_fft` + +`fourier.plan_fft(direction, method, n)` + +Create a reusable plan after checking length, prime or radix requirements. No input data or external buffers are retained. + +Original: [`HMath.Fourier.planFFT`](haskell/HMath-Fourier.md#v:planFFT). + +```haskell +Direction -> FFTAlgorithm -> Int -> Either MathError FFTPlan +``` + +```c +hmath_status hmath_fourier_value_plan_fft(hmath_context *context, const hmath_value *direction, const hmath_value *method, const hmath_value *n, hmath_value **out); +``` + +## `fourier.execute_fft` + +`fourier.execute_fft(value, value2)` + +Apply a plan to exactly its declared number of finite complex samples; reject nonfinite intermediate results. + +Original: [`HMath.Fourier.executeFFT`](haskell/HMath-Fourier.md#v:executeFFT). + +```haskell +FFTPlan -> [Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_execute_fft(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.fft` + +`fourier.fft(xs)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.fft`](haskell/HMath-Fourier.md#v:fft). + +```haskell +[Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_fft(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.ifft` + +`fourier.ifft(xs)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.ifft`](haskell/HMath-Fourier.md#v:ifft). + +```haskell +[Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_ifft(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.dft` + +`fourier.dft(xs)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.dft`](haskell/HMath-Fourier.md#v:dft). + +```haskell +[Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_dft(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.real_fft` + +`fourier.real_fft(value)` + +Full complex spectrum; the real-spectrum inverse checks Hermitian symmetry. + +Original: [`HMath.Fourier.realFFT`](haskell/HMath-Fourier.md#v:realFFT). + +```haskell +[Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_real_fft(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.inverse_real_fft` + +`fourier.inverse_real_fft(tolerance, xs)` + +Inverse of a full real spectrum; require conjugate symmetry within the supplied absolute tolerance. + +Original: [`HMath.Fourier.inverseRealFFT`](haskell/HMath-Fourier.md#v:inverseRealFFT). + +```haskell +Double -> [Complex Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_inverse_real_fft(hmath_context *context, const hmath_value *tolerance, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.fft_batch` + +`fourier.fft_batch(value, value2)` + +Apply one immutable plan independently to each batch; any inconsistent row length fails. + +Original: [`HMath.Fourier.fftBatch`](haskell/HMath-Fourier.md#v:fftBatch). + +```haskell +FFTPlan -> [[Complex Double]] -> Either MathError [[Complex Double]] +``` + +```c +hmath_status hmath_fourier_value_fft_batch(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.fft_nd` + +`fourier.fft_nd(direction, dims, xs)` + +Transform all axes. Product budget is 65536; last axis varies fastest. + +Original: [`HMath.Fourier.fftND`](haskell/HMath-Fourier.md#v:fftND). + +```haskell +Direction -> [Int] -> [Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_fft_nd(hmath_context *context, const hmath_value *direction, const hmath_value *dims, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.dct` + +`fourier.dct(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.dct`](haskell/HMath-Fourier.md#v:dct). + +```haskell +TransformType -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_dct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.idct` + +`fourier.idct(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.idct`](haskell/HMath-Fourier.md#v:idct). + +```haskell +TransformType -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_idct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.dst` + +`fourier.dst(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.dst`](haskell/HMath-Fourier.md#v:dst). + +```haskell +TransformType -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_dst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.idst` + +`fourier.idst(value, value2)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.idst`](haskell/HMath-Fourier.md#v:idst). + +```haskell +TransformType -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_idst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `fourier.stft_frames` + +`fourier.stft_frames(value)` + +Read the full complex spectra in increasing frame-start order. + +Original: [`HMath.Fourier.stftFrames`](haskell/HMath-Fourier.md#v:stftFrames). + +```haskell +STFT -> [[Complex Double]] +``` + +```c +hmath_status hmath_fourier_value_stft_frames(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.stft` + +`fourier.stft(window, hop, xs)` + +Windowed analysis with an explicit hop in samples, padded endpoint frames, and a 1048576-coefficient storage budget. + +Original: [`HMath.Fourier.stft`](haskell/HMath-Fourier.md#v:stft). + +```haskell +[Double] -> Int -> [Double] -> Either MathError STFT +``` + +```c +hmath_status hmath_fourier_value_stft(hmath_context *context, const hmath_value *window, const hmath_value *hop, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.istft` + +`fourier.istft(value)` + +Overlap-add inverse with squared-window normalization; reject every uncovered original sample. + +Original: [`HMath.Fourier.istft`](haskell/HMath-Fourier.md#v:istft). + +```haskell +STFT -> Either MathError [Double] +``` + +```c +hmath_status hmath_fourier_value_istft(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.magnitude_spectrum` + +`fourier.magnitude_spectrum(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.magnitudeSpectrum`](haskell/HMath-Fourier.md#v:magnitudeSpectrum). + +```haskell +[Complex Double] -> [Double] +``` + +```c +hmath_status hmath_fourier_value_magnitude_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.phase_spectrum` + +`fourier.phase_spectrum(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.phaseSpectrum`](haskell/HMath-Fourier.md#v:phaseSpectrum). + +```haskell +[Complex Double] -> [Double] +``` + +```c +hmath_status hmath_fourier_value_phase_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.power_spectrum` + +`fourier.power_spectrum(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.powerSpectrum`](haskell/HMath-Fourier.md#v:powerSpectrum). + +```haskell +[Complex Double] -> [Double] +``` + +```c +hmath_status hmath_fourier_value_power_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fourier.cross_spectrum` + +`fourier.cross_spectrum(rate, window, x, y)` + +Two-sided conjugate(X)*Y cross PSD using the same sample-rate/window-energy normalization as periodogram. + +Original: [`HMath.Fourier.crossSpectrum`](haskell/HMath-Fourier.md#v:crossSpectrum). + +```haskell +Double -> [Double] -> [Double] -> [Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_cross_spectrum(hmath_context *context, const hmath_value *rate, const hmath_value *window, const hmath_value *x, const hmath_value *y, hmath_value **out); +``` + +## `fourier.spectrogram` + +`fourier.spectrogram(w, h, xs)` + +Squared-magnitude STFT frames, retaining the explicit padding/frame order of stft. + +Original: [`HMath.Fourier.spectrogram`](haskell/HMath-Fourier.md#v:spectrogram). + +```haskell +[Double] -> Int -> [Double] -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_fourier_value_spectrogram(hmath_context *context, const hmath_value *w, const hmath_value *h, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.analytic_signal` + +`fourier.analytic_signal(xs)` + +Real signal plus imaginary Hilbert transform, formed by doubling positive-frequency bins and retaining DC/Nyquist. + +Original: [`HMath.Fourier.analyticSignal`](haskell/HMath-Fourier.md#v:analyticSignal). + +```haskell +[Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_analytic_signal(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.chirp_z` + +`fourier.chirp_z(count, a, w, xs)` + +Direct bounded Z-transform along z_k=a*w^(-k); nonzero a,w required. + +Original: [`HMath.Fourier.chirpZ`](haskell/HMath-Fourier.md#v:chirpZ). + +```haskell +Int -> Complex Double -> Complex Double -> [Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_chirp_z(hmath_context *context, const hmath_value *count, const hmath_value *a, const hmath_value *w, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.goertzel` + +`fourier.goertzel(omega, xs)` + +One arbitrary-frequency DFT value from a second-order real resonator; omega is radians/sample. + +Original: [`HMath.Fourier.goertzel`](haskell/HMath-Fourier.md#v:goertzel). + +```haskell +Double -> [Double] -> Either MathError (Complex Double) +``` + +```c +hmath_status hmath_fourier_value_goertzel(hmath_context *context, const hmath_value *omega, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.fft_convolve` + +`fourier.fft_convolve(a, b)` + +Full zero-padded complex linear convolution; padded transform length is limited to 65536. + +Original: [`HMath.Fourier.fftConvolve`](haskell/HMath-Fourier.md#v:fftConvolve). + +```haskell +[Complex Double] -> [Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_fft_convolve(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `fourier.fft_correlate` + +`fourier.fft_correlate(a, b)` + +Correlation lags -(length b-1)..length a-1, conjugating b. + +Original: [`HMath.Fourier.fftCorrelate`](haskell/HMath-Fourier.md#v:fftCorrelate). + +```haskell +[Complex Double] -> [Complex Double] -> Either MathError [Complex Double] +``` + +```c +hmath_status hmath_fourier_value_fft_correlate(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +``` + +## `fourier.fft_shift` + +`fourier.fft_shift(xs)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.fftShift`](haskell/HMath-Fourier.md#v:fftShift). + +```haskell +[a] -> [a] +``` + +```c +hmath_status hmath_fourier_value_fft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.ifft_shift` + +`fourier.ifft_shift(xs)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.Fourier.ifftShift`](haskell/HMath-Fourier.md#v:ifftShift). + +```haskell +[a] -> [a] +``` + +```c +hmath_status hmath_fourier_value_ifft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `fourier.fft_in_place` + +`fourier.fft_in_place(plan, buffer)` mutates a writable, one-dimensional, native-endian, C-contiguous NumPy `complex128` array using the original `fftInPlace`. The wrapper borrows its storage; the original routine stages and validates input before writing the result. Keep the buffer alive and exclude concurrent access during the call. Invalid lengths and nonfinite input follow the original MathError contract; storage is unchanged on failure. C takes a borrowed `double *` with interleaved real/imaginary components and a signed `ptrdiff_t` complex-element count. + +```c +hmath_status hmath_fourier_value_fft_in_place(hmath_context *context, const hmath_value *plan, double *interleaved, ptrdiff_t count); +``` + +## `describe` + +`signal.describe(value)`, `fourier.describe(value)` and `interpolation.describe(value)` return the original Haskell Show representation of a domain object. C uses `hmath_spectral_describe(context, value, out)` and receives an owned String value. diff --git a/docs/reference/stochastic.md b/docs/reference/stochastic.md new file mode 100644 index 0000000..ea3a48b --- /dev/null +++ b/docs/reference/stochastic.md @@ -0,0 +1,876 @@ +# Random streams, distributions and statistics + +Every function calls the original Haskell implementation. RNG owners retain the complete immutable algorithm state, including buffered outputs. Seeds and generated words use exact Word64 transport. All seven generators, continuation/clone/split/serialization behavior, original distributions, model validation, sample ordering, diagnostics, resource budgets and error recovery are preserved. Values are owned and support `close()`/context management; results survive closing inputs. Generic sample elements preserve arbitrary typed Values rather than coercing through a numeric dtype. + +Callbacks use the original argument order. Raising a `MathError` from a checked callback becomes the original source `Left`; the algorithm retains its original recovery behavior. Unexpected Python exceptions rethrow after native cleanup. Pure callbacks abort on failure. Keep C callbacks/userdata alive as long as any owner/derived closure can invoke them. No package import initializes global RNG state or consumes entropy. + +## `random.clone_rng` + +Copy an immutable state; the copy produces exactly the same future outputs. + +Original signature: `RNG -> RNG`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.seed_rng` + +Deterministically encode a 64-bit seed. Shift engines use SplitMix64 expansion; MT uses the low 32 bits and its standard initialization recurrence. PCG uses a fixed odd stream increment and an offset initial state. Counter engines use the seed as key; ChaCha expands it into a 256-bit simulation key. + +Original signature: `Generator -> Word64 -> RNG`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.next_word64` + +Produce one word and its successor state. Fixed-width arithmetic wraps modulo 2^32 or 2^64 as required by the algorithm. + +Original signature: `RNG -> (Word64, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.split_rng` + +Create two deterministic child streams by hashing two successive parent words. The original immutable parent is unchanged; see the module-level non-overlap caveat. + +Original signature: `RNG -> (RNG, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.serialize_rng` + +Serialize full state, including pending block output, with the versioned hmath-rng-1 prefix. + +Original signature: `RNG -> String`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.restore_rng` + +Parse a versioned full state and validate generator lengths, forbidden zero states, and MT word/index ranges. + +Original signature: `String -> Either MathError RNG`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.uniform` + +Uniform 53-bit real on [0,1), using the most significant random bits. + +Original signature: `RNG -> (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.uniform_open` + +Uniform 52-bit midpoint real on (0,1), safe as input to logarithms. + +Original signature: `RNG -> (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.uniform_int` + +Unbiased inclusive integer range using 64-bit rejection. Supports the complete machine Int range; rejects reversed bounds. + +Original signature: `Int -> Int -> RNG -> Either MathError (Int, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.sample_n` + +Run a checked sampler sequentially, returning values and final state. Count must lie in [0,10000000]. + +Original signature: `Int -> (RNG -> Either MathError (a, RNG)) -> RNG -> Either MathError ([a], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.box_muller` + +Standard normal through the polar-coordinate Box--Muller transform, consuming two uniforms. + +Original signature: `RNG -> (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.marsaglia_normal` + +Standard normal through Marsaglia polar disk rejection, with 10000-proposal budget. + +Original signature: `RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.ziggurat_normal` + +Marsaglia--Tsang 128-layer Ziggurat normal generator. Horizontal rectangles have equal area; the base includes an exponentially proposed tail. Published normal cutoff/area constants: https://doi.org/10.18637/jss.v005.i08 Tables are generated by the area recurrence, not embedded implementation data. + +Original signature: `RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.normal` + +Normal sample with finite mean and strictly positive standard deviation. Arithmetic overflow returns NonFiniteResult. + +Original signature: `Double -> Double -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.exponential` + +Exponential sample parameterized by strictly positive rate, via an open-uniform logarithm. + +Original signature: `Double -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.gamma` + +Gamma shape/scale sample using Marsaglia--Tsang rejection and the shape-augmentation identity below shape one; 10000-proposal budget. + +Original signature: `Double -> Double -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.beta` + +Beta(a,b) as the ratio of independent gamma variates. Positive parameters required; unresolved underflow returns an error. + +Original signature: `Double -> Double -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.poisson` + +Poisson count by exponential-arrival inversion. Rate is in [0,100000], work is capped at one million arrivals. + +Original signature: `Double -> RNG -> Either MathError (Int, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.binomial` + +Binomial count from n independent Bernoulli trials. n<=10000000 and p in [0,1]. + +Original signature: `Int -> Double -> RNG -> Either MathError (Int, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.weighted` + +Draw an index in proportion to finite nonnegative weights; max scaling handles subnormal or overflowing totals and zero weights are never selected. + +Original signature: `[Double] -> RNG -> Either MathError (Int, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.alias_table` + +Build a Walker alias table from finite nonnegative weights with positive maximum; max scaling avoids overflow. + +Original signature: `[Double] -> Either MathError AliasTable`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.alias_sample` + +Draw an index from an already validated alias table, using one uniform integer and one uniform real. + +Original signature: `AliasTable -> RNG -> Either MathError (Int, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.shuffle` + +Fisher--Yates permutation of list positions. This immutable list reference implementation costs quadratic time. + +Original signature: `[a] -> RNG -> Either MathError ([a], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.with_replacement` + +Draw count values independently from a nonempty finite population, preserving duplicates. + +Original signature: `Int -> [a] -> RNG -> Either MathError ([a], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.without_replacement` + +Uniform subset in shuffled order. Count cannot exceed population length; uniqueness is by position. + +Original signature: `Int -> [a] -> RNG -> Either MathError ([a], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.reservoir` + +Algorithm R reservoir over a finite stream, retaining k positions uniformly without replacement. + +Original signature: `Int -> [a] -> RNG -> Either MathError ([a], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.stratified` + +One uniform point per equal-width interval of [0,1), in increasing stratum order. + +Original signature: `Int -> RNG -> Either MathError ([Double], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.rejection` + +Accept proposals with the supplied target/envelope probability in [0,1]; the first argument is a hard proposal budget. + +Original signature: `Int -> (Double -> Double) -> (RNG -> Either MathError (Double, RNG)) -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.inverse_transform` + +Apply a checked inverse CDF to an open uniform; propagates inverse-domain or nonconvergence errors. + +Original signature: `(Double -> Either MathError Double) -> RNG -> Either MathError (Double, RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.metropolis_hastings` + +Symmetric random-walk Metropolis in log density. Returned chain includes each post-proposal state. Non-finite log densities are rejected. + +Original signature: `Int -> Double -> (Double -> Double) -> Double -> RNG -> Either MathError ([Double], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.gibbs` + +A full Gibbs sweep uses caller-supplied exact conditional samplers in coordinate order. Shape is checked after each conditional. + +Original signature: `Int -> [([Double] -> RNG -> Either MathError (Double, RNG))] -> [Double] -> RNG -> Either MathError ([[Double]], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.hamiltonian_monte_carlo` + +Identity-mass HMC with Gaussian momentum, leapfrog count and positive step size, log density and its gradient. Returns post-Metropolis states; finite-gradient shapes are checked. + +Original signature: `Int -> Int -> Double -> ([Double] -> Double) -> ([Double] -> [Double]) -> [Double] -> RNG -> Either MathError ([[Double]], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.monte_carlo` + +Uniform-[0,1] Monte Carlo integral and estimated standard error from at least two draws. This is a stochastic estimate, not a certified bound. + +Original signature: `(Double -> Double) -> Int -> RNG -> Either MathError ((Double, Double), RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.latin_hypercube` + +Random n-by-d Latin hypercube in [0,1), with a separate Fisher--Yates stratum permutation per axis; n>0 and 1<=d<=1024. + +Original signature: `Int -> Int -> RNG -> Either MathError ([[Double]], RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.random_quality` + +Mean, population variance, and lag-one correlation; descriptive quality diagnostics, not a cryptographic certification or a replacement for TestU01. + +Original signature: `Int -> RNG -> Either MathError ((Double, Double, Double), RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.entropy_seed` + +Read eight bytes from the operating system entropy device, little endian. IO exceptions are propagated; this deliberately has no time-based fallback. + +Original signature: `IO Word64`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.pcg32` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.xoshiro256_star_star` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.xoroshiro128_plus` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.mt19937` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.philox4x32` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.threefry2x64` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `random.cha_cha20` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.validate_distribution` + +Check finite parameters, support ordering, probability normalization, and declared per-family reference budgets. + +Original signature: `Distribution -> Either MathError ()`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.log_density` + +Log density or mass; zero probability is negative infinity, while an integrable endpoint singularity is positive infinity. Observations must be finite. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.density` + +Probability mass for discrete families or density for continuous families. At integrable density singularities the result can be positive infinity; outside support it is zero. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.cdf` + +P(X\<=x). Gamma/beta and classical transformed families use analytic special-function identities. Remaining finite-support continuous cases use 2048-panel Simpson integration; Skellam drops a tail beyond 14 standard deviations plus 20 counts. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.survival` + +P(X>x), using direct upper tails for normal, gamma, beta, t, F, binomial and Poisson to avoid cancellation. Other families use the CDF complement. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.quantile` + +Generalized inverse CDF, p in [0,1]; endpoints return mathematical support bounds, including infinities. Interior values use analytic transforms or bounded bracketing/bisection. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.hazard` + +Density divided by survival. For zero survival returns positive infinity by convention. + +Original signature: `Distribution -> Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.log_likelihood` + +Sum of independent observation log probabilities. Impossible data produce negative infinity. + +Original signature: `Distribution -> [Double] -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.moments` + +Mean and population variance. Infinite/nonexistent moments return a domain error rather than a numeric value that could be mistaken for a finite moment. + +Original signature: `Distribution -> Either MathError (Double, Double)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.entropy` + +Shannon or differential entropy in nats. Closed forms are used when available; other families use the documented expectation quadrature. + +Original signature: `Distribution -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.expectation` + +Reference expectation under a distribution. Empirical/mixture cases are exact weighted sums; count families truncate at 1e-10 tail quantiles, continuous families use 4096 midpoint probability-space nodes. No certified quadrature error is claimed. + +Original signature: `Distribution -> (Double -> Double) -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.sample` + +Draw a model sample and updated immutable RNG; specialized gamma/normal/count samplers are reused, with inverse-CDF sampling for remaining families. + +Original signature: `Distribution -> R.RNG -> Either MathError (Double, R.RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fit_normal` + +Normal maximum-likelihood fit; variance divides by n. Constant data are rejected because this continuous family requires positive standard deviation. + +Original signature: `[Double] -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fit_exponential` + +Maximum-likelihood rate for nonnegative observations with strictly positive total. + +Original signature: `[Double] -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fit_bernoulli` + +Maximum-likelihood probability for nonempty binary observations. + +Original signature: `[Double] -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fit_mle_grid` + +Select the maximum-likelihood model from an explicit finite candidate grid; this is grid search, not continuous parameter optimization. + +Original signature: `[Distribution] -> [Double] -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fit_map_grid` + +Select the maximum log-likelihood plus caller-supplied log prior over a finite model grid. Log priors must be finite. + +Original signature: `[Distribution] -> [Double] -> (Distribution -> Double) -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.beta_bernoulli_update` + +Conjugate Beta prior update from success/failure observations, returning posterior concentrations (alpha,beta). + +Original signature: `Double -> Double -> [Bool] -> Either MathError (Double, Double)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.goodness_of_fit` + +Two-sided one-sample Kolmogorov distance against a specified CDF. Returns the distance only; no discrete-null p-value is implied. + +Original signature: `Distribution -> [Double] -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.gaussian_kde` + +Construct an equal-weight Gaussian kernel density with strictly positive bandwidth and finite nonempty observations. + +Original signature: `Double -> [Double] -> Either MathError Distribution`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.multivariate_normal_log_density` + +Log density for a finite mean/point and symmetric positive-definite covariance, validated by Cholesky. + +Original signature: `[Double] -> Matrix Double -> [Double] -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.sample_multivariate_normal` + +Cholesky-transform independent standard normals; returns a vector and updated state. + +Original signature: `[Double] -> Matrix Double -> R.RNG -> Either MathError ([Double], R.RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.wishart_log_density` + +Wishart log density for real degrees of freedom nu>p-1 and positive-definite p-by-p scale and observation matrices. + +Original signature: `Double -> Matrix Double -> Matrix Double -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.sample_wishart` + +Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu\<=100000. + +Original signature: `Int -> Matrix Double -> R.RNG -> Either MathError (Matrix Double, R.RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.markov` + +Validate and construct a row-stochastic matrix with 1..1024 states; row sums tolerate absolute error 1e-12. + +Original signature: `[[Double]] -> Either MathError Markov`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.transition` + +Advance a normalized state-probability row vector by one Markov step. + +Original signature: `Markov -> [Double] -> Either MathError [Double]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.stationary` + +Stationary probabilities by damped power iteration, with caller iteration budget and positive residual tolerance. Reducible chains can have multiple stationary laws. + +Original signature: `Int -> Double -> Markov -> Either MathError [Double]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.hmm` + +Validate initial probabilities, square transition matrix and equally sized categorical-emission rows. + +Original signature: `[Double] -> [[Double]] -> [[Double]] -> Either MathError HMM`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.forward` + +Scaled forward returns log likelihood, normalized alpha rows and per-time scaling constants. This avoids the product underflow of raw probability DP. + +Original signature: `HMM -> [Int] -> Either MathError (Double, [[Double]], [Double])`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.backward` + +Scaled backward messages using the same per-time normalizers as forward; terminal message is the all-ones vector. + +Original signature: `HMM -> [Int] -> Either MathError [[Double]]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.posterior_states` + +Posterior state probabilities at each observation time from normalized alpha-beta products. + +Original signature: `HMM -> [Int] -> Either MathError [[Double]]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.viterbi` + +Most likely state path and its joint log probability, via max-product dynamic programming in log space. + +Original signature: `HMM -> [Int] -> Either MathError ([Int], Double)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.baum_welch` + +Baum--Welch EM for one observation sequence, pseudocount>=0. Transition rows with zero expected occupancy retain their old row. Fixed iteration budget. + +Original signature: `Int -> Double -> HMM -> [Int] -> Either MathError HMM`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.bernoulli` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.binomial` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.negative_binomial` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.geometric` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.hypergeometric` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.poisson` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.categorical` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.discrete_uniform` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.uniform` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.normal` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.log_normal` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.exponential` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.gamma` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.beta` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.chi_square` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.student_t` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.fisher_f` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.cauchy` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.laplace` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.logistic` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.weibull` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.pareto` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.rayleigh` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.maxwell` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.gumbel` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.generalized_extreme_value` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.beta_binomial` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.skellam` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.von_mises` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.triangular` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.truncated_normal` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.mixture` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.empirical` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `probability.new_gaussian_kde` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.covariance_matrix` + +Covariance matrix for variables supplied as columns (each list is one variable). Boolean selects sample correction. + +Original signature: `Bool -> [[Double]] -> Either MathError [[Double]]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.partial_correlation` + +Partial correlation of variable indices i,j conditional on every other supplied column, through the inverse sample covariance. + +Original signature: `[[Double]] -> Int -> Int -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.empty_streaming` + +Zero-count Welford accumulator. + +Original signature: `Streaming`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.update_streaming` + +Add one finite observation by Welford recurrence; nonfinite arithmetic is rejected. + +Original signature: `Streaming -> Double -> Either MathError Streaming`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.combine_streaming` + +Chan parallel merge of two Welford accumulators; empty accumulators are identities. + +Original signature: `Streaming -> Streaming -> Either MathError Streaming`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.streaming_result` + +Return count, mean and variance; True uses n-1 correction and requires at least two samples. + +Original signature: `Bool -> Streaming -> Either MathError (Integer, Double, Double)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.histogram_nd` + +Histogram edges must increase strictly; intervals are [a,b), with the last interval closed on its right. Points outside any axis are excluded. Flattening is row-major, the last axis varies fastest. Weights need not sum to one. + +Original signature: `[[Double]] -> [[Double]] -> [Double] -> Either MathError [Double]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.mutual_information` + +Mutual information in nats from a rectangular normalized joint-probability table. + +Original signature: `[[Double]] -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.bootstrap` + +Seeded nonparametric resampling with replacement. Returns caller statistic for each replicate and final RNG state. + +Original signature: `Int -> ([Double] -> Either MathError Double) -> [Double] -> R.RNG -> Either MathError ([Double], R.RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.jackknife` + +Leave-one-out bias-corrected statistic and jackknife standard error; requires n>=2. + +Original signature: `([Double] -> Either MathError Double) -> [Double] -> Either MathError (Double, Double)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.one_sample_t` + +Two-sided one-sample Student t test against a finite null mean; assumes independent normal observations. + +Original signature: `Double -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.two_sample_t` + +Two-sided pooled t test when True, Welch unequal-variance test when False; each group requires n>=2 and positive combined variation. + +Original signature: `Bool -> [Double] -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.paired_t` + +Two-sided one-sample t test on paired differences; matching group lengths required. + +Original signature: `[Double] -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.z_test` + +Two-sided one-sample normal z test with known strictly positive population standard deviation. + +Original signature: `Double -> Double -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.chi_square_test` + +Pearson goodness-of-fit chi-square statistic for observed and positive expected counts; first argument is number of fitted nuisance parameters. + +Original signature: `Int -> [Double] -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.variance_f_test` + +Two-sided normal-population variance-ratio F test, requiring positive sample variances. + +Original signature: `[Double] -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.anova` + +One-way fixed-effects F test on independent normal groups with common variance; each group requires n>=2. + +Original signature: `[[Double]] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.welch_anova` + +Welch one-way heteroscedastic F test with Satterthwaite denominator degrees of freedom. + +Original signature: `[[Double]] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.kruskal_wallis` + +Tie-corrected Kruskal--Wallis H statistic with chi-square asymptotic calibration. + +Original signature: `[[Double]] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.mann_whitney` + +Mann--Whitney U for the first sample; two-sided tie-corrected normal approximation with continuity correction. + +Original signature: `[Double] -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.wilcoxon` + +Wilcoxon signed-rank test for differences, dropping zeros and using average absolute tied ranks and continuity-corrected normal calibration. + +Original signature: `[Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.kolmogorov_smirnov` + +Two-sided KS statistic and asymptotic p value against a fully specified continuous distribution. A Jacobi theta transformation handles very small statistics. Fitting parameters from these observations invalidates this null calibration. + +Original signature: `P.Distribution -> [Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.shapiro_wilk` + +Royston's AS R94 coefficients and normal-tail approximation, n=3..5000, uncensored samples. Numerical constants are published statistical data. Reference: https://doi.org/10.2307/2986146 + +Original signature: `[Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.anderson_darling` + +Anderson--Darling normality test after fitting the sample mean and unbiased sample standard deviation. The returned statistic is raw A²; Stephens' p-value approximation uses A²*(1+0.75/n+2.25/n²). For adjusted A²>13, the published approximation is outside its calibrated range and the extreme tail is reported as zero instead of extrapolating its quadratic back upward. + +Original signature: `[Double] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.levene` + +One-way ANOVA on absolute deviations; True chooses group medians (Brown--Forsythe), False chooses means. + +Original signature: `Bool -> [[Double]] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.bartlett` + +Bartlett homogeneity-of-variance test, appropriate for normal samples; positive group variances required. + +Original signature: `[[Double]] -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.fisher_exact` + +Two-sided Fisher exact test on nonnegative 2-by-2 counts (a,b;c,d). Enumerates tables with mass no larger than the observed table. + +Original signature: `Int -> Int -> Int -> Int -> Either MathError TestResult`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.permutation_test` + +Seeded two-sided random-label permutation p value for a caller statistic, with the (b+1)/(B+1) correction. + +Original signature: `Int -> ([Double] -> [Double] -> Either MathError Double) -> [Double] -> [Double] -> R.RNG -> Either MathError (TestResult, R.RNG)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.eta_squared` + +One-way ANOVA explained sum of squares divided by total sum of squares. + +Original signature: `[[Double]] -> Either MathError Double`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.grubbs` + +Two-sided single-outlier Grubbs test, returning candidate index, G statistic and rejection decision at alpha; normality assumption required. + +Original signature: `Double -> [Double] -> Either MathError (Int, Double, Bool)`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.masked` + +Keep True-mask observations, then validate retained values. Excluded NaN/infinity do not contaminate results. + +Original signature: `[Bool] -> [Double] -> Either MathError [Double]`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.test_statistic` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `TestResult -> field`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.p_value` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `TestResult -> field`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.degrees_of_freedom` + +Read the original immutable public field; no numerical conversion is performed. + +Original signature: `TestResult -> field`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + +## `statistics_advanced.TestResult` + +Construct the original public variant; positional fields retain their exact source types and order. + +Original signature: `constructor`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error. + diff --git a/docs/reference/tensor-bindings.md b/docs/reference/tensor-bindings.md new file mode 100644 index 0000000..9fcd306 --- /dev/null +++ b/docs/reference/tensor-bindings.md @@ -0,0 +1,687 @@ +# Typed tensors, graphs and mutable buffers + +`from hmath import tensor` exposes the original `HMath.Tensor` and +`HMath.Tensor.Mutable` APIs. C and C++ include `hmath_tensor_bindings.h` and use +shared owned `hmath_value` handles. Shapes, element strides, offsets, layouts, +copy/view choices, explicit dtype conversion, errors and arithmetic follow the +original functions. + +```python +from hmath import tensor + +with tensor.tensor([2, 2], [1, 2, 3, 4], dtype="float32") as source: + with tensor.transpose_tensor(source) as view: + print(view.shape, view.strides, view.values) + with tensor.sum_axes([0], False, source) as sums: + assert sums.values == [4.0, 6.0] +``` + +The Python `tensor.Tensor` owner retains the original boxed Haskell tensor. +`tensor.TensorDouble` is the same native object returned by the Image API's +`to_tensor`; it interchanges without reconstructing values. The buffer kernels +behind the top-level `hmath.Tensor` have their own buffer-oriented API. + +## Elements and type selection + +Constructors take `dtype="float64"` by default. Available standard elements are +`float32`, `float64`, `integer`, `rational`, `complex64`, `complex128`, signed and +unsigned fixed-width integers, `intp`, `uintp`, `bool`, `string`. Exact integers +and rational fractions do not pass through floating-point intermediates. A +boxed original `Numeric.Dual` or Quaternion coefficient can select its complete +nested coefficient type as a prototype. Structural providers retain their +actual original type, such as `API.Algebra.Exact`, without inventing a Num +instance. + +There is no automatic promotion between differently typed tensor operands. +`promote_tensor(dtype, tensor)` invokes the original explicit Real→Fractional +conversion. Operations require their original class instances: Integer has no +Fractional division, Complex has no Ord sorting, and Rational has no RealFloat +norm. Such unavailable specializations return `HMATH_UNSUPPORTED`; they are +never computed through Double as a fallback. Standard numerical dtypes retain +original fixed-width wraparound during arithmetic; input conversion checks +whether a supplied Python integer fits the selected bounded representation. + +`tensor_full` infers a type from its fill value when `dtype` is omitted. +`new_mutable` defaults to `float64`. List operations infer the first tensor's +type, or use the explicit `dtype`; an empty list defaults to `float64` where a +type is otherwise undetermined. `einsum([], "", [], dtype=...)` therefore keeps +the original type-selected scalar-product identity. + +`tensor.element_type` / `element_type(tensor)` returns an owned prototype. For a +structural element this is a type token, retaining its actual codec and original +instance dictionaries. Supply it as `dtype` to construct matching arrays, +map outputs or scalar fills; release the token afterward. Structural scalar +values must be constructed by their original provider. Numerical methods remain +unavailable when that source type has no Num instance. + +## Shapes, storage and inspection + +Scalars have shape `[]` and one element; zero axes retain their dimensions and +have no elements. Dimensions use Haskell Int. Original nonnegative shape, +element-count and Int-overflow checks remain in force. These APIs do not impose +the legacy byte-buffer ABI's rank-eight or one-million-element caps. + +`Tensor.shape`, `.strides`, `.offset`, `.layout`, `.device`, `.numel`, +`.is_contiguous`, `.type_name` and `.values` call the original accessors. +Strides/offsets count **elements**, including negative reversed strides and zero +broadcast strides. Values are copied in logical row-major order. `type_name` is +the original Haskell diagnostic type name; `dtype` is the standard scalar dtype +name where one exists. Generic numeric tensors permit NaN/Inf according to their +original numeric type; checked consumers such as neural layers retain their own +finite-value requirements. + +`tensor_column_major` accepts column-major storage order. Views retain original +backing arrays after a parent owner closes. `contiguous` copies logical values +into row-major storage; reshape uses the original view/copy rules. Tensor +comparison calls the original Eq instance, including its NaN behavior. The +layout enums are `Layout.ROW_MAJOR`, `COLUMN_MAJOR`, `STRIDED`; `Device.CPU` is the +original supported device. + +## Scalar callbacks and deferred graphs + +```python +with tensor.tensor([2], [2, 3], dtype="float32") as values: + with tensor.input_graph(values) as leaf: + with tensor.map_graph(lambda x: x*x, leaf) as deferred: + with tensor.evaluate_graph(deferred) as result: + assert result.values == [4.0, 9.0] +``` + +`map_tensor` / `zip_tensor` accept scalar functions; `map_graph` / `zip_graph` +compose deferred functions and preserve original broadcast validation and +fusion. Graph construction does not call the function or allocate its output +array. Evaluation runs the original graph evaluator. + +Numeric callback arguments are borrowed typed `NumericValue` objects: their +arithmetic operators and methods such as `.sin()` use the original element +instance, preserving Float computation. Bool and String inputs use ordinary +Python values. Copy `.value` or clone a typed scalar to retain a numeric input +past callback return. An optional `dtype` selects the output type; its default +is the first input's type. A callback can return a typed scalar of that type or +a representable ordinary value. Different typed outputs require explicit type +selection. + +Python retains callback references transitively while derived handles can use +them. C function pointers/userdata must remain alive for that same lifetime. +Callbacks are synchronous and may reenter HMath. A checked callback failure uses +the [shared callback wire](errors.md#checked-callbacks): statuses 11, 12, 13 +preserve full MathError, ExprError or InterchangeError payloads. Unexpected +Python exceptions abort and are re-raised after native temporary cleanup. + +## Mutable tensors and borrowed storage + +`new_mutable`, `thaw_tensor`, `read_mutable`, `write_mutable`, `modify_mutable`, +`slice_mutable`, `transpose_mutable`, `freeze_tensor` call the original IO APIs. +Pinned storage is shared by views; freeze/thaw copy, so later writes do not alter +an immutable frozen result. Callers synchronize concurrent writes. Mutable types +require an original Storable instance: standard Float/Double, complex, +fixed-width integers and Bool qualify; Integer/Rational and numeric towers do +not gain one through conversion. Structural providers may expose an existing +Storable instance. + +```python +with tensor.new_mutable([3], 0, dtype="float32") as values: + def fill(buffer): + assert buffer.itemsize == 4 + buffer.pointer[0] = 7 + return buffer.shape + + assert tensor.with_mutable_buffer(values, fill) == [3] + with tensor.freeze_tensor(values) as frozen: + assert frozen.values == [7.0, 0.0, 0.0] +``` + +`with_mutable_buffer` holds the original ForeignPtr alive for the callback. +`BorrowedBuffer` provides logical `shape`, signed element `strides`, actual +Storable `itemsize`/`alignment` and a scoped typed ctypes `pointer`. Honor strides +and extents, and do not retain a pointer or use it after return. Accessing the +wrapper's pointer afterward raises ValueError. Bool uses the source Storable +Bool representation (CInt-sized on supported builds), independent of +Interchange Bool8's one-byte wire format; dtype16 never determines byte size by +itself. C receives the same pointer and metadata tuple +`(prototype, shape, strides, itemsize, alignment)`. The callback may return any +representable shared Value. + +## C ownership and representations + +Original immutable Double tensors use Value kind161, other typed tensors270, +graphs271, mutable views272, callback closures273 and structural type tokens294. +Every output owns one reference; use `hmath_value_release`. All live handles +reserve the runtime. Final shutdown returns BUSY until references and active +calls are gone. Inputs are borrowed for each call; do not race a final release +with its use. Public output pointer storage remains untouched on failure. +Mutable writes have the original operation's effects and synchronization rules. + +C prototypes select an element type using an exact typed scalar, Boolean, +String or structural token; they are type witnesses, rather than fill values. +Use `hmath_tensor_object_callback` for scalar functions and +`hmath_tensor_object_buffer_callback` for borrowed-buffer functions. A successful +callback transfers one owned Value result. Scalar inputs are borrowed tuples; +retain a borrowed object before returning it. Structured errors use +`hmath_callback_error` and length-delimited strings. The additive +`hmath_tensor_object_full_typed` supplies a structural type token to original +`tensorFull` without requiring Num. All numerical algorithms remain the original +Haskell implementations. + +## Function reference + +Signatures below show Python argument order, including language-level dtype +selection. C wrappers follow original source argument order with an explicit +prototype where a source polymorphic type cannot be inferred. C `context` is +first, owned `Value **out` last. Details link to the original +[Tensor](haskell/HMath-Tensor.md) and +[mutable Tensor](haskell/HMath-Tensor-Mutable.md) references. + +### HMath.Tensor + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `RowMajor` | `Layout` | `hmath_tensor_object_row_major_create` | +| `ColumnMajor` | `Layout` | `hmath_tensor_object_column_major_create` | +| `Strided` | `Layout` | `hmath_tensor_object_strided_create` | +| `CPU` | `Device` | `hmath_tensor_object_cpu_create` | +| `tensor(shape, values, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor` | +| `tensor_column_major(shape, values, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_column_major` | +| `tensor_full(shape, value, *, dtype=None)` | `Tensor` | `hmath_tensor_object_tensor_full` | +| `tensor_zeros(shape, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_zeros` | +| `tensor_ones(shape, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_ones` | +| `tensor_arange(start, end, step, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_arange` | +| `tensor_linspace(start, end, count, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_linspace` | +| `tensor_logspace(base, start, end, count, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_tensor_logspace` | +| `tensor_random(seed, shape)` | `(Tensor,Integer)` | `hmath_tensor_object_tensor_random` | +| `tensor_values(tensor)` | `Elements` | `hmath_tensor_object_tensor_values` | +| `tensor_shape(tensor)` | `[Int]` | `hmath_tensor_object_tensor_shape` | +| `tensor_strides(tensor)` | `[Int]` | `hmath_tensor_object_tensor_strides` | +| `tensor_offset(tensor)` | `Int` | `hmath_tensor_object_tensor_offset` | +| `tensor_dtype(tensor)` | `String` | `hmath_tensor_object_tensor_d_type` | +| `tensor_device(tensor)` | `Device` | `hmath_tensor_object_tensor_device` | +| `tensor_layout(tensor)` | `Layout` | `hmath_tensor_object_tensor_layout` | +| `numel(tensor)` | `Int` | `hmath_tensor_object_numel` | +| `is_contiguous(tensor)` | `Bool` | `hmath_tensor_object_is_contiguous` | +| `shape_size(shape)` | `Int` | `hmath_tensor_object_shape_size` | +| `infer_broadcast(left, right)` | `[Int]` | `hmath_tensor_object_infer_broadcast` | +| `contiguous(tensor)` | `Tensor` | `hmath_tensor_object_contiguous` | +| `index_tensor(tensor, coordinates)` | `Element` | `hmath_tensor_object_index_tensor` | +| `slice_tensor(axis, start, count, step, tensor)` | `Tensor` | `hmath_tensor_object_slice_tensor` | +| `fancy_index(axis, indices, tensor)` | `Tensor` | `hmath_tensor_object_fancy_index` | +| `gather(axis, indices, tensor)` | `Tensor` | `hmath_tensor_object_gather` | +| `boolean_index(mask, tensor)` | `Tensor` | `hmath_tensor_object_boolean_index` | +| `scatter(axis, indices, updates, target)` | `Tensor` | `hmath_tensor_object_scatter` | +| `scatter_add(axis, indices, updates, target)` | `Tensor` | `hmath_tensor_object_scatter_add` | +| `reshape_tensor(shape, tensor)` | `Tensor` | `hmath_tensor_object_reshape_tensor` | +| `flatten_tensor(tensor)` | `Tensor` | `hmath_tensor_object_flatten_tensor` | +| `squeeze(tensor)` | `Tensor` | `hmath_tensor_object_squeeze` | +| `unsqueeze(axis, tensor)` | `Tensor` | `hmath_tensor_object_unsqueeze` | +| `expand(shape, tensor)` | `Tensor` | `hmath_tensor_object_expand` | +| `permute(axes, tensor)` | `Tensor` | `hmath_tensor_object_permute` | +| `transpose_tensor(tensor)` | `Tensor` | `hmath_tensor_object_transpose_tensor` | +| `move_axis(from_axis, to_axis, tensor)` | `Tensor` | `hmath_tensor_object_move_axis` | +| `swap_axes(from_axis, to_axis, tensor)` | `Tensor` | `hmath_tensor_object_swap_axes` | +| `broadcast_to(shape, tensor)` | `Tensor` | `hmath_tensor_object_broadcast_to` | +| `repeat_tensor(axis, count, tensor)` | `Tensor` | `hmath_tensor_object_repeat_tensor` | +| `tile(counts, tensor)` | `Tensor` | `hmath_tensor_object_tile` | +| `concatenate(axis, tensors, *, dtype=None)` | `Tensor` | `hmath_tensor_object_concatenate` | +| `stack(axis, tensors, *, dtype=None)` | `Tensor` | `hmath_tensor_object_stack` | +| `split_tensor(axis, segments, tensor)` | `[Tensor]` | `hmath_tensor_object_split_tensor` | +| `chunk_tensor(axis, count, tensor)` | `[Tensor]` | `hmath_tensor_object_chunk_tensor` | +| `pad_tensor(padding, value, tensor)` | `Tensor` | `hmath_tensor_object_pad_tensor` | +| `roll(axis, shift, tensor)` | `Tensor` | `hmath_tensor_object_roll` | +| `flip_tensor(axis, tensor)` | `Tensor` | `hmath_tensor_object_flip_tensor` | +| `rotate(first, second, turns, tensor)` | `Tensor` | `hmath_tensor_object_rotate` | +| `sort_tensor(tensor)` | `Tensor` | `hmath_tensor_object_sort_tensor` | +| `unique(tensor)` | `Tensor` | `hmath_tensor_object_unique` | +| `argsort(tensor)` | `Tensor` | `hmath_tensor_object_argsort` | +| `topk(count, tensor)` | `(Tensor,Tensor)` | `hmath_tensor_object_topk` | +| `nonzero(tensor)` | `Tensor` | `hmath_tensor_object_nonzero` | +| `where_tensor(mask, left, right)` | `Tensor` | `hmath_tensor_object_where_tensor` | +| `masked_fill(mask, value, tensor)` | `Tensor` | `hmath_tensor_object_masked_fill` | +| `masked_select(mask, tensor)` | `Tensor` | `hmath_tensor_object_masked_select` | +| `map_tensor(function, tensor, *, dtype=None)` | `Tensor` | `hmath_tensor_object_map_tensor` | +| `zip_tensor(function, left, right, *, dtype=None)` | `Tensor` | `hmath_tensor_object_zip_tensor` | +| `tensor_add(a, b)` | `Tensor` | `hmath_tensor_object_tensor_add` | +| `tensor_subtract(a, b)` | `Tensor` | `hmath_tensor_object_tensor_subtract` | +| `tensor_multiply(a, b)` | `Tensor` | `hmath_tensor_object_tensor_multiply` | +| `tensor_divide(a, b)` | `Tensor` | `hmath_tensor_object_tensor_divide` | +| `tensor_equal(a, b)` | `Tensor` | `hmath_tensor_object_tensor_equal` | +| `tensor_less(a, b)` | `Tensor` | `hmath_tensor_object_tensor_less` | +| `tensor_and(a, b)` | `Tensor` | `hmath_tensor_object_tensor_and` | +| `tensor_or(a, b)` | `Tensor` | `hmath_tensor_object_tensor_or` | +| `tensor_not(tensor)` | `Tensor` | `hmath_tensor_object_tensor_not` | +| `promote_tensor(dtype, tensor)` | `Tensor` | `hmath_tensor_object_promote_tensor` | +| `sum_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_sum_axes` | +| `product_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_product_axes` | +| `mean_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_mean_axes` | +| `variance_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_variance_axes` | +| `norm_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_norm_axes` | +| `min_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_min_axes` | +| `max_axes(axes, keep_dimensions, tensor)` | `Tensor` | `hmath_tensor_object_max_axes` | +| `argmin(tensor)` | `Int` | `hmath_tensor_object_argmin` | +| `argmax(tensor)` | `Int` | `hmath_tensor_object_argmax` | +| `cumulative_sum(axis, tensor)` | `Tensor` | `hmath_tensor_object_cumulative_sum` | +| `cumulative_product(axis, tensor)` | `Tensor` | `hmath_tensor_object_cumulative_product` | +| `tensordot(left_axes, right_axes, left, right)` | `Tensor` | `hmath_tensor_object_tensordot` | +| `einsum(labels, output, tensors, *, dtype=None)` | `Tensor` | `hmath_tensor_object_einsum` | +| `batched_matmul(a, b)` | `Tensor` | `hmath_tensor_object_batched_matmul` | +| `tensor_kronecker(a, b)` | `Tensor` | `hmath_tensor_object_tensor_kronecker` | +| `serialize_tensor(tensor)` | `String` | `hmath_tensor_object_serialize_tensor` | +| `deserialize_tensor(source, *, dtype='float64')` | `Tensor` | `hmath_tensor_object_deserialize_tensor` | +| `input_graph(tensor)` | `TensorGraph` | `hmath_tensor_object_input_graph` | +| `map_graph(function, graph, *, dtype=None)` | `TensorGraph` | `hmath_tensor_object_map_graph` | +| `zip_graph(function, left, right, *, dtype=None)` | `TensorGraph` | `hmath_tensor_object_zip_graph` | +| `evaluate_graph(tensor)` | `Tensor` | `hmath_tensor_object_evaluate_graph` | + +#### `tensor(shape, values, *, dtype='float64')` + +Given shape then flat row-major values, construct an immutable CPU tensor. Require exactly the shape product values; invalid dimensions/count return Left MathError. Generic values are not validated for finiteness. + +#### `tensor_column_major(shape, values, *, dtype='float64')` + +Given shape then values in column-major storage order, construct a column-major CPU tensor. Validate shape/count as tensor; logical tensorValues still traverses row-major coordinates. + +#### `tensor_full(shape, value, *, dtype=None)` + +Given shape then fill value, construct an immutable row-major tensor with every element equal to that value. Invalid/overflowing shape fails. + +#### `tensor_zeros(shape, *, dtype='float64')` + +Construct a row-major tensor of zeros with the supplied shape. Invalid dimensions or element-product overflow return Left MathError. + +#### `tensor_ones(shape, *, dtype='float64')` + +Construct a row-major tensor of ones with the supplied shape. Scalars contain one 1; zero axes contain no values. + +#### `tensor_arange(start, end, step, *, dtype='float64')` + +Given finite start, exclusive stop, and nonzero finite step, construct a rank-one arithmetic progression. A step pointing away from stop yields empty output. Reject invalid inputs or Int-size count overflow. + +#### `tensor_linspace(start, end, count, *, dtype='float64')` + +Given start, stop, then nonnegative count, return a rank-one evenly spaced sequence including both endpoints when count>=2. Count zero gives empty, count one gives start. Negative count fails; generic arithmetic is unchecked. + +#### `tensor_logspace(base, start, end, count, *, dtype='float64')` + +Given base, starting exponent, ending exponent, then count, return base raised to tensorLinspace exponents. Negative count fails; Floating domain/overflow behavior follows the element type. + +#### `tensor_random(seed, shape)` + +Explicit deterministic LCG seed. Values are uniform in [0,1); the returned seed continues the stream, and does not access global mutable generator state. + +#### `tensor_values(tensor)` + +Return logical values in row-major coordinate order, honoring strides/offsets rather than exposing raw backing storage. + +#### `tensor_shape(tensor)` + +Return dimensions in axis order. Scalar shape is []; empty axes are retained. + +#### `tensor_strides(tensor)` + +Return signed element strides for each axis. These describe shared views; they are not byte offsets and can be zero (broadcast) or negative (reverse slices). + +#### `tensor_offset(tensor)` + +Return backing-array offset in elements of the logical coordinate origin. Combine with tensorStrides for view indexing. + +#### `tensor_dtype(tensor)` + +Return the Typeable element type name as a String. This is diagnostic metadata, not an implicit conversion or stable external dtype code. + +#### `tensor_device(tensor)` + +Return CPU, the supported device for this Haskell tensor implementation. + +#### `tensor_layout(tensor)` + +Classify canonical row-major strides first, then column-major, otherwise Strided. Ambiguous single-axis layouts are classified RowMajor. + +#### `numel(tensor)` + +Return logical element count (product of shape), including one for scalars and zero for any empty axis. + +#### `is_contiguous(tensor)` + +Test whether stored strides exactly match canonical row-major strides for this shape. Offset does not prevent a contiguous view; column-major layouts generally return False. + +#### `shape_size(shape)` + +Validate nonnegative dimensions and return their product as Int. Scalar [] has one element; a zero axis gives zero. Negative dimensions or an Int-overflowing product return Left InvalidArgument. Haskell tensors do not inherit the C ABI's smaller rank/element caps. + +#### `infer_broadcast(left, right)` + +Given two shapes, align trailing dimensions; equal sizes or a size-one dimension are compatible. Return the broadcasted shape after nonnegative/Int-size validation; incompatible dimensions fail. + +#### `contiguous(tensor)` + +Copy logical values into a new canonical row-major tensor of the same shape. Return checked construction result; existing views remain unchanged. + +#### `index_tensor(tensor, coordinates)` + +Given tensor then complete zero-based coordinate list, return the element. Wrong coordinate rank or out-of-range index returns Left InvalidArgument. + +#### `slice_tensor(axis, start, count, step, tensor)` + +Given axis,start,count,nonzero step,then tensor, return a zero-copy strided view. Negative steps are supported with valid reachable coordinates. Invalid axis/extent, stride overflow or backing bounds return Left MathError. + +#### `fancy_index(axis, indices, tensor)` + +Given axis then index list then tensor, copy selected positions along that axis in index-list order, retaining duplicates. Invalid axis/indices or output-size overflow fail. + +#### `gather(axis, indices, tensor)` + +Alias of fancyIndex: given axis, zero-based index list, then tensor, copy those axis positions. Invalid axis/indices fail; index-list order and duplicates are preserved. + +#### `boolean_index(mask, tensor)` + +Given an identically shaped Bool mask then tensor, return a rank-one tensor of values whose mask is True, in logical row-major order. Mask mismatch fails; alias of maskedSelect. + +#### `scatter(axis, indices, updates, target)` + +Given axis,index list,update tensor,then target, return a new target-shaped tensor with updates written to selected positions. Update shape replaces that axis with index-list length; invalid shape/indices fail. Repeated indices use the last update in traversal order. + +#### `scatter_add(axis, indices, updates, target)` + +Given axis,indices,updates,target, return a new target with updates added at selected coordinates. Duplicate indices accumulate; update shape and indices follow scatter validation. + +#### `reshape_tensor(shape, tensor)` + +Given new dimensions then tensor, preserve logical element order with unchanged count. Contiguous input yields a shared view; non-contiguous input is copied. Invalid dimensions/count fail; no -1 inference. + +#### `flatten_tensor(tensor)` + +Reshape to rank one with numel entries in logical row-major order. Shares contiguous storage and copies non-contiguous input; checked reshape errors propagate. + +#### `squeeze(tensor)` + +Remove every length-one axis as a shared view, preserving storage and logical values. A single-element all-one shape becomes scalar []. + +#### `unsqueeze(axis, tensor)` + +Given insertion axis in [0,rank] then tensor, insert a length-one dimension as a shared view. Out-of-range axis returns Left InvalidArgument. + +#### `expand(shape, tensor)` + +Alias of broadcastTo: expand singleton dimensions to a requested compatible target shape without copying values. Invalid broadcast shapes fail. + +#### `permute(axes, tensor)` + +Given a permutation of all zero-based axes then tensor, return a zero-copy view with shape/strides reordered. Missing, duplicate or invalid axes fail. + +#### `transpose_tensor(tensor)` + +Reverse every axis of a tensor as a shared view. For rank two this exchanges rows/columns; it is not restricted to matrices. + +#### `move_axis(from_axis, to_axis, tensor)` + +Given source axis,destination axis,then tensor, move one axis while preserving the order of others. Both axes must identify existing dimensions; invalid axes fail. + +#### `swap_axes(from_axis, to_axis, tensor)` + +Given two existing axes then tensor, exchange their dimensions/strides in a shared view. Invalid axes return Left MathError. + +#### `broadcast_to(shape, tensor)` + +Given target shape then tensor, return a shared zero-stride view where existing/trailing size-one axes can expand. Target must be exactly a valid broadcast destination; incompatible/overflowing shapes fail. + +#### `repeat_tensor(axis, count, tensor)` + +Given axis,repetition count,then tensor, repeat each individual axis position consecutively. Nonnegative count is required; zero yields an empty axis. Invalid axis/count or size overflow fails. + +#### `tile(counts, tensor)` + +Given one nonnegative repetition count per existing axis then tensor, tile whole axis contents into repeated blocks. Rank mismatch, negative repetitions or resulting size overflow fail. + +#### `concatenate(axis, tensors, *, dtype=None)` + +Given existing axis then nonempty tensor list, copy tensors end-to-end along that axis. All other dimensions must match; empty list, axis/shape mismatch or size overflow fails. + +#### `stack(axis, tensors, *, dtype=None)` + +Given insertion axis then nonempty list of equally shaped tensors, insert that axis and concatenate along it. Invalid insertion axis or incompatible input shapes fail. + +#### `split_tensor(axis, segments, tensor)` + +Given axis,nonnegative segment sizes,then tensor, return shared slices partitioning that axis exactly. Sizes must sum to the axis length; invalid axis/partition fails. + +#### `chunk_tensor(axis, count, tensor)` + +Given axis,positive chunk count,then tensor, split into exactly that many near-equal shared slices; earlier chunks get the remainder. Empty chunks are allowed if chunks exceed axis size. Invalid axis/count fails. + +#### `pad_tensor(padding, value, tensor)` + +Given (before,after) nonnegative padding for every axis,fill value,then tensor, copy into a padded output. Rank mismatch, negative padding or output-size overflow fails. + +#### `roll(axis, shift, tensor)` + +Given axis,signed shift,then tensor, cyclically shift elements along the axis, preserving shape. Positive shifts move values toward larger indices. Invalid axis fails; the output is copied. + +#### `flip_tensor(axis, tensor)` + +Given axis then tensor, reverse that axis using a negative-stride shared slice. Invalid axis returns Left MathError. + +#### `rotate(first, second, turns, tensor)` + +Given two distinct axes,integer quarter-turn count,then tensor, repeatedly swap axes and flip the first. Turns are reduced modulo four; invalid/equal axes fail. + +#### `sort_tensor(tensor)` + +Flatten logical values and return a rank-one tensor sorted ascending under Ord. Original shape is not preserved. + +#### `unique(tensor)` + +Return sorted distinct logical values as a rank-one tensor. Input shape/order are not preserved. + +#### `argsort(tensor)` + +Flatten logical values and return a rank-one tensor of stable zero-based ascending-sort indices. Ties preserve original order. + +#### `topk(count, tensor)` + +Given k in [0,numel] then tensor, return rank-one (values,flat indices) for k largest values in descending order. Equal values use reverse stable-sort order. Invalid k fails. + +#### `nonzero(tensor)` + +Return a count-by-rank tensor of zero-based coordinates of nonzero elements in row-major traversal order. For a nonzero scalar the shape is [1,0]. + +#### `where_tensor(mask, left, right)` + +Given Bool mask,yes tensor,no tensor, broadcast all three shapes and select yes/no values elementwise. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `masked_fill(mask, value, tensor)` + +Given broadcastable mask,fill value,then tensor, return a copied result with True positions replaced. Incompatible mask broadcast or output construction fails. + +#### `masked_select(mask, tensor)` + +Given mask then identically shaped tensor, return a rank-one copy of True-selected values in row-major order. Shape mismatch returns Left InvalidArgument. + +#### `map_tensor(function, tensor, *, dtype=None)` + +Apply scalar arithmetic, comparisons, logic, or elementary functions such as `sin`, `exp`, and `log` to each logical element. A contiguous output is created; scalar numeric domain/overflow behavior follows the supplied function. + +#### `zip_tensor(function, left, right, *, dtype=None)` + +Given binary element function then two tensors, broadcast compatible shapes and return a new contiguous result. Shape/size failures return Left MathError; function evaluation/domain errors follow the supplied function. + +#### `tensor_add(a, b)` + +Given two tensors, broadcast compatible shapes and add corresponding values, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_subtract(a, b)` + +Given two tensors, broadcast compatible shapes and subtract right values from left, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_multiply(a, b)` + +Given two tensors, broadcast compatible shapes and multiply corresponding values, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_divide(a, b)` + +Given two tensors, broadcast compatible shapes and divide left values by right, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. Division-by-zero/non-finite behavior follows Fractional; it is not additionally checked. + +#### `tensor_equal(a, b)` + +Given two tensors, broadcast compatible shapes and compare corresponding values for equality, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_less(a, b)` + +Given two tensors, broadcast compatible shapes and compare corresponding values with (\<), returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_and(a, b)` + +Given two tensors, broadcast compatible shapes and combine Bool values with logical AND, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_or(a, b)` + +Given two tensors, broadcast compatible shapes and combine Bool values with logical OR, returning a new contiguous tensor. Incompatible/overflowing broadcast shapes return Left MathError. + +#### `tensor_not(tensor)` + +Negate each Bool element, returning a new contiguous tensor of the same shape. No broadcast or ownership mutation occurs. + +#### `promote_tensor(dtype, tensor)` + +Explicitly convert each Real element through exact Rational to the destination Fractional type, preserving shape. Destination rounding/overflow follows its conversion; no implicit promotion occurs elsewhere. + +#### `sum_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by sum. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty reduced groups use zero. + +#### `product_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by product. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty reduced groups use one. + +#### `mean_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by arithmetic mean. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Nonempty output with an empty reduced group fails. + +#### `variance_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by population variance (dividing by group size). True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty reduced groups fail as meanAxes. + +#### `norm_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by scaled Euclidean norm. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty groups have norm zero; IEEE NaN/infinity propagate. + +#### `min_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by minimum. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty reduced groups fail. + +#### `max_axes(axes, keep_dimensions, tensor)` + +Given unique zero-based axis list,keep-dimensions Bool,then tensor, reduce those axes by maximum. True retains reduced dimensions as size one; False removes them. Invalid/duplicate axes fail. Empty reduced groups fail. + +#### `argmin(tensor)` + +Return first zero-based flat row-major index of a minimum logical element. Empty input returns Left DomainError. + +#### `argmax(tensor)` + +Return first zero-based flat row-major index of a maximum logical element. Empty input returns Left DomainError. + +#### `cumulative_sum(axis, tensor)` + +Given existing axis then tensor, return inclusive running sums along that axis, preserving shape. Invalid axis fails; arithmetic follows Num. + +#### `cumulative_product(axis, tensor)` + +Given existing axis then tensor, return inclusive running products along that axis, preserving shape. Invalid axis fails; arithmetic follows Num. + +#### `tensordot(left_axes, right_axes, left, right)` + +Given contraction axes for the first tensor,axes for the second,then both tensors, sum products over matched axis pairs. Noncontracted left axes precede right axes in the output. Reject duplicate/out-of-range axes or mismatched contraction dimensions. + +#### `einsum(labels, output, tensors, *, dtype=None)` + +Explicit Einstein notation; each operand has one label per axis. Repeated labels select diagonals; absent output labels are summed. Ellipses are not accepted: callers express batch labels explicitly, preventing ambiguity. + +#### `batched_matmul(a, b)` + +Multiply tensors on their final two dimensions and broadcast leading batch dimensions. Require rank>=2 and matching inner dimensions; incompatible broadcast or size overflow fails. Generic Num arithmetic is unchanged. + +#### `tensor_kronecker(a, b)` + +Return multidimensional Kronecker product, left-padding the lower-rank shape with ones and multiplying corresponding axis sizes. Invalid/overflowing resulting dimensions fail. + +#### `serialize_tensor(tensor)` + +Serialize (shape,logical row-major values) using Haskell Show. Storage strides/offsets are not retained; the encoding requires a compatible Read instance for round-trip. + +#### `deserialize_tensor(source, *, dtype='float64')` + +Read a complete Haskell (shape,values) encoding, permitting only trailing whitespace, and validate shape/count. Malformed input or invalid dimensions/count returns Left MathError. + +#### `input_graph(tensor)` + +Wrap an immutable tensor as a lazy TensorGraph leaf, retaining its backing storage without evaluating a new output array. + +#### `map_graph(function, graph, *, dtype=None)` + +Given element function then graph, compose a lazy element transform, preserving shape. No output tensor is allocated until evaluateGraph. + +#### `zip_graph(function, left, right, *, dtype=None)` + +Given binary function then two graphs, validate broadcast shapes and return a fused lazy graph. Incompatible shapes return Left MathError before evaluation. + +#### `evaluate_graph(tensor)` + +Evaluate a lazy graph into one contiguous row-major tensor. Adjacent map/zip operations are fused; scalar evaluation behavior follows supplied functions and checked output shape errors propagate. + +### HMath.Tensor.Mutable + +| Python callable/constructor | Result | C wrapper | +| --- | --- | --- | +| `new_mutable(shape, value, *, dtype='float64')` | `MutableTensor` | `hmath_tensor_object_new_mutable` | +| `thaw_tensor(tensor)` | `MutableTensor` | `hmath_tensor_object_thaw_tensor` | +| `freeze_tensor(tensor)` | `Tensor` | `hmath_tensor_object_freeze_tensor` | +| `mutable_shape(tensor)` | `[Int]` | `hmath_tensor_object_mutable_shape` | +| `read_mutable(tensor, coordinates)` | `Element` | `hmath_tensor_object_read_mutable` | +| `write_mutable(tensor, coordinates, value)` | `Unit` | `hmath_tensor_object_write_mutable` | +| `modify_mutable(tensor, coordinates, function)` | `Unit` | `hmath_tensor_object_modify_mutable` | +| `slice_mutable(axis, start, count, step, tensor)` | `MutableTensor` | `hmath_tensor_object_slice_mutable` | +| `transpose_mutable(tensor)` | `MutableTensor` | `hmath_tensor_object_transpose_mutable` | +| `mutable_alignment(dtype)` | `Int` | `hmath_tensor_object_mutable_alignment` | +| `with_mutable_buffer(tensor, function)` | `Generic` | `hmath_tensor_object_with_mutable_buffer` | + +#### `new_mutable(shape, value, *, dtype='float64')` + +Given checked dimensions then fill value, allocate pinned row-major storage filled with that value. Shape/byte-size overflow returns Left MathError; allocation errors remain IO exceptions. Empty tensors are valid. + +#### `thaw_tensor(tensor)` + +Copy logical immutable tensor values to new contiguous pinned mutable storage. Byte-size overflow returns Left InvalidArgument; allocation failures remain IO exceptions. The source stays unchanged. + +#### `freeze_tensor(tensor)` + +Copy current logical view values into a new immutable tensor in row-major order. Return checked tensor construction errors; later mutable writes do not affect the result. + +#### `mutable_shape(tensor)` + +Return current mutable-view dimensions in axis order. Slices/transposes can change the view shape while sharing storage. + +#### `read_mutable(tensor, coordinates)` + +Given a mutable view then full zero-based coordinate list, read one element through the view strides. Wrong rank or out-of-range coordinates return Left InvalidArgument. Callers synchronize concurrent writes. + +#### `write_mutable(tensor, coordinates, value)` + +Given a mutable view, full coordinate list, then value, update that storage element. Invalid coordinates return Left InvalidArgument without writing; synchronize concurrent access externally. + +#### `modify_mutable(tensor, coordinates, function)` + +Given view, coordinates, then transformation, read and replace an element. Invalid coordinates fail. This read-modify-write is not atomic across threads; callers provide synchronization. + +#### `slice_mutable(axis, start, count, step, tensor)` + +Given axis, start, count, nonzero step, then view, return a zero-copy mutable slice retaining shared ForeignPtr ownership. Negative steps are supported if all reached indices stay in bounds. Invalid extent/axis or stride overflow fails. + +#### `transpose_mutable(tensor)` + +Reverse the order of all shape axes and strides, returning a zero-copy mutable view. For rank two this is a matrix transpose; storage ownership remains shared. + +#### `mutable_alignment(dtype)` + +Given a type Proxy, return the Storable ABI alignment in bytes. This reports the element type requirement, not a user-selectable alignment. + +#### `with_mutable_buffer(tensor, function)` + +The pointer is valid only during the callback. Shape/strides describe views; callbacks must honor their extents and may not retain the borrowed pointer. diff --git a/docs/reference/timeseries-bindings.md b/docs/reference/timeseries-bindings.md new file mode 100644 index 0000000..dd226ef --- /dev/null +++ b/docs/reference/timeseries-bindings.md @@ -0,0 +1,1628 @@ +# Time-series bindings + +C includes `hmath_timeseries.h`; Python uses `from hmath import timeseries`. These functions call the original Haskell time-series implementation. Timestamps retain caller-defined units, ordering and explicit missing values; no calendar interpretation or automatic data cleaning is added. The source observation, work and fitting limits remain in force. + +All inputs are borrowed during a synchronous call; every successful C output owns one [structured value](values.md) reference. Outputs are unchanged on error. Checked `Left MathError` returns status11 with the original structured error. Immutable objects support concurrent readers with independent references and output addresses. Python owners have `close()` and context managers. `Maybe Double` observations use `None` for missingness. Forecast models and configuration constructors retain the original argument order and defaults. `OptimizeOptions` comes from `hmath.optimization`. + +ARMA/SARIMA use the original local conditional sum-of-squares fit, not a substituted exact likelihood model. Stationarity and interval estimates are not inferred by forecasting calls. Refer to the linked source contract for each model and diagnostic. + +## `describe` + +`timeseries.describe(value)` returns the original Haskell `Show` representation of one time-series object or Gaussian state. It preserves the original constructor and fields as text, including Unicode and embedded NUL. C receives an owned String value through `hmath_timeseries_describe(context, value, out)`. Mathematical operations use the typed object directly. + +## `backward_fill` + +`timeseries.backward_fill()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.BackwardFill`](haskell/HMath-TimeSeries-Core.md#v:BackwardFill). + +```haskell +Fill +``` + +```c +hmath_status hmath_timeseries_backward_fill(hmath_context *context, hmath_value **out); +``` + +## `bin_last` + +`timeseries.bin_last()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.BinLast`](haskell/HMath-TimeSeries-Core.md#v:BinLast). + +```haskell +Resampling +``` + +```c +hmath_status hmath_timeseries_bin_last(hmath_context *context, hmath_value **out); +``` + +## `bin_mean` + +`timeseries.bin_mean()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.BinMean`](haskell/HMath-TimeSeries-Core.md#v:BinMean). + +```haskell +Resampling +``` + +```c +hmath_status hmath_timeseries_bin_mean(hmath_context *context, hmath_value **out); +``` + +## `forward_fill` + +`timeseries.forward_fill()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.ForwardFill`](haskell/HMath-TimeSeries-Core.md#v:ForwardFill). + +```haskell +Fill +``` + +```c +hmath_status hmath_timeseries_forward_fill(hmath_context *context, hmath_value **out); +``` + +## `inner` + +`timeseries.inner()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.Inner`](haskell/HMath-TimeSeries-Core.md#v:Inner). + +```haskell +Alignment +``` + +```c +hmath_status hmath_timeseries_inner(hmath_context *context, hmath_value **out); +``` + +## `left_aligned` + +`timeseries.left_aligned()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.LeftAligned`](haskell/HMath-TimeSeries-Core.md#v:LeftAligned). + +```haskell +Alignment +``` + +```c +hmath_status hmath_timeseries_left_aligned(hmath_context *context, hmath_value **out); +``` + +## `linear_fill` + +`timeseries.linear_fill()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.LinearFill`](haskell/HMath-TimeSeries-Core.md#v:LinearFill). + +```haskell +Fill +``` + +```c +hmath_status hmath_timeseries_linear_fill(hmath_context *context, hmath_value **out); +``` + +## `linear_samples` + +`timeseries.linear_samples()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.LinearSamples`](haskell/HMath-TimeSeries-Core.md#v:LinearSamples). + +```haskell +Resampling +``` + +```c +hmath_status hmath_timeseries_linear_samples(hmath_context *context, hmath_value **out); +``` + +## `moving_maximum` + +`timeseries.moving_maximum()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.MovingMaximum`](haskell/HMath-TimeSeries-Core.md#v:MovingMaximum). + +```haskell +Rolling +``` + +```c +hmath_status hmath_timeseries_moving_maximum(hmath_context *context, hmath_value **out); +``` + +## `moving_mean` + +`timeseries.moving_mean()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.MovingMean`](haskell/HMath-TimeSeries-Core.md#v:MovingMean). + +```haskell +Rolling +``` + +```c +hmath_status hmath_timeseries_moving_mean(hmath_context *context, hmath_value **out); +``` + +## `moving_minimum` + +`timeseries.moving_minimum()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.MovingMinimum`](haskell/HMath-TimeSeries-Core.md#v:MovingMinimum). + +```haskell +Rolling +``` + +```c +hmath_status hmath_timeseries_moving_minimum(hmath_context *context, hmath_value **out); +``` + +## `moving_sd` + +`timeseries.moving_sd()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.MovingSD`](haskell/HMath-TimeSeries-Core.md#v:MovingSD). + +```haskell +Rolling +``` + +```c +hmath_status hmath_timeseries_moving_sd(hmath_context *context, hmath_value **out); +``` + +## `moving_variance` + +`timeseries.moving_variance()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.MovingVariance`](haskell/HMath-TimeSeries-Core.md#v:MovingVariance). + +```haskell +Rolling +``` + +```c +hmath_status hmath_timeseries_moving_variance(hmath_context *context, hmath_value **out); +``` + +## `outer` + +`timeseries.outer()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Core.Outer`](haskell/HMath-TimeSeries-Core.md#v:Outer). + +```haskell +Alignment +``` + +```c +hmath_status hmath_timeseries_outer(hmath_context *context, hmath_value **out); +``` + +## `align` + +`timeseries.align(value, value2, value3)` + +Exact timestamp equality. Missing alignment positions are explicit Nothing. + +Original: [`HMath.TimeSeries.Core.align`](haskell/HMath-TimeSeries-Core.md#v:align). + +```haskell +Alignment -> Series -> Series -> Either MathError (Series, Series) +``` + +```c +hmath_status hmath_timeseries_align(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `autocorrelation` + +`timeseries.autocorrelation(lags, xs)` + +Biased covariance divided by lag-zero covariance, global sample mean. + +Original: [`HMath.TimeSeries.Core.autocorrelation`](haskell/HMath-TimeSeries-Core.md#v:autocorrelation). + +```haskell +Int -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_autocorrelation(hmath_context *context, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +``` + +## `cross_correlation` + +`timeseries.cross_correlation(lag, xs, ys)` + +Corr(x_t,y_(t+lag)), global means and full lag-zero energy normalization. + +Original: [`HMath.TimeSeries.Core.crossCorrelation`](haskell/HMath-TimeSeries-Core.md#v:crossCorrelation). + +```haskell +Int -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_timeseries_cross_correlation(hmath_context *context, const hmath_value *lag, const hmath_value *xs, const hmath_value *ys, hmath_value **out); +``` + +## `cumulative_returns` + +`timeseries.cumulative_returns(xs)` + +Cumulative simple return relative to the first strictly positive price. + +Original: [`HMath.TimeSeries.Core.cumulativeReturns`](haskell/HMath-TimeSeries-Core.md#v:cumulativeReturns). + +```haskell +[Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_cumulative_returns(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `difference` + +`timeseries.difference(order, lag, xs)` + +Apply (1-B^lag)^order. Zero order preserves data; at least one output is required. + +Original: [`HMath.TimeSeries.Core.difference`](haskell/HMath-TimeSeries-Core.md#v:difference). + +```haskell +Int -> Int -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_difference(hmath_context *context, const hmath_value *order, const hmath_value *lag, const hmath_value *xs, hmath_value **out); +``` + +## `durbin_levinson` + +`timeseries.durbin_levinson(covariance)` + + Levinson recursion for a positive definite Toeplitz covariance. Returns AR coefficients, innovation variance, and PACF (without the lag-zero one). + +Original: [`HMath.TimeSeries.Core.durbinLevinson`](haskell/HMath-TimeSeries-Core.md#v:durbinLevinson). + +```haskell +[Double] -> Either MathError ([Double], Double, [Double]) +``` + +```c +hmath_status hmath_timeseries_durbin_levinson(hmath_context *context, const hmath_value *covariance, hmath_value **out); +``` + +## `exponential_average` + +`timeseries.exponential_average(alpha, xs)` + +Recursive EMA, initialized at the first observation; 0 [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_exponential_average(hmath_context *context, const hmath_value *alpha, const hmath_value *xs, hmath_value **out); +``` + +## `fill_missing` + +`timeseries.fill_missing(value, value2)` + + Directional filling leaves the unavailable leading/trailing end missing. Linear filling interpolates between finite anchors and never extrapolates. + +Original: [`HMath.TimeSeries.Core.fillMissing`](haskell/HMath-TimeSeries-Core.md#v:fillMissing). + +```haskell +Fill -> Series -> Either MathError Series +``` + +```c +hmath_status hmath_timeseries_fill_missing(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `is_regular` + +`timeseries.is_regular(value, value2)` + +Relative spacing tolerance; fewer than three observations are regular. + +Original: [`HMath.TimeSeries.Core.isRegular`](haskell/HMath-TimeSeries-Core.md#v:isRegular). + +```haskell +Double -> Series -> Either MathError Bool +``` + +```c +hmath_status hmath_timeseries_is_regular(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `logarithmic_returns` + +`timeseries.logarithmic_returns(xs)` + +Consecutive log returns, using log prices to avoid ratio overflow. + +Original: [`HMath.TimeSeries.Core.logarithmicReturns`](haskell/HMath-TimeSeries-Core.md#v:logarithmicReturns). + +```haskell +[Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_logarithmic_returns(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `observations` + +`timeseries.observations(value)` + + Extract time-ordered (timestamp,Maybe value) observations from a validated Series. Missing values remain Nothing. + +Original: [`HMath.TimeSeries.Core.observations`](haskell/HMath-TimeSeries-Core.md#v:observations). + +```haskell +Series -> [(Double, Maybe Double)] +``` + +```c +hmath_status hmath_timeseries_observations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `partial_autocorrelation` + +`timeseries.partial_autocorrelation(order, xs)` + + Given maximum lag then samples, compute ACF and Durbin-Levinson partial correlations, returning lag zero (1) followed by requested PACF lags. Invalid lag/data or singular covariance recurrence returns Left MathError. + +Original: [`HMath.TimeSeries.Core.partialAutocorrelation`](haskell/HMath-TimeSeries-Core.md#v:partialAutocorrelation). + +```haskell +Int -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_partial_autocorrelation(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +``` + +## `regular_series` + +`timeseries.regular_series(start, step, xs)` + +Sample times start+i*step. Rounded duplicate times are rejected as well. + +Original: [`HMath.TimeSeries.Core.regularSeries`](haskell/HMath-TimeSeries-Core.md#v:regularSeries). + +```haskell +Double -> Double -> [Maybe Double] -> Either MathError Series +``` + +```c +hmath_status hmath_timeseries_regular_series(hmath_context *context, const hmath_value *start, const hmath_value *step, const hmath_value *xs, hmath_value **out); +``` + +## `resample` + +`timeseries.resample(value, value2, value3, value4, value5)` + + Linear samples require brackets (or an exact timestamp). Bins are [start+i*step,start+(i+1)*step); the final right endpoint is excluded. + +Original: [`HMath.TimeSeries.Core.resample`](haskell/HMath-TimeSeries-Core.md#v:resample). + +```haskell +Resampling -> Double -> Double -> Int -> Series -> Either MathError Series +``` + +```c +hmath_status hmath_timeseries_resample(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `rolling` + +`timeseries.rolling(method, width, xs)` + +Full trailing windows only; variance is population variance (ddof=0). + +Original: [`HMath.TimeSeries.Core.rolling`](haskell/HMath-TimeSeries-Core.md#v:rolling). + +```haskell +Rolling -> Int -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_rolling(hmath_context *context, const hmath_value *method, const hmath_value *width, const hmath_value *xs, hmath_value **out); +``` + +## `series` + +`timeseries.series(xs)` + +Preserve order and missing values; reject duplicate or nonfinite times. + +Original: [`HMath.TimeSeries.Core.series`](haskell/HMath-TimeSeries-Core.md#v:series). + +```haskell +[(Double, Maybe Double)] -> Either MathError Series +``` + +```c +hmath_status hmath_timeseries_series(hmath_context *context, const hmath_value *xs, hmath_value **out); +``` + +## `series_values` + +`timeseries.series_values(value)` + +Complete-data conversion never silently drops a missing observation. + +Original: [`HMath.TimeSeries.Core.seriesValues`](haskell/HMath-TimeSeries-Core.md#v:seriesValues). + +```haskell +Series -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_series_values(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `weighted_average` + +`timeseries.weighted_average(ws, xs)` + +Nonnegative chronological weights: first weight multiplies oldest sample. + +Original: [`HMath.TimeSeries.Core.weightedAverage`](haskell/HMath-TimeSeries-Core.md#v:weightedAverage). + +```haskell +[Double] -> [Double] -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_weighted_average(hmath_context *context, const hmath_value *ws, const hmath_value *xs, hmath_value **out); +``` + +## `yule_walker` + +`timeseries.yule_walker(order, xs)` + +Biased sample autocovariances with centered data; returns mean separately. + +Original: [`HMath.TimeSeries.Core.yuleWalker`](haskell/HMath-TimeSeries-Core.md#v:yuleWalker). + +```haskell +Int -> [Double] -> Either MathError ([Double], Double, Double) +``` + +```c +hmath_status hmath_timeseries_yule_walker(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +``` + +## `dtw_result` + +`timeseries.dtw_result(distance, path)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.DTWResult`](haskell/HMath-TimeSeries-Diagnostics.md#v:DTWResult). + +```haskell +Double -> [(Int, Int)] -> DTWResult +``` + +```c +hmath_status hmath_timeseries_dtw_result(hmath_context *context, const hmath_value *distance, const hmath_value *path, hmath_value **out); +``` + +## `level` + +`timeseries.level()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.Level`](haskell/HMath-TimeSeries-Diagnostics.md#v:Level). + +```haskell +Deterministic +``` + +```c +hmath_status hmath_timeseries_level(hmath_context *context, hmath_value **out); +``` + +## `linear_trend` + +`timeseries.linear_trend()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.LinearTrend`](haskell/HMath-TimeSeries-Diagnostics.md#v:LinearTrend). + +```haskell +Deterministic +``` + +```c +hmath_status hmath_timeseries_linear_trend(hmath_context *context, hmath_value **out); +``` + +## `mae` + +`timeseries.mae()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.MAE`](haskell/HMath-TimeSeries-Diagnostics.md#v:MAE). + +```haskell +ForecastMetric +``` + +```c +hmath_status hmath_timeseries_mae(hmath_context *context, hmath_value **out); +``` + +## `mape` + +`timeseries.mape()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.MAPE`](haskell/HMath-TimeSeries-Diagnostics.md#v:MAPE). + +```haskell +ForecastMetric +``` + +```c +hmath_status hmath_timeseries_mape(hmath_context *context, hmath_value **out); +``` + +## `mase` + +`timeseries.mase(period, training)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.MASE`](haskell/HMath-TimeSeries-Diagnostics.md#v:MASE). + +```haskell +Int -> [Double] -> ForecastMetric +``` + +```c +hmath_status hmath_timeseries_mase(hmath_context *context, const hmath_value *period, const hmath_value *training, hmath_value **out); +``` + +## `mse` + +`timeseries.mse()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.MSE`](haskell/HMath-TimeSeries-Diagnostics.md#v:MSE). + +```haskell +ForecastMetric +``` + +```c +hmath_status hmath_timeseries_mse(hmath_context *context, hmath_value **out); +``` + +## `rmse` + +`timeseries.rmse()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.RMSE`](haskell/HMath-TimeSeries-Diagnostics.md#v:RMSE). + +```haskell +ForecastMetric +``` + +```c +hmath_status hmath_timeseries_rmse(hmath_context *context, hmath_value **out); +``` + +## `smape` + +`timeseries.smape()` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.SMAPE`](haskell/HMath-TimeSeries-Diagnostics.md#v:SMAPE). + +```haskell +ForecastMetric +``` + +```c +hmath_status hmath_timeseries_smape(hmath_context *context, hmath_value **out); +``` + +## `stationarity` + +`timeseries.stationarity(statistic, critical_values, observations, null_hypothesis)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.Stationarity`](haskell/HMath-TimeSeries-Diagnostics.md#v:Stationarity). + +```haskell +Double -> [(Double, Double)] -> Int -> String -> Stationarity +``` + +```c +hmath_status hmath_timeseries_stationarity(hmath_context *context, const hmath_value *statistic, const hmath_value *critical_values, const hmath_value *observations, const hmath_value *null_hypothesis, hmath_value **out); +``` + +## `anomalies` + +`timeseries.anomalies(threshold, xs)` + + Median/MAD outliers, using the normal-consistency factor 1.4826022185. If MAD is zero, every value different from the median is an anomaly. + +Original: [`HMath.TimeSeries.Diagnostics.anomalies`](haskell/HMath-TimeSeries-Diagnostics.md#v:anomalies). + +```haskell +Double -> [Double] -> Either MathError [Int] +``` + +```c +hmath_status hmath_timeseries_anomalies(hmath_context *context, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +``` + +## `augmented_dickey_fuller` + +`timeseries.augmented_dickey_fuller(deterministic, lags, xs)` + + OLS of delta x_t on x_(t-1), an intercept, optional trend, and explicitly supplied lagged differences. Returns the lagged-level t statistic. Critical values use MacKinnon (2010) finite-sample polynomials for one series: https://www.statsmodels.org/stable/generated/statsmodels.tsa.stattools.adfuller.html . There is no automatic lag selection or normal/Student-t p-value shortcut. + +Original: [`HMath.TimeSeries.Diagnostics.augmentedDickeyFuller`](haskell/HMath-TimeSeries-Diagnostics.md#v:augmentedDickeyFuller). + +```haskell +Deterministic -> Int -> [Double] -> Either MathError Stationarity +``` + +```c +hmath_status hmath_timeseries_augmented_dickey_fuller(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +``` + +## `change_points` + +`timeseries.change_points(penalty, min_segment, xs)` + + Exact quadratic dynamic programming for piecewise-constant least squares, minimizing total within-segment SSE plus penalty per change. Break indices are zero-based starts of new segments. No pruning/approximation is used. + +Original: [`HMath.TimeSeries.Diagnostics.changePoints`](haskell/HMath-TimeSeries-Diagnostics.md#v:changePoints). + +```haskell +Double -> Int -> [Double] -> Either MathError [Int] +``` + +```c +hmath_status hmath_timeseries_change_points(hmath_context *context, const hmath_value *penalty, const hmath_value *min_segment, const hmath_value *xs, hmath_value **out); +``` + +## `cusum` + +`timeseries.cusum(mean, sd, drift, threshold, xs)` + + Two-sided Page CUSUM with supplied baseline mean/SD. A threshold crossing emits its index and resets both cumulative scores. drift and threshold are in standardized observation units. + +Original: [`HMath.TimeSeries.Diagnostics.cusum`](haskell/HMath-TimeSeries-Diagnostics.md#v:cusum). + +```haskell +Double -> Double -> Double -> Double -> [Double] -> Either MathError [Int] +``` + +```c +hmath_status hmath_timeseries_cusum(hmath_context *context, const hmath_value *mean, const hmath_value *sd, const hmath_value *drift, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +``` + +## `dtw_distance` + +`timeseries.dtw_distance(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.dtwDistance`](haskell/HMath-TimeSeries-Diagnostics.md#v:dtwDistance). + +```haskell +DTWResult -> Double +``` + +```c +hmath_status hmath_timeseries_dtw_distance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `dtw_path` + +`timeseries.dtw_path(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.dtwPath`](haskell/HMath-TimeSeries-Diagnostics.md#v:dtwPath). + +```haskell +DTWResult -> [(Int, Int)] +``` + +```c +hmath_status hmath_timeseries_dtw_path(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `dynamic_time_warping` + +`timeseries.dynamic_time_warping(radius, xs, ys)` + + Absolute local cost; Sakoe--Chiba radius must include both endpoints. Returns the unnormalized path cost, with diagonal/up/left tie priority. + +Original: [`HMath.TimeSeries.Diagnostics.dynamicTimeWarping`](haskell/HMath-TimeSeries-Diagnostics.md#v:dynamicTimeWarping). + +```haskell +Int -> [Double] -> [Double] -> Either MathError DTWResult +``` + +```c +hmath_status hmath_timeseries_dynamic_time_warping(hmath_context *context, const hmath_value *radius, const hmath_value *xs, const hmath_value *ys, hmath_value **out); +``` + +## `forecast_error` + +`timeseries.forecast_error(metric, actual, predicted)` + + MAPE and sMAPE are percentages; zero/zero sMAPE contributes zero. MASE supplies its separate training set and seasonal lag to avoid test leakage. + +Original: [`HMath.TimeSeries.Diagnostics.forecastError`](haskell/HMath-TimeSeries-Diagnostics.md#v:forecastError). + +```haskell +ForecastMetric -> [Double] -> [Double] -> Either MathError Double +``` + +```c +hmath_status hmath_timeseries_forecast_error(hmath_context *context, const hmath_value *metric, const hmath_value *actual, const hmath_value *predicted, hmath_value **out); +``` + +## `kpss` + +`timeseries.kpss(deterministic, lags, xs)` + + KPSS level/trend stationarity with an explicit Bartlett/Newey--West lag bandwidth. Critical values are Table 1 of Kwiatkowski et al. (1992), as documented at https://www.statsmodels.org/stable/generated/statsmodels.tsa.stattools.kpss.html . + +Original: [`HMath.TimeSeries.Diagnostics.kpss`](haskell/HMath-TimeSeries-Diagnostics.md#v:kpss). + +```haskell +Deterministic -> Int -> [Double] -> Either MathError Stationarity +``` + +```c +hmath_status hmath_timeseries_kpss(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +``` + +## `spectrum` + +`timeseries.spectrum(sample_rate, xs)` + + One-sided unwindowed periodogram density. Non-DC/Nyquist bins are doubled; integral of density over frequency equals the sample mean square. + +Original: [`HMath.TimeSeries.Diagnostics.spectrum`](haskell/HMath-TimeSeries-Diagnostics.md#v:spectrum). + +```haskell +Double -> [Double] -> Either MathError [(Double, Double)] +``` + +```c +hmath_status hmath_timeseries_spectrum(hmath_context *context, const hmath_value *sample_rate, const hmath_value *xs, hmath_value **out); +``` + +## `stationarity_critical_values` + +`timeseries.stationarity_critical_values(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.stationarityCriticalValues`](haskell/HMath-TimeSeries-Diagnostics.md#v:stationarityCriticalValues). + +```haskell +Stationarity -> [(Double, Double)] +``` + +```c +hmath_status hmath_timeseries_stationarity_critical_values(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stationarity_null` + +`timeseries.stationarity_null(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.stationarityNull`](haskell/HMath-TimeSeries-Diagnostics.md#v:stationarityNull). + +```haskell +Stationarity -> String +``` + +```c +hmath_status hmath_timeseries_stationarity_null(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stationarity_observations` + +`timeseries.stationarity_observations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.stationarityObservations`](haskell/HMath-TimeSeries-Diagnostics.md#v:stationarityObservations). + +```haskell +Stationarity -> Int +``` + +```c +hmath_status hmath_timeseries_stationarity_observations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stationarity_statistic` + +`timeseries.stationarity_statistic(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Diagnostics.stationarityStatistic`](haskell/HMath-TimeSeries-Diagnostics.md#v:stationarityStatistic). + +```haskell +Stationarity -> Double +``` + +```c +hmath_status hmath_timeseries_stationarity_statistic(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `decomposition` + +`timeseries.decomposition(trend, seasonal, remainder)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.Decomposition`](haskell/HMath-TimeSeries-Models.md#v:Decomposition). + +```haskell +[Double] -> [Double] -> [Double] -> Decomposition +``` + +```c +hmath_status hmath_timeseries_decomposition(hmath_context *context, const hmath_value *trend, const hmath_value *seasonal, const hmath_value *remainder, hmath_value **out); +``` + +## `holt` + +`timeseries.holt(alpha, beta)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.Holt`](haskell/HMath-TimeSeries-Models.md#v:Holt). + +```haskell +Double -> Double -> Smoothing +``` + +```c +hmath_status hmath_timeseries_holt(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, hmath_value **out); +``` + +## `holt_winters` + +`timeseries.holt_winters(period, alpha, beta, gamma)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.HoltWinters`](haskell/HMath-TimeSeries-Models.md#v:HoltWinters). + +```haskell +Int -> Double -> Double -> Double -> Smoothing +``` + +```c +hmath_status hmath_timeseries_holt_winters(hmath_context *context, const hmath_value *period, const hmath_value *alpha, const hmath_value *beta, const hmath_value *gamma, hmath_value **out); +``` + +## `sarima_order` + +`timeseries.sarima_order(ar, difference, ma, seasonal_ar, seasonal_difference, seasonal_ma, period)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.SARIMAOrder`](haskell/HMath-TimeSeries-Models.md#v:SARIMAOrder). + +```haskell +Int -> Int -> Int -> Int -> Int -> Int -> Int -> SARIMAOrder +``` + +```c +hmath_status hmath_timeseries_sarima_order(hmath_context *context, const hmath_value *ar, const hmath_value *difference, const hmath_value *ma, const hmath_value *seasonal_ar, const hmath_value *seasonal_difference, const hmath_value *seasonal_ma, const hmath_value *period, hmath_value **out); +``` + +## `stl_config` + +`timeseries.stl_config(period, seasonal_window, trend_window, low_pass_window, inner_iterations, robust_iterations)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.STLConfig`](haskell/HMath-TimeSeries-Models.md#v:STLConfig). + +```haskell +Int -> Int -> Int -> Int -> Int -> Int -> STLConfig +``` + +```c +hmath_status hmath_timeseries_stl_config(hmath_context *context, const hmath_value *period, const hmath_value *seasonal_window, const hmath_value *trend_window, const hmath_value *low_pass_window, const hmath_value *inner_iterations, const hmath_value *robust_iterations, hmath_value **out); +``` + +## `simple` + +`timeseries.simple(alpha)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.Simple`](haskell/HMath-TimeSeries-Models.md#v:Simple). + +```haskell +Double -> Smoothing +``` + +```c +hmath_status hmath_timeseries_simple(hmath_context *context, const hmath_value *alpha, hmath_value **out); +``` + +## `ar_coefficients` + +`timeseries.ar_coefficients(value)` + + Return AR intercept followed by lag-1 through lag-p coefficients. The model retains observations chronologically for forecastAR. + +Original: [`HMath.TimeSeries.Models.arCoefficients`](haskell/HMath-TimeSeries-Models.md#v:arCoefficients). + +```haskell +ARModel -> [Double] +``` + +```c +hmath_status hmath_timeseries_ar_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `ar_order` + +`timeseries.ar_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.arOrder`](haskell/HMath-TimeSeries-Models.md#v:arOrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `arima_innovation_variance` + +`timeseries.arima_innovation_variance(value)` + +Return fitted innovation-variance estimate stored in an ARIMA/SARIMA model. + +Original: [`HMath.TimeSeries.Models.arimaInnovationVariance`](haskell/HMath-TimeSeries-Models.md#v:arimaInnovationVariance). + +```haskell +ARIMAModel -> Double +``` + +```c +hmath_status hmath_timeseries_arima_innovation_variance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `arima_parameters` + +`timeseries.arima_parameters(value)` + + Return fitted intercept,ordinary AR,ordinary MA,seasonal AR,seasonal MA parameters in that order. Intercept belongs to the differenced process. + +Original: [`HMath.TimeSeries.Models.arimaParameters`](haskell/HMath-TimeSeries-Models.md#v:arimaParameters). + +```haskell +ARIMAModel -> [Double] +``` + +```c +hmath_status hmath_timeseries_arima_parameters(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `arima_residuals` + +`timeseries.arima_residuals(value)` + + Return fitted innovation residuals in chronological order, on the model's differenced process. + +Original: [`HMath.TimeSeries.Models.arimaResiduals`](haskell/HMath-TimeSeries-Models.md#v:arimaResiduals). + +```haskell +ARIMAModel -> [Double] +``` + +```c +hmath_status hmath_timeseries_arima_residuals(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `decompose` + +`timeseries.decompose(period, xs)` + + Classical additive decomposition with local linear trend smoothing and centered phase means. Requires at least two complete periods. + +Original: [`HMath.TimeSeries.Models.decompose`](haskell/HMath-TimeSeries-Models.md#v:decompose). + +```haskell +Int -> [Double] -> Either MathError Decomposition +``` + +```c +hmath_status hmath_timeseries_decompose(hmath_context *context, const hmath_value *period, const hmath_value *xs, hmath_value **out); +``` + +## `default_stl_config` + +`timeseries.default_stl_config(period)` + + Given seasonal period, construct STL options with seasonal window 7, odd trend window above 2*period, odd low-pass window at/above period, two inner iterations and no robust outer iterations. stl validates the resulting configuration. + +Original: [`HMath.TimeSeries.Models.defaultSTLConfig`](haskell/HMath-TimeSeries-Models.md#v:defaultSTLConfig). + +```haskell +Int -> STLConfig +``` + +```c +hmath_status hmath_timeseries_default_stl_config(hmath_context *context, const hmath_value *period, hmath_value **out); +``` + +## `difference_order` + +`timeseries.difference_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.differenceOrder`](haskell/HMath-TimeSeries-Models.md#v:differenceOrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `fit_ar` + +`timeseries.fit_ar(order, xs)` + + Given AR order then finite chronological samples, fit intercept and lag coefficients by checked OLS. Require order in [0,64], <=4096 samples and more than 2*order+1 observations; invalid/ill-conditioned fits fail. + +Original: [`HMath.TimeSeries.Models.fitAR`](haskell/HMath-TimeSeries-Models.md#v:fitAR). + +```haskell +Int -> [Double] -> Either MathError ARModel +``` + +```c +hmath_status hmath_timeseries_fit_ar(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +``` + +## `fit_arima` + +`timeseries.fit_arima(value, value2, value3, value4, value5)` + + Given optimization options,p,d,q,then finite chronological series, fit nonseasonal ARIMA through fitSARIMA with seasonal orders zero. Invalid order/sample bounds, unstable or nonconvergent/ill-conditioned fit returns Left MathError. + +Original: [`HMath.TimeSeries.Models.fitARIMA`](haskell/HMath-TimeSeries-Models.md#v:fitARIMA). + +```haskell +OptimizeOptions -> Int -> Int -> Int -> [Double] -> Either MathError ARIMAModel +``` + +```c +hmath_status hmath_timeseries_fit_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +``` + +## `fit_arma` + +`timeseries.fit_arma(value, value2, value3, value4)` + + Given optimization options,AR order p,MA order q,then samples, fit ARIMA(p,0,q). Invalid or nonconvergent fits return Left MathError. + +Original: [`HMath.TimeSeries.Models.fitARMA`](haskell/HMath-TimeSeries-Models.md#v:fitARMA). + +```haskell +OptimizeOptions -> Int -> Int -> [Double] -> Either MathError ARIMAModel +``` + +```c +hmath_status hmath_timeseries_fit_arma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +``` + +## `fit_ma` + +`timeseries.fit_ma(value, value2, value3)` + + Given optimization options,MA order q,then samples, fit ARIMA(0,0,q). Order/sample/optimization errors propagate from fitARIMA. + +Original: [`HMath.TimeSeries.Models.fitMA`](haskell/HMath-TimeSeries-Models.md#v:fitMA). + +```haskell +OptimizeOptions -> Int -> [Double] -> Either MathError ARIMAModel +``` + +```c +hmath_status hmath_timeseries_fit_ma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +``` + +## `fit_sarima` + +`timeseries.fit_sarima(options, order, xs)` + + Parameters are intercept, ordinary AR, ordinary MA, seasonal AR, seasonal MA. Multiplicative seasonal polynomials include cross-lag interactions. Intercept always belongs to the differenced process. Caller supplies fit budgets; exhausted or ill-conditioned fits return MathError. + +Original: [`HMath.TimeSeries.Models.fitSARIMA`](haskell/HMath-TimeSeries-Models.md#v:fitSARIMA). + +```haskell +OptimizeOptions -> SARIMAOrder -> [Double] -> Either MathError ARIMAModel +``` + +```c +hmath_status hmath_timeseries_fit_sarima(hmath_context *context, const hmath_value *options, const hmath_value *order, const hmath_value *xs, hmath_value **out); +``` + +## `fit_var` + +`timeseries.fit_var(order, xs)` + + Given lag order then chronological multivariate rows, fit response-wise OLS with intercept and lag-major features. Require finite rectangular data, dimensions<=16, rows<=2048, order in [1,16], sufficient samples and <=20000000 fitting work. Invalid/ill-conditioned fits fail. + +Original: [`HMath.TimeSeries.Models.fitVAR`](haskell/HMath-TimeSeries-Models.md#v:fitVAR). + +```haskell +Int -> [[Double]] -> Either MathError VARModel +``` + +```c +hmath_status hmath_timeseries_fit_var(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +``` + +## `forecast_ar` + +`timeseries.forecast_ar(value, value2)` + + Given horizon in [0,16384] then fitted AR model, recursively forecast future samples from latest observations. Zero horizon returns []; invalid horizon or non-finite predictions fail. + +Original: [`HMath.TimeSeries.Models.forecastAR`](haskell/HMath-TimeSeries-Models.md#v:forecastAR). + +```haskell +Int -> ARModel -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_forecast_ar(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `forecast_arima` + +`timeseries.forecast_arima(value, value2)` + + Given horizon in [0,16384] then fitted ARIMA/SARIMA model, forecast recursively with future innovations set to zero and undo ordinary/seasonal differencing. Invalid horizon or non-finite predictions fail. + +Original: [`HMath.TimeSeries.Models.forecastARIMA`](haskell/HMath-TimeSeries-Models.md#v:forecastARIMA). + +```haskell +Int -> ARIMAModel -> Either MathError [Double] +``` + +```c +hmath_status hmath_timeseries_forecast_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `forecast_var` + +`timeseries.forecast_var(value, value2)` + + Given horizon then VAR model, recursively return future multivariate observation rows. Require horizon in [0,16384] and horizon*components<=262144; invalid bounds or non-finite predictions fail. + +Original: [`HMath.TimeSeries.Models.forecastVAR`](haskell/HMath-TimeSeries-Models.md#v:forecastVAR). + +```haskell +Int -> VARModel -> Either MathError [[Double]] +``` + +```c +hmath_status hmath_timeseries_forecast_var(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +``` + +## `kalman_series` + +`timeseries.kalman_series(transition, observation, q, r, initial, measured)` + + Reuse the checked Joseph-form linear Kalman update for each complete observation. Returns posterior states, excluding the caller's initial state. + +Original: [`HMath.TimeSeries.Models.kalmanSeries`](haskell/HMath-TimeSeries-Models.md#v:kalmanSeries). + +```haskell +[[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> GaussianState -> [[Double]] -> Either MathError [GaussianState] +``` + +```c +hmath_status hmath_timeseries_kalman_series(hmath_context *context, const hmath_value *transition, const hmath_value *observation, const hmath_value *q, const hmath_value *r, const hmath_value *initial, const hmath_value *measured, hmath_value **out); +``` + +## `ma_order` + +`timeseries.ma_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.maOrder`](haskell/HMath-TimeSeries-Models.md#v:maOrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `remainder_component` + +`timeseries.remainder_component(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.remainderComponent`](haskell/HMath-TimeSeries-Models.md#v:remainderComponent). + +```haskell +Decomposition -> [Double] +``` + +```c +hmath_status hmath_timeseries_remainder_component(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `seasonal_ar_order` + +`timeseries.seasonal_ar_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.seasonalAROrder`](haskell/HMath-TimeSeries-Models.md#v:seasonalAROrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_seasonal_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `seasonal_component` + +`timeseries.seasonal_component(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.seasonalComponent`](haskell/HMath-TimeSeries-Models.md#v:seasonalComponent). + +```haskell +Decomposition -> [Double] +``` + +```c +hmath_status hmath_timeseries_seasonal_component(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `seasonal_difference_order` + +`timeseries.seasonal_difference_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.seasonalDifferenceOrder`](haskell/HMath-TimeSeries-Models.md#v:seasonalDifferenceOrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_seasonal_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `seasonal_ma_order` + +`timeseries.seasonal_ma_order(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.seasonalMAOrder`](haskell/HMath-TimeSeries-Models.md#v:seasonalMAOrder). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_seasonal_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `seasonal_period` + +`timeseries.seasonal_period(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.seasonalPeriod`](haskell/HMath-TimeSeries-Models.md#v:seasonalPeriod). + +```haskell +SARIMAOrder -> Int +``` + +```c +hmath_status hmath_timeseries_seasonal_period(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `smooth_forecast` + +`timeseries.smooth_forecast(method, horizon, xs)` + + Fitted one-step means and future means. Simple/Holt initialize from the first sample/first difference. Additive Holt--Winters initializes the level and seasonal indices from a complete first cycle, and the trend from the difference between the first two cycle means. Initial fitted cycle is the initializer, not an out-of-sample prediction. + +Original: [`HMath.TimeSeries.Models.smoothForecast`](haskell/HMath-TimeSeries-Models.md#v:smoothForecast). + +```haskell +Smoothing -> Int -> [Double] -> Either MathError ([Double], [Double]) +``` + +```c +hmath_status hmath_timeseries_smooth_forecast(hmath_context *context, const hmath_value *method, const hmath_value *horizon, const hmath_value *xs, hmath_value **out); +``` + +## `stl` + +`timeseries.stl(config, xs)` + + Cleveland-style STL reference backfitting: smooth seasonal subseries by degree-one tricube LOESS with one-cycle extrapolation; remove a period, period, three-point moving-average low-pass followed by LOESS, then smooth the deseasonalized trend. Optional bisquare robust outer iterations use six times median absolute residual. Every index is evaluated (no jump shortcut). See https://search.r-project.org/R/refmans/stats/html/stl.html . + +Original: [`HMath.TimeSeries.Models.stl`](haskell/HMath-TimeSeries-Models.md#v:stl). + +```haskell +STLConfig -> [Double] -> Either MathError Decomposition +``` + +```c +hmath_status hmath_timeseries_stl(hmath_context *context, const hmath_value *config, const hmath_value *xs, hmath_value **out); +``` + +## `stl_inner_iterations` + +`timeseries.stl_inner_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlInnerIterations`](haskell/HMath-TimeSeries-Models.md#v:stlInnerIterations). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_inner_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stl_low_pass_window` + +`timeseries.stl_low_pass_window(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlLowPassWindow`](haskell/HMath-TimeSeries-Models.md#v:stlLowPassWindow). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_low_pass_window(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stl_period` + +`timeseries.stl_period(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlPeriod`](haskell/HMath-TimeSeries-Models.md#v:stlPeriod). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_period(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stl_robust_iterations` + +`timeseries.stl_robust_iterations(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlRobustIterations`](haskell/HMath-TimeSeries-Models.md#v:stlRobustIterations). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_robust_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stl_seasonal_window` + +`timeseries.stl_seasonal_window(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlSeasonalWindow`](haskell/HMath-TimeSeries-Models.md#v:stlSeasonalWindow). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_seasonal_window(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `stl_trend_window` + +`timeseries.stl_trend_window(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.stlTrendWindow`](haskell/HMath-TimeSeries-Models.md#v:stlTrendWindow). + +```haskell +STLConfig -> Int +``` + +```c +hmath_status hmath_timeseries_stl_trend_window(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `trend_component` + +`timeseries.trend_component(value)` + +Construct or inspect the original immutable record; field order follows the source signature. + +Original: [`HMath.TimeSeries.Models.trendComponent`](haskell/HMath-TimeSeries-Models.md#v:trendComponent). + +```haskell +Decomposition -> [Double] +``` + +```c +hmath_status hmath_timeseries_trend_component(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `var_coefficients` + +`timeseries.var_coefficients(value)` + +Rows are response components, columns are intercept then lag-major predictors. + +Original: [`HMath.TimeSeries.Models.varCoefficients`](haskell/HMath-TimeSeries-Models.md#v:varCoefficients). + +```haskell +VARModel -> [[Double]] +``` + +```c +hmath_status hmath_timeseries_var_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `gaussian_state` + +`timeseries.gaussian_state(mean, covariance)` + + Validate a mean and symmetric positive semidefinite covariance; Cholesky roundoff tolerance is 1e-12*max(1,diagonal). Accepted tiny negative pivots are clipped, and the stored covariance is reconstructed from that factor. Thus a tolerated negative input variance never escapes through stateCovariance. + +Original: [`HMath.Signal.gaussianState`](haskell/HMath-Signal.md#v:gaussianState). + +```haskell +[Double] -> [[Double]] -> Either MathError GaussianState +``` + +```c +hmath_status hmath_timeseries_gaussian_state(hmath_context *context, const hmath_value *mean, const hmath_value *covariance, hmath_value **out); +``` + +## `state_mean` + +`timeseries.state_mean(value)` + +Read the posterior mean vector. + +Original: [`HMath.Signal.stateMean`](haskell/HMath-Signal.md#v:stateMean). + +```haskell +GaussianState -> [Double] +``` + +```c +hmath_status hmath_timeseries_state_mean(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + +## `state_covariance` + +`timeseries.state_covariance(value)` + +Read the symmetric posterior covariance matrix. + +Original: [`HMath.Signal.stateCovariance`](haskell/HMath-Signal.md#v:stateCovariance). + +```haskell +GaussianState -> [[Double]] +``` + +```c +hmath_status hmath_timeseries_state_covariance(hmath_context *context, const hmath_value *value, hmath_value **out); +``` + diff --git a/docs/reference/units-values.md b/docs/reference/units-values.md new file mode 100644 index 0000000..03f6d71 --- /dev/null +++ b/docs/reference/units-values.md @@ -0,0 +1,792 @@ +# Exact units and quantities + +Unit conversion and quantity arithmetic call the original `HMath.Units` implementation. Values are exact `fractions.Fraction` objects, including affine offsets; exponents are arbitrary integers. Nine dimensions distinguish seven SI base dimensions, data, and plane angle. Invalid conversions preserve original `MathError` constructors and messages. + +```python +from fractions import Fraction +from hmath import units as u + +with u.kilometre() as km, u.metre() as metre: + assert u.convert(km, metre, Fraction(3, 2)) == 1500 +with u.celsius() as c, u.fahrenheit() as f: + assert u.convert(c, f, 100) == 212 +``` + +Catalog names are zero-argument functions returning independently owned immutable Unit/Dimension handles. Use `close()` or a context manager; releasing an input cannot invalidate a returned quantity or derived unit. Constants are not initialized at import time. `Dimension`, `Unit`, `Quantity`, and `SIPrefix` constructors follow their original source constructors; named functions provide equivalent access. Their equality uses original derived Haskell `Eq`. + +Absolute temperatures and differences retain their original hidden distinction: absolute plus absolute fails, absolute minus absolute yields a difference, difference minus absolute fails, and multiplying/dividing an absolute temperature fails. `temperature_difference` ignores the unit's affine offset. `in_unit` subtracts an affine offset only for absolute quantities. Zero divisor, incompatible dimensions, invalid scale, affine unit products/prefixes, and prefix resource limits retain original errors. The SI prefix catalog includes exactly the source ordering and spellings. + +Python integer inputs to Rational fields are converted exactly, and `Fraction` values never pass through FP64. A Python float is converted to the exact fraction representing that already-rounded float; use `Fraction("0.1")` when decimal 0.1 is intended. Prefix exponents must fit Haskell `Int`; unit powers and dimension exponents use unbounded `Integer`. The existing four angle-conversion numeric functions retain their Float/Double interfaces. + +Include `hmath_units.h` plus `hmath_value.h` in C. Unit/quantity scalar inputs use Rational Values, dimensional/power exponents use Integer Values, and prefix exponents use Index or an exact Int-range integral Value. Text uses length-delimited codepoints, preserving Unicode, embedded NUL and Haskell Char surrogates. Every result is owned and must be released once. Errors leave `out` untouched. Inputs are immutable and borrowed for the call only; independent calls may share them. + +## `dimension` + +Exponents in order length, mass, time, current, temperature, amount, luminous intensity, data, plane angle. Require exactly nine exponents. + +`dimension(exponents)` returns `Dimension` or raises the original checked error. Parameters: `exponents`: `[Integer]` + +```c +hmath_status hmath_units_value_dimension(hmath_context *context, const hmath_value *exponents, hmath_value **out); +``` + +## `dimension_exponents` + +Return nine exact integer exponents ordered as length, mass, time, current, temperature, amount, luminous intensity, data, plane angle. + +`dimension_exponents(dimension)` returns `[Integer]`. Parameters: `dimension`: `Dimension` + +```c +hmath_status hmath_units_value_dimension_exponents(hmath_context *context, const hmath_value *dimension, hmath_value **out); +``` + +## `dimensionless` + +Dimension witness with all nine exponents zero; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`dimensionless()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_dimensionless(hmath_context *context, hmath_value **out); +``` + +## `length_dimension` + +Dimension witness with length exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`length_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_length_dimension(hmath_context *context, hmath_value **out); +``` + +## `mass_dimension` + +Dimension witness with mass exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`mass_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_mass_dimension(hmath_context *context, hmath_value **out); +``` + +## `time_dimension` + +Dimension witness with time exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`time_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_time_dimension(hmath_context *context, hmath_value **out); +``` + +## `temperature_dimension` + +Dimension witness with temperature exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`temperature_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_temperature_dimension(hmath_context *context, hmath_value **out); +``` + +## `angle_dimension` + +Dimension witness with plane-angle tag exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`angle_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_angle_dimension(hmath_context *context, hmath_value **out); +``` + +## `data_dimension` + +Dimension witness with data tag exponent one; all unspecified exponents are zero. Use to construct or compare dimension-safe units/quantities. + +`data_dimension()` returns `Dimension`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_data_dimension(hmath_context *context, hmath_value **out); +``` + +## `unit` + +SI = value * scale + offset. Only temperature units may have an offset. + +`unit(name, dimension, scale, offset)` returns `Unit` or raises the original checked error. Parameters: `name`: `String`, `dimension`: `Dimension`, `scale`: `Rational`, `offset`: `Rational` + +```c +hmath_status hmath_units_value_unit(hmath_context *context, const hmath_value *name, const hmath_value *dimension, const hmath_value *scale, const hmath_value *offset, hmath_value **out); +``` + +## `unit_name` + +Return the display name/symbol of a Unit, for example "m". No conversion is performed. + +`unit_name(unit)` returns `String`. Parameters: `unit`: `Unit` + +```c +hmath_status hmath_units_value_unit_name(hmath_context *context, const hmath_value *unit, hmath_value **out); +``` + +## `unit_dimension` + +Return the dimensional-exponent witness of a Unit. Compatible conversions require equal dimensions. + +`unit_dimension(unit)` returns `Dimension`. Parameters: `unit`: `Unit` + +```c +hmath_status hmath_units_value_unit_dimension(hmath_context *context, const hmath_value *unit, hmath_value **out); +``` + +## `unit_scale` + +Return exact Rational scale in the conversion SI = value*scale + offset. All public Unit constructors require a positive scale. + +`unit_scale(unit)` returns `Rational`. Parameters: `unit`: `Unit` + +```c +hmath_status hmath_units_value_unit_scale(hmath_context *context, const hmath_value *unit, hmath_value **out); +``` + +## `unit_offset` + +Return exact Rational affine offset in SI = value*scale + offset. Only temperature units may have a nonzero offset. + +`unit_offset(unit)` returns `Rational`. Parameters: `unit`: `Unit` + +```c +hmath_status hmath_units_value_unit_offset(hmath_context *context, const hmath_value *unit, hmath_value **out); +``` + +## `unit_product` + +Multiply two zero-offset units: add dimension exponents and multiply Rational scales. Any affine offset returns Left DomainError. This constructs a Unit, not a Quantity. + +`unit_product(left, right)` returns `Unit` or raises the original checked error. Parameters: `left`: `Unit`, `right`: `Unit` + +```c +hmath_status hmath_units_value_unit_product(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `unit_quotient` + +Divide two zero-offset units: subtract dimension exponents and divide their positive scales. Affine units fail with DomainError. + +`unit_quotient(numerator, denominator)` returns `Unit` or raises the original checked error. Parameters: `numerator`: `Unit`, `denominator`: `Unit` + +```c +hmath_status hmath_units_value_unit_quotient(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `unit_power` + +Given zero-offset Unit then Integer exponent, multiply its exponents and raise its positive scale to that power. Negative powers are valid; affine units fail. + +`unit_power(unit, exponent)` returns `Unit` or raises the original checked error. Parameters: `unit`: `Unit`, `exponent`: `Integer` + +```c +hmath_status hmath_units_value_unit_power(hmath_context *context, const hmath_value *unit, const hmath_value *exponent, hmath_value **out); +``` + +## `quantity` + +Given Unit then Rational value, construct an exact SI-valued Quantity using its scale and offset. A temperature unit constructs an absolute temperature; use temperatureDifference for differences. + +`quantity(unit, value)` returns `Quantity`. Parameters: `unit`: `Unit`, `value`: `Rational` + +```c +hmath_status hmath_units_value_quantity(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out); +``` + +## `temperature_difference` + +Given Unit then Rational value, construct an exact SI-valued Quantity using its scale and offset. A temperature unit constructs an absolute temperature; use + +`temperature_difference(unit, value)` returns `Quantity` or raises the original checked error. Parameters: `unit`: `Unit`, `value`: `Rational` + +```c +hmath_status hmath_units_value_temperature_difference(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out); +``` + +## `quantity_dimension` + +Return a Quantity's dimensional-exponent witness, without changing its SI value or absolute-temperature tag. + +`quantity_dimension(quantity)` returns `Dimension`. Parameters: `quantity`: `Quantity` + +```c +hmath_status hmath_units_value_quantity_dimension(hmath_context *context, const hmath_value *quantity, hmath_value **out); +``` + +## `si_value` + +Return exact Rational SI value of a Quantity. For absolute temperature this is an absolute kelvin value; preserve quantityDimension when interpreting the number. + +`si_value(quantity)` returns `Rational`. Parameters: `quantity`: `Quantity` + +```c +hmath_status hmath_units_value_si_value(hmath_context *context, const hmath_value *quantity, hmath_value **out); +``` + +## `in_unit` + +Given destination Unit then Quantity, convert its SI value to that unit. Reject incompatible dimensions. Apply affine offsets only for absolute temperatures, not differences. + +`in_unit(unit, quantity)` returns `Rational` or raises the original checked error. Parameters: `unit`: `Unit`, `quantity`: `Quantity` + +```c +hmath_status hmath_units_value_in_unit(hmath_context *context, const hmath_value *unit, const hmath_value *quantity, hmath_value **out); +``` + +## `convert` + +Given source Unit, destination Unit, then Rational value, convert exactly through SI. Incompatible dimensions fail. Example: convert kilometre metre 2 == Right 2000. + +`convert(source, destination, value)` returns `Rational` or raises the original checked error. Parameters: `source`: `Unit`, `destination`: `Unit`, `value`: `Rational` + +```c +hmath_status hmath_units_value_convert(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *value, hmath_value **out); +``` + +## `add_quantity` + +Original public HMath.Units constructor or field. + +`add_quantity(left, right)` returns `Quantity` or raises the original checked error. Parameters: `left`: `Quantity`, `right`: `Quantity` + +```c +hmath_status hmath_units_value_add_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `subtract_quantity` + +Original public HMath.Units constructor or field. + +`subtract_quantity(left, right)` returns `Quantity` or raises the original checked error. Parameters: `left`: `Quantity`, `right`: `Quantity` + +```c +hmath_status hmath_units_value_subtract_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `multiply_quantity` + +Original public HMath.Units constructor or field. + +`multiply_quantity(left, right)` returns `Quantity` or raises the original checked error. Parameters: `left`: `Quantity`, `right`: `Quantity` + +```c +hmath_status hmath_units_value_multiply_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +``` + +## `divide_quantity` + +Original public HMath.Units constructor or field. + +`divide_quantity(numerator, denominator)` returns `Quantity` or raises the original checked error. Parameters: `numerator`: `Quantity`, `denominator`: `Quantity` + +```c +hmath_status hmath_units_value_divide_quantity(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +``` + +## `si_prefix` + +Original public HMath.Units constructor or field. + +`si_prefix(name, symbol, exponent)` returns `SIPrefix`. Parameters: `name`: `String`, `symbol`: `String`, `exponent`: `Int` + +```c +hmath_status hmath_units_value_si_prefix(hmath_context *context, const hmath_value *name, const hmath_value *symbol, const hmath_value *exponent, hmath_value **out); +``` + +## `si_prefixes` + +BIPM prefixes through the 2022 quetta/ronna and ronto/quecto additions. Source: https://www.bipm.org/en/measurement-units/si-prefixes + +`si_prefixes()` returns `[SIPrefix]`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_si_prefixes(hmath_context *context, hmath_value **out); +``` + +## `prefixed` + +Given SIPrefix then zero-offset Unit, multiply its scale by 10^prefixExponent and prepend its symbol. Reject affine units or absolute exponent above 10000. + +`prefixed(prefix, unit)` returns `Unit` or raises the original checked error. Parameters: `prefix`: `SIPrefix`, `unit`: `Unit` + +```c +hmath_status hmath_units_value_prefixed(hmath_context *context, const hmath_value *prefix, const hmath_value *unit, hmath_value **out); +``` + +## `metre` + +The metre Unit: 1 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`metre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_metre(hmath_context *context, hmath_value **out); +``` + +## `kilometre` + +The kilometre Unit: 1000 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`kilometre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_kilometre(hmath_context *context, hmath_value **out); +``` + +## `centimetre` + +The centimetre Unit: 0.01 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`centimetre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_centimetre(hmath_context *context, hmath_value **out); +``` + +## `millimetre` + +The millimetre Unit: 0.001 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`millimetre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_millimetre(hmath_context *context, hmath_value **out); +``` + +## `inch` + +The inch Unit: 0.0254 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`inch()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_inch(hmath_context *context, hmath_value **out); +``` + +## `foot` + +The foot Unit: 0.3048 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`foot()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_foot(hmath_context *context, hmath_value **out); +``` + +## `yard` + +The yard Unit: 0.9144 metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`yard()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_yard(hmath_context *context, hmath_value **out); +``` + +## `mile` + +The mile Unit: 1609.344 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`mile()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_mile(hmath_context *context, hmath_value **out); +``` + +## `nautical_mile` + +The nauticalMile Unit: 1852 metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`nautical_mile()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_nautical_mile(hmath_context *context, hmath_value **out); +``` + +## `square_metre` + +The squareMetre Unit: 1 square metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`square_metre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_square_metre(hmath_context *context, hmath_value **out); +``` + +## `hectare` + +The hectare Unit: 10000 square metres. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`hectare()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_hectare(hmath_context *context, hmath_value **out); +``` + +## `cubic_metre` + +The cubicMetre Unit: 1 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`cubic_metre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_cubic_metre(hmath_context *context, hmath_value **out); +``` + +## `litre` + +The litre Unit: 0.001 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`litre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_litre(hmath_context *context, hmath_value **out); +``` + +## `millilitre` + +The millilitre Unit: 0.000001 cubic metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`millilitre()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_millilitre(hmath_context *context, hmath_value **out); +``` + +## `kilogram` + +The kilogram Unit: 1 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`kilogram()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_kilogram(hmath_context *context, hmath_value **out); +``` + +## `gram` + +The gram Unit: 0.001 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`gram()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_gram(hmath_context *context, hmath_value **out); +``` + +## `tonne` + +The tonne Unit: 1000 kilograms. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`tonne()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_tonne(hmath_context *context, hmath_value **out); +``` + +## `pound` + +The pound Unit: 0.45359237 kilogram. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`pound()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_pound(hmath_context *context, hmath_value **out); +``` + +## `second` + +The second Unit: 1 second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`second()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_second(hmath_context *context, hmath_value **out); +``` + +## `minute` + +The minute Unit: 60 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`minute()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_minute(hmath_context *context, hmath_value **out); +``` + +## `hour` + +The hour Unit: 3600 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`hour()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_hour(hmath_context *context, hmath_value **out); +``` + +## `day` + +The day Unit: 86400 seconds. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`day()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_day(hmath_context *context, hmath_value **out); +``` + +## `metres_per_second` + +The metresPerSecond Unit: 1 metre per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`metres_per_second()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_metres_per_second(hmath_context *context, hmath_value **out); +``` + +## `kilometres_per_hour` + +The kilometresPerHour Unit: 1000/3600 metres per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`kilometres_per_hour()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_kilometres_per_hour(hmath_context *context, hmath_value **out); +``` + +## `miles_per_hour` + +The milesPerHour Unit: 1609.344/3600 metres per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`miles_per_hour()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_miles_per_hour(hmath_context *context, hmath_value **out); +``` + +## `metres_per_second_squared` + +The metresPerSecondSquared Unit: 1 metre per second squared. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`metres_per_second_squared()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_metres_per_second_squared(hmath_context *context, hmath_value **out); +``` + +## `newton` + +The newton Unit: 1 kg*m/s^2. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`newton()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_newton(hmath_context *context, hmath_value **out); +``` + +## `joule` + +The joule Unit: 1 newton metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`joule()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_joule(hmath_context *context, hmath_value **out); +``` + +## `watt` + +The watt Unit: 1 joule per second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`watt()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_watt(hmath_context *context, hmath_value **out); +``` + +## `pascal` + +The pascal Unit: 1 newton per square metre. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`pascal()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_pascal(hmath_context *context, hmath_value **out); +``` + +## `bar` + +The bar Unit: 100000 pascals. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`bar()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_bar(hmath_context *context, hmath_value **out); +``` + +## `atmosphere` + +The atmosphere Unit: 101325 pascals. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`atmosphere()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_atmosphere(hmath_context *context, hmath_value **out); +``` + +## `kelvin` + +The kelvin Unit: absolute temperature with SI=value. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`kelvin()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_kelvin(hmath_context *context, hmath_value **out); +``` + +## `celsius` + +The celsius Unit: absolute temperature with SI=value+273.15 kelvin. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`celsius()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_celsius(hmath_context *context, hmath_value **out); +``` + +## `fahrenheit` + +The fahrenheit Unit: absolute temperature with SI=(value-32)*5/9+273.15 kelvin. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`fahrenheit()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_fahrenheit(hmath_context *context, hmath_value **out); +``` + +## `hertz` + +The hertz Unit: 1 inverse second. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`hertz()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_hertz(hmath_context *context, hmath_value **out); +``` + +## `bit` + +The bit Unit: 1 data bit. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`bit()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_bit(hmath_context *context, hmath_value **out); +``` + +## `byte` + +The byte Unit: 8 data bits. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`byte()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_byte(hmath_context *context, hmath_value **out); +``` + +## `kibibyte` + +The kibibyte Unit: 8192 data bits (1024 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`kibibyte()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_kibibyte(hmath_context *context, hmath_value **out); +``` + +## `mebibyte` + +The mebibyte Unit: 8388608 data bits (1024^2 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`mebibyte()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_mebibyte(hmath_context *context, hmath_value **out); +``` + +## `gigabyte` + +The gigabyte Unit: 8000000000 data bits (10^9 bytes). Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`gigabyte()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_gigabyte(hmath_context *context, hmath_value **out); +``` + +## `radian` + +The radian Unit: 1 radian. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`radian()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_radian(hmath_context *context, hmath_value **out); +``` + +## `degree` + +The degree Unit: pi/180 radian, using the stored 50-place Rational pi approximation. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`degree()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_degree(hmath_context *context, hmath_value **out); +``` + +## `gradian` + +The gradian Unit: pi/200 radian, using the stored Rational pi approximation. Non-temperature definitions use an exact Rational scale and zero affine offset. Use quantity or convert to construct/convert values; temperature differences use temperatureDifference. + +`gradian()` returns `Unit`. Parameters: none; returns a new owned reference to the source catalog value. + +```c +hmath_status hmath_units_value_gradian(hmath_context *context, hmath_value **out); +``` + +## `prefix_name` + +Original public HMath.Units constructor or field. + +`prefix_name(prefix)` returns `String`. Parameters: `prefix`: `SIPrefix` + +```c +hmath_status hmath_units_value_prefix_name(hmath_context *context, const hmath_value *prefix, hmath_value **out); +``` + +## `prefix_symbol` + +Original public HMath.Units constructor or field. + +`prefix_symbol(prefix)` returns `String`. Parameters: `prefix`: `SIPrefix` + +```c +hmath_status hmath_units_value_prefix_symbol(hmath_context *context, const hmath_value *prefix, hmath_value **out); +``` + +## `prefix_exponent` + +Original public HMath.Units constructor or field. + +`prefix_exponent(prefix)` returns `Int`. Parameters: `prefix`: `SIPrefix` + +```c +hmath_status hmath_units_value_prefix_exponent(hmath_context *context, const hmath_value *prefix, hmath_value **out); +``` + diff --git a/docs/reference/values.md b/docs/reference/values.md new file mode 100644 index 0000000..fc432aa --- /dev/null +++ b/docs/reference/values.md @@ -0,0 +1,148 @@ +# Structured values and ownership + +`hmath_value.h` represents exact scalars, lists, tuples and original Haskell +objects used by the structured C APIs. Each domain header declares named +operations with the original argument order. The mathematical implementation +remains in Haskell. + +## Lifetime + +Every successful output owns one reference. Release it with +`hmath_value_release`; retain an additional reference with `hmath_value_retain`. +Releasing a null pointer is allowed. Inputs are borrowed for the duration of a +synchronous call. A returned object or container holds its Haskell values +independently of the input handles, so input handles can then be released. + +Each live handle keeps the runtime active. Release all handles before the final +`hmath_shutdown`. Immutable values may be shared between concurrent calls when +each caller keeps a reference alive. Output locations must be independent; +releasing the final reference concurrently with a call using that handle is +invalid. Context cancellation and limits follow the individual domain contract. + +Python domain objects provide `close()` and context managers. Ordinary scalar, +list and tuple results are converted to Python values. Objects returned inside +containers retain independent native references. + +## Value kinds + +`hmath_value_info(value, &kind, &dtype, &count)` queries metadata without +changing the last-error state. All three output pointers are required. A dtype +of `-1` means the object has no scalar coefficient type. `count` is logical +length; interpretation for an opaque object is specified by its domain. + +| Kind | Representation | +| --- | --- | +| 0 | `Nothing`, represented by Python `None` | +| 1 | Typed scalar coefficient | +| 2 | Haskell `Int`, represented with `ptrdiff_t` | +| 3 | Boolean | +| 4 | List | +| 5 | Tuple, including `()` | +| 6–8 | Polynomial, power series, rational function | +| 9 | Dense matrix | +| 10 | Haskell `String` | +| Other | Opaque object declared by its domain header | + +`Maybe a` uses kind 0 for `Nothing` and the value's own representation for +`Just`. Tuple/list shape remains significant: an empty list, unit tuple and +`Nothing` are distinct values. Consult the specific function's contract where +an interface uses unit only to signal success. + +## Construct scalars + +Every constructor takes `hmath_context *context` first and +`hmath_value **out` last. A null context selects the default execution context. +On failure, the output pointer is unchanged. + +| Constructor | Input and coefficient type | +| --- | --- | +| `hmath_value_f32` | `float`, binary32 | +| `hmath_value_f64` | `double`, binary64 | +| `hmath_value_complex_f32` | Real and imaginary `float`, `Complex Float` | +| `hmath_value_complex_f64` | Real and imaginary `double`, `Complex Double` | +| `hmath_value_integer` | Signed decimal ASCII, arbitrary-precision `Integer` | +| `hmath_value_integral` | Integral dtype plus signed decimal ASCII; rejects values outside that type | +| `hmath_value_rational` | Decimal numerator and nonzero denominator; exact normalized `Rational` | +| `hmath_value_index` | `ptrdiff_t`, Haskell `Int` | +| `hmath_value_boolean` | C integer, zero false and nonzero true | +| `hmath_value_none` | No payload, `Nothing` | + +Coefficient enums distinguish binary32/binary64, complex64/complex128, +arbitrary `Integer`, exact `Rational`, signed and unsigned 8/16/32/64-bit +integers and native-width `Int`/`Word`. A domain operation determines which +original Haskell instances it supports. It rejects mismatched types rather +than silently choosing a different mathematical domain. + +Binary constructors preserve the selected floating representation, including +signed zero and NaN/Inf. The called mathematical function applies its original +finite-input policy. Exact constructors never convert through floating point. + +## Construct and inspect containers + +`hmath_value_list` and `hmath_value_tuple` take an array of borrowed +`const hmath_value *` items and a `size_t` count. The resulting container owns +the contained Haskell values independently of those item handles. A null array +is permitted only when count is zero. + +`hmath_value_item(context, sequence, index, out)` accepts a list or tuple and +returns an independently owned item. Indices are zero-based Haskell `Int` +values; out-of-range indices fail. + +```c +#include + +/* After hmath_init has succeeded: build an exact pair (1/3, 2/7). */ +hmath_value *a = NULL, *b = NULL, *pair = NULL; +hmath_status status = hmath_value_rational(NULL, "1", "3", &a); +if (status == HMATH_OK) + status = hmath_value_rational(NULL, "2", "7", &b); +if (status == HMATH_OK) { + const hmath_value *items[] = {a, b}; + status = hmath_value_tuple(NULL, items, 2, &pair); +} +hmath_value_release(a); +hmath_value_release(b); +/* pair remains valid here if status == HMATH_OK. */ +hmath_value_release(pair); +``` + +## Read scalars and strings + +All getters borrow their input. Required output addresses must be nonnull. +They reject an incompatible kind or dtype and preserve outputs on failure. + +| Getter | Result | +| --- | --- | +| `hmath_value_get_f32` | Real and imaginary `float`; accepts binary32 or complex64 | +| `hmath_value_get_f64` | Real and imaginary `double`; accepts binary64 or complex128 | +| `hmath_value_get_exact` | Two owned decimal strings, numerator and denominator; integers use denominator `1` | +| `hmath_value_get_index` | `ptrdiff_t` from kind 2 | +| `hmath_value_get_boolean` | C integer Boolean from kind 3 | +| `hmath_value_get_text` | Unicode codepoints from kind 10 into a caller-owned buffer | + +Both floating outputs are required; real inputs produce imaginary zero. Free +each string from `hmath_value_get_exact` with `hmath_value_string_free`, which +also accepts null. These strings use their own allocation and remain valid +after the input handle is released. + +`hmath_value_text` takes `uint32_t` Unicode codepoints and their explicit count. +This preserves every Haskell `Char`, including embedded NUL and surrogate +codepoints, without normalization. For `hmath_value_get_text`, obtain the count +with `hmath_value_info`, then provide that many elements. An undersized buffer +fails without changing its contents. String length counts codepoints, not +UTF-8 bytes. + +## Errors + +Each operation returns `hmath_status`. Representation errors, allocation +failure, cancellation and runtime lifecycle errors use the C ABI status codes. +A checked Haskell `Left MathError` returns `HMATH_MATH_ERROR` (11), with its +original constructor and payload available through `hmath_last_math_error` in +`hmath_error.h`. Read the payload before another operation changes the thread's +last error. + +Python raises `HMathError`; its `math_error` field contains the structured +Haskell error when status is 11. Unexpected Python exceptions in callbacks are +retained and re-raised after native cleanup. Domain documentation specifies +whether a callback may return a recoverable mathematical error and whether an +operation can retain that callback. diff --git a/hmath.cabal b/hmath.cabal index 84477c5..fae3a30 100644 --- a/hmath.cabal +++ b/hmath.cabal @@ -44,6 +44,16 @@ extra-source-files: bench/native.c cabal.project cbits/native_internal.h + cbits/numeric_internal.h + bindings/schema/*.json + bindings/schema/*.txt + bindings/python/_hmath_native/*.py + include/hmath_numeric.h + include/hmath_optimization.h + include/hmath_matrix.h + include/hmath_autodiff.h + include/hmath_execution.h + include/hmath_error.h examples/c/main.c examples/haskell/Domains.hs examples/haskell/Foundations.hs @@ -77,6 +87,34 @@ extra-source-files: tools/benchmark.py tools/build_python_wheel.sh tools/check_python_wheel.py + tools/build_c_sdk.py + tools/check_c_sdk.py + tools/release_version.py + tools/release_manifest.py + tools/check_release_remote.py + tools/publish_github_release.py + tools/generate_matrix_bindings.py + tools/check_matrix_equivalence.py + tools/check_autodiff_equivalence.py + test/native/matrix_contracts.c + test/native/kernel_storage.c + test/native/execution_blas_spy.c + tools/check_execution.py + tools/numeric_specializations.py + tools/select_release_candidate.py + tools/verify_release_candidate.py + test/native/execution_smoke.c + include/hmath_execution.h + include/hmath_error.h + test/native/autodiff_contracts.c + test/native/autodiff_bindings.py + .github/workflows/prepare-release.yml + tools/generate_numeric_bindings.py + tools/check_binding_coverage.py + tools/check_numeric_equivalence.py + test/native/numeric_contracts.c + test/native/numeric_contracts.cpp + test/native/expanded_bindings.py tools/build_docs.py tools/check_docs_examples.py tools/check_abi.py @@ -85,9 +123,156 @@ extra-source-files: tools/interchange_adapters.py tools/run_fuzz.py tools/run_wave.py + cbits/value_internal.h + cbits/matrix_internal.h + include/hmath_value.h + include/hmath_matrix_value.h + include/hmath_polynomial.h + include/hmath_graph.h + include/hmath_numeric_types.h + include/hmath_optimization_all.h + test/release_candidate.py + test/release_publishing.py + test/native/numeric_variants.c + test/native/value_bindings.py + test/native/polynomial_bindings.py + test/native/polynomial_contracts.c + tools/generate_graph_bindings.py + tools/check_haskell_doc_examples.py + tools/check_docs_links.py + tools/check_api_docs.py + tools/check_polynomial_equivalence.py + tools/check_matrix_value_equivalence.py + tools/haskell_reference.py + tools/generate_numeric_types.py + tools/generate_polynomial_bindings.py + tools/generate_matrix_value_bindings.py + tools/check_numeric_types_equivalence.py + tools/generate_units_bindings.py + tools/check_optimization_equivalence.py + tools/check_graph_equivalence.py + include/hmath_units.h + tools/generate_optimization_bindings.py + tools/check_units_equivalence.py + test/native/units_bindings.py + test/native/optimization_bindings.py + test/native/numeric_types.c + include/hmath_timeseries.h + include/hmath_rotations.h + include/hmath_expression_error.h + tools/generate_rotation_bindings.py + tools/generate_linear_bindings.py + tools/check_rotation_equivalence.py + tools/generate_timeseries_bindings.py + tools/generate_expression_bindings.py + test/native/rotations.c + test/native/optimization_contracts.c + test/native/structured_contracts.c + tools/check_timeseries_equivalence.py + include/hmath_image.h + include/hmath_expression.h + tools/check_image_equivalence.py + tools/generate_image_bindings.py + include/hmath_linear.h + include/hmath_numerical.h + tools/check_linear_equivalence.py + tools/generate_numerical_bindings.py + tools/generate_geometry_bindings.py + tools/check_expression_equivalence.py + test/native/expression_bindings.py + test/native/image.c + test/native/expression_contracts.c + include/hmath_geometry.h + include/hmath_stochastic.h + include/hmath_spectral.h + tools/generate_stochastic_bindings.py + tools/check_numerical_equivalence.py + tools/check_stochastic_equivalence.py + tools/check_geometry_equivalence.py + tools/generate_spectral_bindings.py + test/native/stochastic_bindings.py + test/native/linear_bindings.py + test/native/geometry.c + test/native/stochastic_contracts.c + test/native/linear_contracts.c + include/hmath_tensor_bindings.h + include/hmath_deeplearning.h + include/hmath_machinelearning.h + include/hmath_bytes.h + include/hmath_interchange_error.h + tools/generate_tensor_bindings.py + tools/generate_deeplearning_bindings.py + tools/generate_machinelearning_bindings.py + tools/check_spectral_equivalence.py + tools/check_structural_matrix_equivalence.py + test/native/numerical_bindings.py extra-doc-files: CHANGELOG.md + .github/workflows/compatibility.yml + include/hmath_algebra.h + include/hmath_callback.h + include/hmath_foundation.h + include/hmath_interchange.h + include/hmath_scalar_extras.h + include/hmath_shape.h + test/native/foundation_bindings.py + test/native/foundation_contracts.c + test/native/machinelearning.c + test/native/structural_matrix_contracts.c + test/native/tensor_bindings.py + test/native/tensor_contracts.c + tools/check_algebra_equivalence.py + tools/check_foundation_equivalence.py + tools/check_machinelearning_equivalence.py + tools/check_scalar_extras.py + tools/check_shape_equivalence.py + tools/check_tensor_equivalence.py + tools/generate_algebra_bindings.py + tools/generate_foundation_bindings.py + tools/generate_interchange_bindings.py + tools/generate_scalar_extras.py + tools/generate_shape_bindings.py + + include/hmath_buffer.h + test/native/callback_errors.py + test/native/deeplearning_contracts.c + test/native/scalar_extras.c + test/native/spectral_bindings.py + test/native/spectral_contracts.c + tools/check_deeplearning_equivalence.py + tools/check_interchange_bindings_equivalence.py + tools/generate_buffer_bindings.py + + include/hmath_numeric_objects.h + test/native/autodiff_checked_contracts.c + test/native/autodiff_checked_contracts.cpp + test/native/buffer_contracts.c + test/native/buffer_contracts.cpp + test/native/deeplearning_bindings.py + test/native/deeplearning_contracts.cpp + test/native/foundation_contracts.cpp + test/native/interchange_bindings.py + test/native/interchange_contracts.c + test/native/interchange_contracts.cpp + test/native/tensor_contracts.cpp + tools/check_autodiff_coefficients.py + tools/check_buffer_equivalence.py + tools/generate_numeric_objects.py + + include/*.h + cbits/*.h + tools/*.py + tools/*.sh + test/native/*.c + test/native/*.cpp + test/native/*.py + test/*.py + .github/workflows/*.yml + .github/actions/setup-haskell/action.yml + docs/stylesheets/*.css + docs/javascripts/*.js + flag native-backend description: Enable runtime loading of native BLAS and LAPACK providers default: True @@ -245,7 +430,7 @@ library ghc-options: -Wall include-dirs: include - install-includes: hmath.h hmath_dlpack.h + install-includes: hmath.h hmath_algebra.h hmath_autodiff.h hmath_buffer.h hmath_bytes.h hmath_callback.h hmath_deeplearning.h hmath_dlpack.h hmath_error.h hmath_execution.h hmath_expression.h hmath_expression_error.h hmath_foundation.h hmath_geometry.h hmath_graph.h hmath_image.h hmath_interchange.h hmath_interchange_error.h hmath_linear.h hmath_machinelearning.h hmath_matrix.h hmath_matrix_value.h hmath_numeric.h hmath_numeric_objects.h hmath_numeric_types.h hmath_numerical.h hmath_optimization.h hmath_optimization_all.h hmath_polynomial.h hmath_rotations.h hmath_scalar_extras.h hmath_shape.h hmath_spectral.h hmath_stochastic.h hmath_tensor_bindings.h hmath_timeseries.h hmath_units.h hmath_value.h if os(windows) cc-options: -DHMATH_WINDOWS @@ -260,21 +445,187 @@ foreign-library hmath hs-source-dirs: src other-modules: - HMath.FFI + HMath.API.Algebra + HMath.API.Buffer + HMath.API.Convergence + HMath.API.Shape + HMath.Algebra + HMath.Algorithms + HMath.Autodiff + HMath.Backend HMath.Basic + HMath.Calculus + HMath.Combinatorics + HMath.Complex + HMath.Constants + HMath.DataStructure + HMath.DeepLearning.Core + HMath.DeepLearning.Layers + HMath.DeepLearning.Metrics + HMath.DeepLearning.Precision + HMath.Discrete HMath.Error + HMath.Expression + HMath.FFI + HMath.FFI.AlgebraAll + HMath.FFI.AlgebraCodec + HMath.FFI.Autodiff + HMath.FFI.AutodiffChecked + HMath.FFI.AutodiffValue + HMath.FFI.Boundary + HMath.FFI.Buffer + HMath.FFI.Buffer.Codec + HMath.FFI.Bytes + HMath.FFI.Coefficient + HMath.FFI.DeepLearning + HMath.FFI.Execution + HMath.FFI.Expression + HMath.FFI.Foundation + HMath.FFI.FoundationCodec + HMath.FFI.Geometry + HMath.FFI.Graph + HMath.FFI.GraphCodec + HMath.FFI.Image + HMath.FFI.InterchangeAll + HMath.FFI.InterchangeCodec + HMath.FFI.InterchangeElement + HMath.FFI.InterchangeError + HMath.FFI.LinearAll + HMath.FFI.LinearCodec + HMath.FFI.MachineLearning + HMath.FFI.MachineLearning.Codec + HMath.FFI.MachineLearning.Types + HMath.FFI.MathError + HMath.FFI.Matrix + HMath.FFI.MatrixValue + HMath.FFI.Numeric + HMath.FFI.NumericObjects + HMath.FFI.NumericTypes + HMath.FFI.NumericTypes.Core + HMath.FFI.NumericalAll + HMath.FFI.NumericalCodec + HMath.FFI.OptimizationAll + HMath.FFI.Optimizer + HMath.FFI.Ordering + HMath.FFI.Polynomial + HMath.FFI.RandomCodec + HMath.FFI.Rotations + HMath.FFI.ScalarExtras + HMath.FFI.ShapeAll + HMath.FFI.ShapeCodec + HMath.FFI.SpectralAll + HMath.FFI.Stochastic + HMath.FFI.TensorAll + HMath.FFI.TensorCodec + HMath.FFI.TimeSeries + HMath.FFI.Units + HMath.FFI.Value + HMath.Fourier + HMath.Geometry + HMath.Geometry.Collision + HMath.Geometry.Internal + HMath.Geometry.Polygon + HMath.Geometry.Primitives + HMath.Geometry.Spatial + HMath.Geometry.Transform + HMath.Geometry.Triangulation + HMath.Graph + HMath.Graph.Analysis + HMath.Graph.Core + HMath.Graph.Flow + HMath.Graph.Paths + HMath.Image.Color + HMath.Image.Core + HMath.Image.Filter + HMath.Image.Histogram + HMath.Image.Measure + HMath.Image.Spatial + HMath.Interchange.Array + HMath.Interchange.Binary + HMath.Interchange.Compression + HMath.Interchange.IO + HMath.Interchange.Numpy + HMath.Interchange.Text + HMath.Interpolation HMath.Linear + HMath.MachineLearning + HMath.MachineLearning.Clustering + HMath.MachineLearning.Decomposition + HMath.MachineLearning.Internal + HMath.MachineLearning.Neighbors + HMath.MachineLearning.Preprocessing + HMath.MachineLearning.Regression + HMath.Matrix + HMath.Matrix.Advanced + HMath.Matrix.Decomposition + HMath.Matrix.Internal + HMath.Matrix.Iterative + HMath.Matrix.LAPACK + HMath.Matrix.LU + HMath.Matrix.QR + HMath.NumberTheory + HMath.Numeric + HMath.ODE + HMath.ODE.Tableau + HMath.Optimization.Common + HMath.Optimization.Constrained + HMath.Optimization.FirstOrder + HMath.Optimization.Global + HMath.Optimization.Local + HMath.PDE + HMath.Polynomial + HMath.Probability + HMath.Quaternion + HMath.Random + HMath.Root + HMath.Rotation + HMath.Scalar + HMath.Signal + HMath.Signal.Internal + HMath.Sparse + HMath.Sparse.Spectral + HMath.Special HMath.Statistics + HMath.Statistics.Advanced + HMath.Symbolic + HMath.Tensor + HMath.Tensor.Mutable + HMath.TimeSeries + HMath.TimeSeries.Core + HMath.TimeSeries.Diagnostics + HMath.TimeSeries.Models + HMath.Trigonometry + HMath.Units + HMath.Vector build-depends: - base >= 4.16 && < 5 + base >= 4.16 && < 5, + array >= 0.5 && < 0.6, + containers >= 0.6 && < 0.9, + bytestring >= 0.11 && < 0.13, + binary >= 0.8 && < 0.9, + text >= 1.2 && < 2.2 default-language: Haskell2010 ghc-options: -Wall -threaded include-dirs: include cbits - c-sources: cbits/runtime.c cbits/native.c cbits/native_dlpack.c + c-sources: cbits/algebra.c cbits/autodiff_bindings.c cbits/backend.c cbits/buffer.c cbits/bytes.c cbits/deeplearning.c cbits/error_wire.c cbits/execution.c cbits/expression.c cbits/foundation.c cbits/geometry.c cbits/graph_bindings.c cbits/image.c cbits/interchange.c cbits/interchange_io.c cbits/linear.c cbits/machinelearning.c cbits/matrix_bindings.c cbits/matrix_value.c cbits/native.c cbits/native_dlpack.c cbits/numeric_generated.c cbits/numeric_objects.c cbits/numeric_types.c cbits/numerical.c cbits/optimization.c cbits/optimization_all.c cbits/polynomial.c cbits/rotations.c cbits/runtime.c cbits/scalar_extras.c cbits/shape.c cbits/spectral.c cbits/stochastic.c cbits/tensor_bindings.c cbits/timeseries.c cbits/units.c cbits/value.c cc-options: -std=c11 -DHMATH_BUILD_SHARED + if flag(interchange-zlib) + cc-options: -DHMATH_HAVE_ZLIB + extra-libraries: z + if os(windows) + cc-options: -DHMATH_WINDOWS + else + cc-options: -DHMATH_UNIX + if !os(windows) + cc-options: -fvisibility=hidden + if os(linux) + extra-libraries: dl pthread + if !flag(native-backend) + cc-options: -DHMATH_DISABLE_NATIVE + if os(windows) options: standalone diff --git a/include/hmath.h b/include/hmath.h index 9f64695..f2dbd0f 100644 --- a/include/hmath.h +++ b/include/hmath.h @@ -31,7 +31,10 @@ typedef enum hmath_status { HMATH_CANCELLED = 7, HMATH_BOUNDS_ERROR = 8, HMATH_BUSY = 9, - HMATH_UNSUPPORTED = 10 + HMATH_UNSUPPORTED = 10, + HMATH_MATH_ERROR = 11, + HMATH_EXPRESSION_ERROR = 12, + HMATH_INTERCHANGE_ERROR = 13 } hmath_status; typedef struct hmath_context hmath_context; typedef struct hmath_tensor hmath_tensor; @@ -57,7 +60,8 @@ enum hmath_init_result { HMATH_INIT_OK = 0, HMATH_INIT_ALREADY_SHUT_DOWN = 1 }; /* HMath owns its GHC RTS. Do not combine with independently initialized GHC * libraries. Initialization is idempotent; final shutdown is irreversible. * Checked and legacy calls reserve the RTS; shutdown returns BUSY while any - * call is active, including a callback. Retry after joining workers. */ + * call is active, including a callback, or Haskell-backed optimizer states + * remain live. Retry after joining workers and releasing those states. */ HMATH_API int hmath_init(void); HMATH_API hmath_status hmath_runtime_shutdown(void); /* Legacy void form leaves the RTS running on BUSY; inspect last_error_code. */ diff --git a/include/hmath_algebra.h b/include/hmath_algebra.h new file mode 100644 index 0000000..2b0a3be --- /dev/null +++ b/include/hmath_algebra.h @@ -0,0 +1,283 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated original algebra typeclass instances and checked field APIs. */ +#ifndef HMATH_ALGEBRA_H +#define HMATH_ALGEBRA_H +#include "hmath_foundation.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Explicit prototype parameters select actual source instances. They are not + * conversions. Old Algebra: Integer/Rational/Polynomial, Additive groups and + * Integer/Rational list modules. API.Algebra: Integer/Rational/Float/Double/ + * Complex Double/Exact; unsupported original instances return Unsupported. + * Exact has no Num instance. Inputs borrow; outputs own an independent Value. + * Failure leaves *out untouched; release outputs using hmath_value_release. */ +/* HMath.Algebra.linearCombination */ +HMATH_API hmath_status hmath_algebra_core_linear_combination(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.semiringLaws */ +HMATH_API hmath_status hmath_algebra_core_semiring_laws(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.ringLaws */ +HMATH_API hmath_status hmath_algebra_core_ring_laws(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.fieldLaws */ +HMATH_API hmath_status hmath_algebra_core_field_laws(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.groupLaws */ +HMATH_API hmath_status hmath_algebra_core_group_laws(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.moduleLaws */ +HMATH_API hmath_status hmath_algebra_core_module_laws(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.modular */ +HMATH_API hmath_status hmath_algebra_core_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.modularValue */ +HMATH_API hmath_status hmath_algebra_core_modular_value(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.modularModulus */ +HMATH_API hmath_status hmath_algebra_core_modular_modulus(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.addModular */ +HMATH_API hmath_status hmath_algebra_core_add_modular(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.subtractModular */ +HMATH_API hmath_status hmath_algebra_core_subtract_modular(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.multiplyModular */ +HMATH_API hmath_status hmath_algebra_core_multiply_modular(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.inverseModular */ +HMATH_API hmath_status hmath_algebra_core_inverse_modular(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.powerModular */ +HMATH_API hmath_status hmath_algebra_core_power_modular(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.finiteField */ +HMATH_API hmath_status hmath_algebra_core_finite_field(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + const hmath_value *a2, hmath_value **out); +/* HMath.Algebra.primeField */ +HMATH_API hmath_status hmath_algebra_core_prime_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.fieldCharacteristic */ +HMATH_API hmath_status hmath_algebra_core_field_characteristic(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algebra.fieldDegree */ +HMATH_API hmath_status hmath_algebra_core_field_degree(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.fieldCardinality */ +HMATH_API hmath_status hmath_algebra_core_field_cardinality(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algebra.fieldModulus */ +HMATH_API hmath_status hmath_algebra_core_field_modulus(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.fieldElement */ +HMATH_API hmath_status hmath_algebra_core_field_element(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.fieldElementCoefficients */ +HMATH_API hmath_status hmath_algebra_core_field_element_coefficients(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algebra.fieldElements */ +HMATH_API hmath_status hmath_algebra_core_field_elements(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.addField */ +HMATH_API hmath_status hmath_algebra_core_add_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.negateField */ +HMATH_API hmath_status hmath_algebra_core_negate_field(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.subtractField */ +HMATH_API hmath_status hmath_algebra_core_subtract_field(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.multiplyField */ +HMATH_API hmath_status hmath_algebra_core_multiply_field(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.inverseFieldElement */ +HMATH_API hmath_status hmath_algebra_core_inverse_field_element(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algebra.powerField */ +HMATH_API hmath_status hmath_algebra_core_power_field(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.finiteFieldLaws */ +HMATH_API hmath_status hmath_algebra_core_finite_field_laws(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.getAdditive */ +HMATH_API hmath_status hmath_algebra_core_get_additive(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.Additive */ +HMATH_API hmath_status hmath_algebra_core_new_additive(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.horner */ +HMATH_API hmath_status hmath_algebra_api_horner(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.API.Algebra.innerProduct */ +HMATH_API hmath_status hmath_algebra_api_inner_product(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.getExact */ +HMATH_API hmath_status hmath_algebra_api_get_exact(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.API.Algebra.Exact */ +HMATH_API hmath_status hmath_algebra_api_new_exact(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Algebra.zero */ +HMATH_API hmath_status hmath_algebra_core_zero(hmath_context *context, const hmath_value *prototype, + hmath_value **out); +/* HMath.Algebra.one */ +HMATH_API hmath_status hmath_algebra_core_one(hmath_context *context, const hmath_value *prototype, + hmath_value **out); +/* HMath.Algebra.plus */ +HMATH_API hmath_status hmath_algebra_core_plus(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.times */ +HMATH_API hmath_status hmath_algebra_core_times(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.negateRing */ +HMATH_API hmath_status hmath_algebra_core_negate_ring(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.inverseField */ +HMATH_API hmath_status hmath_algebra_core_inverse_field(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.groupIdentity */ +HMATH_API hmath_status hmath_algebra_core_group_identity(hmath_context *context, + const hmath_value *prototype, + hmath_value **out); +/* HMath.Algebra.groupCombine */ +HMATH_API hmath_status hmath_algebra_core_group_combine(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algebra.groupInverse */ +HMATH_API hmath_status hmath_algebra_core_group_inverse(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.Algebra.moduleScale */ +HMATH_API hmath_status hmath_algebra_core_module_scale(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.Algebra.moduleAdd */ +HMATH_API hmath_status hmath_algebra_core_module_add(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.zero */ +HMATH_API hmath_status hmath_algebra_api_zero(hmath_context *context, const hmath_value *prototype, + hmath_value **out); +/* HMath.API.Algebra.one */ +HMATH_API hmath_status hmath_algebra_api_one(hmath_context *context, const hmath_value *prototype, + hmath_value **out); +/* HMath.API.Algebra.plus */ +HMATH_API hmath_status hmath_algebra_api_plus(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.times */ +HMATH_API hmath_status hmath_algebra_api_times(hmath_context *context, const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.negative */ +HMATH_API hmath_status hmath_algebra_api_negative(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.integer */ +HMATH_API hmath_status hmath_algebra_api_integer(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.invert */ +HMATH_API hmath_status hmath_algebra_api_invert(hmath_context *context, + const hmath_value *prototype, const hmath_value *a0, + hmath_value **out); +/* HMath.API.Algebra.conjugateScalar */ +HMATH_API hmath_status hmath_algebra_api_conjugate_scalar(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.machineEpsilon */ +HMATH_API hmath_status hmath_algebra_api_machine_epsilon(hmath_context *context, + const hmath_value *prototype, + hmath_value **out); +/* HMath.API.Algebra.finiteScalar */ +HMATH_API hmath_status hmath_algebra_api_finite_scalar(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.rational */ +HMATH_API hmath_status hmath_algebra_api_rational(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.matrixDimensions */ +HMATH_API hmath_status hmath_algebra_api_matrix_dimensions(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Algebra.matrixElements */ +HMATH_API hmath_status hmath_algebra_api_matrix_elements(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.matrixConstruct */ +HMATH_API hmath_status hmath_algebra_api_matrix_construct(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, hmath_value **out); +/* HMath.API.Algebra.tensorDimensions */ +HMATH_API hmath_status hmath_algebra_api_tensor_dimensions(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Algebra.tensorElements */ +HMATH_API hmath_status hmath_algebra_api_tensor_elements(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.API.Algebra.tensorConstruct */ +HMATH_API hmath_status hmath_algebra_api_tensor_construct(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.API.Algebra.vectorPlus */ +HMATH_API hmath_status hmath_algebra_api_vector_plus(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.vectorScale */ +HMATH_API hmath_status hmath_algebra_api_vector_scale(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.API.Algebra.differential */ +HMATH_API hmath_status hmath_algebra_api_differential(hmath_context *context, const hmath_value *a0, + hmath_value **out); +HMATH_API hmath_status hmath_algebra_api_exact_element_type(hmath_context *context, + hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_autodiff.h b/include/hmath_autodiff.h new file mode 100644 index 0000000..9b06fe3 --- /dev/null +++ b/include/hmath_autodiff.h @@ -0,0 +1,279 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_AUTODIFF_H +#define HMATH_AUTODIFF_H +#include "hmath.h" +#include "hmath_value.h" +#include "hmath_callback.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Immutable, independently owned Haskell values. Every returned handle owns a + * runtime reservation: final shutdown is BUSY until all are released. Callers + * retain input handles throughout each call; never race final release with use. + * Output pointers/buffers must be disjoint from inputs and one another. Outputs + * are untouched on failure. Reverse graphs use the original Double arithmetic; + * Dual leaves select their original explicit Float/Double/Integer/Rational type. + * Original MathError constructors/payloads are reported with + * HMATH_MATH_ERROR; no new domain checks or mathematical defaults are added. + * Context cancellation is checked before entry. A NULL context disables it. + * Coordinate/axis/dimension arguments use Haskell Int, represented by ptrdiff_t. + * Input arrays are borrowed for the call, output arrays belong to the caller. + * Dual operators invoke the original Haskell Dual Double instances. */ +typedef struct hmath_ad_handle hmath_ad_handle; +typedef hmath_ad_handle hmath_ad_expr; +typedef hmath_ad_handle hmath_ad_graph; +typedef hmath_ad_handle hmath_ad_gradient_state; +typedef hmath_ad_handle hmath_ad_tensor; +typedef hmath_ad_handle hmath_ad_dual; +typedef enum hmath_ad_unary_operation { + HMATH_AD_NEGATE = 0, + HMATH_AD_ABSOLUTE = 1, + HMATH_AD_SIGN = 2, + HMATH_AD_RECIPROCAL = 3, + HMATH_AD_EXP = 4, + HMATH_AD_LOG = 5, + HMATH_AD_SQRT = 6, + HMATH_AD_SIN = 7, + HMATH_AD_COS = 8, + HMATH_AD_TAN = 9, + HMATH_AD_ASIN = 10, + HMATH_AD_ACOS = 11, + HMATH_AD_ATAN = 12, + HMATH_AD_SINH = 13, + HMATH_AD_COSH = 14, + HMATH_AD_TANH = 15, + HMATH_AD_ASINH = 16, + HMATH_AD_ACOSH = 17, + HMATH_AD_ATANH = 18, + HMATH_AD_DETACH = 19, + HMATH_AD_STOP_GRADIENT = 20 +} hmath_ad_unary_operation; +typedef enum hmath_ad_binary_operation { + HMATH_AD_ADD = 0, + HMATH_AD_SUBTRACT = 1, + HMATH_AD_MULTIPLY = 2, + HMATH_AD_DIVIDE = 3, + HMATH_AD_POWER = 4 +} hmath_ad_binary_operation; +HMATH_API void hmath_ad_retain(hmath_ad_handle *value); +HMATH_API void hmath_ad_release(hmath_ad_handle *value); +HMATH_API hmath_status hmath_ad_variable(hmath_context *context, ptrdiff_t index, + hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_constant(hmath_context *context, double value, hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_dual_create(hmath_context *context, double primal, double tangent, + hmath_ad_dual **out); +HMATH_API hmath_status hmath_ad_unary(hmath_context *context, hmath_ad_unary_operation operation, + const hmath_ad_handle *value, hmath_ad_handle **out); +HMATH_API hmath_status hmath_ad_binary(hmath_context *context, hmath_ad_binary_operation operation, + const hmath_ad_handle *left, const hmath_ad_handle *right, + hmath_ad_handle **out); +HMATH_API hmath_status hmath_ad_compile_graph(hmath_context *context, ptrdiff_t index, + const hmath_ad_expr *expression, + hmath_ad_graph **out); +HMATH_API hmath_status hmath_ad_differentiate(hmath_context *context, ptrdiff_t index, + const hmath_ad_expr *expression, hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_zero_gradients(hmath_context *context, ptrdiff_t count, + hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_gradient_state_create(hmath_context *context, const double *values, + size_t count, hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_accumulate_gradients(hmath_context *context, + const hmath_ad_gradient_state *state, + const double *values, size_t count, + hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_gradient_hook_result(hmath_context *context, + const hmath_ad_gradient_state *state, + const double *values, size_t count, + hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_reset_gradients(hmath_context *context, + const hmath_ad_gradient_state *state, + hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_clip_gradient(hmath_context *context, double limit, + const double *values, size_t count, + hmath_ad_gradient_state **out); +HMATH_API hmath_status hmath_ad_tensor_create(hmath_context *context, const ptrdiff_t *shape, + size_t rank, const hmath_ad_expr *const *values, + size_t count, hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_broadcast(hmath_context *context, const ptrdiff_t *shape, + size_t rank, const hmath_ad_tensor *tensor, + hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_tensor_add(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_tensor_multiply(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, + hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_matmul(hmath_context *context, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_contract(hmath_context *context, const ptrdiff_t *left_axes, + size_t left_count, const ptrdiff_t *right_axes, + size_t right_count, const hmath_ad_tensor *left, + const hmath_ad_tensor *right, hmath_ad_tensor **out); +HMATH_API hmath_status hmath_ad_sum(hmath_context *context, const hmath_ad_tensor *tensor, + hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_evaluate_graph(hmath_context *context, + const hmath_ad_graph *expression, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_value_and_gradient(hmath_context *context, + const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_gradient(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_hessian(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_hvp(hmath_context *context, const hmath_ad_expr *expression, + const double *values, size_t n, const double *direction, + size_t direction_count, double *out, size_t capacity); +HMATH_API hmath_status hmath_ad_gradient_check(hmath_context *context, + const hmath_ad_expr *expression, + const double *values, size_t n, double step, + double *out, size_t capacity); +HMATH_API hmath_status hmath_ad_complex_gradient(hmath_context *context, + const hmath_ad_expr *expression, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_jacobian(hmath_context *context, + const hmath_ad_expr *const *expressions, size_t count, + const double *values, size_t n, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_jvp(hmath_context *context, const hmath_ad_expr *const *expressions, + size_t count, const double *values, size_t n, + const double *direction, size_t direction_count, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_vjp(hmath_context *context, const hmath_ad_expr *const *expressions, + size_t count, const double *values, size_t n, + const double *direction, size_t direction_count, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_forward_jvp_result(hmath_context *context, + const hmath_ad_dual *const *expressions, + size_t count, const double *values, size_t n, + const double *direction, size_t direction_count, + double *out, size_t capacity); +/* metadata reports logical value count and rank. For Dual count is two; + * gradient state count is its length; tensors report elements and rank. + * values_copy supports Dual [primal,tangent] and GradientState; shape_copy + * supports ADTensor. tensor_values returns owned Expr references; release each. + * Gradient/JVP/VJP/HVP outputs are flat logical lists; Hessian and Jacobian are + * row-major. value_and_gradient writes [value, gradient...], complex_gradient + * writes [real,imag], and forward_jvp_result writes [primals...,tangents...]. */ +HMATH_API hmath_status hmath_ad_metadata(const hmath_ad_handle *value, size_t *count, size_t *rank); +HMATH_API hmath_status hmath_ad_values_copy(const hmath_ad_handle *value, double *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_shape_copy(const hmath_ad_tensor *value, ptrdiff_t *out, + size_t capacity); +HMATH_API hmath_status hmath_ad_tensor_values(const hmath_ad_tensor *value, hmath_ad_expr **out, + size_t capacity); +/* Logical expression list is represented as a rank-one ADTensor. */ +HMATH_API hmath_status hmath_ad_differentiable_step(hmath_context *context, double rate, + const hmath_ad_expr *expression, + const hmath_ad_expr *const *points, + size_t count, hmath_ad_tensor **out); +/* Custom callbacks are synchronous/reentrant and must not throw across C. + * Keep function pointers, userdata and borrowed error strings alive until all + * derived expression/graph/tensor handles are released. HMATH_MATH_ERROR plus + * an original MathError Show message propagates without changing its payload. + * Other nonzero callback statuses propagate as binding failures. + * Rule callbacks write at most partial_capacity values and report actual arity + * in partial_count. Wrong arity is checked by the original reverse evaluator; + * value-only graph evaluation retains its original behavior. + * Builder inputs are borrowed; return one owned expression reference. Retain an + * input before returning it. Callback-created expressions may themselves hold + * callbacks, whose userdata must follow the same transitive lifetime rule. */ +typedef hmath_status (*hmath_ad_rule_callback)(const double *values, size_t count, void *userdata, + double *value, double *partials, + size_t partial_capacity, size_t *partial_count, + const char **error_message); +typedef hmath_status (*hmath_ad_unary_callback)(double value, void *userdata, double *result, + const char **error_message); +typedef hmath_status (*hmath_ad_builder_callback)(const hmath_ad_expr *const *values, size_t count, + void *userdata, hmath_ad_expr **result, + const char **error_message); +HMATH_API hmath_status hmath_ad_custom_operation(hmath_context *context, + hmath_ad_rule_callback callback, void *userdata, + const hmath_ad_expr *const *values, size_t count, + hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_custom_unary(hmath_context *context, + hmath_ad_unary_callback function, + hmath_ad_unary_callback derivative, void *userdata, + const hmath_ad_expr *value, hmath_ad_expr **out); +HMATH_API hmath_status hmath_ad_checkpoint(hmath_context *context, + hmath_ad_builder_callback callback, void *userdata, + const hmath_ad_expr *const *values, size_t count, + hmath_ad_expr **out); +/* Original Dual instances may nest to arbitrary depth over Double leaves. + * Components must have equal scalar types/depth. dual_parts returns two owned + * handles; a scalar leaf has depth zero and values_copy returns one Double. + * A flat Dual has depth one and values_copy returns [primal,tangent]. Deeper + * duals require dual_parts; their flat value count is zero. */ +HMATH_API hmath_status hmath_ad_dual_nested(hmath_context *context, const hmath_ad_dual *primal, + const hmath_ad_dual *tangent, hmath_ad_dual **out); +HMATH_API hmath_status hmath_ad_dual_depth(const hmath_ad_dual *value, size_t *out); +HMATH_API hmath_status hmath_ad_dual_parts(const hmath_ad_dual *value, hmath_ad_dual **out_primal, + hmath_ad_dual **out_tangent); +/* Forward-mode leaf types use original Haskell instances without widening. + * kind follows hmath_coefficient_type (0..15), plus20=Numeric.Dual and + *21=Numeric.Quaternion. Every supported coefficient can be exported from a + * shared Value into a depth-zero handle, then nested with dual_nested. The + * original class dictionaries apply; unavailable Ord/Fractional/Floating + * instances are rejected without conversion. Integer/Rational use signed + * decimal strings, and scalar_text returns owned numerator/denominator strings + * for exact scalar leaf handles (depth zero). Release both with string_free. + * Exact values never pass through floating-point intermediates. Unsupported + * class operations (Integer division, Rational exp, etc.) report InvalidArgument. + * These leaf types can all nest through dual_nested. */ +HMATH_API hmath_status hmath_ad_dual_create_f32(hmath_context *context, float primal, float tangent, + hmath_ad_dual **out); +HMATH_API hmath_status hmath_ad_dual_create_integer(hmath_context *context, const char *primal, + const char *tangent, hmath_ad_dual **out); +HMATH_API hmath_status hmath_ad_dual_create_rational( + hmath_context *context, const char *primal_numerator, const char *primal_denominator, + const char *tangent_numerator, const char *tangent_denominator, hmath_ad_dual **out); +HMATH_API hmath_status hmath_ad_dual_kind(const hmath_ad_dual *value, int *out); +HMATH_API hmath_status hmath_ad_scalar_text(const hmath_ad_dual *value, char **numerator, + char **denominator); +HMATH_API void hmath_ad_string_free(char *value); +/* Relations use original instances: Eq includes both fields; Ord compares + * primal fields only, recursively. operation: 0=Eq,1=LT,2=LE,3=GT,4=GE. */ +HMATH_API hmath_status hmath_ad_dual_relation(hmath_context *context, int operation, + const hmath_ad_dual *left, const hmath_ad_dual *right, + int *out); +/* Additive shared-Value interchange for original AD Expr/ADTensor/Dual values. + * Each conversion returns independent ownership and preserves the original + * object/type. Scalar Dual component leaves use ordinary exact typed Values. + * Keep callback pointers/userdata alive transitively through derived handles. */ +HMATH_API hmath_status hmath_ad_value_import(hmath_context *context, + const hmath_ad_handle *input, + hmath_value **out); +HMATH_API hmath_status hmath_ad_value_export(hmath_context *context, + const hmath_value *input, + hmath_ad_handle **out); +/* Checked additive callbacks preserve full status11/12/13 structured errors. + * Returning11 from a custom rule supplies a genuine original Left MathError; + * other failures abort after cleanup. Pure unary/checkpoint callback failures + * relay at the outer boundary. Function/userdata and error buffers stay valid + * until consumed; derived expressions retain the same borrowed-callback lifetime + * contract as the legacy constructors. written is the logical derivative count; + * never write more than capacity partials (wrong counts retain source errors). */ +typedef hmath_status (*hmath_ad_rule_checked_callback)( + const double *values, size_t count, void *userdata, double *value, + double *partials, size_t capacity, size_t *written, hmath_callback_error *error); +typedef hmath_status (*hmath_ad_unary_checked_callback)( + double value, void *userdata, double *out, hmath_callback_error *error); +typedef hmath_status (*hmath_ad_builder_checked_callback)( + const hmath_ad_expr *const *inputs, size_t count, void *userdata, + hmath_ad_expr **out, hmath_callback_error *error); +HMATH_API hmath_status hmath_ad_custom_operation_checked( + hmath_context *, hmath_ad_rule_checked_callback, void *, + const hmath_ad_expr *const *, size_t, hmath_ad_expr **); +HMATH_API hmath_status hmath_ad_custom_unary_checked( + hmath_context *, hmath_ad_unary_checked_callback, + hmath_ad_unary_checked_callback, void *, const hmath_ad_expr *, hmath_ad_expr **); +HMATH_API hmath_status hmath_ad_checkpoint_checked( + hmath_context *, hmath_ad_builder_checked_callback, void *, + const hmath_ad_expr *const *, size_t, hmath_ad_expr **); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_backend.h b/include/hmath_backend.h index fe6278c..1874246 100644 --- a/include/hmath_backend.h +++ b/include/hmath_backend.h @@ -24,6 +24,13 @@ int hmath_backend_gemm(hmath_backend *, int complex_values, int trans_a, int tra * is an explicit ABI declaration. HMATH_BACKEND=pure disables native dispatch. * The loader is initialized once. Unknown custom ABIs are never inferred. */ int hmath_lapack_available(void); +/* Internal real buffer GEMM. FP32 is optional; missing SGEMM does not reject an + * otherwise valid existing provider. ldc is explicit for padded row storage. */ +int hm_backend_has_real_gemm(hmath_backend *backend, int precision); +int hm_backend_real_gemm(hmath_backend *backend, int precision, int64_t m, int64_t n, int64_t k, + const void *alpha, const void *a, int64_t lda, + const void *b, int64_t ldb, const void *beta, void *c, int64_t ldc); + #ifdef __cplusplus } #endif diff --git a/include/hmath_buffer.h b/include/hmath_buffer.h new file mode 100644 index 0000000..aa1053d --- /dev/null +++ b/include/hmath_buffer.h @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_buffer_bindings.py. */ +#ifndef HMATH_BUFFER_H +#define HMATH_BUFFER_H +#include "hmath_value.h" +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Actual API.Buffer containers, Foundation-kind400. Borrowed input handles; + * successful outputs own one reference and errors leave outputs untouched. + * Boxed generic values preserve exact elements; strictBoxed/mapStrict force + * original WHNF, not deep normal form. Unboxed uses original Double without + * added finite checks. ST region handles may execute only on the callback + * thread inside runSTBuffer; thawSTBuffer takes an explicit region handle. + * IO storage supports actual Storable Float/Double/Complex and bounded/native + * Int/Word, Bool(dtype16), Char(dtype17). Integer/Rational/Dual have no original + * Storable instance. storage_info returns(dtype,size,alignment,length). + * Freeze/thaw copy; aliases share one ForeignPtr and original IO lock. Callback + * args use callback101 Tuple(STBuffer) or Tuple(BorrowedPointer,count). Pointers + * are valid only for the synchronous callback; never retain a raw address or + * reenter locking operations on the same buffer (same-thread reentry is BUSY). + * Scoped operations from another thread/after return are INVALID_ARGUMENT. + * Independent IO operations synchronize using the original lock. Original + * MathError uses status11; allocation/OS/callback exceptions propagate. */ +typedef hmath_value hmath_buffer_boxed_object; +typedef hmath_value hmath_buffer_unboxed_double_object; +typedef hmath_value hmath_buffer_st_buffer_object; +typedef hmath_value hmath_buffer_io_buffer_object; +/* HMath.API.Buffer.lazyBoxed :: [a] -> Boxed a */ +HMATH_API hmath_status hmath_buffer_lazy_boxed(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.API.Buffer.strictBoxed :: [a] -> Boxed a */ +HMATH_API hmath_status hmath_buffer_strict_boxed(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.API.Buffer.boxedValues :: Boxed a -> [a] */ +HMATH_API hmath_status hmath_buffer_boxed_values(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.boxedLength :: Boxed a -> Int */ +HMATH_API hmath_status hmath_buffer_boxed_length(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.mapStrict :: (a -> b) -> Boxed a -> Boxed b */ +HMATH_API hmath_status hmath_buffer_map_strict(hmath_context *context, const hmath_value *function, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.unboxedDouble :: [Double] -> UnboxedDouble */ +HMATH_API hmath_status hmath_buffer_unboxed_double(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.API.Buffer.unboxedValues :: UnboxedDouble -> [Double] */ +HMATH_API hmath_status hmath_buffer_unboxed_values(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.runSTBuffer :: Boxed a -> (forall s. STBuffer s a -> ST s b) -> b */ +HMATH_API hmath_status hmath_buffer_run_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out); +/* HMath.API.Buffer.thawSTBuffer :: Boxed a -> ST s (STBuffer s a) */ +HMATH_API hmath_status hmath_buffer_thaw_st_buffer(hmath_context *context, const hmath_value *region, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.freezeSTBuffer :: STBuffer s a -> ST s (Boxed a) */ +HMATH_API hmath_status hmath_buffer_freeze_st_buffer(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.readSTBuffer :: STBuffer s a -> Int -> ST s (Either MathError a) */ +HMATH_API hmath_status hmath_buffer_read_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out); +/* HMath.API.Buffer.writeSTBuffer :: STBuffer s a -> Int -> a -> ST s (Either MathError ()) */ +HMATH_API hmath_status hmath_buffer_write_st_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out); +/* HMath.API.Buffer.newIOBuffer :: Storable a => Int -> a -> IO (Either MathError (IOBuffer a)) */ +HMATH_API hmath_status hmath_buffer_new_io_buffer(hmath_context *context, const hmath_value *count, const hmath_value *initial, hmath_value **out); +/* HMath.API.Buffer.thawIOBuffer :: Storable a => Boxed a -> IO (Either MathError (IOBuffer a)) */ +HMATH_API hmath_status hmath_buffer_thaw_io_buffer(hmath_context *context, const hmath_value *prototype, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.freezeIOBuffer :: Storable a => IOBuffer a -> IO (Boxed a) */ +HMATH_API hmath_status hmath_buffer_freeze_io_buffer(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.ioBufferLength :: IOBuffer a -> Int */ +HMATH_API hmath_status hmath_buffer_io_buffer_length(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.readIOBuffer :: Storable a => IOBuffer a -> Int -> IO (Either MathError a) */ +HMATH_API hmath_status hmath_buffer_read_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out); +/* HMath.API.Buffer.writeIOBuffer :: Storable a => IOBuffer a -> Int -> a -> IO (Either MathError ()) */ +HMATH_API hmath_status hmath_buffer_write_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out); +/* HMath.API.Buffer.withIOBuffer :: Storable a => IOBuffer a -> (Ptr a -> Int -> IO b) -> IO b */ +HMATH_API hmath_status hmath_buffer_with_io_buffer(hmath_context *context, const hmath_value *value, const hmath_value *callback, hmath_value **out); +/* HMath.API.Buffer.unboxedToBoxed :: UnboxedDouble -> Boxed Double */ +HMATH_API hmath_status hmath_buffer_unboxed_to_boxed(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.API.Buffer.boxedToUnboxed :: Boxed Double -> UnboxedDouble */ +HMATH_API hmath_status hmath_buffer_boxed_to_unboxed(hmath_context *context, const hmath_value *value, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_storage_info(hmath_context *context, const hmath_value *value, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_pointer_info(hmath_context *context, const hmath_value *value, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_pointer_read(hmath_context *context, const hmath_value *value, const hmath_value *index, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_pointer_write(hmath_context *context, const hmath_value *value, const hmath_value *index, const hmath_value *element, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_pointer_address(hmath_context *context, const hmath_value *value, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_st_active(hmath_context *context, const hmath_value *value, hmath_value **out); +/* Scoped representation helper */ +HMATH_API hmath_status hmath_buffer_pointer_active(hmath_context *context, const hmath_value *value, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_bytes.h b/include/hmath_bytes.h new file mode 100644 index 0000000..9dddf04 --- /dev/null +++ b/include/hmath_bytes.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_BYTES_H +#define HMATH_BYTES_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Owned immutable strict ByteString, Value kind450, count=byte length. */ +HMATH_API hmath_status hmath_bytes_copy(hmath_context *context, const void *data, size_t count, + hmath_value **out); +/* Query only; both outputs are required and unchanged on error. The returned + * span is read-only and borrowed until the owning Value's last release. Keep + * a retained reference alive for every view; no terminator is implied. */ +HMATH_API hmath_status hmath_bytes_data(const hmath_value *bytes, const unsigned char **data, + size_t *count); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_callback.h b/include/hmath_callback.h new file mode 100644 index 0000000..66ad857 --- /dev/null +++ b/include/hmath_callback.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_CALLBACK_H +#define HMATH_CALLBACK_H +#include "hmath_error.h" +#ifdef __cplusplus +extern "C" { +#endif +/* ABI-compatible callback error wire. The callback return status determines + * the domain: 11=MathError, 12=ExprError (offset,line,column in details0..2), + * 13=InterchangeError. kind is the corresponding domain constructor code; + * message is length-delimited WTF8 and remains valid until consumed. */ +typedef hmath_math_error hmath_callback_error; +/* Query only: capture a matching current structured error after a nested API + * call. Returns1 on success,0 with out untouched otherwise. Message is borrowed + * until the next checked operation on this thread. */ +HMATH_API int hmath_callback_capture_error(hmath_status status, hmath_callback_error *out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_deeplearning.h b/include/hmath_deeplearning.h new file mode 100644 index 0000000..012e4f0 --- /dev/null +++ b/include/hmath_deeplearning.h @@ -0,0 +1,954 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_DEEPLEARNING_H +#define HMATH_DEEPLEARNING_H +#include "hmath_value.h" +#include "hmath_error.h" +#include "hmath_autodiff.h" +#include "hmath_tensor_bindings.h" +#ifdef __cplusplus +extern "C" { +#endif +/* All functions invoke original fixed-Double neural primitives. Tensor inputs + * use actual original Tensor Double Value161; Float tensors are not silently + * widened. ADExpr287/ADTensor288 share original graphs; RNG240 retains the full + * explicit original random continuation. Constructor/method/state values are + * immutable and independently owned. Release every Value output and nested + * handle; preserve callback owners through AD interchange. Checked MathError + * failures retain all21 constructors; outputs remain untouched on failure. */ +/* BEGIN GENERATED */ +/* HMath.DeepLearning.Core.Sigmoid -> Activation. */ +HMATH_API hmath_status hmath_neural_core_sigmoid_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Tanh -> Activation. */ +HMATH_API hmath_status hmath_neural_core_tanh_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.ReLU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_relu_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.SELU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_selu_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.GELU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_gelu_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.SiLU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_silu_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Mish -> Activation. */ +HMATH_API hmath_status hmath_neural_core_mish_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Softplus -> Activation. */ +HMATH_API hmath_status hmath_neural_core_softplus_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Softsign -> Activation. */ +HMATH_API hmath_status hmath_neural_core_softsign_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.HardSigmoid -> Activation. */ +HMATH_API hmath_status hmath_neural_core_hard_sigmoid_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.HardSwish -> Activation. */ +HMATH_API hmath_status hmath_neural_core_hard_swish_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.LeakyReLU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_leaky_relu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.PReLU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_prelu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.ELU -> Activation. */ +HMATH_API hmath_status hmath_neural_core_elu_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.Sum -> Reduction. */ +HMATH_API hmath_status hmath_neural_core_sum_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Mean -> Reduction. */ +HMATH_API hmath_status hmath_neural_core_mean_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.MeanSquaredError -> Loss. */ +HMATH_API hmath_status hmath_neural_core_mean_squared_error_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.MeanAbsoluteError -> Loss. */ +HMATH_API hmath_status hmath_neural_core_mean_absolute_error_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.BinaryCrossEntropy -> Loss. */ +HMATH_API hmath_status hmath_neural_core_binary_cross_entropy_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.CategoricalCrossEntropy -> Loss. */ +HMATH_API hmath_status hmath_neural_core_categorical_cross_entropy_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.NegativeLogLikelihood -> Loss. */ +HMATH_API hmath_status hmath_neural_core_negative_log_likelihood_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.KLDivergence -> Loss. */ +HMATH_API hmath_status hmath_neural_core_kl_divergence_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.CosineLoss -> Loss. */ +HMATH_API hmath_status hmath_neural_core_cosine_loss_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Core.Huber -> Loss. */ +HMATH_API hmath_status hmath_neural_core_huber_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.SmoothL1 -> Loss. */ +HMATH_API hmath_status hmath_neural_core_smooth_l1_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.Hinge -> Loss. */ +HMATH_API hmath_status hmath_neural_core_hinge_create( + hmath_context *context, + const hmath_value *parameter, + hmath_value **out); + +/* HMath.DeepLearning.Core.activation -> Double. */ +HMATH_API hmath_status hmath_neural_core_activation( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out); + +/* HMath.DeepLearning.Core.activationDerivative -> Double. */ +HMATH_API hmath_status hmath_neural_core_activation_derivative( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out); + +/* HMath.DeepLearning.Core.activationExpr -> ADExpr. */ +HMATH_API hmath_status hmath_neural_core_activation_expr( + hmath_context *context, + const hmath_value *method, + const hmath_value *value, + hmath_value **out); + +/* HMath.DeepLearning.Core.softmax -> [Double]. */ +HMATH_API hmath_status hmath_neural_core_softmax( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.logSoftmax -> [Double]. */ +HMATH_API hmath_status hmath_neural_core_log_softmax( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.sparsemax -> [Double]. */ +HMATH_API hmath_status hmath_neural_core_sparsemax( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.gatedLinearUnit -> [Double]. */ +HMATH_API hmath_status hmath_neural_core_gated_linear_unit( + hmath_context *context, + const hmath_value *values, + const hmath_value *gate, + hmath_value **out); + +/* HMath.DeepLearning.Core.softmaxExpr -> [ADExpr]. */ +HMATH_API hmath_status hmath_neural_core_softmax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.logSoftmaxExpr -> [ADExpr]. */ +HMATH_API hmath_status hmath_neural_core_log_softmax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.sparsemaxExpr -> [ADExpr]. */ +HMATH_API hmath_status hmath_neural_core_sparsemax_expr( + hmath_context *context, + const hmath_value *values, + hmath_value **out); + +/* HMath.DeepLearning.Core.loss -> Double. */ +HMATH_API hmath_status hmath_neural_core_loss( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.lossGradient -> [Double]. */ +HMATH_API hmath_status hmath_neural_core_loss_gradient( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.lossExpr -> ADExpr. */ +HMATH_API hmath_status hmath_neural_core_loss_expr( + hmath_context *context, + const hmath_value *method, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.binaryCrossEntropyLogits -> Double. */ +HMATH_API hmath_status hmath_neural_core_binary_cross_entropy_logits( + hmath_context *context, + const hmath_value *reduction, + const hmath_value *target, + const hmath_value *logits, + hmath_value **out); + +/* HMath.DeepLearning.Core.categoricalCrossEntropyLogits -> Double. */ +HMATH_API hmath_status hmath_neural_core_categorical_cross_entropy_logits( + hmath_context *context, + const hmath_value *target, + const hmath_value *logits, + hmath_value **out); + +/* HMath.DeepLearning.Core.regularization -> Double. */ +HMATH_API hmath_status hmath_neural_core_regularization( + hmath_context *context, + const hmath_value *l1, + const hmath_value *l2, + const hmath_value *weights, + hmath_value **out); + +/* HMath.DeepLearning.Core.contrastiveLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_contrastive_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *similar, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.DeepLearning.Core.tripletLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_triplet_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *anchor, + const hmath_value *positive, + const hmath_value *negative, + hmath_value **out); + +/* HMath.DeepLearning.Core.focalLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_focal_loss( + hmath_context *context, + const hmath_value *alpha, + const hmath_value *gamma, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.diceLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_dice_loss( + hmath_context *context, + const hmath_value *smooth, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.iouLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_iou_loss( + hmath_context *context, + const hmath_value *smooth, + const hmath_value *target, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Core.ctcLoss -> Double. */ +HMATH_API hmath_status hmath_neural_core_ctc_loss( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out); + +/* HMath.DeepLearning.Core.ctcLossGradient -> (Double,[[Double]]). */ +HMATH_API hmath_status hmath_neural_core_ctc_loss_gradient( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out); + +/* HMath.DeepLearning.Core.ctcLossExpr -> ADExpr. */ +HMATH_API hmath_status hmath_neural_core_ctc_loss_expr( + hmath_context *context, + const hmath_value *blank, + const hmath_value *labels, + const hmath_value *log_probabilities, + hmath_value **out); + +/* HMath.DeepLearning.Layers.Training -> Training. */ +HMATH_API hmath_status hmath_neural_layers_training_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.Inference -> Training. */ +HMATH_API hmath_status hmath_neural_layers_inference_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.dropout -> (Tensor,Tensor,RNG). */ +HMATH_API hmath_status hmath_neural_layers_dropout( + hmath_context *context, + const hmath_value *mode, + const hmath_value *probability, + const hmath_value *rng, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.spatialDropout -> (Tensor,Tensor,RNG). */ +HMATH_API hmath_status hmath_neural_layers_spatial_dropout( + hmath_context *context, + const hmath_value *mode, + const hmath_value *probability, + const hmath_value *rng, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.BatchNormState -> BatchNormState. */ +HMATH_API hmath_status hmath_neural_layers_batch_norm_state_create( + hmath_context *context, + const hmath_value *running_mean, + const hmath_value *running_variance, + const hmath_value *batches_seen, + hmath_value **out); + +/* HMath.DeepLearning.Layers.runningMean -> [Double]. */ +HMATH_API hmath_status hmath_neural_layers_running_mean( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Layers.runningVariance -> [Double]. */ +HMATH_API hmath_status hmath_neural_layers_running_variance( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Layers.batchesSeen -> Int. */ +HMATH_API hmath_status hmath_neural_layers_batches_seen( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Layers.batchNorm -> (Tensor,BatchNormState). */ +HMATH_API hmath_status hmath_neural_layers_batch_norm( + hmath_context *context, + const hmath_value *mode, + const hmath_value *momentum, + const hmath_value *epsilon, + const hmath_value *gamma, + const hmath_value *beta, + const hmath_value *state, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.layerNorm -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_layer_norm( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.rmsNorm -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_rms_norm( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.instanceNorm -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_instance_norm( + hmath_context *context, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.groupNorm -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_group_norm( + hmath_context *context, + const hmath_value *groups, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.weightNorm -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_weight_norm( + hmath_context *context, + const hmath_value *axis, + const hmath_value *scales, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.XavierUniform -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_xavier_uniform_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.XavierNormal -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_xavier_normal_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.KaimingUniform -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_kaiming_uniform_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.KaimingNormal -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_kaiming_normal_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.Orthogonal -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_orthogonal_create( + hmath_context *context, + const hmath_value *scale, + hmath_value **out); + +/* HMath.DeepLearning.Layers.TruncatedNormal -> Initializer. */ +HMATH_API hmath_status hmath_neural_layers_truncated_normal_create( + hmath_context *context, + const hmath_value *mean, + const hmath_value *standard_deviation, + const hmath_value *bound, + hmath_value **out); + +/* HMath.DeepLearning.Layers.initializeWeights -> (Tensor,RNG). */ +HMATH_API hmath_status hmath_neural_layers_initialize_weights( + hmath_context *context, + const hmath_value *method, + const hmath_value *fan_in, + const hmath_value *fan_out, + const hmath_value *shape, + const hmath_value *rng, + hmath_value **out); + +/* HMath.DeepLearning.Layers.embedding -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_embedding( + hmath_context *context, + const hmath_value *weights, + const hmath_value *indices, + hmath_value **out); + +/* HMath.DeepLearning.Layers.dense -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_dense( + hmath_context *context, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.denseAD -> ADTensor. */ +HMATH_API hmath_status hmath_neural_layers_dense_ad( + hmath_context *context, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.ConvOptions -> ConvOptions. */ +HMATH_API hmath_status hmath_neural_layers_conv_options_create( + hmath_context *context, + const hmath_value *stride, + const hmath_value *padding, + const hmath_value *dilation, + const hmath_value *groups, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolutionStride -> [Int]. */ +HMATH_API hmath_status hmath_neural_layers_convolution_stride( + hmath_context *context, + const hmath_value *options, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolutionPadding -> [Int]. */ +HMATH_API hmath_status hmath_neural_layers_convolution_padding( + hmath_context *context, + const hmath_value *options, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolutionDilation -> [Int]. */ +HMATH_API hmath_status hmath_neural_layers_convolution_dilation( + hmath_context *context, + const hmath_value *options, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolutionGroups -> Int. */ +HMATH_API hmath_status hmath_neural_layers_convolution_groups( + hmath_context *context, + const hmath_value *options, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolution -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_convolution( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.depthwiseConvolution -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_depthwise_convolution( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.convolutionAD -> ADTensor. */ +HMATH_API hmath_status hmath_neural_layers_convolution_ad( + hmath_context *context, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.transposedConvolution -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_transposed_convolution( + hmath_context *context, + const hmath_value *output_padding, + const hmath_value *options, + const hmath_value *input, + const hmath_value *weights, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.MaxPool -> PoolMode. */ +HMATH_API hmath_status hmath_neural_layers_max_pool_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.AveragePool -> PoolMode. */ +HMATH_API hmath_status hmath_neural_layers_average_pool_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Layers.pooling -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *kernel, + const hmath_value *stride, + const hmath_value *padding, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.adaptivePooling -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_adaptive_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *shape, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.globalPooling -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_global_pooling( + hmath_context *context, + const hmath_value *mode, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.scaledDotProductAttention -> (Tensor,Tensor). */ +HMATH_API hmath_status hmath_neural_layers_scaled_dot_product_attention( + hmath_context *context, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + const hmath_value *bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.multiheadAttention -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_multihead_attention( + hmath_context *context, + const hmath_value *heads, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + hmath_value **out); + +/* HMath.DeepLearning.Layers.causalMask -> [[Bool]]. */ +HMATH_API hmath_status hmath_neural_layers_causal_mask( + hmath_context *context, + const hmath_value *queries, + const hmath_value *keys, + const hmath_value *offset, + hmath_value **out); + +/* HMath.DeepLearning.Layers.rotaryEmbedding -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_rotary_embedding( + hmath_context *context, + const hmath_value *base, + const hmath_value *offset, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.sinusoidalEncoding -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_sinusoidal_encoding( + hmath_context *context, + const hmath_value *length, + const hmath_value *dimensions, + const hmath_value *offset, + hmath_value **out); + +/* HMath.DeepLearning.Layers.alibiBias -> [[Double]]. */ +HMATH_API hmath_status hmath_neural_layers_alibi_bias( + hmath_context *context, + const hmath_value *slope, + const hmath_value *queries, + const hmath_value *keys, + const hmath_value *offset, + hmath_value **out); + +/* HMath.DeepLearning.Layers.emptyCache -> KVCache. */ +HMATH_API hmath_status hmath_neural_layers_empty_cache( + hmath_context *context, + const hmath_value *capacity, + const hmath_value *key_dimensions, + const hmath_value *value_dimensions, + hmath_value **out); + +/* HMath.DeepLearning.Layers.appendCache -> KVCache. */ +HMATH_API hmath_status hmath_neural_layers_append_cache( + hmath_context *context, + const hmath_value *cache, + const hmath_value *key, + const hmath_value *value, + hmath_value **out); + +/* HMath.DeepLearning.Layers.cacheValues -> (Tensor,Tensor). */ +HMATH_API hmath_status hmath_neural_layers_cache_values( + hmath_context *context, + const hmath_value *cache, + hmath_value **out); + +/* HMath.DeepLearning.Layers.transformerFeedForward -> Tensor. */ +HMATH_API hmath_status hmath_neural_layers_transformer_feed_forward( + hmath_context *context, + const hmath_value *activation, + const hmath_value *input, + const hmath_value *first_weights, + const hmath_value *first_bias, + const hmath_value *second_weights, + const hmath_value *second_bias, + hmath_value **out); + +/* HMath.DeepLearning.Layers.layerNormAD -> ADTensor. */ +HMATH_API hmath_status hmath_neural_layers_layer_norm_ad( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.rmsNormAD -> ADTensor. */ +HMATH_API hmath_status hmath_neural_layers_rms_norm_ad( + hmath_context *context, + const hmath_value *axes, + const hmath_value *epsilon, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Layers.scaledDotProductAttentionAD -> ADTensor. */ +HMATH_API hmath_status hmath_neural_layers_scaled_dot_product_attention_ad( + hmath_context *context, + const hmath_value *query, + const hmath_value *key, + const hmath_value *value, + const hmath_value *mask, + hmath_value **out); + +/* HMath.DeepLearning.Precision.Symmetric -> Quantization. */ +HMATH_API hmath_status hmath_neural_precision_symmetric_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Precision.Asymmetric -> Quantization. */ +HMATH_API hmath_status hmath_neural_precision_asymmetric_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Precision.quantize -> QuantizedTensor. */ +HMATH_API hmath_status hmath_neural_precision_quantize( + hmath_context *context, + const hmath_value *scheme, + const hmath_value *axis, + const hmath_value *input, + hmath_value **out); + +/* HMath.DeepLearning.Precision.dequantize -> Tensor. */ +HMATH_API hmath_status hmath_neural_precision_dequantize( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out); + +/* HMath.DeepLearning.Precision.quantizedValues -> [Int8]. */ +HMATH_API hmath_status hmath_neural_precision_quantized_values( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out); + +/* HMath.DeepLearning.Precision.quantizationScales -> [Double]. */ +HMATH_API hmath_status hmath_neural_precision_quantization_scales( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out); + +/* HMath.DeepLearning.Precision.quantizationZeroPoints -> [Int]. */ +HMATH_API hmath_status hmath_neural_precision_quantization_zero_points( + hmath_context *context, + const hmath_value *quantized, + hmath_value **out); + +/* HMath.DeepLearning.Precision.int8Gemm -> Tensor. */ +HMATH_API hmath_status hmath_neural_precision_int8_gemm( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.DeepLearning.Precision.FP16 -> Precision. */ +HMATH_API hmath_status hmath_neural_precision_fp16_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Precision.BF16 -> Precision. */ +HMATH_API hmath_status hmath_neural_precision_bf16_create( + hmath_context *context, + hmath_value **out); + +/* HMath.DeepLearning.Precision.reducedGemm -> Tensor. */ +HMATH_API hmath_status hmath_neural_precision_reduced_gemm( + hmath_context *context, + const hmath_value *precision, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.DeepLearning.Precision.LossScaler -> LossScaler. */ +HMATH_API hmath_status hmath_neural_precision_loss_scaler_create( + hmath_context *context, + const hmath_value *scale, + const hmath_value *growth_interval, + const hmath_value *finite_steps, + hmath_value **out); + +/* HMath.DeepLearning.Precision.lossScale -> Double. */ +HMATH_API hmath_status hmath_neural_precision_loss_scale( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Precision.scaleGrowthInterval -> Int. */ +HMATH_API hmath_status hmath_neural_precision_scale_growth_interval( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Precision.finiteSteps -> Int. */ +HMATH_API hmath_status hmath_neural_precision_finite_steps( + hmath_context *context, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Precision.initialLossScaler -> LossScaler. */ +HMATH_API hmath_status hmath_neural_precision_initial_loss_scaler( + hmath_context *context, + const hmath_value *scale, + const hmath_value *growth_interval, + hmath_value **out); + +/* HMath.DeepLearning.Precision.scaleLoss -> Double. */ +HMATH_API hmath_status hmath_neural_precision_scale_loss( + hmath_context *context, + const hmath_value *state, + const hmath_value *loss, + hmath_value **out); + +/* HMath.DeepLearning.Precision.unscaleGradients -> (Bool,[Double]). */ +HMATH_API hmath_status hmath_neural_precision_unscale_gradients( + hmath_context *context, + const hmath_value *state, + const hmath_value *gradients, + hmath_value **out); + +/* HMath.DeepLearning.Precision.updateLossScaler -> LossScaler. */ +HMATH_API hmath_status hmath_neural_precision_update_loss_scaler( + hmath_context *context, + const hmath_value *finite, + const hmath_value *state, + hmath_value **out); + +/* HMath.DeepLearning.Precision.gradientNorm -> Double. */ +HMATH_API hmath_status hmath_neural_precision_gradient_norm( + hmath_context *context, + const hmath_value *gradient, + hmath_value **out); + +/* HMath.DeepLearning.Precision.clipGradients -> [Double]. */ +HMATH_API hmath_status hmath_neural_precision_clip_gradients( + hmath_context *context, + const hmath_value *maximum, + const hmath_value *gradient, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.ClassificationMetrics -> ClassificationMetrics. */ +HMATH_API hmath_status hmath_neural_metrics_classification_metrics_create( + hmath_context *context, + const hmath_value *accuracy, + const hmath_value *precision, + const hmath_value *recall, + const hmath_value *f1, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.accuracy -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_accuracy( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.precisionByClass -> [Double]. */ +HMATH_API hmath_status hmath_neural_metrics_precision_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.recallByClass -> [Double]. */ +HMATH_API hmath_status hmath_neural_metrics_recall_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.f1ByClass -> [Double]. */ +HMATH_API hmath_status hmath_neural_metrics_f1_by_class( + hmath_context *context, + const hmath_value *metrics, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.confusionMatrix -> [[Int]]. */ +HMATH_API hmath_status hmath_neural_metrics_confusion_matrix( + hmath_context *context, + const hmath_value *classes, + const hmath_value *truth, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.classificationMetrics -> ClassificationMetrics. */ +HMATH_API hmath_status hmath_neural_metrics_classification_metrics( + hmath_context *context, + const hmath_value *classes, + const hmath_value *truth, + const hmath_value *prediction, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.topKAccuracy -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_top_k_accuracy( + hmath_context *context, + const hmath_value *k, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.rocAUC -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_roc_auc( + hmath_context *context, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.prAUC -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_pr_auc( + hmath_context *context, + const hmath_value *truth, + const hmath_value *scores, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.perplexity -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_perplexity( + hmath_context *context, + const hmath_value *negative_log_probabilities, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.cosineSimilarityMatrix -> Tensor. */ +HMATH_API hmath_status hmath_neural_metrics_cosine_similarity_matrix( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.DeepLearning.Metrics.marginRankingLoss -> Double. */ +HMATH_API hmath_status hmath_neural_metrics_margin_ranking_loss( + hmath_context *context, + const hmath_value *margin, + const hmath_value *left, + const hmath_value *right, + const hmath_value *labels, + hmath_value **out); +/* END GENERATED */ +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_error.h b/include/hmath_error.h new file mode 100644 index 0000000..2f16db5 --- /dev/null +++ b/include/hmath_error.h @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_ERROR_H +#define HMATH_ERROR_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Stable transport for the original Haskell MathError sum type. Tuple fields + * are flattened in source order into details. Unused details are ignored. + * message is borrowed UTF-8 with an explicit byte length (embedded NUL allowed). + * Haskell surrogate Char codepoints use the surrogatepass/WTF8 extension. + * Callback error memory lives until the callback result has been consumed. + * The last-error query instead borrows library memory until the next checked + * operation on this thread; copy it before calling another numerical API. */ +typedef enum hmath_math_error_kind { + HMATH_MATH_NEGATIVE_DIMENSIONS = 1, + HMATH_MATH_ELEMENT_COUNT_OVERFLOW = 2, + HMATH_MATH_ELEMENT_COUNT_MISMATCH = 3, + HMATH_MATH_SHAPE_MISMATCH = 4, + HMATH_MATH_INNER_DIMENSION_MISMATCH = 5, + HMATH_MATH_INDEX_OUT_OF_BOUNDS = 6, + HMATH_MATH_SLICE_OUT_OF_BOUNDS = 7, + HMATH_MATH_VECTOR_LENGTH_MISMATCH = 8, + HMATH_MATH_NON_SQUARE_MATRIX = 9, + HMATH_MATH_INVALID_TOLERANCE = 10, + HMATH_MATH_SINGULAR_MATRIX = 11, + HMATH_MATH_NEAR_SINGULAR_MATRIX = 12, + HMATH_MATH_NON_FINITE_MATRIX_ENTRY = 13, + HMATH_MATH_NON_FINITE_VECTOR_ENTRY = 14, + HMATH_MATH_NON_FINITE_RESULT = 15, + HMATH_MATH_RIGHT_HAND_SIDE_MISMATCH = 16, + HMATH_MATH_DOMAIN_ERROR = 17, + HMATH_MATH_INVALID_ARGUMENT = 18, + HMATH_MATH_NON_CONVERGENCE = 19, + HMATH_MATH_RANK_DEFICIENT = 20, + HMATH_MATH_NOT_POSITIVE_DEFINITE = 21 +} hmath_math_error_kind; +typedef struct hmath_math_error { + uint32_t kind; + ptrdiff_t details[6]; + const char *message; + size_t message_length; +} hmath_math_error; +/* Query only: returns 1 when a complete structured MathError is available, + * otherwise 0. It does not modify the last status/message. NULL out returns 0. */ +HMATH_API int hmath_last_math_error(hmath_math_error *out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_execution.h b/include/hmath_execution.h new file mode 100644 index 0000000..cde7efd --- /dev/null +++ b/include/hmath_execution.h @@ -0,0 +1,67 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_EXECUTION_H +#define HMATH_EXECUTION_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum hmath_execution_provider { + HMATH_EXECUTION_REFERENCE = 0, + HMATH_EXECUTION_OPENBLAS = 1, + HMATH_EXECUTION_BLIS = 2, + HMATH_EXECUTION_MKL = 3, + HMATH_EXECUTION_ACCELERATE = 4 +} hmath_execution_provider; +typedef struct hmath_execution_options { + hmath_execution_provider provider; + unsigned integer_bits; /* BLAS LP64=32 or ILP64=64; 0 means LP64. */ + const char *library_path; /* Optional explicit provider path, borrowed for create. */ + size_t max_elements; /* Per logical A/B/C view; 0 means no artificial cap. */ + size_t max_multiply_adds; /* m*n*k per call; 0 means no artificial cap. */ +} hmath_execution_options; +typedef struct hmath_execution hmath_execution; +/* Row-major, consecutive columns, optional padding between rows. Counts and + * leading dimensions are in elements, not bytes. No transpose/negative strides. + * storage_count bounds the reachable span; caller guarantees actual allocation. */ +typedef struct hmath_execution_view { + const void *data; + size_t storage_count, rows, columns, leading_dimension; +} hmath_execution_view; +typedef struct hmath_execution_output { + void *data; + size_t storage_count, rows, columns, leading_dimension; +} hmath_execution_output; +/* NULL options selects the reference path with unlimited resource policies. + * Provider selection is explicit; unavailable/mismatched providers never silently + * fall back. No OpenBLAS dependency is needed for the reference path. */ +HMATH_API hmath_status hmath_execution_create(const hmath_execution_options *options, + hmath_execution **out); +HMATH_API void hmath_execution_retain(hmath_execution *execution); +HMATH_API void hmath_execution_release(hmath_execution *execution); +/* C := alpha*A*B + beta*C, borrowing all buffers for this synchronous call. + * A/B may overlap each other, but C must not overlap either input (including + * padding spans). C must initially contain finite values even when beta=0, + * matching the existing checked Backend.gemm input policy. Inputs/scalars are + * finite checked; failures report original NonFiniteVectorEntry numbering over + * [alpha,beta] ++ logical(A) ++ logical(B) ++ logical(C), and output errors number + * logical(C). Validation failures leave C untouched. Once execution starts, + * failure/cancellation may leave C modified; direct-output execution is not + * transactional. Output padding is preserved. Reference executes original + * Matrix.multiplyChecked/scaleMatrix/addMatrixChecked at the selected precision; + * optimized providers may use different floating reduction/FMA order. Existing + * pure Matrix and tensor APIs are unchanged. Concurrent calls require independent + * C outputs and live execution/context references. Cancellation is checked before + * and after a kernel, not inside a BLAS call. Runtime initialization is required. */ +HMATH_API hmath_status hmath_execution_gemm_f32(hmath_execution *execution, hmath_context *context, + float alpha, const hmath_execution_view *a, + const hmath_execution_view *b, float beta, + const hmath_execution_output *c); +HMATH_API hmath_status hmath_execution_gemm_f64(hmath_execution *execution, hmath_context *context, + double alpha, const hmath_execution_view *a, + const hmath_execution_view *b, double beta, + const hmath_execution_output *c); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_expression.h b/include/hmath_expression.h new file mode 100644 index 0000000..5836074 --- /dev/null +++ b/include/hmath_expression.h @@ -0,0 +1,600 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_EXPRESSION_H +#define HMATH_EXPRESSION_H +#include "hmath_expression_error.h" +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original positioned ASTs/compiled DAGs/cache/registries/patterns/assumptions + * and symbolic matrices are immutable native Values (kind80..87). Records and + * sum payloads use lossless structural tuples; enums are Index values. Exact + * Rational and Double arithmetic remains selected explicitly by Precision. + * Every named wrapper has ctx first, original arguments in source order and + * owned Value** out last. Inputs borrowed; output untouched on failure. */ +HMATH_API hmath_status hmath_expression_node_fields(hmath_context *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_symbolic_pattern_fields(hmath_context *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_expression_compare(hmath_context *,const hmath_value *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_expression_node_compare(hmath_context *,const hmath_value *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_symbolic_pattern_equal(hmath_context *,const hmath_value *,const hmath_value *,hmath_value **); +/* BEGIN GENERATED */ +/* HMath.Expression.SourcePos -> SourcePos. */ +HMATH_API hmath_status hmath_expression_source_pos_create(hmath_context *context, const hmath_value *offset, const hmath_value *line, const hmath_value *column, hmath_value **out); + +/* HMath.Expression.unknownPosition -> SourcePos. */ +HMATH_API hmath_status hmath_expression_unknown_position(hmath_context *context, hmath_value **out); + +/* HMath.Expression.sourceOffset -> Int. */ +HMATH_API hmath_status hmath_expression_source_offset(hmath_context *context, const hmath_value *position, hmath_value **out); + +/* HMath.Expression.sourceLine -> Int. */ +HMATH_API hmath_status hmath_expression_source_line(hmath_context *context, const hmath_value *position, hmath_value **out); + +/* HMath.Expression.sourceColumn -> Int. */ +HMATH_API hmath_status hmath_expression_source_column(hmath_context *context, const hmath_value *position, hmath_value **out); + +/* HMath.Expression.Negate -> UnaryOp. */ +HMATH_API hmath_status hmath_expression_negate_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Add -> BinaryOp. */ +HMATH_API hmath_status hmath_expression_add_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Subtract -> BinaryOp. */ +HMATH_API hmath_status hmath_expression_subtract_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Multiply -> BinaryOp. */ +HMATH_API hmath_status hmath_expression_multiply_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Divide -> BinaryOp. */ +HMATH_API hmath_status hmath_expression_divide_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Power -> BinaryOp. */ +HMATH_API hmath_status hmath_expression_power_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Pi -> NamedConstant. */ +HMATH_API hmath_status hmath_expression_pi_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Euler -> NamedConstant. */ +HMATH_API hmath_status hmath_expression_euler_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Tau -> NamedConstant. */ +HMATH_API hmath_status hmath_expression_tau_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.ExactRational -> Precision. */ +HMATH_API hmath_status hmath_expression_exact_rational_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Float64 -> Precision. */ +HMATH_API hmath_status hmath_expression_float64_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.SyntaxError -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_syntax_error_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.UnknownName -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_unknown_name_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.TypeMismatch -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_type_mismatch_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.DomainFailure -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_domain_failure_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.NonFinite -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_non_finite_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.StepLimit -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_step_limit_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.DepthLimit -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_depth_limit_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.MemoryLimit -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_memory_limit_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.InvalidLimits -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_invalid_limits_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Unsupported -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_unsupported_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Sin -> Builtin. */ +HMATH_API hmath_status hmath_expression_sin_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Cos -> Builtin. */ +HMATH_API hmath_status hmath_expression_cos_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Tan -> Builtin. */ +HMATH_API hmath_status hmath_expression_tan_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Exp -> Builtin. */ +HMATH_API hmath_status hmath_expression_exp_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Log -> Builtin. */ +HMATH_API hmath_status hmath_expression_log_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Sqrt -> Builtin. */ +HMATH_API hmath_status hmath_expression_sqrt_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Abs -> Builtin. */ +HMATH_API hmath_status hmath_expression_abs_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Signum -> Builtin. */ +HMATH_API hmath_status hmath_expression_signum_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Floor -> Builtin. */ +HMATH_API hmath_status hmath_expression_floor_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Ceiling -> Builtin. */ +HMATH_API hmath_status hmath_expression_ceiling_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Min -> Builtin. */ +HMATH_API hmath_status hmath_expression_min_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Max -> Builtin. */ +HMATH_API hmath_status hmath_expression_max_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Asin -> Builtin. */ +HMATH_API hmath_status hmath_expression_asin_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Acos -> Builtin. */ +HMATH_API hmath_status hmath_expression_acos_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Atan -> Builtin. */ +HMATH_API hmath_status hmath_expression_atan_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Sinh -> Builtin. */ +HMATH_API hmath_status hmath_expression_sinh_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Cosh -> Builtin. */ +HMATH_API hmath_status hmath_expression_cosh_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Tanh -> Builtin. */ +HMATH_API hmath_status hmath_expression_tanh_create(hmath_context *context, hmath_value **out); + +/* HMath.Expression.Expr -> Expr. */ +HMATH_API hmath_status hmath_expression_expr_create(hmath_context *context, const hmath_value *position, const hmath_value *node, hmath_value **out); + +/* HMath.Expression.expressionPosition -> SourcePos. */ +HMATH_API hmath_status hmath_expression_expression_position(hmath_context *context, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.expressionNode -> ExprNode. */ +HMATH_API hmath_status hmath_expression_expression_node(hmath_context *context, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.Literal -> ExprNode. */ +HMATH_API hmath_status hmath_expression_literal_create(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.Variable -> ExprNode. */ +HMATH_API hmath_status hmath_expression_variable_create(hmath_context *context, const hmath_value *name, hmath_value **out); + +/* HMath.Expression.Constant -> ExprNode. */ +HMATH_API hmath_status hmath_expression_constant_create(hmath_context *context, const hmath_value *constant, hmath_value **out); + +/* HMath.Expression.Unary -> ExprNode. */ +HMATH_API hmath_status hmath_expression_unary_create(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out); + +/* HMath.Expression.Binary -> ExprNode. */ +HMATH_API hmath_status hmath_expression_binary_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Expression.Call -> ExprNode. */ +HMATH_API hmath_status hmath_expression_call_create(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out); + +/* HMath.Expression.Let -> ExprNode. */ +HMATH_API hmath_status hmath_expression_let_create(hmath_context *context, const hmath_value *name, const hmath_value *value, const hmath_value *body, hmath_value **out); + +/* HMath.Expression.literal -> Expr. */ +HMATH_API hmath_status hmath_expression_literal(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.variable -> Expr. */ +HMATH_API hmath_status hmath_expression_variable(hmath_context *context, const hmath_value *name, hmath_value **out); + +/* HMath.Expression.constant -> Expr. */ +HMATH_API hmath_status hmath_expression_constant(hmath_context *context, const hmath_value *constant, hmath_value **out); + +/* HMath.Expression.unary -> Expr. */ +HMATH_API hmath_status hmath_expression_unary(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out); + +/* HMath.Expression.binary -> Expr. */ +HMATH_API hmath_status hmath_expression_binary(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Expression.call -> Expr. */ +HMATH_API hmath_status hmath_expression_call(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out); + +/* HMath.Expression.letIn -> Expr. */ +HMATH_API hmath_status hmath_expression_let_in(hmath_context *context, const hmath_value *name, const hmath_value *value, const hmath_value *body, hmath_value **out); + +/* HMath.Expression.Limits -> Limits. */ +HMATH_API hmath_status hmath_expression_limits_create(hmath_context *context, const hmath_value *maximum_steps, const hmath_value *maximum_depth, const hmath_value *maximum_nodes, const hmath_value *maximum_input_chars, const hmath_value *maximum_integer_bits, const hmath_value *maximum_cache_entries, hmath_value **out); + +/* HMath.Expression.defaultLimits -> Limits. */ +HMATH_API hmath_status hmath_expression_default_limits(hmath_context *context, hmath_value **out); + +/* HMath.Expression.maximumSteps -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_steps(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.maximumDepth -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_depth(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.maximumNodes -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_nodes(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.maximumInputChars -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_input_chars(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.maximumIntegerBits -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_integer_bits(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.maximumCacheEntries -> Int. */ +HMATH_API hmath_status hmath_expression_maximum_cache_entries(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.ExprError -> ExprError. */ +HMATH_API hmath_status hmath_expression_expr_error_create(hmath_context *context, const hmath_value *kind, const hmath_value *position, const hmath_value *message, hmath_value **out); + +/* HMath.Expression.errorKind -> ErrorKind. */ +HMATH_API hmath_status hmath_expression_error_kind_get(hmath_context *context, const hmath_value *error, hmath_value **out); + +/* HMath.Expression.errorPosition -> SourcePos. */ +HMATH_API hmath_status hmath_expression_error_position(hmath_context *context, const hmath_value *error, hmath_value **out); + +/* HMath.Expression.errorMessage -> String. */ +HMATH_API hmath_status hmath_expression_error_message(hmath_context *context, const hmath_value *error, hmath_value **out); + +/* HMath.Expression.validateLimits -> Unit. */ +HMATH_API hmath_status hmath_expression_validate_limits(hmath_context *context, const hmath_value *limits, hmath_value **out); + +/* HMath.Expression.validateExpression -> Unit. */ +HMATH_API hmath_status hmath_expression_validate_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.parseExpression -> Expr. */ +HMATH_API hmath_status hmath_expression_parse_expression(hmath_context *context, const hmath_value *limits, const hmath_value *source, hmath_value **out); + +/* HMath.Expression.prettyExpression -> String. */ +HMATH_API hmath_status hmath_expression_pretty_expression(hmath_context *context, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.freeVariables -> [String]. */ +HMATH_API hmath_status hmath_expression_free_variables(hmath_context *context, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.ExactValue -> ExpressionValue. */ +HMATH_API hmath_status hmath_expression_exact_value_create(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.FloatValue -> ExpressionValue. */ +HMATH_API hmath_status hmath_expression_float_value_create(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.defaultRegistry -> Registry. */ +HMATH_API hmath_status hmath_expression_default_registry(hmath_context *context, hmath_value **out); + +/* HMath.Expression.emptyRegistry -> Registry. */ +HMATH_API hmath_status hmath_expression_empty_registry(hmath_context *context, hmath_value **out); + +/* HMath.Expression.registerFunction -> Registry. */ +HMATH_API hmath_status hmath_expression_register_function(hmath_context *context, const hmath_value *name, const hmath_value *builtin, const hmath_value *registry, hmath_value **out); + +/* HMath.Expression.allowedFunctions -> [String]. */ +HMATH_API hmath_status hmath_expression_allowed_functions(hmath_context *context, const hmath_value *registry, hmath_value **out); + +/* HMath.Expression.typeCheckExpression -> Precision. */ +HMATH_API hmath_status hmath_expression_type_check_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.evaluateExpression -> ExpressionValue. */ +HMATH_API hmath_status hmath_expression_evaluate_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.evaluateText -> ExpressionValue. */ +HMATH_API hmath_status hmath_expression_evaluate_text(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *source, hmath_value **out); + +/* HMath.Expression.evaluateCompiled -> ExpressionValue. */ +HMATH_API hmath_status hmath_expression_evaluate_compiled(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *registry, const hmath_value *bindings, const hmath_value *compiled, hmath_value **out); + +/* HMath.Expression.compileExpression -> Compiled. */ +HMATH_API hmath_status hmath_expression_compile_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.compiledNodeCount -> Int. */ +HMATH_API hmath_status hmath_expression_compiled_node_count(hmath_context *context, const hmath_value *compiled, hmath_value **out); + +/* HMath.Expression.optimizeExpression -> Expr. */ +HMATH_API hmath_status hmath_expression_optimize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *precision, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.emptyExpressionCache -> ExpressionCache. */ +HMATH_API hmath_status hmath_expression_empty_expression_cache(hmath_context *context, hmath_value **out); + +/* HMath.Expression.cacheSize -> Int. */ +HMATH_API hmath_status hmath_expression_cache_size(hmath_context *context, const hmath_value *cache, hmath_value **out); + +/* HMath.Expression.cachedExpression -> (Compiled,ExpressionCache). */ +HMATH_API hmath_status hmath_expression_cached_expression(hmath_context *context, const hmath_value *limits, const hmath_value *source, const hmath_value *cache, hmath_value **out); + +/* HMath.Expression.formatScientific -> String. */ +HMATH_API hmath_status hmath_expression_format_scientific(hmath_context *context, const hmath_value *digits, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.formatRadix -> String. */ +HMATH_API hmath_status hmath_expression_format_radix(hmath_context *context, const hmath_value *radix, const hmath_value *value, hmath_value **out); + +/* HMath.Expression.serializeExpression -> String. */ +HMATH_API hmath_status hmath_expression_serialize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); + +/* HMath.Expression.deserializeExpression -> Expr. */ +HMATH_API hmath_status hmath_expression_deserialize_expression(hmath_context *context, const hmath_value *limits, const hmath_value *serialized, hmath_value **out); + +/* HMath.Expression.expressionHash -> Word64. */ +HMATH_API hmath_status hmath_expression_expression_hash(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.Real -> Property. */ +HMATH_API hmath_status hmath_symbolic_real_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.NonZero -> Property. */ +HMATH_API hmath_status hmath_symbolic_non_zero_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Positive -> Property. */ +HMATH_API hmath_status hmath_symbolic_positive_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.NonNegative -> Property. */ +HMATH_API hmath_status hmath_symbolic_non_negative_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Integral -> Property. */ +HMATH_API hmath_status hmath_symbolic_integral_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Negative -> Property. */ +HMATH_API hmath_status hmath_symbolic_negative_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.NonPositive -> Property. */ +HMATH_API hmath_status hmath_symbolic_non_positive_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.FromLeft -> Direction. */ +HMATH_API hmath_status hmath_symbolic_from_left_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.FromRight -> Direction. */ +HMATH_API hmath_status hmath_symbolic_from_right_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.TwoSided -> Direction. */ +HMATH_API hmath_status hmath_symbolic_two_sided_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Equal -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_equal_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.NotEqual -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_not_equal_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Less -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_less_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.LessEqual -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_less_equal_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.Greater -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_greater_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.GreaterEqual -> RelationOp. */ +HMATH_API hmath_status hmath_symbolic_greater_equal_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.assumptions -> Assumptions. */ +HMATH_API hmath_status hmath_symbolic_assumptions(hmath_context *context, const hmath_value *entries, hmath_value **out); + +/* HMath.Symbolic.noAssumptions -> Assumptions. */ +HMATH_API hmath_status hmath_symbolic_no_assumptions(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.proves -> Bool. */ +HMATH_API hmath_status hmath_symbolic_proves(hmath_context *context, const hmath_value *assumptions, const hmath_value *property, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.SymbolicOptions -> SymbolicOptions. */ +HMATH_API hmath_status hmath_symbolic_symbolic_options_create(hmath_context *context, const hmath_value *limits, const hmath_value *assumptions, hmath_value **out); + +/* HMath.Symbolic.defaultSymbolicOptions -> SymbolicOptions. */ +HMATH_API hmath_status hmath_symbolic_default_symbolic_options(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.symbolicLimits -> Limits. */ +HMATH_API hmath_status hmath_symbolic_symbolic_limits(hmath_context *context, const hmath_value *options, hmath_value **out); + +/* HMath.Symbolic.symbolicAssumptions -> Assumptions. */ +HMATH_API hmath_status hmath_symbolic_symbolic_assumptions(hmath_context *context, const hmath_value *options, hmath_value **out); + +/* HMath.Symbolic.normalize -> Expr. */ +HMATH_API hmath_status hmath_symbolic_normalize(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.simplify -> Expr. */ +HMATH_API hmath_status hmath_symbolic_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.expand -> Expr. */ +HMATH_API hmath_status hmath_symbolic_expand(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.collectTerms -> Expr. */ +HMATH_API hmath_status hmath_symbolic_collect_terms(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.trigonometricSimplify -> Expr. */ +HMATH_API hmath_status hmath_symbolic_trigonometric_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.logarithmicSimplify -> Expr. */ +HMATH_API hmath_status hmath_symbolic_logarithmic_simplify(hmath_context *context, const hmath_value *options, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.factorPolynomial -> PolynomialFactorization. */ +HMATH_API hmath_status hmath_symbolic_factor_polynomial(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.rationalSimplify -> Expr. */ +HMATH_API hmath_status hmath_symbolic_rational_simplify(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.differentiate -> Expr. */ +HMATH_API hmath_status hmath_symbolic_differentiate(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.integrateBasic -> Expr. */ +HMATH_API hmath_status hmath_symbolic_integrate_basic(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.toPolynomial -> Polynomial. */ +HMATH_API hmath_status hmath_symbolic_to_polynomial(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.exactPolynomialRoots -> ([(Rational,Int)],Expr). */ +HMATH_API hmath_status hmath_symbolic_exact_polynomial_roots(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.numericalPolynomialRoots -> [Complex]. */ +HMATH_API hmath_status hmath_symbolic_numerical_polynomial_roots(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.PolynomialFactorization -> PolynomialFactorization. */ +HMATH_API hmath_status hmath_symbolic_polynomial_factorization_create(hmath_context *context, const hmath_value *leading, const hmath_value *terms, hmath_value **out); + +/* HMath.Symbolic.factorLeading -> Rational. */ +HMATH_API hmath_status hmath_symbolic_factor_leading(hmath_context *context, const hmath_value *factorization, hmath_value **out); + +/* HMath.Symbolic.factorTerms -> [(Expr,Int)]. */ +HMATH_API hmath_status hmath_symbolic_factor_terms(hmath_context *context, const hmath_value *factorization, hmath_value **out); + +/* HMath.Symbolic.substitute -> Expr. */ +HMATH_API hmath_status hmath_symbolic_substitute(hmath_context *context, const hmath_value *limits, const hmath_value *bindings, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.Any -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_any_create(hmath_context *context, const hmath_value *name, hmath_value **out); + +/* HMath.Symbolic.Exactly -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_exactly_create(hmath_context *context, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.UnaryPattern -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_unary_pattern_create(hmath_context *context, const hmath_value *operator_, const hmath_value *child, hmath_value **out); + +/* HMath.Symbolic.BinaryPattern -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_binary_pattern_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Symbolic.CallPattern -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_call_pattern_create(hmath_context *context, const hmath_value *name, const hmath_value *arguments, hmath_value **out); + +/* HMath.Symbolic.matchPattern -> Maybe[(String,Expr)]. */ +HMATH_API hmath_status hmath_symbolic_match_pattern(hmath_context *context, const hmath_value *limits, const hmath_value *pattern, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.RewriteRule -> RewriteRule. */ +HMATH_API hmath_status hmath_symbolic_rewrite_rule_create(hmath_context *context, const hmath_value *pattern, const hmath_value *replacement, const hmath_value *requirements, hmath_value **out); + +/* HMath.Symbolic.rewritePattern -> Pattern. */ +HMATH_API hmath_status hmath_symbolic_rewrite_pattern(hmath_context *context, const hmath_value *rule, hmath_value **out); + +/* HMath.Symbolic.rewriteReplacement -> Expr. */ +HMATH_API hmath_status hmath_symbolic_rewrite_replacement(hmath_context *context, const hmath_value *rule, hmath_value **out); + +/* HMath.Symbolic.rewriteRequirements -> [(String,Property)]. */ +HMATH_API hmath_status hmath_symbolic_rewrite_requirements(hmath_context *context, const hmath_value *rule, hmath_value **out); + +/* HMath.Symbolic.applyRewrite -> Expr. */ +HMATH_API hmath_status hmath_symbolic_apply_rewrite(hmath_context *context, const hmath_value *options, const hmath_value *rule, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.gradient -> [Expr]. */ +HMATH_API hmath_status hmath_symbolic_gradient(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.hessian -> [[Expr]]. */ +HMATH_API hmath_status hmath_symbolic_hessian(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.jacobian -> [[Expr]]. */ +HMATH_API hmath_status hmath_symbolic_jacobian(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *expressions, hmath_value **out); + +/* HMath.Symbolic.integrateByParts -> Expr. */ +HMATH_API hmath_status hmath_symbolic_integrate_by_parts(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *u, const hmath_value *dv, hmath_value **out); + +/* HMath.Symbolic.integrateSubstitution -> Expr. */ +HMATH_API hmath_status hmath_symbolic_integrate_substitution(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *temporary, const hmath_value *inner, const hmath_value *outer, const hmath_value *integrand, hmath_value **out); + +/* HMath.Symbolic.integrateRational -> Expr. */ +HMATH_API hmath_status hmath_symbolic_integrate_rational(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); + +/* HMath.Symbolic.FiniteLimit -> LimitResult. */ +HMATH_API hmath_status hmath_symbolic_finite_limit_create(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Symbolic.PositiveInfinity -> LimitResult. */ +HMATH_API hmath_status hmath_symbolic_positive_infinity_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.NegativeInfinity -> LimitResult. */ +HMATH_API hmath_status hmath_symbolic_negative_infinity_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.DoesNotExist -> LimitResult. */ +HMATH_API hmath_status hmath_symbolic_does_not_exist_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.symbolicLimit -> LimitResult. */ +HMATH_API hmath_status hmath_symbolic_symbolic_limit(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *direction, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.Series -> Series. */ +HMATH_API hmath_status hmath_symbolic_series_create(hmath_context *context, const hmath_value *center, const hmath_value *minimum_power, const hmath_value *terms, hmath_value **out); + +/* HMath.Symbolic.seriesCenter -> Rational. */ +HMATH_API hmath_status hmath_symbolic_series_center(hmath_context *context, const hmath_value *series, hmath_value **out); + +/* HMath.Symbolic.seriesMinimumPower -> Int. */ +HMATH_API hmath_status hmath_symbolic_series_minimum_power(hmath_context *context, const hmath_value *series, hmath_value **out); + +/* HMath.Symbolic.seriesTerms -> [Expr]. */ +HMATH_API hmath_status hmath_symbolic_series_terms(hmath_context *context, const hmath_value *series, hmath_value **out); + +/* HMath.Symbolic.taylorSeries -> Series. */ +HMATH_API hmath_status hmath_symbolic_taylor_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *order, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.laurentSeries -> Series. */ +HMATH_API hmath_status hmath_symbolic_laurent_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *center, const hmath_value *order, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.maclaurinSeries -> Series. */ +HMATH_API hmath_status hmath_symbolic_maclaurin_series(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *order, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.formalPowerSeries -> PowerSeries. */ +HMATH_API hmath_status hmath_symbolic_formal_power_series(hmath_context *context, const hmath_value *options, const hmath_value *coefficients, hmath_value **out); + +/* HMath.Symbolic.multiplyFormalSeries -> PowerSeries. */ +HMATH_API hmath_status hmath_symbolic_multiply_formal_series(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Symbolic.reciprocalFormalSeries -> PowerSeries. */ +HMATH_API hmath_status hmath_symbolic_reciprocal_formal_series(hmath_context *context, const hmath_value *options, const hmath_value *series, hmath_value **out); + +/* HMath.Symbolic.fromPolynomial -> Expr. */ +HMATH_API hmath_status hmath_symbolic_from_polynomial(hmath_context *context, const hmath_value *variable, const hmath_value *polynomial, hmath_value **out); + +/* HMath.Symbolic.Relation -> Relation. */ +HMATH_API hmath_status hmath_symbolic_relation_create(hmath_context *context, const hmath_value *operator_, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Symbolic.Truth -> RelationResult. */ +HMATH_API hmath_status hmath_symbolic_truth_create(hmath_context *context, const hmath_value *value, hmath_value **out); + +/* HMath.Symbolic.Unresolved -> RelationResult. */ +HMATH_API hmath_status hmath_symbolic_unresolved_create(hmath_context *context, const hmath_value *relation, hmath_value **out); + +/* HMath.Symbolic.simplifyRelation -> RelationResult. */ +HMATH_API hmath_status hmath_symbolic_simplify_relation(hmath_context *context, const hmath_value *options, const hmath_value *relation, hmath_value **out); + +/* HMath.Symbolic.solveLinearInequality -> RelationResult. */ +HMATH_API hmath_status hmath_symbolic_solve_linear_inequality(hmath_context *context, const hmath_value *options, const hmath_value *variable, const hmath_value *relation, hmath_value **out); + +/* HMath.Symbolic.Inconsistent -> LinearSolution. */ +HMATH_API hmath_status hmath_symbolic_inconsistent_create(hmath_context *context, hmath_value **out); + +/* HMath.Symbolic.ParametricSolution -> LinearSolution. */ +HMATH_API hmath_status hmath_symbolic_parametric_solution_create(hmath_context *context, const hmath_value *bindings, const hmath_value *free_variables, hmath_value **out); + +/* HMath.Symbolic.solveLinearEquations -> LinearSolution. */ +HMATH_API hmath_status hmath_symbolic_solve_linear_equations(hmath_context *context, const hmath_value *options, const hmath_value *variables, const hmath_value *equations, hmath_value **out); + +/* HMath.Symbolic.symbolicMatrix -> SymbolicMatrix. */ +HMATH_API hmath_status hmath_symbolic_symbolic_matrix(hmath_context *context, const hmath_value *options, const hmath_value *rows, hmath_value **out); + +/* HMath.Symbolic.matrixExpressions -> [[Expr]]. */ +HMATH_API hmath_status hmath_symbolic_matrix_expressions(hmath_context *context, const hmath_value *matrix, hmath_value **out); + +/* HMath.Symbolic.matrixAdd -> SymbolicMatrix. */ +HMATH_API hmath_status hmath_symbolic_matrix_add(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Symbolic.matrixMultiply -> SymbolicMatrix. */ +HMATH_API hmath_status hmath_symbolic_matrix_multiply(hmath_context *context, const hmath_value *options, const hmath_value *left, const hmath_value *right, hmath_value **out); + +/* HMath.Symbolic.symbolicDeterminant -> Expr. */ +HMATH_API hmath_status hmath_symbolic_symbolic_determinant(hmath_context *context, const hmath_value *options, const hmath_value *matrix, hmath_value **out); + +/* HMath.Symbolic.Guarded -> Guarded. */ +HMATH_API hmath_status hmath_symbolic_guarded_create(hmath_context *context, const hmath_value *value, const hmath_value *conditions, hmath_value **out); + +/* HMath.Symbolic.guardedValue -> Generic. */ +HMATH_API hmath_status hmath_symbolic_guarded_value(hmath_context *context, const hmath_value *guarded, hmath_value **out); + +/* HMath.Symbolic.requiredConditions -> [(Expr,Property)]. */ +HMATH_API hmath_status hmath_symbolic_required_conditions(hmath_context *context, const hmath_value *guarded, hmath_value **out); + +/* HMath.Symbolic.symbolicEigenvalues -> Guarded[Expr]. */ +HMATH_API hmath_status hmath_symbolic_symbolic_eigenvalues(hmath_context *context, const hmath_value *options, const hmath_value *matrix, hmath_value **out); + +/* HMath.Symbolic.numericalSubstitution -> ExpressionValue. */ +HMATH_API hmath_status hmath_symbolic_numerical_substitution(hmath_context *context, const hmath_value *options, const hmath_value *precision, const hmath_value *bindings, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.toLaTeX -> String. */ +HMATH_API hmath_status hmath_symbolic_to_la_te_x(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); + +/* HMath.Symbolic.toMathML -> String. */ +HMATH_API hmath_status hmath_symbolic_to_math_ml(hmath_context *context, const hmath_value *limits, const hmath_value *expression, hmath_value **out); +/* END GENERATED */ +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_expression_error.h b/include/hmath_expression_error.h new file mode 100644 index 0000000..bbf844c --- /dev/null +++ b/include/hmath_expression_error.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_EXPRESSION_ERROR_H +#define HMATH_EXPRESSION_ERROR_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original HMath.Expression.ExprError, independent of MathError. */ +typedef enum hmath_expression_error_kind { + HMATH_EXPRESSION_SYNTAX_ERROR = 0, + HMATH_EXPRESSION_UNKNOWN_NAME = 1, + HMATH_EXPRESSION_TYPE_MISMATCH = 2, + HMATH_EXPRESSION_DOMAIN_FAILURE = 3, + HMATH_EXPRESSION_NON_FINITE = 4, + HMATH_EXPRESSION_STEP_LIMIT = 5, + HMATH_EXPRESSION_DEPTH_LIMIT = 6, + HMATH_EXPRESSION_MEMORY_LIMIT = 7, + HMATH_EXPRESSION_INVALID_LIMITS = 8, + HMATH_EXPRESSION_UNSUPPORTED = 9 +} hmath_expression_error_kind; +typedef struct hmath_expression_error { + uint32_t kind; + ptrdiff_t source_offset; + ptrdiff_t source_line; + ptrdiff_t source_column; + const char *message; + size_t message_length; +} hmath_expression_error; +/* Query only. Message is library-owned UTF8 (surrogatepass/WTF8 for isolated + * Haskell Char surrogates), with embedded NUL and full explicit length. Copy + * before the next checked operation on this thread. Returns 1 iff present. */ +HMATH_API int hmath_last_expression_error(hmath_expression_error *out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_foundation.h b/include/hmath_foundation.h new file mode 100644 index 0000000..1f480a1 --- /dev/null +++ b/include/hmath_foundation.h @@ -0,0 +1,656 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_foundation_bindings.py. */ +#ifndef HMATH_FOUNDATION_H +#define HMATH_FOUNDATION_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original persistent data/discrete/combinatorial/convergence operations. + * Opaque kind400 records own independent references; inputs borrow for the call. + * Value callback101 transports original argument tuples; checked status11 + * becomes genuine Left, pure callback failures abort. Generic Either results + * retain explicit Left/Right; optional Just(None) retains its distinction. + * No arbitrary precision integer, original budget, order, callback or error + * contract is replaced. Release each owned output with hmath_value_release. */ +HMATH_API hmath_status hmath_foundation_object_type(hmath_context *context, + const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_foundation_object_parts(hmath_context *context, + const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_foundation_left(hmath_context *context, const hmath_value *value, + hmath_value **out); +HMATH_API hmath_status hmath_foundation_right(hmath_context *context, const hmath_value *value, + hmath_value **out); +HMATH_API hmath_status hmath_foundation_just(hmath_context *context, const hmath_value *value, + hmath_value **out); +/* HMath.DataStructure.fenwick */ +HMATH_API hmath_status hmath_foundation_datastructure_fenwick(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.fenwickAdd */ +HMATH_API hmath_status hmath_foundation_datastructure_fenwick_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.fenwickPrefix */ +HMATH_API hmath_status hmath_foundation_datastructure_fenwick_prefix(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.fenwickRange */ +HMATH_API hmath_status hmath_foundation_datastructure_fenwick_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.segmentTree */ +HMATH_API hmath_status hmath_foundation_datastructure_segment_tree(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.segmentSet */ +HMATH_API hmath_status hmath_foundation_datastructure_segment_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.segmentRange */ +HMATH_API hmath_status hmath_foundation_datastructure_segment_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.sparseTable */ +HMATH_API hmath_status hmath_foundation_datastructure_sparse_table(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.sparseMinimum */ +HMATH_API hmath_status hmath_foundation_datastructure_sparse_minimum(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.disjointSparseTable */ +HMATH_API hmath_status hmath_foundation_datastructure_disjoint_sparse_table(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.disjointRange */ +HMATH_API hmath_status hmath_foundation_datastructure_disjoint_range(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.nextGreater */ +HMATH_API hmath_status hmath_foundation_datastructure_next_greater(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.emptyHeap */ +HMATH_API hmath_status hmath_foundation_datastructure_empty_heap(hmath_context *context, + hmath_value **out); +/* HMath.DataStructure.heapInsert */ +HMATH_API hmath_status hmath_foundation_datastructure_heap_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.heapPop */ +HMATH_API hmath_status hmath_foundation_datastructure_heap_pop(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.heapFromList */ +HMATH_API hmath_status hmath_foundation_datastructure_heap_from_list(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.binaryHeap */ +HMATH_API hmath_status hmath_foundation_datastructure_binary_heap(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.binaryInsert */ +HMATH_API hmath_status hmath_foundation_datastructure_binary_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.binaryPop */ +HMATH_API hmath_status hmath_foundation_datastructure_binary_pop(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.indexedHeap */ +HMATH_API hmath_status hmath_foundation_datastructure_indexed_heap(hmath_context *context, + hmath_value **out); +/* HMath.DataStructure.indexedSet */ +HMATH_API hmath_status hmath_foundation_datastructure_indexed_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.indexedPop */ +HMATH_API hmath_status hmath_foundation_datastructure_indexed_pop(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.unionFind */ +HMATH_API hmath_status hmath_foundation_datastructure_union_find(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.findRoot */ +HMATH_API hmath_status hmath_foundation_datastructure_find_root(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.union */ +HMATH_API hmath_status hmath_foundation_datastructure_union(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.connected */ +HMATH_API hmath_status hmath_foundation_datastructure_connected(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.components */ +HMATH_API hmath_status hmath_foundation_datastructure_components(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.bloom */ +HMATH_API hmath_status hmath_foundation_datastructure_bloom(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.bloomInsert */ +HMATH_API hmath_status hmath_foundation_datastructure_bloom_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.bloomMember */ +HMATH_API hmath_status hmath_foundation_datastructure_bloom_member(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.bloomFalsePositiveBound */ +HMATH_API hmath_status hmath_foundation_datastructure_bloom_false_positive_bound( + hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.DataStructure.countMin */ +HMATH_API hmath_status hmath_foundation_datastructure_count_min(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.countMinAdd */ +HMATH_API hmath_status hmath_foundation_datastructure_count_min_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.DataStructure.countMinEstimate */ +HMATH_API hmath_status hmath_foundation_datastructure_count_min_estimate(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.countMinErrorBound */ +HMATH_API hmath_status hmath_foundation_datastructure_count_min_error_bound(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.hyperLogLog */ +HMATH_API hmath_status hmath_foundation_datastructure_hyper_log_log(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.hllAdd */ +HMATH_API hmath_status hmath_foundation_datastructure_hll_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.hllEstimate */ +HMATH_API hmath_status hmath_foundation_datastructure_hll_estimate(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.reservoir */ +HMATH_API hmath_status hmath_foundation_datastructure_reservoir(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.reservoirAdd */ +HMATH_API hmath_status hmath_foundation_datastructure_reservoir_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.reservoirValues */ +HMATH_API hmath_status hmath_foundation_datastructure_reservoir_values(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.onlineQuantiles */ +HMATH_API hmath_status hmath_foundation_datastructure_online_quantiles(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.quantileAdd */ +HMATH_API hmath_status hmath_foundation_datastructure_quantile_add(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.DataStructure.onlineQuantile */ +HMATH_API hmath_status hmath_foundation_datastructure_online_quantile(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multiset */ +HMATH_API hmath_status hmath_foundation_discrete_multiset(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Discrete.multiplicity */ +HMATH_API hmath_status hmath_foundation_discrete_multiplicity(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multisetEntries */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_entries(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.multisetInsert */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multisetDelete */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_delete(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multisetUnion */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_union(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multisetIntersection */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_intersection(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.multisetDifference */ +HMATH_API hmath_status hmath_foundation_discrete_multiset_difference(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitSet */ +HMATH_API hmath_status hmath_foundation_discrete_bit_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Discrete.bitWidth */ +HMATH_API hmath_status hmath_foundation_discrete_bit_width(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.bitValue */ +HMATH_API hmath_status hmath_foundation_discrete_bit_value(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.bitMember */ +HMATH_API hmath_status hmath_foundation_discrete_bit_member(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitInsert */ +HMATH_API hmath_status hmath_foundation_discrete_bit_insert(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitDelete */ +HMATH_API hmath_status hmath_foundation_discrete_bit_delete(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitUnion */ +HMATH_API hmath_status hmath_foundation_discrete_bit_union(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitIntersection */ +HMATH_API hmath_status hmath_foundation_discrete_bit_intersection(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.bitDifference */ +HMATH_API hmath_status hmath_foundation_discrete_bit_difference(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.resizeBitSet */ +HMATH_API hmath_status hmath_foundation_discrete_resize_bit_set(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.populationCount */ +HMATH_API hmath_status hmath_foundation_discrete_population_count(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.leadingZeros */ +HMATH_API hmath_status hmath_foundation_discrete_leading_zeros(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.trailingZeros */ +HMATH_API hmath_status hmath_foundation_discrete_trailing_zeros(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.rotateBits */ +HMATH_API hmath_status hmath_foundation_discrete_rotate_bits(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.reverseBits */ +HMATH_API hmath_status hmath_foundation_discrete_reverse_bits(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.grayEncode */ +HMATH_API hmath_status hmath_foundation_discrete_gray_encode(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.grayDecode */ +HMATH_API hmath_status hmath_foundation_discrete_gray_decode(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.hammingDistance */ +HMATH_API hmath_status hmath_foundation_discrete_hamming_distance(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.transitiveClosure */ +HMATH_API hmath_status hmath_foundation_discrete_transitive_closure(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.equivalenceClosure */ +HMATH_API hmath_status hmath_foundation_discrete_equivalence_closure(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.isEquivalence */ +HMATH_API hmath_status hmath_foundation_discrete_is_equivalence(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.booleanMultiply */ +HMATH_API hmath_status hmath_foundation_discrete_boolean_multiply(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.evaluateProp */ +HMATH_API hmath_status hmath_foundation_discrete_evaluate_prop(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.truthTable */ +HMATH_API hmath_status hmath_foundation_discrete_truth_table(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.implicantCovers */ +HMATH_API hmath_status hmath_foundation_discrete_implicant_covers(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.quineMcCluskey */ +HMATH_API hmath_status hmath_foundation_discrete_quine_mc_cluskey( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Discrete.Literal */ +HMATH_API hmath_status hmath_foundation_discrete_new_literal(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.Variable */ +HMATH_API hmath_status hmath_foundation_discrete_new_variable(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.Not */ +HMATH_API hmath_status hmath_foundation_discrete_new_not(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Discrete.And */ +HMATH_API hmath_status hmath_foundation_discrete_new_and(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Discrete.Or */ +HMATH_API hmath_status hmath_foundation_discrete_new_or(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Discrete.Xor */ +HMATH_API hmath_status hmath_foundation_discrete_new_xor(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Discrete.Implies */ +HMATH_API hmath_status hmath_foundation_discrete_new_implies(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Discrete.Iff */ +HMATH_API hmath_status hmath_foundation_discrete_new_iff(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Discrete.implicantValue */ +HMATH_API hmath_status hmath_foundation_discrete_implicant_value(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.implicantMask */ +HMATH_API hmath_status hmath_foundation_discrete_implicant_mask(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Discrete.Implicant */ +HMATH_API hmath_status hmath_foundation_discrete_new_implicant(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.binarySearch */ +HMATH_API hmath_status hmath_foundation_algorithms_binary_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.interpolationSearch */ +HMATH_API hmath_status hmath_foundation_algorithms_interpolation_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.exponentialSearch */ +HMATH_API hmath_status hmath_foundation_algorithms_exponential_search(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.ternarySearch */ +HMATH_API hmath_status hmath_foundation_algorithms_ternary_search( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Algorithms.numericGroups */ +HMATH_API hmath_status hmath_foundation_algorithms_numeric_groups(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algorithms.runLengthEncode */ +HMATH_API hmath_status hmath_foundation_algorithms_run_length_encode(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algorithms.runLengthDecode */ +HMATH_API hmath_status hmath_foundation_algorithms_run_length_decode(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.coordinateCompression */ +HMATH_API hmath_status hmath_foundation_algorithms_coordinate_compression(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algorithms.intervalSweep */ +HMATH_API hmath_status hmath_foundation_algorithms_interval_sweep(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Algorithms.divideConquerDP */ +HMATH_API hmath_status hmath_foundation_algorithms_divide_conquer_dp(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.tabulateDP */ +HMATH_API hmath_status hmath_foundation_algorithms_tabulate_dp(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.memoizedDP */ +HMATH_API hmath_status hmath_foundation_algorithms_memoized_dp(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Algorithms.integerMatrixPower */ +HMATH_API hmath_status hmath_foundation_algorithms_integer_matrix_power(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.permutationsOf */ +HMATH_API hmath_status hmath_foundation_combinatorics_permutations_of(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Combinatorics.combinationsOf */ +HMATH_API hmath_status hmath_foundation_combinatorics_combinations_of(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Combinatorics.derangements */ +HMATH_API hmath_status hmath_foundation_combinatorics_derangements(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.integerPartitions */ +HMATH_API hmath_status hmath_foundation_combinatorics_integer_partitions(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.setPartitions */ +HMATH_API hmath_status hmath_foundation_combinatorics_set_partitions(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.pascalTriangle */ +HMATH_API hmath_status hmath_foundation_combinatorics_pascal_triangle(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Combinatorics.subsets */ +HMATH_API hmath_status hmath_foundation_combinatorics_subsets(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.cartesianProduct */ +HMATH_API hmath_status hmath_foundation_combinatorics_cartesian_product(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.multisetPermutations */ +HMATH_API hmath_status hmath_foundation_combinatorics_multiset_permutations(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Combinatorics.generatingCoefficients */ +HMATH_API hmath_status hmath_foundation_combinatorics_generating_coefficients( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + hmath_value **out); +/* HMath.Combinatorics.finiteDifferences */ +HMATH_API hmath_status hmath_foundation_combinatorics_finite_differences( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, hmath_value **out); +/* HMath.API.Convergence.defaultIterationOptions */ +HMATH_API hmath_status +hmath_foundation_convergence_default_iteration_options(hmath_context *context, hmath_value **out); +/* HMath.API.Convergence.iterateUntil */ +HMATH_API hmath_status hmath_foundation_convergence_iterate_until( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.API.Convergence.requireConvergence */ +HMATH_API hmath_status hmath_foundation_convergence_require_convergence(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.API.Convergence.resultMaybe */ +HMATH_API hmath_status hmath_foundation_convergence_result_maybe(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.fromMaybeError */ +HMATH_API hmath_status hmath_foundation_convergence_from_maybe_error(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.API.Convergence.ResidualSatisfied */ +HMATH_API hmath_status hmath_foundation_convergence_new_residual_satisfied(hmath_context *context, + hmath_value **out); +/* HMath.API.Convergence.IterationLimit */ +HMATH_API hmath_status hmath_foundation_convergence_new_iteration_limit(hmath_context *context, + hmath_value **out); +/* HMath.API.Convergence.Stagnation */ +HMATH_API hmath_status hmath_foundation_convergence_new_stagnation(hmath_context *context, + hmath_value **out); +/* HMath.API.Convergence.estimate */ +HMATH_API hmath_status hmath_foundation_convergence_estimate(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.iterationCount */ +HMATH_API hmath_status hmath_foundation_convergence_iteration_count(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.finalResidual */ +HMATH_API hmath_status hmath_foundation_convergence_final_residual(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.stopReason */ +HMATH_API hmath_status hmath_foundation_convergence_stop_reason(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.Convergence */ +HMATH_API hmath_status hmath_foundation_convergence_new_convergence( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.API.Convergence.maximumIterations */ +HMATH_API hmath_status hmath_foundation_convergence_maximum_iterations(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.absoluteTolerance */ +HMATH_API hmath_status hmath_foundation_convergence_absolute_tolerance(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.relativeTolerance */ +HMATH_API hmath_status hmath_foundation_convergence_relative_tolerance(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.API.Convergence.IterationOptions */ +HMATH_API hmath_status hmath_foundation_convergence_new_iteration_options(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.API.Convergence.Converged */ +HMATH_API hmath_status hmath_foundation_convergence_converged(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.DataStructure.nextGreater */ +HMATH_API hmath_status hmath_foundation_datastructure_next_greater_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, hmath_value **out); +/* HMath.Algorithms.binarySearch */ +HMATH_API hmath_status hmath_foundation_algorithms_binary_search_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Algorithms.exponentialSearch */ +HMATH_API hmath_status hmath_foundation_algorithms_exponential_search_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Algorithms.numericGroups */ +HMATH_API hmath_status hmath_foundation_algorithms_numeric_groups_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, hmath_value **out); +/* HMath.Algorithms.coordinateCompression */ +HMATH_API hmath_status hmath_foundation_algorithms_coordinate_compression_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, hmath_value **out); +/* HMath.Combinatorics.multisetPermutations */ +HMATH_API hmath_status hmath_foundation_combinatorics_multiset_permutations_typed( + hmath_context *context, const hmath_value *prototype, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +HMATH_API hmath_status hmath_foundation_ordered_type(hmath_context *context, + const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_foundation_optional_type(hmath_context *context, + const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_foundation_heap_from_list_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *values, + hmath_value **out); +HMATH_API hmath_status hmath_foundation_multiset_typed(hmath_context *context, + const hmath_value *prototype, + const hmath_value *values, + hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_geometry.h b/include/hmath_geometry.h new file mode 100644 index 0000000..ac1a62e --- /dev/null +++ b/include/hmath_geometry.h @@ -0,0 +1,310 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_geometry_bindings.py. */ +#ifndef HMATH_GEOMETRY_H +#define HMATH_GEOMETRY_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Actual immutable Geometry objects use kinds169..199. Inputs are borrowed; + * successful outputs transfer one owned Value, unchanged on failure. Release + * with hmath_value_release; each live owner pins the runtime. Source shape, + * coordinate1e50, work/iteration budgets, exact Rational predicates and original + * Double results are preserved. Raw public constructors remain unchecked; + * checked operations retain their original validation and MathError/status11. + * Matrices are shared Dense Matrix Double values. IndexedTriangle is an Int + * triple. Ordering is a Haskell Int value -1(LT),0(EQ),1(GT). Other lists, tuples + * and optional values retain source structure; nested Maybe results explicitly + * return Tuple(Bool outer_present, inner_optional), distinguishing coincidence + * from no intersection. Readers retain independent references per thread. */ +typedef hmath_value hmath_geometry_point2_object; /* kind169 */ +typedef hmath_value hmath_geometry_point3_object; /* kind170 */ +typedef hmath_value hmath_geometry_point_nd_object; /* kind171 */ +typedef hmath_value hmath_geometry_line_object; /* kind172 */ +typedef hmath_value hmath_geometry_ray_object; /* kind173 */ +typedef hmath_value hmath_geometry_segment_object; /* kind174 */ +typedef hmath_value hmath_geometry_plane_object; /* kind175 */ +typedef hmath_value hmath_geometry_triangle_object; /* kind176 */ +typedef hmath_value hmath_geometry_rectangle_object; /* kind177 */ +typedef hmath_value hmath_geometry_circle_object; /* kind178 */ +typedef hmath_value hmath_geometry_ellipse_object; /* kind179 */ +typedef hmath_value hmath_geometry_polygon_object; /* kind180 */ +typedef hmath_value hmath_geometry_sphere_object; /* kind181 */ +typedef hmath_value hmath_geometry_aabb_object; /* kind182 */ +typedef hmath_value hmath_geometry_obb_object; /* kind183 */ +typedef hmath_value hmath_geometry_capsule_object; /* kind184 */ +typedef hmath_value hmath_geometry_cylinder_object; /* kind185 */ +typedef hmath_value hmath_geometry_cone_object; /* kind186 */ +typedef hmath_value hmath_geometry_frustum_object; /* kind187 */ +typedef hmath_value hmath_geometry_orientation_object; /* kind188 */ +typedef hmath_value hmath_geometry_location_object; /* kind189 */ +typedef hmath_value hmath_geometry_penetration_object; /* kind190 */ +typedef hmath_value hmath_geometry_hull_algorithm_object; /* kind191 */ +typedef hmath_value hmath_geometry_boolean_operation_object; /* kind192 */ +typedef hmath_value hmath_geometry_metric_object; /* kind193 */ +typedef hmath_value hmath_geometry_intersection2_object; /* kind194 */ +typedef hmath_value hmath_geometry_circle_intersection_object; /* kind195 */ +typedef hmath_value hmath_geometry_spatial_kind_object; /* kind196 */ +typedef hmath_value hmath_geometry_point_cloud_object; /* kind197 */ +typedef hmath_value hmath_geometry_spatial_index_object; /* kind198 */ +typedef hmath_value hmath_geometry_neighbor_query_object; /* kind199 */ +typedef hmath_value hmath_geometry_indexed_triangle_object; /* tuple(Int,Int,Int) */ +HMATH_API hmath_status hmath_geometry_parts(hmath_context *context,const hmath_value *value0,hmath_value **out); +HMATH_API hmath_status hmath_geometry_describe(hmath_context *context,const hmath_value *value0,hmath_value **out); +HMATH_API hmath_status hmath_geometry_equal(hmath_context *context,const hmath_value *value0,const hmath_value *value1,hmath_value **out); +/* HMath.Geometry.Collision.Penetration :: Double -> Point2 -> Double -> Int -> Penetration */ +HMATH_API hmath_status hmath_geometry_penetration(hmath_context *context, const hmath_value *number, const hmath_value *point2, const hmath_value *number2, const hmath_value *count, hmath_value **out); +/* HMath.Geometry.Collision.epa :: Int -> Double -> [Point2] -> [Point2] -> Either MathError (Maybe Penetration) */ +HMATH_API hmath_status hmath_geometry_epa(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Collision.gjk :: Int -> [Point2] -> [Point2] -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_gjk(hmath_context *context, const hmath_value *count, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Collision.penetrationDepth :: Penetration -> Double */ +HMATH_API hmath_status hmath_geometry_penetration_depth(hmath_context *context, const hmath_value *penetration, hmath_value **out); +/* HMath.Geometry.Collision.penetrationError :: Penetration -> Double */ +HMATH_API hmath_status hmath_geometry_penetration_error(hmath_context *context, const hmath_value *penetration, hmath_value **out); +/* HMath.Geometry.Collision.penetrationIterations :: Penetration -> Int */ +HMATH_API hmath_status hmath_geometry_penetration_iterations(hmath_context *context, const hmath_value *penetration, hmath_value **out); +/* HMath.Geometry.Collision.penetrationNormal :: Penetration -> Point2 */ +HMATH_API hmath_status hmath_geometry_penetration_normal(hmath_context *context, const hmath_value *penetration, hmath_value **out); +/* HMath.Geometry.Collision.separatingAxis :: [Point2] -> [Point2] -> Either MathError (Maybe Penetration) */ +HMATH_API hmath_status hmath_geometry_separating_axis(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Internal.AABB :: PointND -> PointND -> AABB */ +HMATH_API hmath_status hmath_geometry_aabb(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Internal.Boundary :: Location */ +HMATH_API hmath_status hmath_geometry_boundary(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.Capsule :: Point3 -> Point3 -> Double -> Capsule */ +HMATH_API hmath_status hmath_geometry_capsule(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.Circle :: Point2 -> Double -> Circle */ +HMATH_API hmath_status hmath_geometry_circle(hmath_context *context, const hmath_value *point2, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.Clockwise :: Orientation */ +HMATH_API hmath_status hmath_geometry_clockwise(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.Collinear :: Orientation */ +HMATH_API hmath_status hmath_geometry_collinear(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.Cone :: Point3 -> Point3 -> Double -> Cone */ +HMATH_API hmath_status hmath_geometry_cone(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.Counterclockwise :: Orientation */ +HMATH_API hmath_status hmath_geometry_counterclockwise(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.Cylinder :: Point3 -> Point3 -> Double -> Cylinder */ +HMATH_API hmath_status hmath_geometry_cylinder(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.Ellipse :: Point2 -> Double -> Double -> Double -> Ellipse */ +HMATH_API hmath_status hmath_geometry_ellipse(hmath_context *context, const hmath_value *point2, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +/* HMath.Geometry.Internal.Frustum :: [Plane] -> Frustum */ +HMATH_API hmath_status hmath_geometry_frustum(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Internal.Inside :: Location */ +HMATH_API hmath_status hmath_geometry_inside(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.Line :: PointND -> PointND -> Line */ +HMATH_API hmath_status hmath_geometry_line(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Internal.OBB :: Point3 -> [Point3] -> Point3 -> OBB */ +HMATH_API hmath_status hmath_geometry_obb(hmath_context *context, const hmath_value *point3, const hmath_value *values, const hmath_value *point32, hmath_value **out); +/* HMath.Geometry.Internal.Outside :: Location */ +HMATH_API hmath_status hmath_geometry_outside(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Internal.P2 :: Double -> Double -> Point2 */ +HMATH_API hmath_status hmath_geometry_p2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +/* HMath.Geometry.Internal.P3 :: Double -> Double -> Double -> Point3 */ +HMATH_API hmath_status hmath_geometry_p3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +/* HMath.Geometry.Internal.Plane :: Point3 -> Double -> Plane */ +HMATH_API hmath_status hmath_geometry_plane(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.PointND :: [Double] -> PointND */ +HMATH_API hmath_status hmath_geometry_point_nd_raw(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Internal.Polygon :: [Point2] -> Polygon */ +HMATH_API hmath_status hmath_geometry_polygon(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Internal.Ray :: Point3 -> Point3 -> Ray */ +HMATH_API hmath_status hmath_geometry_ray(hmath_context *context, const hmath_value *point3, const hmath_value *point32, hmath_value **out); +/* HMath.Geometry.Internal.Rectangle :: Point2 -> Point2 -> Rectangle */ +HMATH_API hmath_status hmath_geometry_rectangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out); +/* HMath.Geometry.Internal.Segment :: PointND -> PointND -> Segment */ +HMATH_API hmath_status hmath_geometry_segment(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Internal.Sphere :: Point3 -> Double -> Sphere */ +HMATH_API hmath_status hmath_geometry_sphere(hmath_context *context, const hmath_value *point3, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Internal.Triangle :: Point2 -> Point2 -> Point2 -> Triangle */ +HMATH_API hmath_status hmath_geometry_triangle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out); +/* HMath.Geometry.Internal.point2 :: Double -> Double -> Either MathError Point2 */ +HMATH_API hmath_status hmath_geometry_point2(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +/* HMath.Geometry.Internal.point3 :: Double -> Double -> Double -> Either MathError Point3 */ +HMATH_API hmath_status hmath_geometry_point3(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, hmath_value **out); +/* HMath.Geometry.Internal.pointND :: [Double] -> Either MathError PointND */ +HMATH_API hmath_status hmath_geometry_point_nd(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Polygon.Difference :: BooleanOperation */ +HMATH_API hmath_status hmath_geometry_difference(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.GiftWrapping :: HullAlgorithm */ +HMATH_API hmath_status hmath_geometry_gift_wrapping(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.GrahamScan :: HullAlgorithm */ +HMATH_API hmath_status hmath_geometry_graham_scan(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.Intersection :: BooleanOperation */ +HMATH_API hmath_status hmath_geometry_intersection(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.MonotoneChain :: HullAlgorithm */ +HMATH_API hmath_status hmath_geometry_monotone_chain(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.Quickhull :: HullAlgorithm */ +HMATH_API hmath_status hmath_geometry_quickhull(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.Union :: BooleanOperation */ +HMATH_API hmath_status hmath_geometry_union(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Polygon.clipPolygon :: Polygon -> Polygon -> Either MathError [Point2] */ +HMATH_API hmath_status hmath_geometry_clip_polygon(hmath_context *context, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out); +/* HMath.Geometry.Polygon.convexHull :: HullAlgorithm -> [Point2] -> Either MathError [Point2] */ +HMATH_API hmath_status hmath_geometry_convex_hull(hmath_context *context, const hmath_value *hull_algorithm, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Polygon.minimumBoundingCircle :: [Point2] -> Either MathError Circle */ +HMATH_API hmath_status hmath_geometry_minimum_bounding_circle(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Polygon.minimumBoundingRectangle :: [Point2] -> Either MathError [Point2] */ +HMATH_API hmath_status hmath_geometry_minimum_bounding_rectangle(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Polygon.minkowskiSum :: [Point2] -> [Point2] -> Either MathError [Point2] */ +HMATH_API hmath_status hmath_geometry_minkowski_sum(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Polygon.polygonArea :: Polygon -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_polygon_area(hmath_context *context, const hmath_value *polygon, hmath_value **out); +/* HMath.Geometry.Polygon.polygonBoolean :: BooleanOperation -> Polygon -> Polygon -> Either MathError [Polygon] */ +HMATH_API hmath_status hmath_geometry_polygon_boolean(hmath_context *context, const hmath_value *boolean_operation, const hmath_value *polygon, const hmath_value *polygon2, hmath_value **out); +/* HMath.Geometry.Polygon.polygonCentroid :: Polygon -> Either MathError Point2 */ +HMATH_API hmath_status hmath_geometry_polygon_centroid(hmath_context *context, const hmath_value *polygon, hmath_value **out); +/* HMath.Geometry.Polygon.shoelace :: Polygon -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_shoelace(hmath_context *context, const hmath_value *polygon, hmath_value **out); +/* HMath.Geometry.Primitives.Chebyshev :: Metric */ +HMATH_API hmath_status hmath_geometry_chebyshev(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.CirclePoints :: [Point2] -> CircleIntersection */ +HMATH_API hmath_status hmath_geometry_circle_points(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Primitives.CoincidentCircles :: CircleIntersection */ +HMATH_API hmath_status hmath_geometry_coincident_circles(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.CoincidentLine :: Intersection2 */ +HMATH_API hmath_status hmath_geometry_coincident_line(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.DisjointCircles :: CircleIntersection */ +HMATH_API hmath_status hmath_geometry_disjoint_circles(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.Euclidean :: Metric */ +HMATH_API hmath_status hmath_geometry_euclidean(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.IntersectionPoint :: Point2 -> Intersection2 */ +HMATH_API hmath_status hmath_geometry_intersection_point(hmath_context *context, const hmath_value *point2, hmath_value **out); +/* HMath.Geometry.Primitives.Manhattan :: Metric */ +HMATH_API hmath_status hmath_geometry_manhattan(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.Minkowski :: Double -> Metric */ +HMATH_API hmath_status hmath_geometry_minkowski(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Primitives.NoIntersection :: Intersection2 */ +HMATH_API hmath_status hmath_geometry_no_intersection(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Primitives.OverlapSegment :: Point2 -> Point2 -> Intersection2 */ +HMATH_API hmath_status hmath_geometry_overlap_segment(hmath_context *context, const hmath_value *point2, const hmath_value *point22, hmath_value **out); +/* HMath.Geometry.Primitives.boxContains :: AABB -> PointND -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_box_contains(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out); +/* HMath.Geometry.Primitives.boxSDF :: AABB -> PointND -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_box_sdf(hmath_context *context, const hmath_value *aabb, const hmath_value *point_nd, hmath_value **out); +/* HMath.Geometry.Primitives.capsuleSDF :: Capsule -> Point3 -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_capsule_sdf(hmath_context *context, const hmath_value *capsule, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.circleIntersection :: Circle -> Circle -> Either MathError CircleIntersection */ +HMATH_API hmath_status hmath_geometry_circle_intersection(hmath_context *context, const hmath_value *circle, const hmath_value *circle2, hmath_value **out); +/* HMath.Geometry.Primitives.circumcenter :: Triangle -> Either MathError Point2 */ +HMATH_API hmath_status hmath_geometry_circumcenter(hmath_context *context, const hmath_value *triangle, hmath_value **out); +/* HMath.Geometry.Primitives.coneSDF :: Cone -> Point3 -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_cone_sdf(hmath_context *context, const hmath_value *cone, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.cosineDistance :: PointND -> PointND -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_cosine_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Primitives.cylinderSDF :: Cylinder -> Point3 -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_cylinder_sdf(hmath_context *context, const hmath_value *cylinder, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.distance :: Metric -> PointND -> PointND -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_distance(hmath_context *context, const hmath_value *metric, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Primitives.ellipseContains :: Ellipse -> Point2 -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_ellipse_contains(hmath_context *context, const hmath_value *ellipse, const hmath_value *point2, hmath_value **out); +/* HMath.Geometry.Primitives.hausdorffDistance :: [PointND] -> [PointND] -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_hausdorff_distance(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Primitives.incenter :: Triangle -> Either MathError Point2 */ +HMATH_API hmath_status hmath_geometry_incenter(hmath_context *context, const hmath_value *triangle, hmath_value **out); +/* HMath.Geometry.Primitives.incircle :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Ordering */ +HMATH_API hmath_status hmath_geometry_incircle(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +/* HMath.Geometry.Primitives.lineIntersection :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2 */ +HMATH_API hmath_status hmath_geometry_line_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +/* HMath.Geometry.Primitives.linePlaneIntersection :: Line -> Plane -> Either MathError (Maybe (Maybe Point3)) */ +HMATH_API hmath_status hmath_geometry_line_plane_intersection(hmath_context *context, const hmath_value *line, const hmath_value *plane, hmath_value **out); +/* HMath.Geometry.Primitives.mahalanobisDistance :: [[Double]] -> PointND -> PointND -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_mahalanobis_distance(hmath_context *context, const hmath_value *values, const hmath_value *point_nd, const hmath_value *point_nd2, hmath_value **out); +/* HMath.Geometry.Primitives.obbSDF :: OBB -> Point3 -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_obb_sdf(hmath_context *context, const hmath_value *obb, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.orientation :: Point2 -> Point2 -> Point2 -> Either MathError Orientation */ +HMATH_API hmath_status hmath_geometry_orientation(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, hmath_value **out); +/* HMath.Geometry.Primitives.planeIntersection :: Plane -> Plane -> Either MathError (Maybe (Maybe Line)) */ +HMATH_API hmath_status hmath_geometry_plane_intersection(hmath_context *context, const hmath_value *plane, const hmath_value *plane2, hmath_value **out); +/* HMath.Geometry.Primitives.pointLineDistance :: PointND -> Line -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_point_line_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *line, hmath_value **out); +/* HMath.Geometry.Primitives.pointPlaneDistance :: Point3 -> Plane -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_point_plane_distance(hmath_context *context, const hmath_value *point3, const hmath_value *plane, hmath_value **out); +/* HMath.Geometry.Primitives.pointSegmentDistance :: PointND -> Segment -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_point_segment_distance(hmath_context *context, const hmath_value *point_nd, const hmath_value *segment, hmath_value **out); +/* HMath.Geometry.Primitives.polygonLocation :: Polygon -> Point2 -> Either MathError Location */ +HMATH_API hmath_status hmath_geometry_polygon_location(hmath_context *context, const hmath_value *polygon, const hmath_value *point2, hmath_value **out); +/* HMath.Geometry.Primitives.rayBox :: Ray -> AABB -> Either MathError (Maybe (Double, Double)) */ +HMATH_API hmath_status hmath_geometry_ray_box(hmath_context *context, const hmath_value *ray, const hmath_value *aabb, hmath_value **out); +/* HMath.Geometry.Primitives.raySphere :: Ray -> Sphere -> Either MathError (Maybe (Double, Double)) */ +HMATH_API hmath_status hmath_geometry_ray_sphere(hmath_context *context, const hmath_value *ray, const hmath_value *sphere, hmath_value **out); +/* HMath.Geometry.Primitives.rayTriangle :: Ray -> (Point3, Point3, Point3) -> Either MathError (Maybe Double) */ +HMATH_API hmath_status hmath_geometry_ray_triangle(hmath_context *context, const hmath_value *ray, const hmath_value *tuple_value, hmath_value **out); +/* HMath.Geometry.Primitives.segmentIntersection :: Point2 -> Point2 -> Point2 -> Point2 -> Either MathError Intersection2 */ +HMATH_API hmath_status hmath_geometry_segment_intersection(hmath_context *context, const hmath_value *point2, const hmath_value *point22, const hmath_value *point23, const hmath_value *point24, hmath_value **out); +/* HMath.Geometry.Primitives.sphereContains :: Sphere -> Point3 -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_sphere_contains(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.sphereSDF :: Sphere -> Point3 -> Either MathError Double */ +HMATH_API hmath_status hmath_geometry_sphere_sdf(hmath_context *context, const hmath_value *sphere, const hmath_value *point3, hmath_value **out); +/* HMath.Geometry.Primitives.triangleBarycentric :: Triangle -> Point2 -> Either MathError [Double] */ +HMATH_API hmath_status hmath_geometry_triangle_barycentric(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out); +/* HMath.Geometry.Primitives.triangleIntersection :: Triangle -> Triangle -> Either MathError [Point2] */ +HMATH_API hmath_status hmath_geometry_triangle_intersection(hmath_context *context, const hmath_value *triangle, const hmath_value *triangle2, hmath_value **out); +/* HMath.Geometry.Primitives.triangleLocation :: Triangle -> Point2 -> Either MathError Location */ +HMATH_API hmath_status hmath_geometry_triangle_location(hmath_context *context, const hmath_value *triangle, const hmath_value *point2, hmath_value **out); +/* HMath.Geometry.Spatial.BVH :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_bvh(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.BallTree :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_ball_tree(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.KDTree :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_kd_tree(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.NeighborQuery :: [(Int, Double)] -> Int -> Bool -> NeighborQuery */ +HMATH_API hmath_status hmath_geometry_neighbor_query(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out); +/* HMath.Geometry.Spatial.Octree :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_octree(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.Quadtree :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_quadtree(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.RTree :: SpatialKind */ +HMATH_API hmath_status hmath_geometry_r_tree(hmath_context *context, hmath_value **out); +/* HMath.Geometry.Spatial.SpatialHash :: Double -> SpatialKind */ +HMATH_API hmath_status hmath_geometry_spatial_hash(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Spatial.buildSpatialIndex :: SpatialKind -> PointCloud -> Either MathError SpatialIndex */ +HMATH_API hmath_status hmath_geometry_build_spatial_index(hmath_context *context, const hmath_value *spatial_kind, const hmath_value *point_cloud, hmath_value **out); +/* HMath.Geometry.Spatial.cloudPoints :: PointCloud -> [PointND] */ +HMATH_API hmath_status hmath_geometry_cloud_points(hmath_context *context, const hmath_value *point_cloud, hmath_value **out); +/* HMath.Geometry.Spatial.nearestQuery :: Int -> Int -> SpatialIndex -> PointND -> Either MathError NeighborQuery */ +HMATH_API hmath_status hmath_geometry_nearest_query(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *point_nd, hmath_value **out); +/* HMath.Geometry.Spatial.pointCloud :: [PointND] -> Either MathError PointCloud */ +HMATH_API hmath_status hmath_geometry_point_cloud(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Spatial.queryExhaustive :: NeighborQuery -> Bool */ +HMATH_API hmath_status hmath_geometry_query_exhaustive(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +/* HMath.Geometry.Spatial.queryLeaves :: NeighborQuery -> Int */ +HMATH_API hmath_status hmath_geometry_query_leaves(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +/* HMath.Geometry.Spatial.queryNeighbors :: NeighborQuery -> [(Int, Double)] */ +HMATH_API hmath_status hmath_geometry_query_neighbors(hmath_context *context, const hmath_value *neighbor_query, hmath_value **out); +/* HMath.Geometry.Spatial.radiusQuery :: SpatialIndex -> PointND -> Double -> Either MathError [Int] */ +HMATH_API hmath_status hmath_geometry_radius_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *point_nd, const hmath_value *number, hmath_value **out); +/* HMath.Geometry.Spatial.rangeQuery :: SpatialIndex -> AABB -> Either MathError [Int] */ +HMATH_API hmath_status hmath_geometry_range_query(hmath_context *context, const hmath_value *spatial_index, const hmath_value *aabb, hmath_value **out); +/* HMath.Geometry.Transform.affineTransform :: Matrix Double -> PointND -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_affine_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out); +/* HMath.Geometry.Transform.applyTransform :: Matrix Double -> PointND -> Either MathError PointND */ +HMATH_API hmath_status hmath_geometry_apply_transform(hmath_context *context, const hmath_value *matrix, const hmath_value *point_nd, hmath_value **out); +/* HMath.Geometry.Transform.composeTransforms :: Matrix Double -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_compose_transforms(hmath_context *context, const hmath_value *matrix, const hmath_value *matrix2, hmath_value **out); +/* HMath.Geometry.Transform.cullBox :: Frustum -> AABB -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_cull_box(hmath_context *context, const hmath_value *frustum, const hmath_value *aabb, hmath_value **out); +/* HMath.Geometry.Transform.cullSphere :: Frustum -> Sphere -> Either MathError Bool */ +HMATH_API hmath_status hmath_geometry_cull_sphere(hmath_context *context, const hmath_value *frustum, const hmath_value *sphere, hmath_value **out); +/* HMath.Geometry.Transform.extractFrustum :: Matrix Double -> Either MathError Frustum */ +HMATH_API hmath_status hmath_geometry_extract_frustum(hmath_context *context, const hmath_value *matrix, hmath_value **out); +/* HMath.Geometry.Transform.inverseTransform :: Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_inverse_transform(hmath_context *context, const hmath_value *matrix, hmath_value **out); +/* HMath.Geometry.Transform.lookAt :: Point3 -> Point3 -> Point3 -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_look_at(hmath_context *context, const hmath_value *point3, const hmath_value *point32, const hmath_value *point33, hmath_value **out); +/* HMath.Geometry.Transform.orthographic :: Double -> Double -> Double -> Double -> Double -> Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_orthographic(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, const hmath_value *number5, const hmath_value *number6, hmath_value **out); +/* HMath.Geometry.Transform.perspective :: Double -> Double -> Double -> Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_geometry_perspective(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *number3, const hmath_value *number4, hmath_value **out); +/* HMath.Geometry.Triangulation.constrainedDelaunay :: [Point2] -> [(Int, Int)] -> Either MathError [IndexedTriangle] */ +HMATH_API hmath_status hmath_geometry_constrained_delaunay(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.Geometry.Triangulation.delaunay :: [Point2] -> Either MathError [IndexedTriangle] */ +HMATH_API hmath_status hmath_geometry_delaunay(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Geometry.Triangulation.earClip :: Polygon -> Either MathError [IndexedTriangle] */ +HMATH_API hmath_status hmath_geometry_ear_clip(hmath_context *context, const hmath_value *polygon, hmath_value **out); +/* HMath.Geometry.Triangulation.voronoi :: Rectangle -> [Point2] -> Either MathError [[Point2]] */ +HMATH_API hmath_status hmath_geometry_voronoi(hmath_context *context, const hmath_value *rectangle, const hmath_value *values, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_graph.h b/include/hmath_graph.h new file mode 100644 index 0000000..83da323 --- /dev/null +++ b/include/hmath_graph.h @@ -0,0 +1,655 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_graph_bindings.py. */ +#ifndef HMATH_GRAPH_H +#define HMATH_GRAPH_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original Graph types are owned hmath_value objects (kinds 60..67). + * Pass Boolean, Haskell Int, binary64, exact Integer, String, list and + * tuple values matching each source signature. No algorithms or source + * limits are replaced. Every output owns one reference; release with + * hmath_value_release. Error outputs are untouched. MathError payloads + * are available through hmath_last_math_error. Cancellation is checked + * before entry; original per-algorithm budgets still apply. */ +typedef hmath_status (*hmath_graph_heuristic)(ptrdiff_t vertex, void *userdata, double *out); +typedef hmath_value hmath_graph_graph_object; +typedef hmath_value hmath_graph_edge_object; +typedef hmath_value hmath_graph_csr_object; +typedef hmath_value hmath_graph_bipartite_graph_object; +typedef hmath_value hmath_graph_hypergraph_object; +typedef hmath_value hmath_graph_network_object; +typedef hmath_value hmath_graph_network_edge_object; +typedef hmath_value hmath_graph_flow_result_object; +/* HMath.Graph.Analysis.betweennessCentrality :: Graph -> [Double] */ +HMATH_API hmath_status hmath_graph_betweenness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.bipartiteColors :: Graph -> Maybe [Bool] */ +HMATH_API hmath_status hmath_graph_bipartite_colors( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.closenessCentrality :: Graph -> [Double] */ +HMATH_API hmath_status hmath_graph_closeness_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.clusteringCoefficients :: Graph -> Either MathError [Double] */ +HMATH_API hmath_status hmath_graph_clustering_coefficients( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.degreeCentrality :: Graph -> [Double] */ +HMATH_API hmath_status hmath_graph_degree_centrality( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.density :: Graph -> Double */ +HMATH_API hmath_status hmath_graph_density( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.diameterRadius :: Graph -> Maybe (Int, Int) */ +HMATH_API hmath_status hmath_graph_diameter_radius( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.eigenvectorCentrality :: Int -> Double -> Graph -> Either MathError [Double] */ +HMATH_API hmath_status hmath_graph_eigenvector_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.eulerianPath :: Graph -> Either MathError (Maybe ([Int], [Int])) */ +HMATH_API hmath_status hmath_graph_eulerian_path( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.exactColoring :: Int -> Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_exact_coloring( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.graphEditDistance :: Int -> Graph -> Graph -> Either MathError Int */ +HMATH_API hmath_status hmath_graph_graph_edit_distance( + hmath_context *context, + const hmath_value *budget, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); +/* HMath.Graph.Analysis.graphLaplacian :: Bool -> Graph -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_graph_graph_laplacian( + hmath_context *context, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.graphSimilarity :: Graph -> Graph -> Either MathError Double */ +HMATH_API hmath_status hmath_graph_graph_similarity( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); +/* HMath.Graph.Analysis.greedyColoring :: Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_greedy_coloring( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.hamiltonianPath :: Int -> Graph -> Either MathError (Maybe [Int]) */ +HMATH_API hmath_status hmath_graph_hamiltonian_path( + hmath_context *context, + const hmath_value *fuel, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.katzCentrality :: Int -> Double -> Double -> Double -> Graph -> Either MathError [Double] */ +HMATH_API hmath_status hmath_graph_katz_centrality( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *alpha, + const hmath_value *beta, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.labelPropagation :: Int -> Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_label_propagation( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.laplacianSpectrum :: Int -> Double -> Bool -> Graph -> Either MathError [Double] */ +HMATH_API hmath_status hmath_graph_laplacian_spectrum( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *normalized, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.louvain :: Int -> Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_louvain( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.modularity :: Graph -> [Int] -> Either MathError Double */ +HMATH_API hmath_status hmath_graph_modularity( + hmath_context *context, + const hmath_value *graph, + const hmath_value *labels, + hmath_value **out); +/* HMath.Graph.Analysis.nearestNeighborTour :: Graph -> Int -> Either MathError (Maybe (Double, [Int])) */ +HMATH_API hmath_status hmath_graph_nearest_neighbor_tour( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +/* HMath.Graph.Analysis.pageRank :: Int -> Double -> Double -> Graph -> Either MathError [Double] */ +HMATH_API hmath_status hmath_graph_page_rank( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *tolerance, + const hmath_value *damping, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Analysis.randomWalk :: Int -> Word64 -> Graph -> Int -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_random_walk( + hmath_context *context, + const hmath_value *count, + const hmath_value *seed, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +/* HMath.Graph.Analysis.twoOptTour :: Int -> Graph -> [Int] -> Either MathError (Double, [Int]) */ +HMATH_API hmath_status hmath_graph_two_opt_tour( + hmath_context *context, + const hmath_value *iterations, + const hmath_value *graph, + const hmath_value *tour, + hmath_value **out); +/* HMath.Graph.Core.CSR :: Bool -> Int -> [Int] -> [Int] -> [Double] -> [Int] -> [(Int, Int)] -> CSR */ +HMATH_API hmath_status hmath_graph_csr( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *offsets, + const hmath_value *targets, + const hmath_value *weights, + const hmath_value *edge_ids, + const hmath_value *orientations, + hmath_value **out); +/* HMath.Graph.Core.Edge :: Int -> Int -> Int -> Double -> Edge */ +HMATH_API hmath_status hmath_graph_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *weight, + hmath_value **out); +/* HMath.Graph.Core.adjacencyList :: Graph -> [[(Int, Double, Int)]] */ +HMATH_API hmath_status hmath_graph_adjacency_list( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.adjacencyMatrix :: Graph -> [[[(Int, Double)]]] */ +HMATH_API hmath_status hmath_graph_adjacency_matrix( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.arcs :: Graph -> [Edge] */ +HMATH_API hmath_status hmath_graph_arcs( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.articulationPoints :: Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_articulation_points( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.bfs :: Graph -> Int -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_bfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +/* HMath.Graph.Core.bipartiteBase :: BipartiteGraph -> Graph */ +HMATH_API hmath_status hmath_graph_bipartite_base( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out); +/* HMath.Graph.Core.bipartiteGraph :: Int -> Int -> [(Int, Int, Double)] -> Either MathError BipartiteGraph */ +HMATH_API hmath_status hmath_graph_bipartite_graph( + hmath_context *context, + const hmath_value *left_vertices, + const hmath_value *right_vertices, + const hmath_value *edges, + hmath_value **out); +/* HMath.Graph.Core.bipartiteParts :: BipartiteGraph -> (Int, Int) */ +HMATH_API hmath_status hmath_graph_bipartite_parts( + hmath_context *context, + const hmath_value *bipartite_graph, + hmath_value **out); +/* HMath.Graph.Core.boruvka :: Graph -> Either MathError [Edge] */ +HMATH_API hmath_status hmath_graph_boruvka( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.bridges :: Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_bridges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.checkVertex :: Graph -> Int -> Either MathError () */ +HMATH_API hmath_status hmath_graph_check_vertex( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out); +/* HMath.Graph.Core.connectedComponents :: Graph -> [[Int]] */ +HMATH_API hmath_status hmath_graph_connected_components( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.csrDirected :: CSR -> Bool */ +HMATH_API hmath_status hmath_graph_csr_directed( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrIds :: CSR -> [Int] */ +HMATH_API hmath_status hmath_graph_csr_ids( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrOffsets :: CSR -> [Int] */ +HMATH_API hmath_status hmath_graph_csr_offsets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrOrientations :: CSR -> [(Int, Int)] */ +HMATH_API hmath_status hmath_graph_csr_orientations( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrTargets :: CSR -> [Int] */ +HMATH_API hmath_status hmath_graph_csr_targets( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrVertices :: CSR -> Int */ +HMATH_API hmath_status hmath_graph_csr_vertices( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.csrWeights :: CSR -> [Double] */ +HMATH_API hmath_status hmath_graph_csr_weights( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.deserializeBipartiteGraph :: String -> Either MathError BipartiteGraph */ +HMATH_API hmath_status hmath_graph_deserialize_bipartite_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +/* HMath.Graph.Core.deserializeGraph :: String -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_deserialize_graph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +/* HMath.Graph.Core.deserializeHypergraph :: String -> Either MathError Hypergraph */ +HMATH_API hmath_status hmath_graph_deserialize_hypergraph( + hmath_context *context, + const hmath_value *text, + hmath_value **out); +/* HMath.Graph.Core.dfs :: Graph -> Int -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_dfs( + hmath_context *context, + const hmath_value *graph, + const hmath_value *start, + hmath_value **out); +/* HMath.Graph.Core.directed :: Graph -> Bool */ +HMATH_API hmath_status hmath_graph_directed( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.edgeFrom :: Edge -> Int */ +HMATH_API hmath_status hmath_graph_edge_from( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +/* HMath.Graph.Core.edgeId :: Edge -> Int */ +HMATH_API hmath_status hmath_graph_edge_id( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +/* HMath.Graph.Core.edgeTo :: Edge -> Int */ +HMATH_API hmath_status hmath_graph_edge_to( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +/* HMath.Graph.Core.edgeWeight :: Edge -> Double */ +HMATH_API hmath_status hmath_graph_edge_weight( + hmath_context *context, + const hmath_value *edge, + hmath_value **out); +/* HMath.Graph.Core.edges :: Graph -> [Edge] */ +HMATH_API hmath_status hmath_graph_edges( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.finite :: Double -> Bool */ +HMATH_API hmath_status hmath_graph_finite( + hmath_context *context, + const hmath_value *x, + hmath_value **out); +/* HMath.Graph.Core.fromAdjacencyList :: Bool -> [[(Int, Double, Int)]] -> [(Int, Int)] -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_from_adjacency_list( + hmath_context *context, + const hmath_value *directed, + const hmath_value *rows, + const hmath_value *orientations, + hmath_value **out); +/* HMath.Graph.Core.fromAdjacencyMatrix :: Bool -> [[[Double]]] -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_from_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + hmath_value **out); +/* HMath.Graph.Core.fromCSR :: CSR -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_from_csr( + hmath_context *context, + const hmath_value *csr, + hmath_value **out); +/* HMath.Graph.Core.fromLabeledAdjacencyMatrix :: Bool -> [[[(Int, Double)]]] -> [(Int, Int)] -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_from_labeled_adjacency_matrix( + hmath_context *context, + const hmath_value *directed, + const hmath_value *cells, + const hmath_value *orientations, + hmath_value **out); +/* HMath.Graph.Core.graph :: Bool -> Int -> [(Int, Int, Double)] -> Either MathError Graph */ +HMATH_API hmath_status hmath_graph_graph( + hmath_context *context, + const hmath_value *directed, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out); +/* HMath.Graph.Core.hasCycle :: Graph -> Bool */ +HMATH_API hmath_status hmath_graph_has_cycle( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.hyperVertices :: Hypergraph -> Int */ +HMATH_API hmath_status hmath_graph_hyper_vertices( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +/* HMath.Graph.Core.hyperedges :: Hypergraph -> [[Int]] */ +HMATH_API hmath_status hmath_graph_hyperedges( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +/* HMath.Graph.Core.hypergraph :: Int -> [[Int]] -> Either MathError Hypergraph */ +HMATH_API hmath_status hmath_graph_hypergraph( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *hyperedges, + hmath_value **out); +/* HMath.Graph.Core.iterativeDeepening :: Int -> Graph -> Int -> Int -> Either MathError (Maybe [Int]) */ +HMATH_API hmath_status hmath_graph_iterative_deepening( + hmath_context *context, + const hmath_value *budget, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +/* HMath.Graph.Core.kosarajuSCC :: Graph -> [[Int]] */ +HMATH_API hmath_status hmath_graph_kosaraju_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.kruskal :: Graph -> Either MathError [Edge] */ +HMATH_API hmath_status hmath_graph_kruskal( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.neighbors :: Graph -> Int -> [(Int, Double, Int)] */ +HMATH_API hmath_status hmath_graph_neighbors( + hmath_context *context, + const hmath_value *graph, + const hmath_value *vertex, + hmath_value **out); +/* HMath.Graph.Core.prim :: Graph -> Either MathError [Edge] */ +HMATH_API hmath_status hmath_graph_prim( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.requireUndirected :: Graph -> Either MathError () */ +HMATH_API hmath_status hmath_graph_require_undirected( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.serializeBipartiteGraph :: BipartiteGraph -> String */ +HMATH_API hmath_status hmath_graph_serialize_bipartite_graph( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out); +/* HMath.Graph.Core.serializeGraph :: Graph -> String */ +HMATH_API hmath_status hmath_graph_serialize_graph( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.serializeHypergraph :: Hypergraph -> String */ +HMATH_API hmath_status hmath_graph_serialize_hypergraph( + hmath_context *context, + const hmath_value *hypergraph, + hmath_value **out); +/* HMath.Graph.Core.tarjanSCC :: Graph -> [[Int]] */ +HMATH_API hmath_status hmath_graph_tarjan_scc( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.toCSR :: Graph -> CSR */ +HMATH_API hmath_status hmath_graph_to_csr( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.topologicalSort :: Graph -> Either MathError [Int] */ +HMATH_API hmath_status hmath_graph_topological_sort( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Core.vertexCount :: Graph -> Int */ +HMATH_API hmath_status hmath_graph_vertex_count( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Flow.FlowResult :: Integer -> [Integer] -> Integer -> FlowResult */ +HMATH_API hmath_status hmath_graph_flow_result( + hmath_context *context, + const hmath_value *value, + const hmath_value *edge_flows, + const hmath_value *cost, + hmath_value **out); +/* HMath.Graph.Flow.NetworkEdge :: Int -> Int -> Int -> Integer -> Integer -> NetworkEdge */ +HMATH_API hmath_status hmath_graph_network_edge( + hmath_context *context, + const hmath_value *edge_id, + const hmath_value *source, + const hmath_value *target, + const hmath_value *capacity, + const hmath_value *cost, + hmath_value **out); +/* HMath.Graph.Flow.dinic :: Int -> Network -> Int -> Int -> Either MathError FlowResult */ +HMATH_API hmath_status hmath_graph_dinic( + hmath_context *context, + const hmath_value *budget, + const hmath_value *network, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +/* HMath.Graph.Flow.edgeFlows :: FlowResult -> [Integer] */ +HMATH_API hmath_status hmath_graph_edge_flows( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +/* HMath.Graph.Flow.edmondsKarp :: Int -> Network -> Int -> Int -> Either MathError FlowResult */ +HMATH_API hmath_status hmath_graph_edmonds_karp( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +/* HMath.Graph.Flow.flowCost :: FlowResult -> Integer */ +HMATH_API hmath_status hmath_graph_flow_cost( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +/* HMath.Graph.Flow.flowValue :: FlowResult -> Integer */ +HMATH_API hmath_status hmath_graph_flow_value( + hmath_context *context, + const hmath_value *flow_result, + hmath_value **out); +/* HMath.Graph.Flow.fordFulkerson :: Int -> Network -> Int -> Int -> Either MathError FlowResult */ +HMATH_API hmath_status hmath_graph_ford_fulkerson( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +/* HMath.Graph.Flow.hopcroftKarp :: BipartiteGraph -> [(Int, Int)] */ +HMATH_API hmath_status hmath_graph_hopcroft_karp( + hmath_context *context, + const hmath_value *bipartite, + hmath_value **out); +/* HMath.Graph.Flow.hungarian :: [[Integer]] -> Either MathError (Integer, [(Int, Int)]) */ +HMATH_API hmath_status hmath_graph_hungarian( + hmath_context *context, + const hmath_value *costs, + hmath_value **out); +/* HMath.Graph.Flow.minimumCostMaximumFlow :: Int -> Network -> Int -> Int -> Either MathError FlowResult */ +HMATH_API hmath_status hmath_graph_minimum_cost_maximum_flow( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +/* HMath.Graph.Flow.minimumCut :: Int -> Network -> Int -> Int -> Either MathError ([Int], Integer) */ +HMATH_API hmath_status hmath_graph_minimum_cut( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +/* HMath.Graph.Flow.network :: Int -> [(Int, Int, Integer, Integer)] -> Either MathError Network */ +HMATH_API hmath_status hmath_graph_network( + hmath_context *context, + const hmath_value *vertex_count, + const hmath_value *edges, + hmath_value **out); +/* HMath.Graph.Flow.networkCapacity :: NetworkEdge -> Integer */ +HMATH_API hmath_status hmath_graph_network_capacity( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +/* HMath.Graph.Flow.networkCost :: NetworkEdge -> Integer */ +HMATH_API hmath_status hmath_graph_network_cost( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +/* HMath.Graph.Flow.networkEdgeId :: NetworkEdge -> Int */ +HMATH_API hmath_status hmath_graph_network_edge_id( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +/* HMath.Graph.Flow.networkEdges :: Network -> [NetworkEdge] */ +HMATH_API hmath_status hmath_graph_network_edges( + hmath_context *context, + const hmath_value *network, + hmath_value **out); +/* HMath.Graph.Flow.networkFrom :: NetworkEdge -> Int */ +HMATH_API hmath_status hmath_graph_network_from( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +/* HMath.Graph.Flow.networkTo :: NetworkEdge -> Int */ +HMATH_API hmath_status hmath_graph_network_to( + hmath_context *context, + const hmath_value *network_edge, + hmath_value **out); +/* HMath.Graph.Flow.pushRelabel :: Int -> Network -> Int -> Int -> Either MathError FlowResult */ +HMATH_API hmath_status hmath_graph_push_relabel( + hmath_context *context, + const hmath_value *value, + const hmath_value *network, + const hmath_value *value3, + const hmath_value *value4, + hmath_value **out); +/* HMath.Graph.Paths.aStar :: Graph -> (Int -> Double) -> Int -> Int -> Either MathError (Maybe (Double, [Int])) */ +HMATH_API hmath_status hmath_graph_a_star( + hmath_context *context, + const hmath_value *graph, + hmath_graph_heuristic heuristic, + void *userdata, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +/* HMath.Graph.Paths.bellmanFord :: Graph -> Int -> Either MathError [Maybe Double] */ +HMATH_API hmath_status hmath_graph_bellman_ford( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +/* HMath.Graph.Paths.bidirectionalDijkstra :: Graph -> Int -> Int -> Either MathError (Maybe Double) */ +HMATH_API hmath_status hmath_graph_bidirectional_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +/* HMath.Graph.Paths.dijkstra :: Graph -> Int -> Either MathError [Maybe Double] */ +HMATH_API hmath_status hmath_graph_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +/* HMath.Graph.Paths.floydWarshall :: Graph -> Either MathError [[Maybe Double]] */ +HMATH_API hmath_status hmath_graph_floyd_warshall( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Paths.johnson :: Graph -> Either MathError [[Maybe Double]] */ +HMATH_API hmath_status hmath_graph_johnson( + hmath_context *context, + const hmath_value *graph, + hmath_value **out); +/* HMath.Graph.Paths.kShortestPaths :: Int -> Int -> Graph -> Int -> Int -> Either MathError [(Double, [Int], [Int])] */ +HMATH_API hmath_status hmath_graph_k_shortest_paths( + hmath_context *context, + const hmath_value *budget, + const hmath_value *count, + const hmath_value *graph, + const hmath_value *source, + const hmath_value *target, + hmath_value **out); +/* HMath.Graph.Paths.longestDAGPaths :: Graph -> Int -> Either MathError [Maybe Double] */ +HMATH_API hmath_status hmath_graph_longest_dag_paths( + hmath_context *context, + const hmath_value *graph, + const hmath_value *source, + hmath_value **out); +/* HMath.Graph.Paths.multiSourceDijkstra :: Graph -> [Int] -> Either MathError [Maybe Double] */ +HMATH_API hmath_status hmath_graph_multi_source_dijkstra( + hmath_context *context, + const hmath_value *graph, + const hmath_value *sources, + hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_image.h b/include/hmath_image.h new file mode 100644 index 0000000..6f52b80 --- /dev/null +++ b/include/hmath_image.h @@ -0,0 +1,195 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_image_bindings.py. */ +#ifndef HMATH_IMAGE_H +#define HMATH_IMAGE_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original finite interleaved ND Image algorithms; all coefficients are Double. + * Inputs are borrowed; successful outputs transfer one immutable Value owner. + * Outputs stay untouched on failure. Release with hmath_value_release. Live + * owners pin the runtime. Source MathError/status11 retains its full payload. + * Source shape/sample/work budgets, boundary policies, color ranges, tie order + * and unchecked-helper errors remain unchanged. Callbacks are synchronous and + * deterministic: input is a borrowed tuple of Double values; output transfers + * one owned Double scalar. Retain input children if keeping them after return. + * Callbacks may reenter checked APIs and must not unwind through C. */ +typedef hmath_status (*hmath_image_callback)(const hmath_value *arguments,void *userdata,hmath_value **out); +typedef hmath_value hmath_image_image_object; /* kind160 */ +typedef hmath_value hmath_image_tensor_double_object; /* kind161 */ +typedef hmath_value hmath_image_boundary_object; /* kind162 */ +typedef hmath_value hmath_image_gradient_operator_object; /* kind163 */ +typedef hmath_value hmath_image_morphology_object; /* kind164 */ +typedef hmath_value hmath_image_template_metric_object; /* kind165 */ +typedef hmath_value hmath_image_interpolation_object; /* kind166 */ +typedef hmath_value hmath_image_connectivity_object; /* kind167 */ +typedef hmath_value hmath_image_color_space_object; /* kind168 */ +/* HMath.Image.Core.image :: [Int] -> Int -> [Double] -> Either MathError Image */ +HMATH_API hmath_status hmath_image_image(hmath_context *context, const hmath_value *shape, const hmath_value *channels, const hmath_value *values, hmath_value **out); +/* HMath.Image.Core.fromTensor :: Tensor Double -> Either MathError Image */ +HMATH_API hmath_status hmath_image_from_tensor(hmath_context *context, const hmath_value *tensor, hmath_value **out); +/* HMath.Image.Core.toTensor :: Image -> Either MathError Tensor Double */ +HMATH_API hmath_status hmath_image_to_tensor(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.imageShape :: Image -> [Int] */ +HMATH_API hmath_status hmath_image_image_shape(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.imageChannels :: Image -> Int */ +HMATH_API hmath_status hmath_image_image_channels(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.imageValues :: Image -> [Double] */ +HMATH_API hmath_status hmath_image_image_values(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.pixel :: Image -> [Int] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_image_pixel(hmath_context *context, const hmath_value *image, const hmath_value *coordinates, hmath_value **out); +/* HMath.Image.Core.channel :: Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_channel(hmath_context *context, const hmath_value *index, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.combineChannels :: [Image] -> Either MathError Image */ +HMATH_API hmath_status hmath_image_combine_channels(hmath_context *context, const hmath_value *images, hmath_value **out); +/* HMath.Image.Core.mapImage :: (Double -> Double) -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_map_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.zipImage :: (Double -> Double -> Double) -> Image -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_zip_image(hmath_context *context, hmath_image_callback function, void *userdata, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Image.Core.normalize :: Double -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_normalize(hmath_context *context, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.brightness :: Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_brightness(hmath_context *context, const hmath_value *offset, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.contrast :: Double -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_contrast(hmath_context *context, const hmath_value *factor, const hmath_value *pivot, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.gamma :: Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_gamma(hmath_context *context, const hmath_value *power, const hmath_value *image, hmath_value **out); +/* HMath.Image.Core.Constant :: Double -> Boundary */ +HMATH_API hmath_status hmath_image_constant(hmath_context *context, const hmath_value *fill, hmath_value **out); +/* HMath.Image.Core.Clamp :: Boundary */ +HMATH_API hmath_status hmath_image_clamp(hmath_context *context, hmath_value **out); +/* HMath.Image.Core.Reflect :: Boundary */ +HMATH_API hmath_status hmath_image_reflect(hmath_context *context, hmath_value **out); +/* HMath.Image.Core.Wrap :: Boundary */ +HMATH_API hmath_status hmath_image_wrap(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.convolve :: Boundary -> [Int] -> [Double] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_convolve(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.correlate :: Boundary -> [Int] -> [Double] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_correlate(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *weights, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.gaussianBlur :: Boundary -> Double -> Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_gaussian_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.boxBlur :: Boundary -> Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_box_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.medianBlur :: Boundary -> Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_median_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.bilateralBlur :: Boundary -> Double -> Double -> Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_bilateral_blur(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma_space, const hmath_value *sigma_range, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.sharpen :: Boundary -> Double -> Double -> Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_sharpen(hmath_context *context, const hmath_value *boundary, const hmath_value *amount, const hmath_value *sigma, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.gradient :: GradientOperator -> Boundary -> Image -> Either MathError (Image, Image, Image, Image) */ +HMATH_API hmath_status hmath_image_gradient(hmath_context *context, const hmath_value *method, const hmath_value *boundary, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.laplacian :: Boundary -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_laplacian(hmath_context *context, const hmath_value *boundary, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.canny :: Boundary -> Double -> Int -> Double -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_canny(hmath_context *context, const hmath_value *boundary, const hmath_value *sigma, const hmath_value *radius, const hmath_value *low, const hmath_value *high, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.morphology :: Morphology -> Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_morphology(hmath_context *context, const hmath_value *operation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.morphologicalGradient :: Boundary -> [Int] -> [Bool] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_morphological_gradient(hmath_context *context, const hmath_value *boundary, const hmath_value *shape, const hmath_value *mask, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.validateBoundary :: Boundary -> Either MathError () */ +HMATH_API hmath_status hmath_image_validate_boundary(hmath_context *context, const hmath_value *boundary, hmath_value **out); +/* HMath.Image.Filter.scalar2D :: Image -> Either MathError (Int, Int) */ +HMATH_API hmath_status hmath_image_scalar2_d(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.windowOffsets :: Int -> Image -> Either MathError [[Int]] */ +HMATH_API hmath_status hmath_image_window_offsets(hmath_context *context, const hmath_value *radius, const hmath_value *image, hmath_value **out); +/* HMath.Image.Filter.Sobel :: GradientOperator */ +HMATH_API hmath_status hmath_image_sobel(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Prewitt :: GradientOperator */ +HMATH_API hmath_status hmath_image_prewitt(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Scharr :: GradientOperator */ +HMATH_API hmath_status hmath_image_scharr(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Erosion :: Morphology */ +HMATH_API hmath_status hmath_image_erosion(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Dilation :: Morphology */ +HMATH_API hmath_status hmath_image_dilation(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Opening :: Morphology */ +HMATH_API hmath_status hmath_image_opening(hmath_context *context, hmath_value **out); +/* HMath.Image.Filter.Closing :: Morphology */ +HMATH_API hmath_status hmath_image_closing(hmath_context *context, hmath_value **out); +/* HMath.Image.Histogram.histogram :: Int -> Image -> Either MathError [[Int]] */ +HMATH_API hmath_status hmath_image_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +/* HMath.Image.Histogram.equalizeHistogram :: Int -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_equalize_histogram(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +/* HMath.Image.Histogram.clahe :: Int -> (Int, Int) -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_clahe(hmath_context *context, const hmath_value *bins, const hmath_value *tiles, const hmath_value *clip_limit, const hmath_value *image, hmath_value **out); +/* HMath.Image.Histogram.threshold :: Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_threshold(hmath_context *context, const hmath_value *level, const hmath_value *image, hmath_value **out); +/* HMath.Image.Histogram.otsu :: Int -> Image -> Either MathError ([Double], Image) */ +HMATH_API hmath_status hmath_image_otsu(hmath_context *context, const hmath_value *bins, const hmath_value *image, hmath_value **out); +/* HMath.Image.Histogram.adaptiveThreshold :: Bool -> Boundary -> Int -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_adaptive_threshold(hmath_context *context, const hmath_value *gaussian, const hmath_value *boundary, const hmath_value *radius, const hmath_value *offset, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.templateMatch :: TemplateMetric -> Image -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_template_match(hmath_context *context, const hmath_value *metric, const hmath_value *needle, const hmath_value *haystack, hmath_value **out); +/* HMath.Image.Measure.rawMoment :: Int -> Int -> Image -> Either MathError Double */ +HMATH_API hmath_status hmath_image_raw_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.centralMoment :: Int -> Int -> Image -> Either MathError Double */ +HMATH_API hmath_status hmath_image_central_moment(hmath_context *context, const hmath_value *row_order, const hmath_value *column_order, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.imageCentroid :: Image -> Either MathError (Double, Double) */ +HMATH_API hmath_status hmath_image_image_centroid(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.integralImage :: Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_integral_image(hmath_context *context, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.rectangleSum :: (Int, Int) -> (Int, Int) -> Image -> Either MathError [Double] */ +HMATH_API hmath_status hmath_image_rectangle_sum(hmath_context *context, const hmath_value *origin, const hmath_value *extent, const hmath_value *image, hmath_value **out); +/* HMath.Image.Measure.meanSquaredError :: Image -> Image -> Either MathError Double */ +HMATH_API hmath_status hmath_image_mean_squared_error(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Image.Measure.peakSignalToNoise :: Double -> Image -> Image -> Either MathError Double */ +HMATH_API hmath_status hmath_image_peak_signal_to_noise(hmath_context *context, const hmath_value *data_range, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Image.Measure.structuralSimilarity :: Double -> Int -> Image -> Image -> Either MathError Double */ +HMATH_API hmath_status hmath_image_structural_similarity(hmath_context *context, const hmath_value *data_range, const hmath_value *window, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Image.Measure.SquaredDifference :: TemplateMetric */ +HMATH_API hmath_status hmath_image_squared_difference(hmath_context *context, hmath_value **out); +/* HMath.Image.Measure.NormalizedCorrelation :: TemplateMetric */ +HMATH_API hmath_status hmath_image_normalized_correlation(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.resize :: Interpolation -> Boundary -> (Int, Int) -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_resize(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.warp :: Interpolation -> Boundary -> (Int, Int) -> [[Double]] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_warp(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *shape, const hmath_value *matrix, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.translate :: Interpolation -> Boundary -> Double -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_translate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *row_shift, const hmath_value *column_shift, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.rotate :: Interpolation -> Boundary -> Double -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_rotate(hmath_context *context, const hmath_value *interpolation, const hmath_value *boundary, const hmath_value *angle, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.connectedComponents :: Connectivity -> Image -> Either MathError (Image, [Int]) */ +HMATH_API hmath_status hmath_image_connected_components(hmath_context *context, const hmath_value *connectivity, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.distanceTransform :: [Double] -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_distance_transform(hmath_context *context, const hmath_value *spacing, const hmath_value *image, hmath_value **out); +/* HMath.Image.Spatial.Nearest :: Interpolation */ +HMATH_API hmath_status hmath_image_nearest(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.Bilinear :: Interpolation */ +HMATH_API hmath_status hmath_image_bilinear(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.Bicubic :: Interpolation */ +HMATH_API hmath_status hmath_image_bicubic(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.Lanczos :: Interpolation */ +HMATH_API hmath_status hmath_image_lanczos(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.AxisConnected :: Connectivity */ +HMATH_API hmath_status hmath_image_axis_connected(hmath_context *context, hmath_value **out); +/* HMath.Image.Spatial.FullyConnected :: Connectivity */ +HMATH_API hmath_status hmath_image_fully_connected(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.convertColor :: ColorSpace -> ColorSpace -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_convert_color(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *image, hmath_value **out); +/* HMath.Image.Color.grayscale :: ColorSpace -> Image -> Either MathError Image */ +HMATH_API hmath_status hmath_image_grayscale(hmath_context *context, const hmath_value *source, const hmath_value *image, hmath_value **out); +/* HMath.Image.Color.SRGB :: ColorSpace */ +HMATH_API hmath_status hmath_image_srgb(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.LinearRGB :: ColorSpace */ +HMATH_API hmath_status hmath_image_linear_rgb(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.HSV :: ColorSpace */ +HMATH_API hmath_status hmath_image_hsv(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.HSL :: ColorSpace */ +HMATH_API hmath_status hmath_image_hsl(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.XYZ :: ColorSpace */ +HMATH_API hmath_status hmath_image_xyz(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.Lab :: ColorSpace */ +HMATH_API hmath_status hmath_image_lab(hmath_context *context, hmath_value **out); +/* HMath.Image.Color.YCbCr :: ColorSpace */ +HMATH_API hmath_status hmath_image_y_cb_cr(hmath_context *context, hmath_value **out); +/* HMath.Tensor.tensor :: [Int] -> [Double] -> Either MathError Tensor Double */ +HMATH_API hmath_status hmath_image_tensor(hmath_context *context, const hmath_value *shape, const hmath_value *values, hmath_value **out); +/* HMath.Tensor.tensorShape :: Tensor Double -> [Int] */ +HMATH_API hmath_status hmath_image_tensor_shape(hmath_context *context, const hmath_value *tensor, hmath_value **out); +/* HMath.Tensor.tensorValues :: Tensor Double -> [Double] */ +HMATH_API hmath_status hmath_image_tensor_values(hmath_context *context, const hmath_value *tensor, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_interchange.h b/include/hmath_interchange.h new file mode 100644 index 0000000..48994b1 --- /dev/null +++ b/include/hmath_interchange.h @@ -0,0 +1,217 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_interchange_bindings.py. */ +#ifndef HMATH_INTERCHANGE_H +#define HMATH_INTERCHANGE_H +#include "hmath_bytes.h" +#include "hmath_callback.h" +#include "hmath_interchange_error.h" +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original fixed-width array formats, Element dictionaries, IO and scoped + * mappings. All inputs are borrowed Value handles; each successful output owns + * one reference. Failure leaves output pointers untouched. Source Left errors + * return13 with hmath_last_interchange_error, not MathError. Callbacks use the + * common kind101 tuple-argument protocol and may reenter checked APIs. Mapping + * reads are valid only during withMappedArray; original retired-capability + * checks reject reads after exit. Bytes copies can survive that scope. + * File writes retain original partial-write/encoding-before-write semantics. + * Typed Element operations take a scalar/Boolean prototype first, selecting + * exactly one of the original13 fixed-width dictionaries. */ +typedef hmath_value hmath_interchange_array_object; /* kind451 */ +typedef hmath_value hmath_interchange_interchange_error_object; /* kind453 */ +typedef hmath_value hmath_interchange_limits_object; /* kind457 */ +typedef hmath_value hmath_interchange_d_type_object; /* kind458 */ +typedef hmath_value hmath_interchange_endian_object; /* kind459 */ +typedef hmath_value hmath_interchange_order_object; /* kind460 */ +typedef hmath_value hmath_interchange_compression_object; /* kind461 */ +typedef hmath_value hmath_interchange_raw_spec_object; /* kind462 */ +typedef hmath_value hmath_interchange_mapped_array_object; /* kind465 */ +/* HMath.Interchange.Array.BigEndian :: Endian */ +HMATH_API hmath_status hmath_interchange_value_big_endian(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.Bool8 :: DType */ +HMATH_API hmath_status hmath_interchange_value_bool8(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.C128 :: DType */ +HMATH_API hmath_status hmath_interchange_value_c128(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.C64 :: DType */ +HMATH_API hmath_status hmath_interchange_value_c64(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.COrder :: Order */ +HMATH_API hmath_status hmath_interchange_value_c_order(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.F32 :: DType */ +HMATH_API hmath_status hmath_interchange_value_f32(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.F64 :: DType */ +HMATH_API hmath_status hmath_interchange_value_f64(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.FOrder :: Order */ +HMATH_API hmath_status hmath_interchange_value_f_order(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.I16 :: DType */ +HMATH_API hmath_status hmath_interchange_value_i16(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.I32 :: DType */ +HMATH_API hmath_status hmath_interchange_value_i32(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.I64 :: DType */ +HMATH_API hmath_status hmath_interchange_value_i64(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.I8 :: DType */ +HMATH_API hmath_status hmath_interchange_value_i8(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.InterchangeIOError :: String -> InterchangeError */ +HMATH_API hmath_status hmath_interchange_value_interchange_io_error(hmath_context *context, const hmath_value *message, hmath_value **out); +/* HMath.Interchange.Array.InvalidData :: String -> InterchangeError */ +HMATH_API hmath_status hmath_interchange_value_invalid_data(hmath_context *context, const hmath_value *message, hmath_value **out); +/* HMath.Interchange.Array.LimitExceeded :: String -> InterchangeError */ +HMATH_API hmath_status hmath_interchange_value_limit_exceeded(hmath_context *context, const hmath_value *message, hmath_value **out); +/* HMath.Interchange.Array.Limits :: Int -> Int -> Int -> Int -> Int -> Limits */ +HMATH_API hmath_status hmath_interchange_value_limits(hmath_context *context, const hmath_value *max_bytes, const hmath_value *max_elements, const hmath_value *max_rank, const hmath_value *max_metadata, const hmath_value *max_archive_entries, hmath_value **out); +/* HMath.Interchange.Array.LittleEndian :: Endian */ +HMATH_API hmath_status hmath_interchange_value_little_endian(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.U16 :: DType */ +HMATH_API hmath_status hmath_interchange_value_u16(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.U32 :: DType */ +HMATH_API hmath_status hmath_interchange_value_u32(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.U64 :: DType */ +HMATH_API hmath_status hmath_interchange_value_u64(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.U8 :: DType */ +HMATH_API hmath_status hmath_interchange_value_u8(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.Unsupported :: String -> InterchangeError */ +HMATH_API hmath_status hmath_interchange_value_unsupported(hmath_context *context, const hmath_value *message, hmath_value **out); +/* HMath.Interchange.Array.array :: Limits -> DType -> Endian -> [Int] -> [Int] -> Int -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *sh, const hmath_value *st, const hmath_value *off, const hmath_value *bs, hmath_value **out); +/* HMath.Interchange.Array.arrayBytes :: Array -> ByteString */ +HMATH_API hmath_status hmath_interchange_value_array_bytes(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayDType :: Array -> DType */ +HMATH_API hmath_status hmath_interchange_value_array_d_type(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayEndian :: Array -> Endian */ +HMATH_API hmath_status hmath_interchange_value_array_endian(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayMetadata :: Array -> [(String, String)] */ +HMATH_API hmath_status hmath_interchange_value_array_metadata(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayOffset :: Array -> Int */ +HMATH_API hmath_status hmath_interchange_value_array_offset(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayShape :: Array -> [Int] */ +HMATH_API hmath_status hmath_interchange_value_array_shape(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.arrayStrides :: Array -> [Int] */ +HMATH_API hmath_status hmath_interchange_value_array_strides(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.contiguousArray :: Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_contiguous_array(hmath_context *context, const hmath_value *lim, const hmath_value *dt, const hmath_value *en, const hmath_value *order, const hmath_value *sh, const hmath_value *bs, hmath_value **out); +/* HMath.Interchange.Array.defaultLimits :: Limits */ +HMATH_API hmath_status hmath_interchange_value_default_limits(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Array.denseStrides :: Order -> Int -> [Int] -> [Int] */ +HMATH_API hmath_status hmath_interchange_value_dense_strides(hmath_context *context, const hmath_value *c_order, const hmath_value *w, const hmath_value *sh, hmath_value **out); +/* HMath.Interchange.Array.elementBytes :: DType -> Int */ +HMATH_API hmath_status hmath_interchange_value_element_bytes(hmath_context *context, const hmath_value *dt, hmath_value **out); +/* HMath.Interchange.Array.elementCount :: Array -> Int */ +HMATH_API hmath_status hmath_interchange_value_element_count(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.elementType :: Element a => proxy a -> DType */ +HMATH_API hmath_status hmath_interchange_value_element_type(hmath_context *context, const hmath_value *prototype, hmath_value **out); +/* HMath.Interchange.Array.fromMatrix :: Element a => Limits -> Endian -> HMath.Matrix.Matrix a -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_from_matrix(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interchange.Array.fromTensor :: Element a => Limits -> Endian -> HMath.Tensor.Tensor a -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_from_tensor(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interchange.Array.fromValues :: Element a => Limits -> Endian -> [Int] -> [a] -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_from_values(hmath_context *context, const hmath_value *prototype, const hmath_value *limits, const hmath_value *endian, const hmath_value *shape, const hmath_value *values, hmath_value **out); +/* HMath.Interchange.Array.getElement :: Element a => Endian -> Data.Binary.Get.Internal.Get a */ +HMATH_API hmath_status hmath_interchange_value_get_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, hmath_value **out); +/* HMath.Interchange.Array.maxArchiveEntries :: Limits -> Int */ +HMATH_API hmath_status hmath_interchange_value_max_archive_entries(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.maxBytes :: Limits -> Int */ +HMATH_API hmath_status hmath_interchange_value_max_bytes(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.maxElements :: Limits -> Int */ +HMATH_API hmath_status hmath_interchange_value_max_elements(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.maxMetadata :: Limits -> Int */ +HMATH_API hmath_status hmath_interchange_value_max_metadata(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.maxRank :: Limits -> Int */ +HMATH_API hmath_status hmath_interchange_value_max_rank(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.putElement :: Element a => Endian -> a -> Data.Binary.Put.Put */ +HMATH_API hmath_status hmath_interchange_value_put_element(hmath_context *context, const hmath_value *prototype, const hmath_value *endian, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Array.rawDecode :: Limits -> DType -> Endian -> Order -> [Int] -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_raw_decode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +/* HMath.Interchange.Array.rawEncode :: Limits -> Endian -> Order -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_raw_encode(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.Interchange.Array.repack :: Limits -> Endian -> Order -> Array -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_repack(hmath_context *context, const hmath_value *lim, const hmath_value *en, const hmath_value *order, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Array.toMatrix :: Element a => Array -> Either InterchangeError (HMath.Matrix.Matrix a) */ +HMATH_API hmath_status hmath_interchange_value_to_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +/* HMath.Interchange.Array.toTensor :: Element a => Array -> Either InterchangeError (HMath.Tensor.Tensor a) */ +HMATH_API hmath_status hmath_interchange_value_to_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +/* HMath.Interchange.Array.toValues :: Element a => Array -> Either InterchangeError [a] */ +HMATH_API hmath_status hmath_interchange_value_to_values(hmath_context *context, const hmath_value *prototype, const hmath_value *array, hmath_value **out); +/* HMath.Interchange.Array.validateShape :: Limits -> [Int] -> Either InterchangeError Int */ +HMATH_API hmath_status hmath_interchange_value_validate_shape(hmath_context *context, const hmath_value *lim, const hmath_value *sh, hmath_value **out); +/* HMath.Interchange.Array.withMetadata :: Limits -> [(String, String)] -> Array -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_with_metadata(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interchange.Binary.crc32 :: ByteString -> Word32 */ +HMATH_API hmath_status hmath_interchange_value_crc32(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interchange.Binary.decodeBinary :: Limits -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_decode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +/* HMath.Interchange.Binary.encodeBinary :: Limits -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_encode_binary(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Compression.Gzip :: Compression */ +HMATH_API hmath_status hmath_interchange_value_gzip(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Compression.RawDeflate :: Compression */ +HMATH_API hmath_status hmath_interchange_value_raw_deflate(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Compression.Zlib :: Compression */ +HMATH_API hmath_status hmath_interchange_value_zlib(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Compression.compress :: Limits -> Compression -> ByteString -> IO (Either InterchangeError ByteString) */ +HMATH_API hmath_status hmath_interchange_value_compress(hmath_context *context, const hmath_value *lim, const hmath_value *wrapper, const hmath_value *input, hmath_value **out); +/* HMath.Interchange.Compression.compressionAvailable :: IO Bool */ +HMATH_API hmath_status hmath_interchange_value_compression_available(hmath_context *context, hmath_value **out); +/* HMath.Interchange.Compression.decompress :: Limits -> Compression -> Int -> ByteString -> IO (Either InterchangeError ByteString) */ +HMATH_API hmath_status hmath_interchange_value_decompress(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.Interchange.IO.RawSpec :: DType -> Endian -> Order -> [Int] -> RawSpec */ +HMATH_API hmath_status hmath_interchange_value_raw_spec(hmath_context *context, const hmath_value *dtype, const hmath_value *endian, const hmath_value *order, const hmath_value *shape, hmath_value **out); +/* HMath.Interchange.IO.mappedReadBytes :: forall {k} (s :: k). MappedArray s -> Int -> Int -> IO (Either InterchangeError ByteString) */ +HMATH_API hmath_status hmath_interchange_value_mapped_read_bytes(hmath_context *context, const hmath_value *mapping, const hmath_value *offset, const hmath_value *count, hmath_value **out); +/* HMath.Interchange.IO.mappedShape :: forall {k} (s :: k). MappedArray s -> [Int] */ +HMATH_API hmath_status hmath_interchange_value_mapped_shape(hmath_context *context, const hmath_value *mapping, hmath_value **out); +/* HMath.Interchange.IO.mappedValue :: forall {k} a (s :: k). Element a => MappedArray s -> [Int] -> IO (Either InterchangeError a) */ +HMATH_API hmath_status hmath_interchange_value_mapped_value(hmath_context *context, const hmath_value *prototype, const hmath_value *mapping, const hmath_value *indices, hmath_value **out); +/* HMath.Interchange.IO.readArrayFile :: Limits -> (ByteString -> Either InterchangeError Array) -> FilePath -> IO (Either InterchangeError Array) */ +HMATH_API hmath_status hmath_interchange_value_read_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *decode, const hmath_value *path, hmath_value **out); +/* HMath.Interchange.IO.readRawChunks :: Limits -> RawSpec -> Int -> Handle -> (Array -> IO (Either InterchangeError Bool)) -> IO (Either InterchangeError ()) */ +HMATH_API hmath_status hmath_interchange_value_read_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.Interchange.IO.withMappedArray :: Limits -> RawSpec -> FilePath -> (forall (s :: k). MappedArray s -> IO a) -> IO (Either InterchangeError a) */ +HMATH_API hmath_status hmath_interchange_value_with_mapped_array(hmath_context *context, const hmath_value *limits, const hmath_value *specification, const hmath_value *path, const hmath_value *callback, hmath_value **out); +/* HMath.Interchange.IO.writeArrayFile :: Limits -> (Limits -> Array -> Either InterchangeError ByteString) -> FilePath -> Array -> IO (Either InterchangeError ()) */ +HMATH_API hmath_status hmath_interchange_value_write_array_file(hmath_context *context, const hmath_value *lim, const hmath_value *encode, const hmath_value *path, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.IO.writeRawChunks :: Limits -> RawSpec -> Int -> Handle -> (Int -> IO (Either InterchangeError (Maybe ByteString))) -> IO (Either InterchangeError ()) */ +HMATH_API hmath_status hmath_interchange_value_write_raw_chunks(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.Interchange.Numpy.decodeNpy :: Limits -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_decode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +/* HMath.Interchange.Numpy.decodeNpz :: Limits -> ByteString -> IO (Either InterchangeError [(String, Array)]) */ +HMATH_API hmath_status hmath_interchange_value_decode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *input, hmath_value **out); +/* HMath.Interchange.Numpy.encodeNpy :: Limits -> Order -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_encode_npy(hmath_context *context, const hmath_value *lim, const hmath_value *order, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Numpy.encodeNpz :: Limits -> Bool -> [(String, Array)] -> IO (Either InterchangeError ByteString) */ +HMATH_API hmath_status hmath_interchange_value_encode_npz(hmath_context *context, const hmath_value *lim, const hmath_value *compressed, const hmath_value *arrays, hmath_value **out); +/* HMath.Interchange.Text.decodeDelimited :: Limits -> Char -> DType -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_decode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *dt, const hmath_value *bs, hmath_value **out); +/* HMath.Interchange.Text.decodeMatrixMarket :: Limits -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_decode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out); +/* HMath.Interchange.Text.decodeText :: Limits -> ByteString -> Either InterchangeError Array */ +HMATH_API hmath_status hmath_interchange_value_decode_text(hmath_context *context, const hmath_value *lim, const hmath_value *bs, hmath_value **out); +/* HMath.Interchange.Text.encodeDelimited :: Limits -> Char -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_encode_delimited(hmath_context *context, const hmath_value *lim, const hmath_value *separator, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Text.encodeMatrixMarket :: Limits -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_encode_matrix_market(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Text.encodeText :: Limits -> Array -> Either InterchangeError ByteString */ +HMATH_API hmath_status hmath_interchange_value_encode_text(hmath_context *context, const hmath_value *lim, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Array.boundedInt :: String -> Integer -> Integer -> Either InterchangeError Int */ +HMATH_API hmath_status hmath_interchange_value_bounded_int(hmath_context *context, const hmath_value *name, const hmath_value *upper, const hmath_value *x, hmath_value **out); +/* HMath.Interchange.Array.byteOffsets :: Array -> [Int] */ +HMATH_API hmath_status hmath_interchange_value_byte_offsets(hmath_context *context, const hmath_value *a, hmath_value **out); +/* HMath.Interchange.Array.checkLimits :: Limits -> Either InterchangeError () */ +HMATH_API hmath_status hmath_interchange_value_check_limits(hmath_context *context, const hmath_value *lim, hmath_value **out); +/* HMath.Interchange.Array.guardI :: Bool -> InterchangeError -> Either InterchangeError () */ +HMATH_API hmath_status hmath_interchange_value_guard_i(hmath_context *context, const hmath_value *p, const hmath_value *e, hmath_value **out); +/* HMath.Interchange.Binary.runDecoder :: Get a -> ByteString -> Either InterchangeError a */ +HMATH_API hmath_status hmath_interchange_value_run_decoder(hmath_context *context, const hmath_value *parser, const hmath_value *data, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_dtype_code(hmath_context *context, const hmath_value *dtype, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_error_fields(hmath_context *context, const hmath_value *error, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_put_bytes(hmath_context *context, const hmath_value *program, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_open_handle(hmath_context *context, const hmath_value *path, const hmath_value *mode, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_close_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_seek_handle(hmath_context *context, const hmath_value *handle, const hmath_value *whence, const hmath_value *offset, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_tell_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_flush_handle(hmath_context *context, const hmath_value *handle, hmath_value **out); +HMATH_API hmath_status hmath_interchange_value_equal_array(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_interchange_error.h b/include/hmath_interchange_error.h new file mode 100644 index 0000000..7bbe1bf --- /dev/null +++ b/include/hmath_interchange_error.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_INTERCHANGE_ERROR_H +#define HMATH_INTERCHANGE_ERROR_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +typedef enum hmath_interchange_error_kind { + HMATH_INTERCHANGE_INVALID_DATA = 0, + HMATH_INTERCHANGE_UNSUPPORTED = 1, + HMATH_INTERCHANGE_LIMIT_EXCEEDED = 2, + HMATH_INTERCHANGE_IO_ERROR = 3 +} hmath_interchange_error_kind; +typedef struct hmath_interchange_error { + uint32_t kind; + const char *message; + size_t message_length; +} hmath_interchange_error; +/* Query only. Returns1 when status13's complete original payload is available. + * Message is borrowed until the next checked operation on this thread. Its + * explicit byte length preserves NUL; surrogate Char values use WTF8. */ +HMATH_API int hmath_last_interchange_error(hmath_interchange_error *out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_linear.h b/include/hmath_linear.h new file mode 100644 index 0000000..7bd35e4 --- /dev/null +++ b/include/hmath_linear.h @@ -0,0 +1,606 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_linear_bindings.py. */ +#ifndef HMATH_LINEAR_H +#define HMATH_LINEAR_H +#include "hmath_value.h" +#include "hmath_matrix.h" +#include "hmath_error.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Direct original Vector, Matrix advanced/decomposition/iterative/LAPACK, + * Sparse, Sparse.Spectral and Backend API. Values are immutable owned handles; + * Matrix uses Dense kind9, linear records use kind100 plus object_type query, + * and typed callback closures use kind101. Retain inputs for the call and + * release every owned result with hmath_value_release. Outputs remain untouched + * on failure. Generic functions take a typed scalar prototype before original + * arguments, even for empty lists. zip_matrix_with takes a tuple of prototypes + * (inputA,inputB,output). fixed_vector adds a runtime natural dimension that + * reifies the original KnownNat witness. Num/Fractional/Ord/RealFloat instance + * availability, defaults, resource limits, finite checks, ordering and errors + * remain the original Haskell operations. No mandatory native provider. + * Callback inputs borrow a Value; output transfers one owned reference. Source + * pure callbacks abort on nonzero status, preserving status11 MathError wire. + * Callback/userdata must outlive every function/derived object using them. */ +typedef hmath_status (*hmath_linear_callback_fn)(const hmath_value *input,void *userdata,hmath_value **out,hmath_math_error *error); +HMATH_API hmath_status hmath_linear_callback(hmath_context *context,hmath_linear_callback_fn callback,void *userdata,hmath_value **out); +HMATH_API hmath_status hmath_linear_object_type(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_linear_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +/* Convert original Backend LU/QR outputs to existing typed dense owners. */ +HMATH_API hmath_status hmath_linear_export_legacy(hmath_context *context,const hmath_value *value,void **out); +typedef hmath_value hmath_linear_vector_vector_object; +typedef hmath_value hmath_linear_vector_fixed_vector_object; +typedef hmath_value hmath_linear_vector_sparse_vector_object; +typedef hmath_value hmath_linear_decomposition_bidiagonal_object; +typedef hmath_value hmath_linear_decomposition_iteration_object; +typedef hmath_value hmath_linear_decomposition_arnoldi_object; +typedef hmath_value hmath_linear_iterative_iterative_options_object; +typedef hmath_value hmath_linear_iterative_iterative_result_object; +typedef hmath_value hmath_linear_iterative_preconditioner_object; +typedef hmath_value hmath_linear_lapack_svd_object; +typedef hmath_value hmath_linear_lapack_eigen_object; +typedef hmath_value hmath_linear_lapack_generalized_eigen_object; +typedef hmath_value hmath_linear_lapack_schur_object; +typedef hmath_value hmath_linear_lapack_qz_object; +typedef hmath_value hmath_linear_lapack_hessenberg_object; +typedef hmath_value hmath_linear_lapack_balance_object; +typedef hmath_value hmath_linear_lapack_complex_svd_object; +typedef hmath_value hmath_linear_sparse_sparse_object; +typedef hmath_value hmath_linear_sparse_sparse_format_object; +typedef hmath_value hmath_linear_sparse_sparse_lu_object; +typedef hmath_value hmath_linear_sparse_sparse_qr_object; +typedef hmath_value hmath_linear_sparse_sparse_tensor_object; +typedef hmath_value hmath_linear_sparse_spectral_sparse_spectral_options_object; +typedef hmath_value hmath_linear_sparse_spectral_sparse_eigen_result_object; +typedef hmath_value hmath_linear_sparse_spectral_sparse_svd_object; +typedef hmath_value hmath_linear_backend_provider_object; +typedef hmath_value hmath_linear_backend_integer_abi_object; +typedef hmath_value hmath_linear_backend_backend_request_object; +typedef hmath_value hmath_linear_backend_backend_info_object; +typedef hmath_value hmath_linear_backend_backend_object; +typedef hmath_value hmath_linear_backend_backend_layout_object; +typedef hmath_value hmath_linear_backend_transpose_object; +/* HMath.Vector.vector :: [a] -> Vector a */ +HMATH_API hmath_status hmath_linear_vector_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +/* HMath.Vector.vectorValues :: Vector a -> [a] */ +HMATH_API hmath_status hmath_linear_vector_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.vectorDimension :: Vector a -> Int */ +HMATH_API hmath_status hmath_linear_vector_vector_dimension(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.fixedVector :: [a] -> Either MathError (FixedVector n a) */ +HMATH_API hmath_status hmath_linear_vector_fixed_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out); +/* HMath.Vector.fixedValues :: FixedVector n a -> [a] */ +HMATH_API hmath_status hmath_linear_vector_fixed_values(hmath_context *context, const hmath_value *prototype, const hmath_value *fixed_vector1, hmath_value **out); +/* HMath.Vector.sparseVector :: Int -> [(Int, a)] -> Either MathError (SparseVector a) */ +HMATH_API hmath_status hmath_linear_vector_sparse_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *values2, hmath_value **out); +/* HMath.Vector.sparseVectorValues :: SparseVector a -> [a] */ +HMATH_API hmath_status hmath_linear_vector_sparse_vector_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_vector1, hmath_value **out); +/* HMath.Vector.vectorSlice :: Int -> Int -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_vector_slice(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *vector3, hmath_value **out); +/* HMath.Vector.vectorConcat :: [Vector a] -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_vector_concat(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +/* HMath.Vector.vectorAdd :: Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_vector_add(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.vectorSubtract :: Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_vector_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.vectorScale :: a -> Vector a -> Vector a */ +HMATH_API hmath_status hmath_linear_vector_vector_scale(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.vectorDot :: Vector a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_vector_dot(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.cross :: Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_cross(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.outer :: Vector a -> Vector a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_vector_outer(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.triple :: Vector a -> Vector a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_triple(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out); +/* HMath.Vector.norm0 :: Vector a -> Int */ +HMATH_API hmath_status hmath_linear_vector_norm0(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.norm1 :: Vector a -> a */ +HMATH_API hmath_status hmath_linear_vector_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.norm2 :: Vector a -> a */ +HMATH_API hmath_status hmath_linear_vector_norm2(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.normInfinity :: Vector a -> a */ +HMATH_API hmath_status hmath_linear_vector_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.normP :: a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_norm_p(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.normalizeVector :: Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_normalize_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, hmath_value **out); +/* HMath.Vector.project :: Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_project(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.reflect :: Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_reflect(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.refract :: a -> Vector a -> Vector a -> Either MathError (Vector a) */ +HMATH_API hmath_status hmath_linear_vector_refract(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *vector2, const hmath_value *vector3, hmath_value **out); +/* HMath.Vector.distance :: Vector a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_distance(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.cosineSimilarity :: Vector a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_cosine_similarity(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.angle :: Vector a -> Vector a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_vector_angle(hmath_context *context, const hmath_value *prototype, const hmath_value *vector1, const hmath_value *vector2, hmath_value **out); +/* HMath.Vector.gramSchmidt :: a -> [Vector a] -> Either MathError [Vector a] */ +HMATH_API hmath_status hmath_linear_vector_gram_schmidt(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, hmath_value **out); +/* HMath.Matrix.Advanced.generateMatrix :: Int -> Int -> (Int -> Int -> a) -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_generate_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *function3, hmath_value **out); +/* HMath.Matrix.Advanced.triangularMatrix :: Bool -> Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_triangular_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.symmetricMatrix :: Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_symmetric_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.hermitianMatrix :: Matrix (Complex a) -> Either MathError (Matrix (Complex a)) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_hermitian_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.permutationMatrix :: [Int] -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_permutation_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +/* HMath.Matrix.Advanced.blockMatrix :: [[Matrix a]] -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_block_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, hmath_value **out); +/* HMath.Matrix.Advanced.bandedMatrix :: Int -> Int -> [(Int, [a])] -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_banded_matrix(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +/* HMath.Matrix.Advanced.conjugateTranspose :: Matrix (Complex a) -> Matrix (Complex a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_conjugate_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.zipMatrixWith :: (a -> b -> c) -> Matrix a -> Matrix b -> Either MathError (Matrix c) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_zip_matrix_with(hmath_context *context, const hmath_value *prototype, const hmath_value *function1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Advanced.batchedMultiply :: [Matrix a] -> [Matrix a] -> Either MathError [Matrix a] */ +HMATH_API hmath_status hmath_linear_matrix_advanced_batched_multiply(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out); +/* HMath.Matrix.Advanced.kronecker :: Matrix a -> Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.khatriRao :: Matrix a -> Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_khatri_rao(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.matrixPower :: Integer -> Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_power(hmath_context *context, const hmath_value *prototype, const hmath_value *integer1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.trace :: Matrix a -> Either MathError a */ +HMATH_API hmath_status hmath_linear_matrix_advanced_trace(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.matrixNorm1 :: Matrix a -> a */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_norm1(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.matrixNormInfinity :: Matrix a -> a */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_norm_infinity(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.frobeniusNorm :: Matrix a -> a */ +HMATH_API hmath_status hmath_linear_matrix_advanced_frobenius_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.spectralNorm :: Matrix Double -> Either MathError Double */ +HMATH_API hmath_status hmath_linear_matrix_advanced_spectral_norm(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.matrixRank :: Double -> Matrix Double -> Either MathError Int */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_rank(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.pseudoinverse :: Double -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.conditionNumber :: Matrix Double -> Either MathError Double */ +HMATH_API hmath_status hmath_linear_matrix_advanced_condition_number(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.columnSpace :: Double -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_column_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.rowSpace :: Double -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_row_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.nullSpace :: Double -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_null_space(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.changeCoordinates :: Matrix a -> Matrix a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_matrix_advanced_change_coordinates(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +/* HMath.Matrix.Advanced.matrixExp :: a -> Int -> Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_exp(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Advanced.matrixLog :: Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_log(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.matrixSqrt :: Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_sqrt(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.polar :: Matrix Double -> Either MathError (Matrix Double, Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_polar(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Advanced.complexPseudoinverse :: Double -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_complex_pseudoinverse(hmath_context *context, const hmath_value *double1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Advanced.matrixSqrtGeneral :: Double -> Int -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_sqrt_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Advanced.matrixLogGeneral :: Double -> Int -> Matrix Double -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_linear_matrix_advanced_matrix_log_general(hmath_context *context, const hmath_value *double1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Decomposition.gaussianElimination :: a -> Matrix a -> Either MathError (Matrix a, [Int]) */ +HMATH_API hmath_status hmath_linear_decomposition_gaussian_elimination(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Decomposition.gaussJordan :: a -> Matrix a -> Either MathError (Matrix a, [Int]) */ +HMATH_API hmath_status hmath_linear_decomposition_gauss_jordan(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Decomposition.cholesky :: Matrix a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_decomposition_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Decomposition.ldlt :: Matrix a -> Either MathError (Matrix a, [a]) */ +HMATH_API hmath_status hmath_linear_decomposition_ldlt(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Decomposition.givensQR :: Matrix a -> Either MathError (Matrix a, Matrix a) */ +HMATH_API hmath_status hmath_linear_decomposition_givens_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Decomposition.bidiagonalize :: Matrix a -> Either MathError (Bidiagonal a) */ +HMATH_API hmath_status hmath_linear_decomposition_bidiagonalize(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Decomposition.tridiagonalize :: Matrix Double -> Either MathError (Matrix Double, Matrix Double) */ +HMATH_API hmath_status hmath_linear_decomposition_tridiagonalize(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Decomposition.powerIteration :: a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a) */ +HMATH_API hmath_status hmath_linear_decomposition_power_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Decomposition.inverseIteration :: a -> Int -> a -> Matrix a -> [a] -> Either MathError (Iteration a) */ +HMATH_API hmath_status hmath_linear_decomposition_inverse_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *matrix4, const hmath_value *values5, hmath_value **out); +/* HMath.Matrix.Decomposition.rayleighIteration :: a -> Int -> Matrix a -> [a] -> Either MathError (Iteration a) */ +HMATH_API hmath_status hmath_linear_decomposition_rayleigh_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Decomposition.arnoldi :: a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a) */ +HMATH_API hmath_status hmath_linear_decomposition_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Decomposition.lanczos :: a -> Int -> Matrix a -> [a] -> Either MathError (Arnoldi a) */ +HMATH_API hmath_status hmath_linear_decomposition_lanczos(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Decomposition.qrIteration :: a -> Int -> Matrix a -> Either MathError (Matrix a, Matrix a) */ +HMATH_API hmath_status hmath_linear_decomposition_qr_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *index2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Decomposition.jordanChains :: a -> Matrix a -> [(a, [[a]])] -> Either MathError (Matrix a, Matrix a) */ +HMATH_API hmath_status hmath_linear_decomposition_jordan_chains(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +/* HMath.Matrix.Decomposition.jordanForm :: Matrix Rational -> [Rational] -> Either MathError (Matrix Rational, Matrix Rational) */ +HMATH_API hmath_status hmath_linear_decomposition_jordan_form(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out); +/* HMath.Matrix.Decomposition.bidiagonalU :: Bidiagonal -> field */ +HMATH_API hmath_status hmath_linear_decomposition_bidiagonal_u(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +/* HMath.Matrix.Decomposition.bidiagonalB :: Bidiagonal -> field */ +HMATH_API hmath_status hmath_linear_decomposition_bidiagonal_b(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +/* HMath.Matrix.Decomposition.bidiagonalV :: Bidiagonal -> field */ +HMATH_API hmath_status hmath_linear_decomposition_bidiagonal_v(hmath_context *context, const hmath_value *prototype, const hmath_value *bidiagonal1, hmath_value **out); +/* HMath.Matrix.Decomposition.Bidiagonal :: constructor */ +HMATH_API hmath_status hmath_linear_decomposition_new_bidiagonal(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.Decomposition.iterationValue :: Iteration -> field */ +HMATH_API hmath_status hmath_linear_decomposition_iteration_value(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +/* HMath.Matrix.Decomposition.iterationVector :: Iteration -> field */ +HMATH_API hmath_status hmath_linear_decomposition_iteration_vector(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +/* HMath.Matrix.Decomposition.iterationResidual :: Iteration -> field */ +HMATH_API hmath_status hmath_linear_decomposition_iteration_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +/* HMath.Matrix.Decomposition.iterationCount :: Iteration -> field */ +HMATH_API hmath_status hmath_linear_decomposition_iteration_count(hmath_context *context, const hmath_value *prototype, const hmath_value *iteration1, hmath_value **out); +/* HMath.Matrix.Decomposition.Iteration :: constructor */ +HMATH_API hmath_status hmath_linear_decomposition_new_iteration(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out); +/* HMath.Matrix.Decomposition.arnoldiBasis :: Arnoldi -> field */ +HMATH_API hmath_status hmath_linear_decomposition_arnoldi_basis(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out); +/* HMath.Matrix.Decomposition.arnoldiHessenberg :: Arnoldi -> field */ +HMATH_API hmath_status hmath_linear_decomposition_arnoldi_hessenberg(hmath_context *context, const hmath_value *prototype, const hmath_value *arnoldi1, hmath_value **out); +/* HMath.Matrix.Decomposition.Arnoldi :: constructor */ +HMATH_API hmath_status hmath_linear_decomposition_new_arnoldi(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Iterative.defaultIterativeOptions :: IterativeOptions a */ +HMATH_API hmath_status hmath_linear_iterative_default_iterative_options(hmath_context *context, const hmath_value *prototype, hmath_value **out); +/* HMath.Matrix.Iterative.applyPreconditioner :: Preconditioner a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_iterative_apply_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *preconditioner1, const hmath_value *values2, hmath_value **out); +/* HMath.Matrix.Iterative.identityPreconditioner :: Int -> Either MathError (Preconditioner a) */ +HMATH_API hmath_status hmath_linear_iterative_identity_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, hmath_value **out); +/* HMath.Matrix.Iterative.jacobiPreconditioner :: Matrix a -> Either MathError (Preconditioner a) */ +HMATH_API hmath_status hmath_linear_iterative_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Iterative.blockJacobiPreconditioner :: [Int] -> Matrix a -> Either MathError (Preconditioner a) */ +HMATH_API hmath_status hmath_linear_iterative_block_jacobi_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.Iterative.ilu0Preconditioner :: Matrix a -> Either MathError (Preconditioner a) */ +HMATH_API hmath_status hmath_linear_iterative_ilu0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Iterative.ic0Preconditioner :: Matrix a -> Either MathError (Preconditioner a) */ +HMATH_API hmath_status hmath_linear_iterative_ic0_preconditioner(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.Iterative.conjugateGradient :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_conjugate_gradient(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.preconditionedCG :: IterativeOptions a -> Preconditioner a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_preconditioned_cg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *preconditioner2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Matrix.Iterative.gmres :: IterativeOptions a -> Int -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_gmres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *index2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Matrix.Iterative.minres :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_minres(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.bicg :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_bicg(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.bicgstab :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_bicgstab(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.lsqr :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_lsqr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.lsmr :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_lsmr(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.jacobiSolve :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_jacobi_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.gaussSeidelSolve :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_gauss_seidel_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.sorSolve :: IterativeOptions a -> a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_sor_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *scalar2, const hmath_value *matrix3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Matrix.Iterative.iterativeRefinement :: IterativeOptions a -> Matrix a -> [a] -> [a] -> Either MathError (IterativeResult a) */ +HMATH_API hmath_status hmath_linear_iterative_iterative_refinement(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, const hmath_value *matrix2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Matrix.Iterative.absoluteTolerance :: IterativeOptions -> field */ +HMATH_API hmath_status hmath_linear_iterative_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +/* HMath.Matrix.Iterative.relativeTolerance :: IterativeOptions -> field */ +HMATH_API hmath_status hmath_linear_iterative_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +/* HMath.Matrix.Iterative.maximumIterations :: IterativeOptions -> field */ +HMATH_API hmath_status hmath_linear_iterative_maximum_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_options1, hmath_value **out); +/* HMath.Matrix.Iterative.IterativeOptions :: constructor */ +HMATH_API hmath_status hmath_linear_iterative_new_iterative_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, hmath_value **out); +/* HMath.Matrix.Iterative.iterativeSolution :: IterativeResult -> field */ +HMATH_API hmath_status hmath_linear_iterative_iterative_solution(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +/* HMath.Matrix.Iterative.iterativeIterations :: IterativeResult -> field */ +HMATH_API hmath_status hmath_linear_iterative_iterative_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +/* HMath.Matrix.Iterative.iterativeResidualNorm :: IterativeResult -> field */ +HMATH_API hmath_status hmath_linear_iterative_iterative_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +/* HMath.Matrix.Iterative.iterativeNormalResidualNorm :: IterativeResult -> field */ +HMATH_API hmath_status hmath_linear_iterative_iterative_normal_residual_norm(hmath_context *context, const hmath_value *prototype, const hmath_value *iterative_result1, hmath_value **out); +/* HMath.Matrix.Iterative.IterativeResult :: constructor */ +HMATH_API hmath_status hmath_linear_iterative_new_iterative_result(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *index2, const hmath_value *scalar3, const hmath_value *scalar4, hmath_value **out); +/* HMath.Matrix.LAPACK.svd :: Matrix Double -> Either MathError SVD */ +HMATH_API hmath_status hmath_linear_lapack_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.fullSVD :: Matrix Double -> Either MathError SVD */ +HMATH_API hmath_status hmath_linear_lapack_full_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.truncatedSVD :: Int -> Matrix Double -> Either MathError SVD */ +HMATH_API hmath_status hmath_linear_lapack_truncated_svd(hmath_context *context, const hmath_value *index1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.LAPACK.randomizedSVD :: Int -> Int -> Int -> Integer -> Matrix Double -> Either MathError SVD */ +HMATH_API hmath_status hmath_linear_lapack_randomized_svd(hmath_context *context, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *integer4, const hmath_value *matrix5, hmath_value **out); +/* HMath.Matrix.LAPACK.eigen :: Matrix Double -> Either MathError Eigen */ +HMATH_API hmath_status hmath_linear_lapack_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.symmetricEigen :: Matrix Double -> Either MathError Eigen */ +HMATH_API hmath_status hmath_linear_lapack_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.generalizedEigen :: Matrix Double -> Matrix Double -> Either MathError GeneralizedEigen */ +HMATH_API hmath_status hmath_linear_lapack_generalized_eigen(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.LAPACK.schur :: Matrix Double -> Either MathError Schur */ +HMATH_API hmath_status hmath_linear_lapack_schur(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.qz :: Matrix Double -> Matrix Double -> Either MathError QZ */ +HMATH_API hmath_status hmath_linear_lapack_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.LAPACK.hessenberg :: Matrix Double -> Either MathError Hessenberg */ +HMATH_API hmath_status hmath_linear_lapack_hessenberg(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.balance :: Matrix Double -> Either MathError Balance */ +HMATH_API hmath_status hmath_linear_lapack_balance(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.complexSVD :: Matrix (Complex Double) -> Either MathError ComplexSVD */ +HMATH_API hmath_status hmath_linear_lapack_complex_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.complexEigen :: Matrix (Complex Double) -> Either MathError Eigen */ +HMATH_API hmath_status hmath_linear_lapack_complex_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Matrix.LAPACK.svdU :: SVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_svd_u(hmath_context *context, const hmath_value *svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.singularValues :: SVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_singular_values(hmath_context *context, const hmath_value *svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.svdVT :: SVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_svd_vt(hmath_context *context, const hmath_value *svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.SVD :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.LAPACK.eigenvalues :: Eigen -> field */ +HMATH_API hmath_status hmath_linear_lapack_eigenvalues(hmath_context *context, const hmath_value *eigen1, hmath_value **out); +/* HMath.Matrix.LAPACK.eigenvectors :: Eigen -> field */ +HMATH_API hmath_status hmath_linear_lapack_eigenvectors(hmath_context *context, const hmath_value *eigen1, hmath_value **out); +/* HMath.Matrix.LAPACK.Eigen :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.LAPACK.eigenAlpha :: GeneralizedEigen -> field */ +HMATH_API hmath_status hmath_linear_lapack_eigen_alpha(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +/* HMath.Matrix.LAPACK.eigenBeta :: GeneralizedEigen -> field */ +HMATH_API hmath_status hmath_linear_lapack_eigen_beta(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +/* HMath.Matrix.LAPACK.generalizedEigenvectors :: GeneralizedEigen -> field */ +HMATH_API hmath_status hmath_linear_lapack_generalized_eigenvectors(hmath_context *context, const hmath_value *generalized_eigen1, hmath_value **out); +/* HMath.Matrix.LAPACK.GeneralizedEigen :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_generalized_eigen(hmath_context *context, const hmath_value *values1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Matrix.LAPACK.schurQ :: Schur -> field */ +HMATH_API hmath_status hmath_linear_lapack_schur_q(hmath_context *context, const hmath_value *schur1, hmath_value **out); +/* HMath.Matrix.LAPACK.schurT :: Schur -> field */ +HMATH_API hmath_status hmath_linear_lapack_schur_t(hmath_context *context, const hmath_value *schur1, hmath_value **out); +/* HMath.Matrix.LAPACK.schurEigenvalues :: Schur -> field */ +HMATH_API hmath_status hmath_linear_lapack_schur_eigenvalues(hmath_context *context, const hmath_value *schur1, hmath_value **out); +/* HMath.Matrix.LAPACK.Schur :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_schur(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +/* HMath.Matrix.LAPACK.qzQ :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_q(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.qzZ :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_z(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.qzS :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_s(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.qzT :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_t(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.qzAlpha :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_alpha(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.qzBeta :: QZ -> field */ +HMATH_API hmath_status hmath_linear_lapack_qz_beta(hmath_context *context, const hmath_value *qz1, hmath_value **out); +/* HMath.Matrix.LAPACK.QZ :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_qz(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, const hmath_value *matrix3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *values6, hmath_value **out); +/* HMath.Matrix.LAPACK.hessenbergQ :: Hessenberg -> field */ +HMATH_API hmath_status hmath_linear_lapack_hessenberg_q(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out); +/* HMath.Matrix.LAPACK.hessenbergH :: Hessenberg -> field */ +HMATH_API hmath_status hmath_linear_lapack_hessenberg_h(hmath_context *context, const hmath_value *hessenberg1, hmath_value **out); +/* HMath.Matrix.LAPACK.Hessenberg :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_hessenberg(hmath_context *context, const hmath_value *matrix1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Matrix.LAPACK.balancedMatrix :: Balance -> field */ +HMATH_API hmath_status hmath_linear_lapack_balanced_matrix(hmath_context *context, const hmath_value *balance1, hmath_value **out); +/* HMath.Matrix.LAPACK.balanceScales :: Balance -> field */ +HMATH_API hmath_status hmath_linear_lapack_balance_scales(hmath_context *context, const hmath_value *balance1, hmath_value **out); +/* HMath.Matrix.LAPACK.Balance :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_balance(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, hmath_value **out); +/* HMath.Matrix.LAPACK.complexU :: ComplexSVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_complex_u(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.complexSingularValues :: ComplexSVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_complex_singular_values(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.complexVT :: ComplexSVD -> field */ +HMATH_API hmath_status hmath_linear_lapack_complex_vt(hmath_context *context, const hmath_value *complex_svd1, hmath_value **out); +/* HMath.Matrix.LAPACK.ComplexSVD :: constructor */ +HMATH_API hmath_status hmath_linear_lapack_new_complex_svd(hmath_context *context, const hmath_value *matrix1, const hmath_value *values2, const hmath_value *matrix3, hmath_value **out); +/* HMath.Sparse.sparse :: Int -> Int -> [(Int, Int, a)] -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +/* HMath.Sparse.sparseShape :: Sparse a -> (Int, Int) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseEntries :: Sparse a -> [(Int, Int, a)] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.nonzeros :: Sparse a -> Int */ +HMATH_API hmath_status hmath_linear_sparse_nonzeros(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.fromFormat :: SparseFormat a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_from_format(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_format1, hmath_value **out); +/* HMath.Sparse.toCOO :: Sparse a -> SparseFormat a */ +HMATH_API hmath_status hmath_linear_sparse_to_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.toCSR :: Sparse a -> SparseFormat a */ +HMATH_API hmath_status hmath_linear_sparse_to_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.toCSC :: Sparse a -> SparseFormat a */ +HMATH_API hmath_status hmath_linear_sparse_to_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.toDIA :: Sparse a -> SparseFormat a */ +HMATH_API hmath_status hmath_linear_sparse_to_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.toBSR :: Int -> Int -> Sparse a -> Either MathError (SparseFormat a) */ +HMATH_API hmath_status hmath_linear_sparse_to_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *sparse3, hmath_value **out); +/* HMath.Sparse.toELLPACK :: Sparse a -> Either MathError (SparseFormat a) */ +HMATH_API hmath_status hmath_linear_sparse_to_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseToDense :: Sparse a -> Either MathError (Matrix a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_to_dense(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.denseToSparse :: Matrix a -> Sparse a */ +HMATH_API hmath_status hmath_linear_sparse_dense_to_sparse(hmath_context *context, const hmath_value *prototype, const hmath_value *matrix1, hmath_value **out); +/* HMath.Sparse.sparseTranspose :: Sparse a -> Sparse a */ +HMATH_API hmath_status hmath_linear_sparse_sparse_transpose(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseAdd :: Sparse a -> Sparse a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_add(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseSubtract :: Sparse a -> Sparse a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_subtract(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.spmv :: Sparse a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_sparse_spmv(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.spmm :: Sparse a -> Sparse a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_spmm(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseKronecker :: Sparse a -> Sparse a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_kronecker(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseTriangularSolve :: Bool -> Sparse a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_triangular_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *flag1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out); +/* HMath.Sparse.sparseDiagonalSolve :: Sparse a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_diagonal_solve(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.sparseLULower :: SparseLU a -> Sparse a */ +HMATH_API hmath_status hmath_linear_sparse_sparse_lu_lower(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +/* HMath.Sparse.sparseLUUpper :: SparseLU a -> Sparse a */ +HMATH_API hmath_status hmath_linear_sparse_sparse_lu_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +/* HMath.Sparse.sparseLUPermutation :: SparseLU a -> [Int] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_lu_permutation(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, hmath_value **out); +/* HMath.Sparse.sparseLU :: a -> Sparse a -> Either MathError (SparseLU a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseSolveLU :: SparseLU a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_solve_lu(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_lu1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.sparseCholesky :: Sparse a -> Either MathError (Sparse a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_cholesky(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseQRUpper :: SparseQR a -> Sparse a */ +HMATH_API hmath_status hmath_linear_sparse_sparse_qr_upper(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, hmath_value **out); +/* HMath.Sparse.sparseQR :: Sparse a -> Either MathError (SparseQR a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_qr(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseQRApplyQT :: SparseQR a -> [a] -> Either MathError [a] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_qr_apply_qt(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_qr1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.sparseGraph :: Sparse a -> Either MathError [(Int, [(Int, a)])] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_graph(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse1, hmath_value **out); +/* HMath.Sparse.sparseStorageBytes :: Int -> Sparse a -> Either MathError Integer */ +HMATH_API hmath_status hmath_linear_sparse_sparse_storage_bytes(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseTensor :: [Int] -> [([Int], a)] -> Either MathError (SparseTensor a) */ +HMATH_API hmath_status hmath_linear_sparse_sparse_tensor(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.sparseTensorShape :: SparseTensor a -> [Int] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_tensor_shape(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out); +/* HMath.Sparse.sparseTensorEntries :: SparseTensor a -> [([Int], a)] */ +HMATH_API hmath_status hmath_linear_sparse_sparse_tensor_entries(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, hmath_value **out); +/* HMath.Sparse.sparseTensorLookup :: SparseTensor a -> [Int] -> Either MathError a */ +HMATH_API hmath_status hmath_linear_sparse_sparse_tensor_lookup(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_tensor1, const hmath_value *values2, hmath_value **out); +/* HMath.Sparse.sparseEigenReference :: Integer -> Sparse Double -> Either MathError Eigen */ +HMATH_API hmath_status hmath_linear_sparse_sparse_eigen_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.sparseSVDReference :: Integer -> Sparse Double -> Either MathError SVD */ +HMATH_API hmath_status hmath_linear_sparse_sparse_svd_reference(hmath_context *context, const hmath_value *integer1, const hmath_value *sparse2, hmath_value **out); +/* HMath.Sparse.COO :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_coo(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +/* HMath.Sparse.CSR :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_csr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Sparse.CSC :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_csc(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Sparse.DIA :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_dia(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *values3, hmath_value **out); +/* HMath.Sparse.BSR :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_bsr(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *values5, const hmath_value *values6, const hmath_value *values7, hmath_value **out); +/* HMath.Sparse.ELLPACK :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_new_ellpack(hmath_context *context, const hmath_value *prototype, const hmath_value *index1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Sparse.Spectral.defaultSparseSpectralOptions :: SparseSpectralOptions a */ +HMATH_API hmath_status hmath_linear_sparse_spectral_default_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, hmath_value **out); +/* HMath.Sparse.Spectral.sparseDominantEigen :: SparseSpectralOptions a -> Sparse a -> [a] -> Either MathError (SparseEigenResult a) */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_dominant_eigen(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *sparse2, const hmath_value *values3, hmath_value **out); +/* HMath.Sparse.Spectral.sparseTruncatedSVD :: SparseSpectralOptions a -> Int -> Integer -> Sparse a -> Either MathError (SparseSVD a) */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_truncated_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, const hmath_value *index2, const hmath_value *integer3, const hmath_value *sparse4, hmath_value **out); +/* HMath.Sparse.Spectral.sparseAbsoluteTolerance :: SparseSpectralOptions -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_absolute_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseRelativeTolerance :: SparseSpectralOptions -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_relative_tolerance(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseIterationLimit :: SparseSpectralOptions -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_iteration_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseWorkspaceLimit :: SparseSpectralOptions -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_workspace_limit(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_spectral_options1, hmath_value **out); +/* HMath.Sparse.Spectral.SparseSpectralOptions :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_spectral_new_sparse_spectral_options(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *scalar2, const hmath_value *index3, const hmath_value *integer4, hmath_value **out); +/* HMath.Sparse.Spectral.sparseEigenvalue :: SparseEigenResult -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_eigenvalue(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseEigenvector :: SparseEigenResult -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_eigenvector(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseEigenResidual :: SparseEigenResult -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_eigen_residual(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseEigenIterations :: SparseEigenResult -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_eigen_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_eigen_result1, hmath_value **out); +/* HMath.Sparse.Spectral.SparseEigenResult :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_spectral_new_sparse_eigen_result(hmath_context *context, const hmath_value *prototype, const hmath_value *scalar1, const hmath_value *values2, const hmath_value *scalar3, const hmath_value *index4, hmath_value **out); +/* HMath.Sparse.Spectral.sparseSingularValues :: SparseSVD -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_singular_values(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseLeftVectors :: SparseSVD -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_left_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseRightVectors :: SparseSVD -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_right_vectors(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseSingularResiduals :: SparseSVD -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_singular_residuals(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +/* HMath.Sparse.Spectral.sparseSingularIterations :: SparseSVD -> field */ +HMATH_API hmath_status hmath_linear_sparse_spectral_sparse_singular_iterations(hmath_context *context, const hmath_value *prototype, const hmath_value *sparse_svd1, hmath_value **out); +/* HMath.Sparse.Spectral.SparseSVD :: constructor */ +HMATH_API hmath_status hmath_linear_sparse_spectral_new_sparse_svd(hmath_context *context, const hmath_value *prototype, const hmath_value *values1, const hmath_value *values2, const hmath_value *values3, const hmath_value *values4, const hmath_value *values5, hmath_value **out); +/* HMath.Backend.backendInfo :: Backend -> BackendInfo */ +HMATH_API hmath_status hmath_linear_backend_backend_info(hmath_context *context, const hmath_value *backend1, hmath_value **out); +/* HMath.Backend.pureBackend :: Backend */ +HMATH_API hmath_status hmath_linear_backend_pure_backend(hmath_context *context, hmath_value **out); +/* HMath.Backend.lapackAvailable :: IO Bool */ +HMATH_API hmath_status hmath_linear_backend_lapack_available(hmath_context *context, hmath_value **out); +/* HMath.Backend.selectBackend :: BackendRequest -> IO (Either MathError Backend) */ +HMATH_API hmath_status hmath_linear_backend_select_backend(hmath_context *context, const hmath_value *backend_request1, hmath_value **out); +/* HMath.Backend.setBackendThreads :: Backend -> Int -> IO (Either MathError ()) */ +HMATH_API hmath_status hmath_linear_backend_set_backend_threads(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, hmath_value **out); +/* HMath.Backend.lapackStatus :: String -> Int -> Either MathError () */ +HMATH_API hmath_status hmath_linear_backend_lapack_status(hmath_context *context, const hmath_value *text1, const hmath_value *index2, hmath_value **out); +/* HMath.Backend.matrixFromLayout :: BackendLayout -> Int -> Int -> [a] -> Either MathError (M.Matrix a) */ +HMATH_API hmath_status hmath_linear_backend_matrix_from_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *index2, const hmath_value *index3, const hmath_value *values4, hmath_value **out); +/* HMath.Backend.matrixToLayout :: BackendLayout -> M.Matrix a -> [a] */ +HMATH_API hmath_status hmath_linear_backend_matrix_to_layout(hmath_context *context, const hmath_value *prototype, const hmath_value *backend_layout1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.axpy :: Backend -> Double -> [Double] -> [Double] -> IO (Either MathError [Double]) */ +HMATH_API hmath_status hmath_linear_backend_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *double2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Backend.dot :: Backend -> [Double] -> [Double] -> IO (Either MathError Double) */ +HMATH_API hmath_status hmath_linear_backend_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, const hmath_value *values3, hmath_value **out); +/* HMath.Backend.nrm2 :: Backend -> [Double] -> IO (Either MathError Double) */ +HMATH_API hmath_status hmath_linear_backend_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out); +/* HMath.Backend.gemv :: Backend -> Transpose -> Double -> M.Matrix Double -> [Double] -> Double -> [Double] -> IO (Either MathError [Double]) */ +HMATH_API hmath_status hmath_linear_backend_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *double3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *double6, const hmath_value *values7, hmath_value **out); +/* HMath.Backend.gemm :: Backend -> Transpose -> Transpose -> Double -> M.Matrix Double -> M.Matrix Double -> Double -> M.Matrix Double -> IO (Either MathError (M.Matrix Double)) */ +HMATH_API hmath_status hmath_linear_backend_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *double7, const hmath_value *matrix8, hmath_value **out); +/* HMath.Backend.complexGemm :: Backend -> Transpose -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> M.Matrix (Complex Double) -> Complex Double -> M.Matrix (Complex Double) -> IO (Either MathError (M.Matrix (Complex Double))) */ +HMATH_API hmath_status hmath_linear_backend_complex_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *complex4, const hmath_value *matrix5, const hmath_value *matrix6, const hmath_value *complex7, const hmath_value *matrix8, hmath_value **out); +/* HMath.Backend.complexAxpy :: Backend -> Complex Double -> [Complex Double] -> [Complex Double] -> IO (Either MathError [Complex Double]) */ +HMATH_API hmath_status hmath_linear_backend_complex_axpy(hmath_context *context, const hmath_value *backend1, const hmath_value *complex2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Backend.complexDot :: Backend -> Bool -> [Complex Double] -> [Complex Double] -> IO (Either MathError (Complex Double)) */ +HMATH_API hmath_status hmath_linear_backend_complex_dot(hmath_context *context, const hmath_value *backend1, const hmath_value *flag2, const hmath_value *values3, const hmath_value *values4, hmath_value **out); +/* HMath.Backend.complexNrm2 :: Backend -> [Complex Double] -> IO (Either MathError Double) */ +HMATH_API hmath_status hmath_linear_backend_complex_nrm2(hmath_context *context, const hmath_value *backend1, const hmath_value *values2, hmath_value **out); +/* HMath.Backend.complexGemv :: Backend -> Transpose -> Complex Double -> M.Matrix (Complex Double) -> [Complex Double] -> Complex Double -> [Complex Double] -> IO (Either MathError [Complex Double]) */ +HMATH_API hmath_status hmath_linear_backend_complex_gemv(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *complex3, const hmath_value *matrix4, const hmath_value *values5, const hmath_value *complex6, const hmath_value *values7, hmath_value **out); +/* HMath.Backend.batchedGemm :: Backend -> Transpose -> Transpose -> Double -> Double -> [(M.Matrix Double, M.Matrix Double, M.Matrix Double)] -> IO (Either MathError [M.Matrix Double]) */ +HMATH_API hmath_status hmath_linear_backend_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *transpose2, const hmath_value *transpose3, const hmath_value *double4, const hmath_value *double5, const hmath_value *values6, hmath_value **out); +/* HMath.Backend.stridedBatchedGemm :: Backend -> Int -> Int -> Int -> Int -> Int -> [Double] -> Int -> [Double] -> IO (Either MathError [M.Matrix Double]) */ +HMATH_API hmath_status hmath_linear_backend_strided_batched_gemm(hmath_context *context, const hmath_value *backend1, const hmath_value *index2, const hmath_value *index3, const hmath_value *index4, const hmath_value *index5, const hmath_value *index6, const hmath_value *values7, const hmath_value *index8, const hmath_value *values9, hmath_value **out); +/* HMath.Backend.backendLU :: Backend -> M.Matrix Double -> Either MathError (LU.LU Double) */ +HMATH_API hmath_status hmath_linear_backend_backend_lu(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.backendQR :: Backend -> M.Matrix Double -> Either MathError (QR.QR Double) */ +HMATH_API hmath_status hmath_linear_backend_backend_qr(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.backendSolve :: Backend -> M.Matrix Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_linear_backend_backend_solve(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +/* HMath.Backend.backendCholesky :: Backend -> M.Matrix Double -> Either MathError (M.Matrix Double) */ +HMATH_API hmath_status hmath_linear_backend_backend_cholesky(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.backendLeastSquares :: Backend -> M.Matrix Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_linear_backend_backend_least_squares(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, const hmath_value *values3, hmath_value **out); +/* HMath.Backend.backendSVD :: Backend -> M.Matrix Double -> Either MathError L.SVD */ +HMATH_API hmath_status hmath_linear_backend_backend_svd(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.backendSymmetricEigen :: Backend -> M.Matrix Double -> Either MathError L.Eigen */ +HMATH_API hmath_status hmath_linear_backend_backend_symmetric_eigen(hmath_context *context, const hmath_value *backend1, const hmath_value *matrix2, hmath_value **out); +/* HMath.Backend.pureSymmetricEigen :: M.Matrix Double -> Either MathError L.Eigen */ +HMATH_API hmath_status hmath_linear_backend_pure_symmetric_eigen(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Backend.pureSVD :: M.Matrix Double -> Either MathError L.SVD */ +HMATH_API hmath_status hmath_linear_backend_pure_svd(hmath_context *context, const hmath_value *matrix1, hmath_value **out); +/* HMath.Backend.Pure :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_pure(hmath_context *context, hmath_value **out); +/* HMath.Backend.OpenBLAS :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_open_blas(hmath_context *context, hmath_value **out); +/* HMath.Backend.BLIS :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_blis(hmath_context *context, hmath_value **out); +/* HMath.Backend.OneMKL :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_one_mkl(hmath_context *context, hmath_value **out); +/* HMath.Backend.Accelerate :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_accelerate(hmath_context *context, hmath_value **out); +/* HMath.Backend.LP64 :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_lp64(hmath_context *context, hmath_value **out); +/* HMath.Backend.ILP64 :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_ilp64(hmath_context *context, hmath_value **out); +/* HMath.Backend.AutoBackend :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_auto_backend(hmath_context *context, hmath_value **out); +/* HMath.Backend.RequireBackend :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_require_backend(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, const hmath_value *maybe3, hmath_value **out); +/* HMath.Backend.selectedProvider :: BackendInfo -> field */ +HMATH_API hmath_status hmath_linear_backend_selected_provider(hmath_context *context, const hmath_value *backend_info1, hmath_value **out); +/* HMath.Backend.selectedIntegerABI :: BackendInfo -> field */ +HMATH_API hmath_status hmath_linear_backend_selected_integer_abi(hmath_context *context, const hmath_value *backend_info1, hmath_value **out); +/* HMath.Backend.BackendInfo :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_backend_info(hmath_context *context, const hmath_value *provider1, const hmath_value *integer_abi2, hmath_value **out); +/* HMath.Backend.RowMajor :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_row_major(hmath_context *context, hmath_value **out); +/* HMath.Backend.ColumnMajor :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_column_major(hmath_context *context, hmath_value **out); +/* HMath.Backend.NoTranspose :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_no_transpose(hmath_context *context, hmath_value **out); +/* HMath.Backend.Transpose :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_transpose(hmath_context *context, hmath_value **out); +/* HMath.Backend.ConjugateTranspose :: constructor */ +HMATH_API hmath_status hmath_linear_backend_new_conjugate_transpose(hmath_context *context, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_machinelearning.h b/include/hmath_machinelearning.h new file mode 100644 index 0000000..08c8b97 --- /dev/null +++ b/include/hmath_machinelearning.h @@ -0,0 +1,381 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_machinelearning_bindings.py. */ +#ifndef HMATH_MACHINELEARNING_H +#define HMATH_MACHINELEARNING_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original immutable models/configurations; Dataset is a list of Double rows. + * Inputs are borrowed; each successful output transfers one owned Value. Error + * outputs remain untouched; release with hmath_value_release. Source fitting + * methods, seeds, data limits, validation, tie order, convergence diagnostics + * and MathError/status11 are unchanged. Calls may share immutable inputs with + * independent references/output addresses. Live owners pin the runtime. + * Search callbacks use kind101 checked callbacks with tuple(config,Fold) and + * Double results; retain function/userdata while referenced. Python preserves + * callback owners and rethrows unexpected exceptions after native cleanup. + * Encoder/stratified labels use actual native Ord/Eq dictionaries, with no + * Double/text conversion. Optional prototype is a representative category + * solely for otherwise uninferrable empty/optional element types. */ +typedef hmath_value hmath_ml_cluster_model_object; /* kind310 */ +typedef hmath_value hmath_ml_gaussian_mixture_object; /* kind311 */ +typedef hmath_value hmath_ml_linkage_object; /* kind312 */ +typedef hmath_value hmath_ml_merge_object; /* kind313 */ +typedef hmath_value hmath_ml_cca_object; /* kind314 */ +typedef hmath_value hmath_ml_factor_analysis_object; /* kind315 */ +typedef hmath_value hmath_ml_ica_object; /* kind316 */ +typedef hmath_value hmath_ml_incremental_pca_object; /* kind317 */ +typedef hmath_value hmath_ml_kernel_pca_object; /* kind318 */ +typedef hmath_value hmath_ml_pca_object; /* kind319 */ +typedef hmath_value hmath_ml_pls_object; /* kind320 */ +typedef hmath_value hmath_ml_fit_object; /* kind321 */ +typedef hmath_value hmath_ml_ml_config_object; /* kind322 */ +typedef hmath_value hmath_ml_index_kind_object; /* kind323 */ +typedef hmath_value hmath_ml_isolation_forest_object; /* kind324 */ +typedef hmath_value hmath_ml_lsh_object; /* kind325 */ +typedef hmath_value hmath_ml_neighbor_result_object; /* kind326 */ +typedef hmath_value hmath_ml_one_class_svm_object; /* kind327 */ +typedef hmath_value hmath_ml_spatial_index_object; /* kind328 */ +typedef hmath_value hmath_ml_encoder_object; /* kind329 */ +typedef hmath_value hmath_ml_fold_object; /* kind330 */ +typedef hmath_value hmath_ml_imputation_object; /* kind331 */ +typedef hmath_value hmath_ml_imputer_object; /* kind332 */ +typedef hmath_value hmath_ml_power_transform_object; /* kind333 */ +typedef hmath_value hmath_ml_quantile_transformer_object; /* kind334 */ +typedef hmath_value hmath_ml_scaler_object; /* kind335 */ +typedef hmath_value hmath_ml_scaling_object; /* kind336 */ +typedef hmath_value hmath_ml_unknown_category_object; /* kind337 */ +typedef hmath_value hmath_ml_bayes_family_object; /* kind338 */ +typedef hmath_value hmath_ml_bayesian_linear_object; /* kind339 */ +typedef hmath_value hmath_ml_discriminant_object; /* kind340 */ +typedef hmath_value hmath_ml_glm_object; /* kind341 */ +typedef hmath_value hmath_ml_glm_family_object; /* kind342 */ +typedef hmath_value hmath_ml_gp_classifier_object; /* kind343 */ +typedef hmath_value hmath_ml_gaussian_process_object; /* kind344 */ +typedef hmath_value hmath_ml_kernel_object; /* kind345 */ +typedef hmath_value hmath_ml_linear_model_object; /* kind346 */ +typedef hmath_value hmath_ml_multinomial_model_object; /* kind347 */ +typedef hmath_value hmath_ml_naive_bayes_object; /* kind348 */ +typedef hmath_value hmath_ml_penalty_object; /* kind349 */ +typedef hmath_value hmath_ml_recursive_ls_object; /* kind350 */ +typedef hmath_value hmath_ml_svm_object; /* kind351 */ +typedef hmath_value hmath_ml_dataset_value; /* list of Double rows */ +HMATH_API hmath_status hmath_ml_describe(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_ml_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +/* HMath.MachineLearning.Clustering.Average :: Linkage */ +HMATH_API hmath_status hmath_ml_average(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Clustering.Complete :: Linkage */ +HMATH_API hmath_status hmath_ml_complete(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Clustering.Merge :: Int -> Int -> Double -> Int -> Merge */ +HMATH_API hmath_status hmath_ml_merge(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *count3, hmath_value **out); +/* HMath.MachineLearning.Clustering.Single :: Linkage */ +HMATH_API hmath_status hmath_ml_single(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Clustering.Ward :: Linkage */ +HMATH_API hmath_status hmath_ml_ward(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Clustering.affinityPropagation :: MLConfig -> Double -> Double -> Dataset -> Either MathError (Fit [Int]) */ +HMATH_API hmath_status hmath_ml_affinity_propagation(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.clusterCenters :: ClusterModel -> Dataset */ +HMATH_API hmath_status hmath_ml_cluster_centers(hmath_context *context, const hmath_value *cluster_model, hmath_value **out); +/* HMath.MachineLearning.Clustering.cutHierarchy :: Int -> Int -> [Merge] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_cut_hierarchy(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Clustering.dbscan :: Double -> Int -> Dataset -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_dbscan(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.extractOPTICS :: Double -> [(Int, Maybe Double, Maybe Double)] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_extract_optics(hmath_context *context, const hmath_value *number, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Clustering.fitGaussianMixture :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit GaussianMixture) */ +HMATH_API hmath_status hmath_ml_fit_gaussian_mixture(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.hierarchical :: Linkage -> Dataset -> Either MathError [Merge] */ +HMATH_API hmath_status hmath_ml_hierarchical(hmath_context *context, const hmath_value *linkage, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.kMeans :: MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel) */ +HMATH_API hmath_status hmath_ml_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.kMeansPlusPlus :: MLConfig -> Int -> Dataset -> Either MathError (Fit ClusterModel) */ +HMATH_API hmath_status hmath_ml_k_means_plus_plus(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.kMedoids :: MLConfig -> Int -> Dataset -> Either MathError (Fit [Int]) */ +HMATH_API hmath_status hmath_ml_k_medoids(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.leftCluster :: Merge -> Int */ +HMATH_API hmath_status hmath_ml_left_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out); +/* HMath.MachineLearning.Clustering.meanShift :: MLConfig -> Double -> Dataset -> Either MathError (Fit ClusterModel) */ +HMATH_API hmath_status hmath_ml_mean_shift(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.mergeDistance :: Merge -> Double */ +HMATH_API hmath_status hmath_ml_merge_distance(hmath_context *context, const hmath_value *merge, hmath_value **out); +/* HMath.MachineLearning.Clustering.mergedSize :: Merge -> Int */ +HMATH_API hmath_status hmath_ml_merged_size(hmath_context *context, const hmath_value *merge, hmath_value **out); +/* HMath.MachineLearning.Clustering.miniBatchKMeans :: MLConfig -> Int -> Int -> Dataset -> Either MathError (Fit ClusterModel) */ +HMATH_API hmath_status hmath_ml_mini_batch_k_means(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.mixtureCovariances :: GaussianMixture -> [Dataset] */ +HMATH_API hmath_status hmath_ml_mixture_covariances(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +/* HMath.MachineLearning.Clustering.mixtureMeans :: GaussianMixture -> Dataset */ +HMATH_API hmath_status hmath_ml_mixture_means(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +/* HMath.MachineLearning.Clustering.mixtureResponsibilities :: GaussianMixture -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_mixture_responsibilities(hmath_context *context, const hmath_value *gaussian_mixture, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.mixtureWeights :: GaussianMixture -> [Double] */ +HMATH_API hmath_status hmath_ml_mixture_weights(hmath_context *context, const hmath_value *gaussian_mixture, hmath_value **out); +/* HMath.MachineLearning.Clustering.optics :: Double -> Int -> Dataset -> Either MathError [(Int, Maybe Double, Maybe Double)] */ +HMATH_API hmath_status hmath_ml_optics(hmath_context *context, const hmath_value *number, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.predictClusters :: ClusterModel -> Dataset -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_predict_clusters(hmath_context *context, const hmath_value *cluster_model, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Clustering.rightCluster :: Merge -> Int */ +HMATH_API hmath_status hmath_ml_right_cluster(hmath_context *context, const hmath_value *merge, hmath_value **out); +/* HMath.MachineLearning.Clustering.spectralClustering :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit [Int]) */ +HMATH_API hmath_status hmath_ml_spectral_clustering(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.canonicalCorrelations :: CCA -> [Double] */ +HMATH_API hmath_status hmath_ml_canonical_correlations(hmath_context *context, const hmath_value *cca, hmath_value **out); +/* HMath.MachineLearning.Decomposition.classicalMDS :: Int -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_classical_mds(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.factorLoadings :: FactorAnalysis -> Dataset */ +HMATH_API hmath_status hmath_ml_factor_loadings(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out); +/* HMath.MachineLearning.Decomposition.factorNoise :: FactorAnalysis -> [Double] */ +HMATH_API hmath_status hmath_ml_factor_noise(hmath_context *context, const hmath_value *factor_analysis, hmath_value **out); +/* HMath.MachineLearning.Decomposition.finishPCA :: Int -> IncrementalPCA -> Either MathError PCA */ +HMATH_API hmath_status hmath_ml_finish_pca(hmath_context *context, const hmath_value *count, const hmath_value *incremental_pca, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitCCA :: Int -> Double -> Dataset -> Dataset -> Either MathError CCA */ +HMATH_API hmath_status hmath_ml_fit_cca(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitFactorAnalysis :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit FactorAnalysis) */ +HMATH_API hmath_status hmath_ml_fit_factor_analysis(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitICA :: MLConfig -> Int -> Dataset -> Either MathError (Fit ICA) */ +HMATH_API hmath_status hmath_ml_fit_ica(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitKernelPCA :: Int -> Kernel -> Dataset -> Either MathError KernelPCA */ +HMATH_API hmath_status hmath_ml_fit_kernel_pca(hmath_context *context, const hmath_value *count, const hmath_value *kernel, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitPCA :: Int -> Dataset -> Either MathError PCA */ +HMATH_API hmath_status hmath_ml_fit_pca(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.fitPLS :: MLConfig -> Int -> Dataset -> Dataset -> Either MathError (Fit PLS) */ +HMATH_API hmath_status hmath_ml_fit_pls(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +/* HMath.MachineLearning.Decomposition.incrementalPCA :: Int -> Either MathError IncrementalPCA */ +HMATH_API hmath_status hmath_ml_incremental_pca(hmath_context *context, const hmath_value *count, hmath_value **out); +/* HMath.MachineLearning.Decomposition.inversePCA :: PCA -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_inverse_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.isomap :: Int -> Int -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_isomap(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.mergePCA :: IncrementalPCA -> IncrementalPCA -> Either MathError IncrementalPCA */ +HMATH_API hmath_status hmath_ml_merge_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *incremental_pca2, hmath_value **out); +/* HMath.MachineLearning.Decomposition.pcaComponents :: PCA -> Dataset */ +HMATH_API hmath_status hmath_ml_pca_components(hmath_context *context, const hmath_value *pca, hmath_value **out); +/* HMath.MachineLearning.Decomposition.pcaMean :: PCA -> [Double] */ +HMATH_API hmath_status hmath_ml_pca_mean(hmath_context *context, const hmath_value *pca, hmath_value **out); +/* HMath.MachineLearning.Decomposition.pcaVariances :: PCA -> [Double] */ +HMATH_API hmath_status hmath_ml_pca_variances(hmath_context *context, const hmath_value *pca, hmath_value **out); +/* HMath.MachineLearning.Decomposition.predictPLS :: PLS -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_predict_pls(hmath_context *context, const hmath_value *pls, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.randomProjection :: MLConfig -> Int -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_random_projection(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.transformCCA :: CCA -> Dataset -> Dataset -> Either MathError (Dataset, Dataset) */ +HMATH_API hmath_status hmath_ml_transform_cca(hmath_context *context, const hmath_value *cca, const hmath_value *dataset, const hmath_value *dataset2, hmath_value **out); +/* HMath.MachineLearning.Decomposition.transformICA :: ICA -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_transform_ica(hmath_context *context, const hmath_value *ica, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.transformKernelPCA :: KernelPCA -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_transform_kernel_pca(hmath_context *context, const hmath_value *kernel_pca, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.transformPCA :: PCA -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_transform_pca(hmath_context *context, const hmath_value *pca, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.truncatedSVD :: Int -> Dataset -> Either MathError (Dataset, [Double], Dataset) */ +HMATH_API hmath_status hmath_ml_truncated_svd(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.tsne :: MLConfig -> Int -> Double -> Dataset -> Either MathError (Fit Dataset) */ +HMATH_API hmath_status hmath_ml_tsne(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.umap :: MLConfig -> Int -> Int -> Double -> Double -> Dataset -> Either MathError (Fit Dataset) */ +HMATH_API hmath_status hmath_ml_umap(hmath_context *context, const hmath_value *ml_config, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Decomposition.updatePCA :: IncrementalPCA -> Dataset -> Either MathError IncrementalPCA */ +HMATH_API hmath_status hmath_ml_update_pca(hmath_context *context, const hmath_value *incremental_pca, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Internal.Fit :: a -> Int -> Double -> Bool -> Fit a */ +HMATH_API hmath_status hmath_ml_fit(hmath_context *context, const hmath_value *value, const hmath_value *count, const hmath_value *number, const hmath_value *flag, hmath_value **out); +/* HMath.MachineLearning.Internal.MLConfig :: Int -> Double -> Double -> Word64 -> MLConfig */ +HMATH_API hmath_status hmath_ml_ml_config(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, const hmath_value *seed, hmath_value **out); +/* HMath.MachineLearning.Internal.defaultMLConfig :: MLConfig */ +HMATH_API hmath_status hmath_ml_default_ml_config(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Internal.fitConverged :: Fit a -> Bool */ +HMATH_API hmath_status hmath_ml_fit_converged(hmath_context *context, const hmath_value *fit, hmath_value **out); +/* HMath.MachineLearning.Internal.fitIterations :: Fit a -> Int */ +HMATH_API hmath_status hmath_ml_fit_iterations(hmath_context *context, const hmath_value *fit, hmath_value **out); +/* HMath.MachineLearning.Internal.fitResidual :: Fit a -> Double */ +HMATH_API hmath_status hmath_ml_fit_residual(hmath_context *context, const hmath_value *fit, hmath_value **out); +/* HMath.MachineLearning.Internal.fitted :: Fit a -> a */ +HMATH_API hmath_status hmath_ml_fitted(hmath_context *context, const hmath_value *fit, hmath_value **out); +/* HMath.MachineLearning.Internal.mlIterations :: MLConfig -> Int */ +HMATH_API hmath_status hmath_ml_ml_iterations(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +/* HMath.MachineLearning.Internal.mlRate :: MLConfig -> Double */ +HMATH_API hmath_status hmath_ml_ml_rate(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +/* HMath.MachineLearning.Internal.mlSeed :: MLConfig -> Word64 */ +HMATH_API hmath_status hmath_ml_ml_seed(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +/* HMath.MachineLearning.Internal.mlTolerance :: MLConfig -> Double */ +HMATH_API hmath_status hmath_ml_ml_tolerance(hmath_context *context, const hmath_value *ml_config, hmath_value **out); +/* HMath.MachineLearning.Neighbors.BallTree :: IndexKind */ +HMATH_API hmath_status hmath_ml_ball_tree(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Neighbors.KDTree :: IndexKind */ +HMATH_API hmath_status hmath_ml_kd_tree(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Neighbors.NeighborResult :: [(Int, Double)] -> Int -> Bool -> NeighborResult */ +HMATH_API hmath_status hmath_ml_neighbor_result(hmath_context *context, const hmath_value *values, const hmath_value *count, const hmath_value *flag, hmath_value **out); +/* HMath.MachineLearning.Neighbors.buildIndex :: IndexKind -> Int -> Dataset -> Either MathError SpatialIndex */ +HMATH_API hmath_status hmath_ml_build_index(hmath_context *context, const hmath_value *index_kind, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.buildLSH :: Word64 -> Int -> Int -> Double -> Dataset -> Either MathError LSH */ +HMATH_API hmath_status hmath_ml_build_lsh(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.decisionOneClassSVM :: OneClassSVM -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_decision_one_class_svm(hmath_context *context, const hmath_value *one_class_svm, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.exhaustive :: NeighborResult -> Bool */ +HMATH_API hmath_status hmath_ml_exhaustive(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +/* HMath.MachineLearning.Neighbors.fitIsolationForest :: Word64 -> Int -> Int -> Dataset -> Either MathError IsolationForest */ +HMATH_API hmath_status hmath_ml_fit_isolation_forest(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.fitOneClassSVM :: MLConfig -> Kernel -> Double -> Dataset -> Either MathError (Fit OneClassSVM) */ +HMATH_API hmath_status hmath_ml_fit_one_class_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.knnClassify :: Int -> SpatialIndex -> [Int] -> Dataset -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_knn_classify(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.knnRegress :: Int -> SpatialIndex -> [Double] -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_knn_regress(hmath_context *context, const hmath_value *count, const hmath_value *spatial_index, const hmath_value *values, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.localOutlierFactor :: Int -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_local_outlier_factor(hmath_context *context, const hmath_value *count, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.nearestNeighbors :: Int -> Int -> SpatialIndex -> [Double] -> Either MathError NeighborResult */ +HMATH_API hmath_status hmath_ml_nearest_neighbors(hmath_context *context, const hmath_value *count, const hmath_value *count2, const hmath_value *spatial_index, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Neighbors.neighbors :: NeighborResult -> [(Int, Double)] */ +HMATH_API hmath_status hmath_ml_neighbors(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +/* HMath.MachineLearning.Neighbors.queryLSH :: Int -> LSH -> [Double] -> Either MathError [(Int, Double)] */ +HMATH_API hmath_status hmath_ml_query_lsh(hmath_context *context, const hmath_value *count, const hmath_value *lsh, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Neighbors.scoreIsolationForest :: IsolationForest -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_score_isolation_forest(hmath_context *context, const hmath_value *isolation_forest, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Neighbors.visitedLeaves :: NeighborResult -> Int */ +HMATH_API hmath_status hmath_ml_visited_leaves(hmath_context *context, const hmath_value *neighbor_result, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.BoxCox :: Double -> PowerTransform */ +HMATH_API hmath_status hmath_ml_box_cox(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.ConstantImpute :: Double -> Imputation */ +HMATH_API hmath_status hmath_ml_constant_impute(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.Fold :: [Int] -> [Int] -> Fold */ +HMATH_API hmath_status hmath_ml_fold(hmath_context *context, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.MeanImpute :: Imputation */ +HMATH_API hmath_status hmath_ml_mean_impute(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.MedianImpute :: Imputation */ +HMATH_API hmath_status hmath_ml_median_impute(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.MinMax :: Scaling */ +HMATH_API hmath_status hmath_ml_min_max(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.RejectUnknown :: UnknownCategory */ +HMATH_API hmath_status hmath_ml_reject_unknown(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.RobustScale :: Scaling */ +HMATH_API hmath_status hmath_ml_robust_scale(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.Standardize :: Scaling */ +HMATH_API hmath_status hmath_ml_standardize(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.YeoJohnson :: Double -> PowerTransform */ +HMATH_API hmath_status hmath_ml_yeo_johnson(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.ZeroUnknown :: UnknownCategory */ +HMATH_API hmath_status hmath_ml_zero_unknown(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.fitEncoder :: Ord a => [a] -> Either MathError (Encoder a) */ +HMATH_API hmath_status hmath_ml_fit_encoder(hmath_context *context, const hmath_value *values, const hmath_value *prototype, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.fitImputer :: Imputation -> Dataset -> Either MathError Imputer */ +HMATH_API hmath_status hmath_ml_fit_imputer(hmath_context *context, const hmath_value *imputation, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.fitQuantileTransformer :: Dataset -> Either MathError QuantileTransformer */ +HMATH_API hmath_status hmath_ml_fit_quantile_transformer(hmath_context *context, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.fitScaler :: Scaling -> Dataset -> Either MathError Scaler */ +HMATH_API hmath_status hmath_ml_fit_scaler(hmath_context *context, const hmath_value *scaling, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.gridSearch :: [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double) */ +HMATH_API hmath_status hmath_ml_grid_search(hmath_context *context, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.impute :: Imputer -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_impute(hmath_context *context, const hmath_value *imputer, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.inversePowerTransform :: PowerTransform -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_inverse_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.inverseQuantileTransform :: QuantileTransformer -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_inverse_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.inverseTransform :: Scaler -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_inverse_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.kFold :: Word64 -> Int -> Int -> Either MathError [Fold] */ +HMATH_API hmath_status hmath_ml_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *count2, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.labelDecode :: Encoder a -> [Int] -> Either MathError [a] */ +HMATH_API hmath_status hmath_ml_label_decode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.labelEncode :: Eq a => Encoder a -> [a] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_label_encode(hmath_context *context, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.oneHotEncode :: Eq a => UnknownCategory -> Encoder a -> [a] -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_one_hot_encode(hmath_context *context, const hmath_value *unknown_category, const hmath_value *encoder, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.powerTransform :: PowerTransform -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_power_transform(hmath_context *context, const hmath_value *power_transform, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.quantileTransform :: QuantileTransformer -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_quantile_transform(hmath_context *context, const hmath_value *quantile_transformer, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.randomSearch :: Word64 -> Int -> [p] -> [Fold] -> (p -> Fold -> Either MathError Double) -> Either MathError (p, Double) */ +HMATH_API hmath_status hmath_ml_random_search(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *values2, const hmath_value *function, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.stratifiedKFold :: Ord a => Word64 -> Int -> [a] -> Either MathError [Fold] */ +HMATH_API hmath_status hmath_ml_stratified_k_fold(hmath_context *context, const hmath_value *seed, const hmath_value *count, const hmath_value *values, const hmath_value *prototype, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.trainTestSplit :: Word64 -> Double -> Int -> Either MathError Fold */ +HMATH_API hmath_status hmath_ml_train_test_split(hmath_context *context, const hmath_value *seed, const hmath_value *number, const hmath_value *count, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.trainingIndices :: Fold -> [Int] */ +HMATH_API hmath_status hmath_ml_training_indices(hmath_context *context, const hmath_value *fold, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.transform :: Scaler -> Dataset -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_transform(hmath_context *context, const hmath_value *scaler, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Preprocessing.validationIndices :: Fold -> [Int] */ +HMATH_API hmath_status hmath_ml_validation_indices(hmath_context *context, const hmath_value *fold, hmath_value **out); +/* HMath.MachineLearning.Regression.BernoulliBayes :: BayesFamily */ +HMATH_API hmath_status hmath_ml_bernoulli_bayes(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.BinomialLogit :: GLMFamily */ +HMATH_API hmath_status hmath_ml_binomial_logit(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.ElasticNet :: Double -> Double -> Penalty */ +HMATH_API hmath_status hmath_ml_elastic_net(hmath_context *context, const hmath_value *number, const hmath_value *number2, hmath_value **out); +/* HMath.MachineLearning.Regression.GaussianBayes :: BayesFamily */ +HMATH_API hmath_status hmath_ml_gaussian_bayes(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.Lasso :: Double -> Penalty */ +HMATH_API hmath_status hmath_ml_lasso(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Regression.LinearKernel :: Kernel */ +HMATH_API hmath_status hmath_ml_linear_kernel(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.MultinomialBayes :: BayesFamily */ +HMATH_API hmath_status hmath_ml_multinomial_bayes(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.Ordinary :: Penalty */ +HMATH_API hmath_status hmath_ml_ordinary(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.PoissonLog :: GLMFamily */ +HMATH_API hmath_status hmath_ml_poisson_log(hmath_context *context, hmath_value **out); +/* HMath.MachineLearning.Regression.PolynomialKernel :: Int -> Double -> Double -> Kernel */ +HMATH_API hmath_status hmath_ml_polynomial_kernel(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out); +/* HMath.MachineLearning.Regression.RBFKernel :: Double -> Kernel */ +HMATH_API hmath_status hmath_ml_rbf_kernel(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Regression.Ridge :: Double -> Penalty */ +HMATH_API hmath_status hmath_ml_ridge(hmath_context *context, const hmath_value *number, hmath_value **out); +/* HMath.MachineLearning.Regression.bayesianCovariance :: BayesianLinear -> Dataset */ +HMATH_API hmath_status hmath_ml_bayesian_covariance(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out); +/* HMath.MachineLearning.Regression.bayesianMean :: BayesianLinear -> LinearModel */ +HMATH_API hmath_status hmath_ml_bayesian_mean(hmath_context *context, const hmath_value *bayesian_linear, hmath_value **out); +/* HMath.MachineLearning.Regression.coefficients :: LinearModel -> [Double] */ +HMATH_API hmath_status hmath_ml_coefficients(hmath_context *context, const hmath_value *linear_model, hmath_value **out); +/* HMath.MachineLearning.Regression.decisionSVM :: SVM -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_decision_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.fitBayesian :: Double -> Double -> Dataset -> [Double] -> Either MathError BayesianLinear */ +HMATH_API hmath_status hmath_ml_fit_bayesian(hmath_context *context, const hmath_value *number, const hmath_value *number2, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitDiscriminant :: Bool -> Double -> Dataset -> [Int] -> Either MathError Discriminant */ +HMATH_API hmath_status hmath_ml_fit_discriminant(hmath_context *context, const hmath_value *flag, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitGLM :: MLConfig -> GLMFamily -> Double -> Dataset -> [Double] -> Either MathError (Fit GLM) */ +HMATH_API hmath_status hmath_ml_fit_glm(hmath_context *context, const hmath_value *ml_config, const hmath_value *glm_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitGPClassifier :: MLConfig -> Kernel -> Dataset -> [Double] -> Either MathError (Fit GPClassifier) */ +HMATH_API hmath_status hmath_ml_fit_gp_classifier(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitGaussianProcess :: Kernel -> Double -> Dataset -> [Double] -> Either MathError GaussianProcess */ +HMATH_API hmath_status hmath_ml_fit_gaussian_process(hmath_context *context, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitLinear :: MLConfig -> Penalty -> Dataset -> [Double] -> Either MathError (Fit LinearModel) */ +HMATH_API hmath_status hmath_ml_fit_linear(hmath_context *context, const hmath_value *ml_config, const hmath_value *penalty, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitMultinomial :: MLConfig -> Double -> Dataset -> [Int] -> Either MathError (Fit MultinomialModel) */ +HMATH_API hmath_status hmath_ml_fit_multinomial(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitNaiveBayes :: BayesFamily -> Double -> Dataset -> [Int] -> Either MathError NaiveBayes */ +HMATH_API hmath_status hmath_ml_fit_naive_bayes(hmath_context *context, const hmath_value *bayes_family, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitRobust :: MLConfig -> Double -> Dataset -> [Double] -> Either MathError (Fit LinearModel) */ +HMATH_API hmath_status hmath_ml_fit_robust(hmath_context *context, const hmath_value *ml_config, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitSVM :: MLConfig -> Kernel -> Double -> Dataset -> [Double] -> Either MathError (Fit SVM) */ +HMATH_API hmath_status hmath_ml_fit_svm(hmath_context *context, const hmath_value *ml_config, const hmath_value *kernel, const hmath_value *number, const hmath_value *dataset, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.fitWeighted :: Dataset -> [Double] -> [Double] -> Either MathError LinearModel */ +HMATH_API hmath_status hmath_ml_fit_weighted(hmath_context *context, const hmath_value *dataset, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.MachineLearning.Regression.kernel :: Kernel -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_ml_kernel(hmath_context *context, const hmath_value *kernel, const hmath_value *values, const hmath_value *values2, hmath_value **out); +/* HMath.MachineLearning.Regression.polynomialFeatures :: Int -> [Double] -> Either MathError Dataset */ +HMATH_API hmath_status hmath_ml_polynomial_features(hmath_context *context, const hmath_value *count, const hmath_value *values, hmath_value **out); +/* HMath.MachineLearning.Regression.predictDiscriminant :: Discriminant -> Dataset -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_predict_discriminant(hmath_context *context, const hmath_value *discriminant, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictGLM :: GLM -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_predict_glm(hmath_context *context, const hmath_value *glm, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictGPClassifier :: GPClassifier -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_predict_gp_classifier(hmath_context *context, const hmath_value *gp_classifier, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictGaussianProcess :: GaussianProcess -> Dataset -> Either MathError [(Double, Double)] */ +HMATH_API hmath_status hmath_ml_predict_gaussian_process(hmath_context *context, const hmath_value *gaussian_process, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictLinear :: LinearModel -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_predict_linear(hmath_context *context, const hmath_value *linear_model, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictMultinomial :: MultinomialModel -> Dataset -> Either MathError [[(Int, Double)]] */ +HMATH_API hmath_status hmath_ml_predict_multinomial(hmath_context *context, const hmath_value *multinomial_model, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictNaiveBayes :: NaiveBayes -> Dataset -> Either MathError [Int] */ +HMATH_API hmath_status hmath_ml_predict_naive_bayes(hmath_context *context, const hmath_value *naive_bayes, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.predictSVM :: SVM -> Dataset -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ml_predict_svm(hmath_context *context, const hmath_value *svm, const hmath_value *dataset, hmath_value **out); +/* HMath.MachineLearning.Regression.recursiveCoefficients :: RecursiveLS -> [Double] */ +HMATH_API hmath_status hmath_ml_recursive_coefficients(hmath_context *context, const hmath_value *recursive_ls, hmath_value **out); +/* HMath.MachineLearning.Regression.recursiveLS :: Int -> Double -> Double -> Either MathError RecursiveLS */ +HMATH_API hmath_status hmath_ml_recursive_ls(hmath_context *context, const hmath_value *count, const hmath_value *number, const hmath_value *number2, hmath_value **out); +/* HMath.MachineLearning.Regression.updateRecursiveLS :: RecursiveLS -> [Double] -> Double -> Either MathError RecursiveLS */ +HMATH_API hmath_status hmath_ml_update_recursive_ls(hmath_context *context, const hmath_value *recursive_ls, const hmath_value *values, const hmath_value *number, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_matrix.h b/include/hmath_matrix.h new file mode 100644 index 0000000..1e00f89 --- /dev/null +++ b/include/hmath_matrix.h @@ -0,0 +1,236 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_bindings.py. */ +#ifndef HMATH_MATRIX_H +#define HMATH_MATRIX_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Immutable Haskell Matrix/LU/QR objects. Each reference pins the runtime; + * release every object before final shutdown. References may be shared across + * threads while each caller holds a reference. Final release concurrent with + * use is invalid. Match _f32/_f64 to the object's dtype; no implicit cast occurs. + * Input buffers are borrowed for the call. Output buffers must be disjoint from + * inputs and each other. All outputs remain untouched on errors. Original + * Maybe failure is OK + NULL object or found=0 (scalar value untouched). + * Original Either failures return HMATH_MATH_ERROR and the original constructor + * and payload in last_error_message. Numerical NaN/Inf policy is unchanged. + * Cancellation is checked before entry, not inside the original algorithm. */ +typedef struct hmath_dense_object hmath_dense_matrix; +typedef struct hmath_dense_object hmath_dense_lu; +typedef struct hmath_dense_object hmath_dense_qr; +typedef struct hmath_dense_object hmath_dense_vector; +typedef struct hmath_dense_object hmath_dense_indices; +HMATH_API void hmath_dense_retain(void *object); +HMATH_API void hmath_dense_release(void *object); +HMATH_API unsigned hmath_dense_precision(const void *object); +/* Metadata/copy helpers represent original shape/toList and list results. */ +HMATH_API hmath_status hmath_dense_shape(hmath_context *context, const hmath_dense_matrix *matrix, ptrdiff_t *rows, ptrdiff_t *columns); +HMATH_API hmath_status hmath_dense_count(hmath_context *context, const void *object, size_t *count); +HMATH_API hmath_status hmath_dense_indices_copy(hmath_context *context, const hmath_dense_indices *indices, ptrdiff_t *out, size_t capacity); +HMATH_API hmath_status hmath_dense_values_f32(hmath_context *context,const void *object,float *out,size_t capacity); +/* HMath.Matrix.fromList: maybe; Float. */ +HMATH_API hmath_status hmath_dense_from_list_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out); +/* HMath.Matrix.zeroMatrix: maybe; Float. */ +HMATH_API hmath_status hmath_dense_zero_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +/* HMath.Matrix.diagonal: maybe; Float. */ +HMATH_API hmath_status hmath_dense_diagonal_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out); +/* HMath.Matrix.at: maybe; Float. */ +HMATH_API hmath_status hmath_dense_at_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out, int *found); +/* HMath.Matrix.sliceMatrix: maybe; Float. */ +HMATH_API hmath_status hmath_dense_slice_matrix_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +/* HMath.Matrix.reshape: maybe; Float. */ +HMATH_API hmath_status hmath_dense_reshape_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +/* HMath.Matrix.addMatrix: maybe; Float. */ +HMATH_API hmath_status hmath_dense_add_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.subtractMatrix: maybe; Float. */ +HMATH_API hmath_status hmath_dense_subtract_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.hadamard: maybe; Float. */ +HMATH_API hmath_status hmath_dense_hadamard_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.multiply: maybe; Float. */ +HMATH_API hmath_status hmath_dense_multiply_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.identity: maybe; Float. */ +HMATH_API hmath_status hmath_dense_identity_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +/* HMath.Matrix.fromListChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_from_list_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const float *a2, size_t a2_count, hmath_dense_matrix **out); +/* HMath.Matrix.zeroMatrixChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_zero_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +/* HMath.Matrix.diagonalChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_diagonal_checked_f32(hmath_context *context, const float *a0, size_t a0_count, hmath_dense_matrix **out); +/* HMath.Matrix.atChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_at_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, float *out); +/* HMath.Matrix.sliceMatrixChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_slice_matrix_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +/* HMath.Matrix.reshapeChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_reshape_checked_f32(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +/* HMath.Matrix.addMatrixChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_add_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.subtractMatrixChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_subtract_matrix_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.hadamardChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_hadamard_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.multiplyChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_multiply_checked_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.identityChecked: either; Float. */ +HMATH_API hmath_status hmath_dense_identity_checked_f32(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +/* HMath.Matrix.scaleMatrix: pure; Float. */ +HMATH_API hmath_status hmath_dense_scale_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.transposeMatrix: pure; Float. */ +HMATH_API hmath_status hmath_dense_transpose_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luDecompose: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_lu_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out); +/* HMath.Matrix.LU.luDecomposeWithTolerance: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_lu **out); +/* HMath.Matrix.LU.luLower: pure; Float. */ +HMATH_API hmath_status hmath_dense_lu_lu_lower_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luUpper: pure; Float. */ +HMATH_API hmath_status hmath_dense_lu_lu_upper_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luPermutation: pure; Float. */ +HMATH_API hmath_status hmath_dense_lu_lu_permutation_f32(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out); +/* HMath.Matrix.LU.solveLU: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_solve_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.LU.solveMatrixLU: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_solve_matrix_lu_f32(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.LU.solve: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_solve_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.LU.solveMatrix: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_solve_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.LU.determinantLU: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_determinant_lu_f32(hmath_context *context, const hmath_dense_lu *a0, float *out); +/* HMath.Matrix.LU.determinant: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_determinant_f32(hmath_context *context, const hmath_dense_matrix *a0, float *out); +/* HMath.Matrix.LU.inverse: either; Float. */ +HMATH_API hmath_status hmath_dense_lu_inverse_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrDecompose: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_decompose_f32(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out); +/* HMath.Matrix.QR.qrDecomposeWithTolerance: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, hmath_dense_qr **out); +/* HMath.Matrix.QR.qrQ: pure; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_q_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrR: pure; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_r_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrPermutation: pure; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_permutation_f32(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out); +/* HMath.Matrix.QR.qrRank: pure; Float. */ +HMATH_API hmath_status hmath_dense_qr_qr_rank_f32(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out); +/* HMath.Matrix.QR.applyQ: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_apply_q_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.applyQT: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_apply_qt_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.solveMatrixQR: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_solve_matrix_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.solveQR: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_solve_qr_f32(hmath_context *context, const hmath_dense_qr *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.leastSquares: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_least_squares_f32(hmath_context *context, const hmath_dense_matrix *a0, const float *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.leastSquaresMatrix: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_least_squares_matrix_f32(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.ridgeSolve: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_ridge_solve_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const float *a2, size_t a2_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.ridgeSolveMatrix: either; Float. */ +HMATH_API hmath_status hmath_dense_qr_ridge_solve_matrix_f32(hmath_context *context, float a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +HMATH_API hmath_status hmath_dense_values_f64(hmath_context *context,const void *object,double *out,size_t capacity); +/* HMath.Matrix.fromList: maybe; Double. */ +HMATH_API hmath_status hmath_dense_from_list_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out); +/* HMath.Matrix.zeroMatrix: maybe; Double. */ +HMATH_API hmath_status hmath_dense_zero_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +/* HMath.Matrix.diagonal: maybe; Double. */ +HMATH_API hmath_status hmath_dense_diagonal_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out); +/* HMath.Matrix.at: maybe; Double. */ +HMATH_API hmath_status hmath_dense_at_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out, int *found); +/* HMath.Matrix.sliceMatrix: maybe; Double. */ +HMATH_API hmath_status hmath_dense_slice_matrix_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +/* HMath.Matrix.reshape: maybe; Double. */ +HMATH_API hmath_status hmath_dense_reshape_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +/* HMath.Matrix.addMatrix: maybe; Double. */ +HMATH_API hmath_status hmath_dense_add_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.subtractMatrix: maybe; Double. */ +HMATH_API hmath_status hmath_dense_subtract_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.hadamard: maybe; Double. */ +HMATH_API hmath_status hmath_dense_hadamard_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.multiply: maybe; Double. */ +HMATH_API hmath_status hmath_dense_multiply_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.identity: maybe; Double. */ +HMATH_API hmath_status hmath_dense_identity_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +/* HMath.Matrix.fromListChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_from_list_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const double *a2, size_t a2_count, hmath_dense_matrix **out); +/* HMath.Matrix.zeroMatrixChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_zero_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, hmath_dense_matrix **out); +/* HMath.Matrix.diagonalChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_diagonal_checked_f64(hmath_context *context, const double *a0, size_t a0_count, hmath_dense_matrix **out); +/* HMath.Matrix.atChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_at_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, ptrdiff_t a1, ptrdiff_t a2, double *out); +/* HMath.Matrix.sliceMatrixChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_slice_matrix_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, ptrdiff_t a2, ptrdiff_t a3, const hmath_dense_matrix *a4, hmath_dense_matrix **out); +/* HMath.Matrix.reshapeChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_reshape_checked_f64(hmath_context *context, ptrdiff_t a0, ptrdiff_t a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +/* HMath.Matrix.addMatrixChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_add_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.subtractMatrixChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_subtract_matrix_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.hadamardChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_hadamard_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.multiplyChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_multiply_checked_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.identityChecked: either; Double. */ +HMATH_API hmath_status hmath_dense_identity_checked_f64(hmath_context *context, ptrdiff_t a0, hmath_dense_matrix **out); +/* HMath.Matrix.scaleMatrix: pure; Double. */ +HMATH_API hmath_status hmath_dense_scale_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.transposeMatrix: pure; Double. */ +HMATH_API hmath_status hmath_dense_transpose_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luDecompose: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_lu_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_lu **out); +/* HMath.Matrix.LU.luDecomposeWithTolerance: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_lu_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_lu **out); +/* HMath.Matrix.LU.luLower: pure; Double. */ +HMATH_API hmath_status hmath_dense_lu_lu_lower_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luUpper: pure; Double. */ +HMATH_API hmath_status hmath_dense_lu_lu_upper_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_matrix **out); +/* HMath.Matrix.LU.luPermutation: pure; Double. */ +HMATH_API hmath_status hmath_dense_lu_lu_permutation_f64(hmath_context *context, const hmath_dense_lu *a0, hmath_dense_indices **out); +/* HMath.Matrix.LU.solveLU: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_solve_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.LU.solveMatrixLU: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_solve_matrix_lu_f64(hmath_context *context, const hmath_dense_lu *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.LU.solve: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_solve_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.LU.solveMatrix: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_solve_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.LU.determinantLU: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_determinant_lu_f64(hmath_context *context, const hmath_dense_lu *a0, double *out); +/* HMath.Matrix.LU.determinant: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_determinant_f64(hmath_context *context, const hmath_dense_matrix *a0, double *out); +/* HMath.Matrix.LU.inverse: either; Double. */ +HMATH_API hmath_status hmath_dense_lu_inverse_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrDecompose: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_decompose_f64(hmath_context *context, const hmath_dense_matrix *a0, hmath_dense_qr **out); +/* HMath.Matrix.QR.qrDecomposeWithTolerance: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_decompose_with_tolerance_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, hmath_dense_qr **out); +/* HMath.Matrix.QR.qrQ: pure; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_q_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrR: pure; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_r_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_matrix **out); +/* HMath.Matrix.QR.qrPermutation: pure; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_permutation_f64(hmath_context *context, const hmath_dense_qr *a0, hmath_dense_indices **out); +/* HMath.Matrix.QR.qrRank: pure; Double. */ +HMATH_API hmath_status hmath_dense_qr_qr_rank_f64(hmath_context *context, const hmath_dense_qr *a0, ptrdiff_t *out); +/* HMath.Matrix.QR.applyQ: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_apply_q_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.applyQT: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_apply_qt_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.solveMatrixQR: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_solve_matrix_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.solveQR: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_solve_qr_f64(hmath_context *context, const hmath_dense_qr *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.leastSquares: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_least_squares_f64(hmath_context *context, const hmath_dense_matrix *a0, const double *a1, size_t a1_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.leastSquaresMatrix: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_least_squares_matrix_f64(hmath_context *context, const hmath_dense_matrix *a0, const hmath_dense_matrix *a1, hmath_dense_matrix **out); +/* HMath.Matrix.QR.ridgeSolve: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_ridge_solve_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const double *a2, size_t a2_count, hmath_dense_vector **out); +/* HMath.Matrix.QR.ridgeSolveMatrix: either; Double. */ +HMATH_API hmath_status hmath_dense_qr_ridge_solve_matrix_f64(hmath_context *context, double a0, const hmath_dense_matrix *a1, const hmath_dense_matrix *a2, hmath_dense_matrix **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_matrix_value.h b/include/hmath_matrix_value.h new file mode 100644 index 0000000..c6275d3 --- /dev/null +++ b/include/hmath_matrix_value.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_value_bindings.py. */ +#ifndef HMATH_MATRIX_VALUE_H +#define HMATH_MATRIX_VALUE_H +#include "hmath_matrix.h" +#include "hmath_value.h" +/* Structural element types have no invented Num instance. */ +#define HMATH_MATRIX_BOOL 16 +#define HMATH_MATRIX_STRING 17 +#ifdef __cplusplus +extern "C" { +#endif +/* Lossless Matrix core over every supported Num coefficient. Inputs borrow + * immutable Value owners. Successful outputs own independent references; + * release with hmath_value_release. Maybe becomes a successful None Value; + * Either preserves complete MathError and failure leaves out untouched. + * prototype is a typed coefficient scalar, required by constructors even when + * the source list is empty. No dtype coercion or mathematical limits added. + * LU/QR retain their original RealFloat restriction to Float and Double. */ +HMATH_API hmath_status hmath_dense_to_value(hmath_context *context,const hmath_dense_matrix *matrix,hmath_value **out); +/* Import real Float/Double Value Matrix into the pre-existing typed Matrix + * owner. Exact/complex values instead use the generic operations below. */ +HMATH_API hmath_status hmath_dense_from_value(hmath_context *context,const hmath_value *value,hmath_dense_matrix **out); +HMATH_API hmath_status hmath_matrix_value_from_list(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_zero_matrix(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_diagonal(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_at(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_slice_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,const hmath_value *a3,const hmath_value *a4,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_reshape(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_add_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_subtract_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_hadamard(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_multiply(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_identity(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_from_list_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_zero_matrix_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_diagonal_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_at_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_slice_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,const hmath_value *a3,const hmath_value *a4,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_reshape_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,const hmath_value *a2,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_add_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_subtract_matrix_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_hadamard_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_multiply_checked(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_identity_checked(hmath_context *context,const hmath_value *prototype,const hmath_value *a0,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_scale_matrix(hmath_context *context,const hmath_value *a0,const hmath_value *a1,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_transpose_matrix(hmath_context *context,const hmath_value *a0,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_to_list(hmath_context *context,const hmath_value *matrix,hmath_value **out); +HMATH_API hmath_status hmath_matrix_value_shape(hmath_context *context,const hmath_value *matrix,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_numeric.h b/include/hmath_numeric.h new file mode 100644 index 0000000..80def59 --- /dev/null +++ b/include/hmath_numeric.h @@ -0,0 +1,6228 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_numeric_bindings.py. */ +#ifndef HMATH_NUMERIC_H +#define HMATH_NUMERIC_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original Haskell semantics, including unchecked NaN/Inf behavior. + * Each checked MathError is reported as HMATH_MATH_ERROR with its + * constructor and payload in hmath_last_error_message(). Pure errors + * return HMATH_HASKELL_EXCEPTION. Output is untouched on failure. + * Integer arguments are NUL-terminated ASCII decimal strings; results + * are exact decimal strings allocated by HMath. Free each string with + * hmath_numeric_string_free, including rational numerator/denominator. + * Pair/complex arguments and tuple results are flattened in order. + * List output capacity is checked (prefixSum needs count + 1). Pointers must + * not overlap one another or inputs. Inputs are borrowed for the call. + * Concurrent calls use independent outputs; error state is thread-local. + * Cancellation is checked before entry, not during pure evaluation. */ +HMATH_API void hmath_numeric_string_free(char *value); +/* Free owned numerical result arrays (and outer exact-string arrays). */ +HMATH_API void hmath_numeric_buffer_free(void *value); +/* Dynamic results return an owned pointer and logical element count. + * Free every exact string first, then the outer buffer. Rational + * arrays contain numerator,denominator pairs (2*count strings). + * Complex arrays contain real,imaginary pairs (2*count components). + * Bounded integer suffixes select the original Haskell numeric + * instance: ordinary arithmetic wraps, checked/saturating functions + * retain their original checks/clamping. Integer/Rational are exact. */ +/* HMath.Basic.factorial; fixed specialization. */ +HMATH_API hmath_status hmath_basic_factorial( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Basic.fibonacci; fixed specialization. */ +HMATH_API hmath_status hmath_basic_fibonacci( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Basic.isPrime; fixed specialization. */ +HMATH_API hmath_status hmath_basic_is_prime( + hmath_context *context, + const char *n, + int *out0); +/* HMath.Basic.clamp; float32 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0); +/* HMath.Basic.clamp; float64 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0); +/* HMath.Basic.clamp; rational specialization. */ +HMATH_API hmath_status hmath_basic_clamp_rational( + hmath_context *context, + const char *low_numerator, + const char *low_denominator, + const char *high_numerator, + const char *high_denominator, + const char *value_numerator, + const char *value_denominator, + char **out0, + char **out1); +/* HMath.Basic.clamp; integer specialization. */ +HMATH_API hmath_status hmath_basic_clamp_integer( + hmath_context *context, + const char *low, + const char *high, + const char *value, + char **out0); +/* HMath.Basic.clamp; int8 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_i8( + hmath_context *context, + int8_t low, + int8_t high, + int8_t value, + int8_t *out0); +/* HMath.Basic.clamp; int16 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_i16( + hmath_context *context, + int16_t low, + int16_t high, + int16_t value, + int16_t *out0); +/* HMath.Basic.clamp; int32 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_i32( + hmath_context *context, + int32_t low, + int32_t high, + int32_t value, + int32_t *out0); +/* HMath.Basic.clamp; int64 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_i64( + hmath_context *context, + int64_t low, + int64_t high, + int64_t value, + int64_t *out0); +/* HMath.Basic.clamp; uint8 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_u8( + hmath_context *context, + uint8_t low, + uint8_t high, + uint8_t value, + uint8_t *out0); +/* HMath.Basic.clamp; uint16 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_u16( + hmath_context *context, + uint16_t low, + uint16_t high, + uint16_t value, + uint16_t *out0); +/* HMath.Basic.clamp; uint32 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_u32( + hmath_context *context, + uint32_t low, + uint32_t high, + uint32_t value, + uint32_t *out0); +/* HMath.Basic.clamp; uint64 specialization. */ +HMATH_API hmath_status hmath_basic_clamp_u64( + hmath_context *context, + uint64_t low, + uint64_t high, + uint64_t value, + uint64_t *out0); +/* HMath.Basic.clamp; intp specialization. */ +HMATH_API hmath_status hmath_basic_clamp_int( + hmath_context *context, + ptrdiff_t low, + ptrdiff_t high, + ptrdiff_t value, + ptrdiff_t *out0); +/* HMath.Basic.clamp; uintp specialization. */ +HMATH_API hmath_status hmath_basic_clamp_word( + hmath_context *context, + size_t low, + size_t high, + size_t value, + size_t *out0); +/* HMath.Basic.lerp; float32 specialization. */ +HMATH_API hmath_status hmath_basic_lerp_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0); +/* HMath.Basic.lerp; float64 specialization. */ +HMATH_API hmath_status hmath_basic_lerp_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0); +/* HMath.Basic.lerp; rational specialization. */ +HMATH_API hmath_status hmath_basic_lerp_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + const char *t_numerator, + const char *t_denominator, + char **out0, + char **out1); +/* HMath.Basic.lerp; complex64 specialization. */ +HMATH_API hmath_status hmath_basic_lerp_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float t_0, + float t_1, + float *out0, + float *out1); +/* HMath.Basic.lerp; complex128 specialization. */ +HMATH_API hmath_status hmath_basic_lerp_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double t_0, + double t_1, + double *out0, + double *out1); +/* HMath.Scalar.add; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_add_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.add; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_add_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.add; rational specialization. */ +HMATH_API hmath_status hmath_scalar_add_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +/* HMath.Scalar.add; integer specialization. */ +HMATH_API hmath_status hmath_scalar_add_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +/* HMath.Scalar.add; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.add; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.add; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.add; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.add; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.add; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.add; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.add; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.add; intp specialization. */ +HMATH_API hmath_status hmath_scalar_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.add; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.add; complex64 specialization. */ +HMATH_API hmath_status hmath_scalar_add_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +/* HMath.Scalar.add; complex128 specialization. */ +HMATH_API hmath_status hmath_scalar_add_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Scalar.subtractScalar; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.subtractScalar; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.subtractScalar; rational specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +/* HMath.Scalar.subtractScalar; integer specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +/* HMath.Scalar.subtractScalar; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.subtractScalar; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.subtractScalar; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.subtractScalar; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.subtractScalar; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.subtractScalar; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.subtractScalar; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.subtractScalar; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.subtractScalar; intp specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.subtractScalar; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.subtractScalar; complex64 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +/* HMath.Scalar.subtractScalar; complex128 specialization. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Scalar.multiply; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.multiply; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.multiply; rational specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +/* HMath.Scalar.multiply; integer specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +/* HMath.Scalar.multiply; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.multiply; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.multiply; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.multiply; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.multiply; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.multiply; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.multiply; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.multiply; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.multiply; intp specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.multiply; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.multiply; complex64 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_c64( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0, + float *out1); +/* HMath.Scalar.multiply; complex128 specialization. */ +HMATH_API hmath_status hmath_scalar_multiply_c128( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Scalar.minimumScalar; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.minimumScalar; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.minimumScalar; rational specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +/* HMath.Scalar.minimumScalar; integer specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +/* HMath.Scalar.minimumScalar; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.minimumScalar; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.minimumScalar; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.minimumScalar; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.minimumScalar; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.minimumScalar; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.minimumScalar; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.minimumScalar; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.minimumScalar; intp specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.minimumScalar; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.maximumScalar; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.maximumScalar; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.maximumScalar; rational specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_rational( + hmath_context *context, + const char *a_numerator, + const char *a_denominator, + const char *b_numerator, + const char *b_denominator, + char **out0, + char **out1); +/* HMath.Scalar.maximumScalar; integer specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_integer( + hmath_context *context, + const char *a, + const char *b, + char **out0); +/* HMath.Scalar.maximumScalar; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.maximumScalar; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.maximumScalar; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.maximumScalar; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.maximumScalar; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.maximumScalar; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.maximumScalar; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.maximumScalar; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.maximumScalar; intp specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.maximumScalar; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.absolute; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.absolute; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.absolute; rational specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +/* HMath.Scalar.absolute; integer specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_integer( + hmath_context *context, + const char *x, + char **out0); +/* HMath.Scalar.absolute; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_i8( + hmath_context *context, + int8_t x, + int8_t *out0); +/* HMath.Scalar.absolute; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_i16( + hmath_context *context, + int16_t x, + int16_t *out0); +/* HMath.Scalar.absolute; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_i32( + hmath_context *context, + int32_t x, + int32_t *out0); +/* HMath.Scalar.absolute; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_i64( + hmath_context *context, + int64_t x, + int64_t *out0); +/* HMath.Scalar.absolute; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0); +/* HMath.Scalar.absolute; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0); +/* HMath.Scalar.absolute; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0); +/* HMath.Scalar.absolute; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0); +/* HMath.Scalar.absolute; intp specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0); +/* HMath.Scalar.absolute; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_word( + hmath_context *context, + size_t x, + size_t *out0); +/* HMath.Scalar.absolute; complex64 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1); +/* HMath.Scalar.absolute; complex128 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1); +/* HMath.Scalar.sign; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.sign; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.sign; rational specialization. */ +HMATH_API hmath_status hmath_scalar_sign_rational( + hmath_context *context, + const char *x_numerator, + const char *x_denominator, + char **out0, + char **out1); +/* HMath.Scalar.sign; integer specialization. */ +HMATH_API hmath_status hmath_scalar_sign_integer( + hmath_context *context, + const char *x, + char **out0); +/* HMath.Scalar.sign; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_i8( + hmath_context *context, + int8_t x, + int8_t *out0); +/* HMath.Scalar.sign; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_i16( + hmath_context *context, + int16_t x, + int16_t *out0); +/* HMath.Scalar.sign; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_i32( + hmath_context *context, + int32_t x, + int32_t *out0); +/* HMath.Scalar.sign; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_i64( + hmath_context *context, + int64_t x, + int64_t *out0); +/* HMath.Scalar.sign; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_u8( + hmath_context *context, + uint8_t x, + uint8_t *out0); +/* HMath.Scalar.sign; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_u16( + hmath_context *context, + uint16_t x, + uint16_t *out0); +/* HMath.Scalar.sign; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_u32( + hmath_context *context, + uint32_t x, + uint32_t *out0); +/* HMath.Scalar.sign; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_u64( + hmath_context *context, + uint64_t x, + uint64_t *out0); +/* HMath.Scalar.sign; intp specialization. */ +HMATH_API hmath_status hmath_scalar_sign_int( + hmath_context *context, + ptrdiff_t x, + ptrdiff_t *out0); +/* HMath.Scalar.sign; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_sign_word( + hmath_context *context, + size_t x, + size_t *out0); +/* HMath.Scalar.sign; complex64 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_c64( + hmath_context *context, + float x_0, + float x_1, + float *out0, + float *out1); +/* HMath.Scalar.sign; complex128 specialization. */ +HMATH_API hmath_status hmath_scalar_sign_c128( + hmath_context *context, + double x_0, + double x_1, + double *out0, + double *out1); +/* HMath.Scalar.divide; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_divide_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.divide; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_divide_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.power; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_power_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.power; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_power_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.hypot; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_hypot_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.hypot; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_hypot_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.clampChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_clamp_checked_f32( + hmath_context *context, + float low, + float high, + float value, + float *out0); +/* HMath.Scalar.clampChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_clamp_checked_f64( + hmath_context *context, + double low, + double high, + double value, + double *out0); +/* HMath.Scalar.lerpChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_lerp_checked_f32( + hmath_context *context, + float a, + float b, + float t, + float *out0); +/* HMath.Scalar.lerpChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_lerp_checked_f64( + hmath_context *context, + double a, + double b, + double t, + double *out0); +/* HMath.Scalar.inverseLerp; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_inverse_lerp_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +/* HMath.Scalar.inverseLerp; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_inverse_lerp_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +/* HMath.Scalar.smoothstep; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_smoothstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +/* HMath.Scalar.smoothstep; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_smoothstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +/* HMath.Scalar.smootherstep; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_smootherstep_f32( + hmath_context *context, + float a, + float b, + float x, + float *out0); +/* HMath.Scalar.smootherstep; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_smootherstep_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +/* HMath.Scalar.remap; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_remap_f32( + hmath_context *context, + float a, + float b, + float c, + float d, + float x, + float *out0); +/* HMath.Scalar.remap; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_remap_f64( + hmath_context *context, + double a, + double b, + double c, + double d, + double x, + double *out0); +/* HMath.Scalar.step; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_step_f32( + hmath_context *context, + float edge, + float x, + float *out0); +/* HMath.Scalar.step; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_step_f64( + hmath_context *context, + double edge, + double x, + double *out0); +/* HMath.Scalar.sqrtChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_sqrt_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.sqrtChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_sqrt_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.cubeRoot; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_cube_root_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.cubeRoot; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_cube_root_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.reciprocalSqrt; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_reciprocal_sqrt_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.reciprocalSqrt; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_reciprocal_sqrt_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.expChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_exp_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.expChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_exp_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.logChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_log_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.logChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_log_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.expm1; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_expm1_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.expm1; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_expm1_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.log1p; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_log1p_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Scalar.log1p; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_log1p_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.integerPower; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_integer_power_f32( + hmath_context *context, + float a, + const char *n, + float *out0); +/* HMath.Scalar.integerPower; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_integer_power_f64( + hmath_context *context, + double a, + const char *n, + double *out0); +/* HMath.Scalar.nthRoot; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_nth_root_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0); +/* HMath.Scalar.nthRoot; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_nth_root_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Scalar.roundDigits; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_round_digits_f32( + hmath_context *context, + ptrdiff_t n, + float x, + float *out0); +/* HMath.Scalar.roundDigits; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_round_digits_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Scalar.absoluteError; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0); +/* HMath.Scalar.absoluteError; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_absolute_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0); +/* HMath.Scalar.relativeError; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_relative_error_f32( + hmath_context *context, + float actual, + float expected, + float *out0); +/* HMath.Scalar.relativeError; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_relative_error_f64( + hmath_context *context, + double actual, + double expected, + double *out0); +/* HMath.Scalar.fusedMultiplyAdd; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_fused_multiply_add_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0); +/* HMath.Scalar.fusedMultiplyAdd; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_fused_multiply_add_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0); +/* HMath.Scalar.checkedFloatMultiply; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_float_multiply_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Scalar.checkedFloatMultiply; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_float_multiply_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Scalar.floorChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_floor_checked_f32( + hmath_context *context, + float x, + char **out0); +/* HMath.Scalar.floorChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_floor_checked_f64( + hmath_context *context, + double x, + char **out0); +/* HMath.Scalar.ceilChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_ceil_checked_f32( + hmath_context *context, + float x, + char **out0); +/* HMath.Scalar.ceilChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_ceil_checked_f64( + hmath_context *context, + double x, + char **out0); +/* HMath.Scalar.roundChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_round_checked_f32( + hmath_context *context, + float x, + char **out0); +/* HMath.Scalar.roundChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_round_checked_f64( + hmath_context *context, + double x, + char **out0); +/* HMath.Scalar.truncateChecked; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_truncate_checked_f32( + hmath_context *context, + float x, + char **out0); +/* HMath.Scalar.truncateChecked; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_truncate_checked_f64( + hmath_context *context, + double x, + char **out0); +/* HMath.Scalar.bankersRound; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_bankers_round_f32( + hmath_context *context, + float x, + char **out0); +/* HMath.Scalar.bankersRound; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_bankers_round_f64( + hmath_context *context, + double x, + char **out0); +/* HMath.Scalar.integerFraction; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_integer_fraction_f32( + hmath_context *context, + float x, + char **out0, + float *out1); +/* HMath.Scalar.integerFraction; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_integer_fraction_f64( + hmath_context *context, + double x, + char **out0, + double *out1); +/* HMath.Scalar.quotientRemainder; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_quotient_remainder( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +/* HMath.Scalar.euclideanDivision; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_euclidean_division( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +/* HMath.Scalar.positiveModulo; integer specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_integer( + hmath_context *context, + const char *a, + const char *modulus, + char **out0); +/* HMath.Scalar.positiveModulo; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_i8( + hmath_context *context, + int8_t a, + int8_t modulus, + int8_t *out0); +/* HMath.Scalar.positiveModulo; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_i16( + hmath_context *context, + int16_t a, + int16_t modulus, + int16_t *out0); +/* HMath.Scalar.positiveModulo; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_i32( + hmath_context *context, + int32_t a, + int32_t modulus, + int32_t *out0); +/* HMath.Scalar.positiveModulo; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_i64( + hmath_context *context, + int64_t a, + int64_t modulus, + int64_t *out0); +/* HMath.Scalar.positiveModulo; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_u8( + hmath_context *context, + uint8_t a, + uint8_t modulus, + uint8_t *out0); +/* HMath.Scalar.positiveModulo; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_u16( + hmath_context *context, + uint16_t a, + uint16_t modulus, + uint16_t *out0); +/* HMath.Scalar.positiveModulo; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_u32( + hmath_context *context, + uint32_t a, + uint32_t modulus, + uint32_t *out0); +/* HMath.Scalar.positiveModulo; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_u64( + hmath_context *context, + uint64_t a, + uint64_t modulus, + uint64_t *out0); +/* HMath.Scalar.positiveModulo; intp specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t modulus, + ptrdiff_t *out0); +/* HMath.Scalar.positiveModulo; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_word( + hmath_context *context, + size_t a, + size_t modulus, + size_t *out0); +/* HMath.Scalar.positiveModulo; integer specialization. */ +HMATH_API hmath_status hmath_scalar_positive_modulo( + hmath_context *context, + const char *a, + const char *modulus, + char **out0); +/* HMath.Scalar.modularPower; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_modular_power( + hmath_context *context, + const char *a, + const char *n, + const char *modulus, + char **out0); +/* HMath.Scalar.factorialChecked; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_factorial_checked( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Scalar.doubleFactorial; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_double_factorial( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Scalar.fibonacciChecked; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_fibonacci_checked( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Scalar.lucas; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_lucas( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Scalar.catalan; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_catalan( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Scalar.risingFactorial; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_rising_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0); +/* HMath.Scalar.fallingFactorial; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_falling_factorial( + hmath_context *context, + const char *x, + const char *n, + char **out0); +/* HMath.Scalar.permutations; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_permutations( + hmath_context *context, + const char *n, + const char *k, + char **out0); +/* HMath.Scalar.combinations; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_combinations( + hmath_context *context, + const char *n, + const char *k, + char **out0); +/* HMath.Scalar.bernoulli; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_bernoulli( + hmath_context *context, + ptrdiff_t n, + char **out0, + char **out1); +/* HMath.Scalar.harmonic; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_harmonic( + hmath_context *context, + const char *n, + char **out0, + char **out1); +/* HMath.Scalar.cumulativeSum; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +/* HMath.Scalar.cumulativeSum; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +/* HMath.Scalar.cumulativeProduct; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +/* HMath.Scalar.cumulativeProduct; owned array result. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; float32 specialization. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0, + size_t out_capacity); +/* HMath.Scalar.prefixSum; float64 specialization. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0, + size_t out_capacity); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_integer( + hmath_context *context, + const char * const *values, + size_t values_count, + char * **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_i8( + hmath_context *context, + const int8_t *values, + size_t values_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_i16( + hmath_context *context, + const int16_t *values, + size_t values_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_i32( + hmath_context *context, + const int32_t *values, + size_t values_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_i64( + hmath_context *context, + const int64_t *values, + size_t values_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_u8( + hmath_context *context, + const uint8_t *values, + size_t values_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_u16( + hmath_context *context, + const uint16_t *values, + size_t values_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_u32( + hmath_context *context, + const uint32_t *values, + size_t values_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_u64( + hmath_context *context, + const uint64_t *values, + size_t values_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_int( + hmath_context *context, + const ptrdiff_t *values, + size_t values_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_word( + hmath_context *context, + const size_t *values, + size_t values_count, + size_t **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_c64( + hmath_context *context, + float const *values, + size_t values_count, + float **out_data, + size_t *out_count); +/* HMath.Scalar.prefixSum; owned array result. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_c128( + hmath_context *context, + double const *values, + size_t values_count, + double **out_data, + size_t *out_count); +/* HMath.Trigonometry.sinChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sin_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.sinChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sin_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.cosChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cos_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.cosChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cos_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.tanChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_tan_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.tanChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_tan_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.asinChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asin_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.asinChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asin_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acosChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acos_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acosChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acos_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.atanChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atan_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.atanChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atan_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.sec; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sec_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.sec; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sec_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.csc; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_csc_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.csc; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_csc_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.cot; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cot_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.cot; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cot_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.asec; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asec_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.asec; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asec_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acsc; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acsc_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acsc; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acsc_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acot; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acot_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acot; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acot_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.sinhChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sinh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.sinhChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sinh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.coshChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cosh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.coshChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cosh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.tanhChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_tanh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.tanhChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_tanh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.asinhChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asinh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.asinhChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asinh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acoshChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acosh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acoshChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acosh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.atanhChecked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atanh_checked_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.atanhChecked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atanh_checked_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.sech; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sech_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.sech; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sech_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.csch; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_csch_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.csch; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_csch_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.coth; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_coth_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.coth; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_coth_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.asech; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asech_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.asech; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_asech_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acsch; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acsch_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acsch; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acsch_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.acoth; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acoth_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.acoth; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_acoth_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.normalizeAngle; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_normalize_angle_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.normalizeAngle; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_normalize_angle_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.normalizeSignedAngle; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_normalize_signed_angle_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.normalizeSignedAngle; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_normalize_signed_angle_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.versine; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_versine_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.versine; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_versine_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.haversine; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_haversine_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.haversine; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_haversine_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.sinc; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sinc_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.sinc; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sinc_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.cosc; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cosc_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Trigonometry.cosc; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_cosc_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Trigonometry.atan2Checked; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atan2_checked_f32( + hmath_context *context, + float y, + float x, + float *out0); +/* HMath.Trigonometry.atan2Checked; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_atan2_checked_f64( + hmath_context *context, + double y, + double x, + double *out0); +/* HMath.Trigonometry.sincos; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sincos_f32( + hmath_context *context, + float x, + float *out0, + float *out1); +/* HMath.Trigonometry.sincos; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_sincos_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Trigonometry.wrap; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_wrap_f32( + hmath_context *context, + float low, + float high, + float x, + float *out0); +/* HMath.Trigonometry.wrap; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_wrap_f64( + hmath_context *context, + double low, + double high, + double x, + double *out0); +/* HMath.Trigonometry.angleDifference; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_angle_difference_f32( + hmath_context *context, + float a, + float b, + float *out0); +/* HMath.Trigonometry.angleDifference; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_angle_difference_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Trigonometry.greatCircleAngle; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_great_circle_angle_f32( + hmath_context *context, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +/* HMath.Trigonometry.greatCircleAngle; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_great_circle_angle_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +/* HMath.Trigonometry.greatCircleDistance; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_great_circle_distance_f32( + hmath_context *context, + float radius, + float a_0, + float a_1, + float b_0, + float b_1, + float *out0); +/* HMath.Trigonometry.greatCircleDistance; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_great_circle_distance_f64( + hmath_context *context, + double radius, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0); +/* HMath.Trigonometry.sphericalSide; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_side_f32( + hmath_context *context, + float a, + float b, + float included, + float *out0); +/* HMath.Trigonometry.sphericalSide; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_side_f64( + hmath_context *context, + double a, + double b, + double included, + double *out0); +/* HMath.Trigonometry.sphericalAngles; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_angles_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0, + float *out1, + float *out2); +/* HMath.Trigonometry.sphericalAngles; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_angles_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0, + double *out1, + double *out2); +/* HMath.Trigonometry.sphericalExcess; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_excess_f32( + hmath_context *context, + float a, + float b, + float c, + float *out0); +/* HMath.Trigonometry.sphericalExcess; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_spherical_excess_f64( + hmath_context *context, + double a, + double b, + double c, + double *out0); +/* HMath.Trigonometry.complexSin; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_sin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexSin; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_sin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexCos; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_cos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexCos; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_cos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexTan; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_tan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexTan; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_tan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAsin; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_asin_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAsin; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_asin_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAcos; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_acos_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAcos; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_acos_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAtan; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_atan_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAtan; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_atan_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexSinh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_sinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexSinh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_sinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexCosh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_cosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexCosh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_cosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexTanh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_tanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexTanh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_tanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAsinh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_asinh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAsinh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_asinh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAcosh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_acosh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAcosh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_acosh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.complexAtanh; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_atanh_f32( + hmath_context *context, + float z_0, + float z_1, + float *out0, + float *out1); +/* HMath.Trigonometry.complexAtanh; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_complex_atanh_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Trigonometry.periodicSawtooth; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_sawtooth_f32( + hmath_context *context, + float period, + float x, + float *out0); +/* HMath.Trigonometry.periodicSawtooth; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_sawtooth_f64( + hmath_context *context, + double period, + double x, + double *out0); +/* HMath.Trigonometry.periodicTriangle; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_triangle_f32( + hmath_context *context, + float period, + float x, + float *out0); +/* HMath.Trigonometry.periodicTriangle; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_triangle_f64( + hmath_context *context, + double period, + double x, + double *out0); +/* HMath.Trigonometry.periodicSquare; float32 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_square_f32( + hmath_context *context, + float period, + float x, + float *out0); +/* HMath.Trigonometry.periodicSquare; float64 specialization. */ +HMATH_API hmath_status hmath_trigonometry_periodic_square_f64( + hmath_context *context, + double period, + double x, + double *out0); +/* HMath.Statistics.mean; float32 specialization. */ +HMATH_API hmath_status hmath_statistics_mean_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +/* HMath.Statistics.mean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_mean_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +/* HMath.Statistics.mean; rational specialization. */ +HMATH_API hmath_status hmath_statistics_mean_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +/* HMath.Statistics.mean; complex64 specialization. */ +HMATH_API hmath_status hmath_statistics_mean_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +/* HMath.Statistics.mean; complex128 specialization. */ +HMATH_API hmath_status hmath_statistics_mean_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +/* HMath.Statistics.variance; float32 specialization. */ +HMATH_API hmath_status hmath_statistics_variance_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +/* HMath.Statistics.variance; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_variance_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +/* HMath.Statistics.variance; rational specialization. */ +HMATH_API hmath_status hmath_statistics_variance_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +/* HMath.Statistics.variance; complex64 specialization. */ +HMATH_API hmath_status hmath_statistics_variance_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +/* HMath.Statistics.variance; complex128 specialization. */ +HMATH_API hmath_status hmath_statistics_variance_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +/* HMath.Statistics.standardDeviation; float32 specialization. */ +HMATH_API hmath_status hmath_statistics_standard_deviation_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +/* HMath.Statistics.standardDeviation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_standard_deviation_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +/* HMath.Statistics.standardDeviation; complex64 specialization. */ +HMATH_API hmath_status hmath_statistics_standard_deviation_c64( + hmath_context *context, + float const *values, + size_t values_count, + float *out0, + float *out1); +/* HMath.Statistics.standardDeviation; complex128 specialization. */ +HMATH_API hmath_status hmath_statistics_standard_deviation_c128( + hmath_context *context, + double const *values, + size_t values_count, + double *out0, + double *out1); +/* HMath.Statistics.median; float32 specialization. */ +HMATH_API hmath_status hmath_statistics_median_f32( + hmath_context *context, + const float *values, + size_t values_count, + float *out0); +/* HMath.Statistics.median; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_median_f64( + hmath_context *context, + const double *values, + size_t values_count, + double *out0); +/* HMath.Statistics.median; rational specialization. */ +HMATH_API hmath_status hmath_statistics_median_rational( + hmath_context *context, + const char * const *values, + size_t values_count, + char **out0, + char **out1); +/* HMath.Constants.piConstant; float32 specialization. */ +HMATH_API hmath_status hmath_constants_pi_constant_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.piConstant; float64 specialization. */ +HMATH_API hmath_status hmath_constants_pi_constant_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.eConstant; float32 specialization. */ +HMATH_API hmath_status hmath_constants_e_constant_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.eConstant; float64 specialization. */ +HMATH_API hmath_status hmath_constants_e_constant_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.tau; float32 specialization. */ +HMATH_API hmath_status hmath_constants_tau_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.tau; float64 specialization. */ +HMATH_API hmath_status hmath_constants_tau_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.goldenRatio; float32 specialization. */ +HMATH_API hmath_status hmath_constants_golden_ratio_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.goldenRatio; float64 specialization. */ +HMATH_API hmath_status hmath_constants_golden_ratio_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.eulerMascheroni; float32 specialization. */ +HMATH_API hmath_status hmath_constants_euler_mascheroni_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.eulerMascheroni; float64 specialization. */ +HMATH_API hmath_status hmath_constants_euler_mascheroni_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.catalanConstant; float32 specialization. */ +HMATH_API hmath_status hmath_constants_catalan_constant_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.catalanConstant; float64 specialization. */ +HMATH_API hmath_status hmath_constants_catalan_constant_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.aperyConstant; float32 specialization. */ +HMATH_API hmath_status hmath_constants_apery_constant_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.aperyConstant; float64 specialization. */ +HMATH_API hmath_status hmath_constants_apery_constant_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.sqrt2; float32 specialization. */ +HMATH_API hmath_status hmath_constants_sqrt2_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.sqrt2; float64 specialization. */ +HMATH_API hmath_status hmath_constants_sqrt2_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.sqrt3; float32 specialization. */ +HMATH_API hmath_status hmath_constants_sqrt3_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.sqrt3; float64 specialization. */ +HMATH_API hmath_status hmath_constants_sqrt3_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.ln2; float32 specialization. */ +HMATH_API hmath_status hmath_constants_ln2_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.ln2; float64 specialization. */ +HMATH_API hmath_status hmath_constants_ln2_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.ln10; float32 specialization. */ +HMATH_API hmath_status hmath_constants_ln10_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.ln10; float64 specialization. */ +HMATH_API hmath_status hmath_constants_ln10_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.infinity; float32 specialization. */ +HMATH_API hmath_status hmath_constants_infinity_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.infinity; float64 specialization. */ +HMATH_API hmath_status hmath_constants_infinity_f64( + hmath_context *context, + double *out0); +/* HMath.Constants.nan; float32 specialization. */ +HMATH_API hmath_status hmath_constants_nan_f32( + hmath_context *context, + float *out0); +/* HMath.Constants.nan; float64 specialization. */ +HMATH_API hmath_status hmath_constants_nan_f64( + hmath_context *context, + double *out0); +/* HMath.Scalar.multinomial; fixed specialization. */ +HMATH_API hmath_status hmath_scalar_multinomial( + hmath_context *context, + const char * const *ks, + size_t ks_count, + char **out0); +/* HMath.NumberTheory.gcdInteger; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_gcd_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0); +/* HMath.NumberTheory.lcmInteger; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_lcm_integer( + hmath_context *context, + const char *argument1, + const char *argument2, + char **out0); +/* HMath.NumberTheory.extendedGCD; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_extended_g_c_d( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1, + char **out2); +/* HMath.NumberTheory.bezout; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_bezout( + hmath_context *context, + const char *a, + const char *b, + char **out0, + char **out1); +/* HMath.NumberTheory.modPow; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_mod_pow( + hmath_context *context, + const char *a, + const char *e, + const char *m, + char **out0); +/* HMath.NumberTheory.modInverse; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_mod_inverse( + hmath_context *context, + const char *a, + const char *m, + char **out0); +/* HMath.NumberTheory.integerSquareRoot; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_integer_square_root( + hmath_context *context, + const char *n, + char **out0); +/* HMath.NumberTheory.isPrimeExact; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_is_prime_exact( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0); +/* HMath.NumberTheory.nextPrime; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_next_prime( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.millerRabin; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_miller_rabin( + hmath_context *context, + const char * const *bases, + size_t bases_count, + const char *n, + int *out0); +/* HMath.NumberTheory.bailliePSW; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_baillie_p_s_w( + hmath_context *context, + const char *n, + int *out0); +/* HMath.NumberTheory.sieveEratosthenes; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_sieve_eratosthenes( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.sieveAtkin; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_sieve_atkin( + hmath_context *context, + ptrdiff_t bound, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.segmentedSieve; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_segmented_sieve( + hmath_context *context, + const char *lo, + const char *hi, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.pollardRho; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_pollard_rho( + hmath_context *context, + ptrdiff_t budget, + const char *seed, + const char *n, + char **out0); +/* HMath.NumberTheory.pollardPMinusOne; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_pollard_p_minus_one( + hmath_context *context, + ptrdiff_t bound, + const char *base, + const char *n, + char **out0); +/* HMath.NumberTheory.fermatFactor; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_fermat_factor( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.divisors; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_divisors( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.divisorSum; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_divisor_sum( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.divisorCount; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_divisor_count( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.eulerTotient; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_euler_totient( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.carmichael; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_carmichael( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.mobius; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_mobius( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.liouville; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_liouville( + hmath_context *context, + ptrdiff_t budget, + const char *n, + char **out0); +/* HMath.NumberTheory.multiplicativeOrder; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_multiplicative_order( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *m, + char **out0); +/* HMath.NumberTheory.primitiveRoot; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_primitive_root( + hmath_context *context, + ptrdiff_t budget, + const char *m, + char **out0); +/* HMath.NumberTheory.discreteLog; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_discrete_log( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + const char *m, + char **out0); +/* HMath.NumberTheory.legendreSymbol; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_legendre_symbol( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +/* HMath.NumberTheory.jacobiSymbol; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_jacobi_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0); +/* HMath.NumberTheory.kroneckerSymbol; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_kronecker_symbol( + hmath_context *context, + const char *a, + const char *n, + char **out0); +/* HMath.NumberTheory.tonelliShanks; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_tonelli_shanks( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *p, + char **out0); +/* HMath.NumberTheory.continuedFraction; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_continued_fraction( + hmath_context *context, + const char *r_numerator, + const char *r_denominator, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.fromContinuedFraction; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_from_continued_fraction( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char **out0, + char **out1); +/* HMath.NumberTheory.convergents; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_convergents( + hmath_context *context, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.farey; owned array result. */ +HMATH_API hmath_status hmath_numbertheory_farey( + hmath_context *context, + const char *n, + char * **out_data, + size_t *out_count); +/* HMath.NumberTheory.pellFundamental; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_pell_fundamental( + hmath_context *context, + ptrdiff_t budget, + const char *d, + char **out0, + char **out1); +/* HMath.NumberTheory.isPerfectNumber; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_is_perfect_number( + hmath_context *context, + ptrdiff_t budget, + const char *n, + int *out0); +/* HMath.NumberTheory.areAmicable; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_are_amicable( + hmath_context *context, + ptrdiff_t budget, + const char *a, + const char *b, + int *out0); +/* HMath.NumberTheory.partitionCount; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_partition_count( + hmath_context *context, + ptrdiff_t n, + char **out0); +/* HMath.NumberTheory.fibonacciFast; fixed specialization. */ +HMATH_API hmath_status hmath_numbertheory_fibonacci_fast( + hmath_context *context, + const char *n, + char **out0); +/* HMath.Combinatorics.permutationsCount; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_permutations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +/* HMath.Combinatorics.combinationsCount; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_combinations_count( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +/* HMath.Combinatorics.multinomial; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_multinomial( + hmath_context *context, + ptrdiff_t const *argument1, + size_t argument1_count, + char **out0); +/* HMath.Combinatorics.rankPermutation; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_rank_permutation( + hmath_context *context, + ptrdiff_t const *p, + size_t p_count, + char **out0); +/* HMath.Combinatorics.unrankPermutation; owned array result. */ +HMATH_API hmath_status hmath_combinatorics_unrank_permutation( + hmath_context *context, + ptrdiff_t n, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Combinatorics.rankCombination; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_rank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t const *xs, + size_t xs_count, + char **out0); +/* HMath.Combinatorics.unrankCombination; owned array result. */ +HMATH_API hmath_status hmath_combinatorics_unrank_combination( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + const char *r, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Combinatorics.derangementCount; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_derangement_count( + hmath_context *context, + ptrdiff_t n, + char **out0); +/* HMath.Combinatorics.stirlingFirst; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_stirling_first( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +/* HMath.Combinatorics.stirlingSecond; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_stirling_second( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +/* HMath.Combinatorics.bellNumber; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_bell_number( + hmath_context *context, + ptrdiff_t n, + char **out0); +/* HMath.Combinatorics.eulerianNumber; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_eulerian_number( + hmath_context *context, + ptrdiff_t argument1, + ptrdiff_t argument2, + char **out0); +/* HMath.Combinatorics.lahNumber; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_lah_number( + hmath_context *context, + ptrdiff_t n, + ptrdiff_t k, + char **out0); +/* HMath.Combinatorics.catalanNumber; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_catalan_number( + hmath_context *context, + ptrdiff_t argument1, + char **out0); +/* HMath.Combinatorics.fibonacci; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_fibonacci( + hmath_context *context, + ptrdiff_t n, + char **out0); +/* HMath.Combinatorics.lucas; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_lucas( + hmath_context *context, + ptrdiff_t n, + char **out0); +/* HMath.Combinatorics.inclusionExclusion; fixed specialization. */ +HMATH_API hmath_status hmath_combinatorics_inclusion_exclusion( + hmath_context *context, + ptrdiff_t n, + const char * const *sizes, + size_t sizes_count, + char **out0); +/* HMath.Combinatorics.multisetCount; float32 specialization. */ +HMATH_API hmath_status hmath_combinatorics_multiset_count_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + char **out0); +/* HMath.Combinatorics.multisetCount; float64 specialization. */ +HMATH_API hmath_status hmath_combinatorics_multiset_count_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + char **out0); +/* HMath.Combinatorics.linearRecurrence; owned array result. */ +HMATH_API hmath_status hmath_combinatorics_linear_recurrence( + hmath_context *context, + ptrdiff_t n, + const char * const *cs, + size_t cs_count, + const char * const *initial, + size_t initial_count, + char * **out_data, + size_t *out_count); +/* HMath.Combinatorics.convolveSeries; owned array result. */ +HMATH_API hmath_status hmath_combinatorics_convolve_series( + hmath_context *context, + ptrdiff_t n, + const char * const *a, + size_t a_count, + const char * const *b, + size_t b_count, + char * **out_data, + size_t *out_count); +/* HMath.Combinatorics.finiteSum; float32 specialization. */ +HMATH_API hmath_status hmath_combinatorics_finite_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Combinatorics.finiteSum; float64 specialization. */ +HMATH_API hmath_status hmath_combinatorics_finite_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Linear.dot; float32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +/* HMath.Linear.dot; float64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +/* HMath.Linear.dot; rational specialization. */ +HMATH_API hmath_status hmath_linear_dot_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +/* HMath.Linear.dot; integer specialization. */ +HMATH_API hmath_status hmath_linear_dot_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +/* HMath.Linear.dot; int8 specialization. */ +HMATH_API hmath_status hmath_linear_dot_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +/* HMath.Linear.dot; int16 specialization. */ +HMATH_API hmath_status hmath_linear_dot_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +/* HMath.Linear.dot; int32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +/* HMath.Linear.dot; int64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +/* HMath.Linear.dot; uint8 specialization. */ +HMATH_API hmath_status hmath_linear_dot_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +/* HMath.Linear.dot; uint16 specialization. */ +HMATH_API hmath_status hmath_linear_dot_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +/* HMath.Linear.dot; uint32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +/* HMath.Linear.dot; uint64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +/* HMath.Linear.dot; intp specialization. */ +HMATH_API hmath_status hmath_linear_dot_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +/* HMath.Linear.dot; uintp specialization. */ +HMATH_API hmath_status hmath_linear_dot_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +/* HMath.Linear.dot; complex64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +/* HMath.Linear.dot; complex128 specialization. */ +HMATH_API hmath_status hmath_linear_dot_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +/* HMath.Linear.dotChecked; float32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +/* HMath.Linear.dotChecked; float64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +/* HMath.Linear.dotChecked; rational specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0, + char **out1); +/* HMath.Linear.dotChecked; integer specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char **out0); +/* HMath.Linear.dotChecked; int8 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t *out0); +/* HMath.Linear.dotChecked; int16 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t *out0); +/* HMath.Linear.dotChecked; int32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t *out0); +/* HMath.Linear.dotChecked; int64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t *out0); +/* HMath.Linear.dotChecked; uint8 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t *out0); +/* HMath.Linear.dotChecked; uint16 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t *out0); +/* HMath.Linear.dotChecked; uint32 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t *out0); +/* HMath.Linear.dotChecked; uint64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t *out0); +/* HMath.Linear.dotChecked; intp specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t *out0); +/* HMath.Linear.dotChecked; uintp specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t *out0); +/* HMath.Linear.dotChecked; complex64 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float *out0, + float *out1); +/* HMath.Linear.dotChecked; complex128 specialization. */ +HMATH_API hmath_status hmath_linear_dot_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double *out0, + double *out1); +/* HMath.Linear.magnitude; float32 specialization. */ +HMATH_API hmath_status hmath_linear_magnitude_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Linear.magnitude; float64 specialization. */ +HMATH_API hmath_status hmath_linear_magnitude_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Linear.magnitude; complex64 specialization. */ +HMATH_API hmath_status hmath_linear_magnitude_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float *out0, + float *out1); +/* HMath.Linear.magnitude; complex128 specialization. */ +HMATH_API hmath_status hmath_linear_magnitude_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double *out0, + double *out1); +/* HMath.Linear.normalize; owned array result. */ +HMATH_API hmath_status hmath_linear_normalize_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.normalize; owned array result. */ +HMATH_API hmath_status hmath_linear_normalize_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.normalize; owned array result. */ +HMATH_API hmath_status hmath_linear_normalize_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.normalize; owned array result. */ +HMATH_API hmath_status hmath_linear_normalize_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.add; owned array result. */ +HMATH_API hmath_status hmath_linear_add_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.addChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_add_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_rational( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_integer( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_i8( + hmath_context *context, + const int8_t *argument1, + size_t argument1_count, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_i16( + hmath_context *context, + const int16_t *argument1, + size_t argument1_count, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_i32( + hmath_context *context, + const int32_t *argument1, + size_t argument1_count, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_i64( + hmath_context *context, + const int64_t *argument1, + size_t argument1_count, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_u8( + hmath_context *context, + const uint8_t *argument1, + size_t argument1_count, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_u16( + hmath_context *context, + const uint16_t *argument1, + size_t argument1_count, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_u32( + hmath_context *context, + const uint32_t *argument1, + size_t argument1_count, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_u64( + hmath_context *context, + const uint64_t *argument1, + size_t argument1_count, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_int( + hmath_context *context, + const ptrdiff_t *argument1, + size_t argument1_count, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_word( + hmath_context *context, + const size_t *argument1, + size_t argument1_count, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_c64( + hmath_context *context, + float const *argument1, + size_t argument1_count, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.subtractChecked; owned array result. */ +HMATH_API hmath_status hmath_linear_subtract_checked_c128( + hmath_context *context, + double const *argument1, + size_t argument1_count, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_f32( + hmath_context *context, + float argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_rational( + hmath_context *context, + const char *argument1_numerator, + const char *argument1_denominator, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_integer( + hmath_context *context, + const char *argument1, + const char * const *argument2, + size_t argument2_count, + char * **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_i8( + hmath_context *context, + int8_t argument1, + const int8_t *argument2, + size_t argument2_count, + int8_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_i16( + hmath_context *context, + int16_t argument1, + const int16_t *argument2, + size_t argument2_count, + int16_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_i32( + hmath_context *context, + int32_t argument1, + const int32_t *argument2, + size_t argument2_count, + int32_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_i64( + hmath_context *context, + int64_t argument1, + const int64_t *argument2, + size_t argument2_count, + int64_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_u8( + hmath_context *context, + uint8_t argument1, + const uint8_t *argument2, + size_t argument2_count, + uint8_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_u16( + hmath_context *context, + uint16_t argument1, + const uint16_t *argument2, + size_t argument2_count, + uint16_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_u32( + hmath_context *context, + uint32_t argument1, + const uint32_t *argument2, + size_t argument2_count, + uint32_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_u64( + hmath_context *context, + uint64_t argument1, + const uint64_t *argument2, + size_t argument2_count, + uint64_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_int( + hmath_context *context, + ptrdiff_t argument1, + const ptrdiff_t *argument2, + size_t argument2_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_word( + hmath_context *context, + size_t argument1, + const size_t *argument2, + size_t argument2_count, + size_t **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_c64( + hmath_context *context, + float argument1_0, + float argument1_1, + float const *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Linear.scale; owned array result. */ +HMATH_API hmath_status hmath_linear_scale_c128( + hmath_context *context, + double argument1_0, + double argument1_1, + double const *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Special.gamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_gamma_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.logGamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_log_gamma_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.logBeta; float64 specialization. */ +HMATH_API hmath_status hmath_special_log_beta_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Special.beta; float64 specialization. */ +HMATH_API hmath_status hmath_special_beta_f64( + hmath_context *context, + double a, + double b, + double *out0); +/* HMath.Special.gammaP; float64 specialization. */ +HMATH_API hmath_status hmath_special_gamma_p_f64( + hmath_context *context, + double a, + double x, + double *out0); +/* HMath.Special.gammaQ; float64 specialization. */ +HMATH_API hmath_status hmath_special_gamma_q_f64( + hmath_context *context, + double a, + double x, + double *out0); +/* HMath.Special.incompleteGamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_incomplete_gamma_f64( + hmath_context *context, + double a, + double x, + double *out0); +/* HMath.Special.betaI; float64 specialization. */ +HMATH_API hmath_status hmath_special_beta_i_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +/* HMath.Special.incompleteBeta; float64 specialization. */ +HMATH_API hmath_status hmath_special_incomplete_beta_f64( + hmath_context *context, + double a, + double b, + double x, + double *out0); +/* HMath.Special.digamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_digamma_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.trigamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_trigamma_f64( + hmath_context *context, + double argument1, + double *out0); +/* HMath.Special.polygamma; float64 specialization. */ +HMATH_API hmath_status hmath_special_polygamma_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.erf; float64 specialization. */ +HMATH_API hmath_status hmath_special_erf_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.erfc; float64 specialization. */ +HMATH_API hmath_status hmath_special_erfc_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.erfcx; float64 specialization. */ +HMATH_API hmath_status hmath_special_erfcx_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.normalCDF; float64 specialization. */ +HMATH_API hmath_status hmath_special_normal_c_d_f_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.normalQuantile; float64 specialization. */ +HMATH_API hmath_status hmath_special_normal_quantile_f64( + hmath_context *context, + double p, + double *out0); +/* HMath.Special.inverseErf; float64 specialization. */ +HMATH_API hmath_status hmath_special_inverse_erf_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Special.dawson; float64 specialization. */ +HMATH_API hmath_status hmath_special_dawson_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.exponentialIntegral; float64 specialization. */ +HMATH_API hmath_status hmath_special_exponential_integral_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.logarithmicIntegral; float64 specialization. */ +HMATH_API hmath_status hmath_special_logarithmic_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.sineIntegral; float64 specialization. */ +HMATH_API hmath_status hmath_special_sine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.cosineIntegral; float64 specialization. */ +HMATH_API hmath_status hmath_special_cosine_integral_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.fresnel; float64 specialization. */ +HMATH_API hmath_status hmath_special_fresnel_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3); +/* HMath.Special.ellipticF; float64 specialization. */ +HMATH_API hmath_status hmath_special_elliptic_f_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1); +/* HMath.Special.ellipticE; float64 specialization. */ +HMATH_API hmath_status hmath_special_elliptic_e_f64( + hmath_context *context, + double phi, + double m, + double *out0, + double *out1); +/* HMath.Special.ellipticPi; float64 specialization. */ +HMATH_API hmath_status hmath_special_elliptic_pi_f64( + hmath_context *context, + double n, + double phi, + double m, + double *out0, + double *out1); +/* HMath.Special.jacobiElliptic; float64 specialization. */ +HMATH_API hmath_status hmath_special_jacobi_elliptic_f64( + hmath_context *context, + double u, + double m, + double *out0, + double *out1, + double *out2); +/* HMath.Special.besselJ; float64 specialization. */ +HMATH_API hmath_status hmath_special_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.besselY; float64 specialization. */ +HMATH_API hmath_status hmath_special_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.besselI; float64 specialization. */ +HMATH_API hmath_status hmath_special_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.scaledBesselI; float64 specialization. */ +HMATH_API hmath_status hmath_special_scaled_bessel_i_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.besselK; float64 specialization. */ +HMATH_API hmath_status hmath_special_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.scaledBesselK; float64 specialization. */ +HMATH_API hmath_status hmath_special_scaled_bessel_k_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.sphericalBesselJ; float64 specialization. */ +HMATH_API hmath_status hmath_special_spherical_bessel_j_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.sphericalBesselY; float64 specialization. */ +HMATH_API hmath_status hmath_special_spherical_bessel_y_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.airy; float64 specialization. */ +HMATH_API hmath_status hmath_special_airy_f64( + hmath_context *context, + double x, + double *out0, + double *out1, + double *out2, + double *out3, + double *out4, + double *out5, + double *out6, + double *out7); +/* HMath.Special.struve; float64 specialization. */ +HMATH_API hmath_status hmath_special_struve_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1); +/* HMath.Special.hypergeometric; float64 specialization. */ +HMATH_API hmath_status hmath_special_hypergeometric_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *bs, + size_t bs_count, + double z, + double *out0, + double *out1); +/* HMath.Special.hypergeometric1F1; float64 specialization. */ +HMATH_API hmath_status hmath_special_hypergeometric1_f1_f64( + hmath_context *context, + double a, + double b, + double z, + double *out0, + double *out1); +/* HMath.Special.hypergeometric2F1; float64 specialization. */ +HMATH_API hmath_status hmath_special_hypergeometric2_f1_f64( + hmath_context *context, + double a, + double b, + double c, + double z, + double *out0, + double *out1); +/* HMath.Special.legendre; float64 specialization. */ +HMATH_API hmath_status hmath_special_legendre_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.associatedLegendre; float64 specialization. */ +HMATH_API hmath_status hmath_special_associated_legendre_f64( + hmath_context *context, + ptrdiff_t l, + ptrdiff_t m, + double x, + double *out0); +/* HMath.Special.hurwitzZeta; float64 specialization. */ +HMATH_API hmath_status hmath_special_hurwitz_zeta_f64( + hmath_context *context, + double s, + double q, + double *out0, + double *out1); +/* HMath.Special.riemannZeta; float64 specialization. */ +HMATH_API hmath_status hmath_special_riemann_zeta_f64( + hmath_context *context, + double s, + double *out0, + double *out1); +/* HMath.Special.polylogarithm; float64 specialization. */ +HMATH_API hmath_status hmath_special_polylogarithm_f64( + hmath_context *context, + double s, + double z, + double *out0, + double *out1); +/* HMath.Special.dilogarithm; float64 specialization. */ +HMATH_API hmath_status hmath_special_dilogarithm_f64( + hmath_context *context, + double x, + double *out0, + double *out1); +/* HMath.Special.lambertW; float64 specialization. */ +HMATH_API hmath_status hmath_special_lambert_w_f64( + hmath_context *context, + ptrdiff_t branch, + double x, + double *out0, + double *out1); +/* HMath.Special.debye; float64 specialization. */ +HMATH_API hmath_status hmath_special_debye_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0, + double *out1); +/* HMath.Special.clausen; float64 specialization. */ +HMATH_API hmath_status hmath_special_clausen_f64( + hmath_context *context, + double theta, + double *out0, + double *out1); +/* HMath.Special.fermiDirac; float64 specialization. */ +HMATH_API hmath_status hmath_special_fermi_dirac_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1); +/* HMath.Special.boseEinstein; float64 specialization. */ +HMATH_API hmath_status hmath_special_bose_einstein_f64( + hmath_context *context, + double order, + double eta, + double *out0, + double *out1); +/* HMath.Special.coulombWave; float64 specialization. */ +HMATH_API hmath_status hmath_special_coulomb_wave_f64( + hmath_context *context, + ptrdiff_t l, + double eta, + double rho, + double *out0, + double *out1, + double *out2, + double *out3); +/* HMath.Special.gegenbauer; float64 specialization. */ +HMATH_API hmath_status hmath_special_gegenbauer_f64( + hmath_context *context, + ptrdiff_t n, + double a, + double x, + double *out0); +/* HMath.Special.parabolicCylinder; float64 specialization. */ +HMATH_API hmath_status hmath_special_parabolic_cylinder_f64( + hmath_context *context, + double nu, + double x, + double *out0, + double *out1); +/* HMath.Special.mathieu; float64 specialization. */ +HMATH_API hmath_status hmath_special_mathieu_f64( + hmath_context *context, + int evenMode, + ptrdiff_t n, + double q, + double x, + double *out0, + double *out1, + double *out2); +/* HMath.Special.bernoulliPolynomial; float64 specialization. */ +HMATH_API hmath_status hmath_special_bernoulli_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.eulerPolynomial; float64 specialization. */ +HMATH_API hmath_status hmath_special_euler_polynomial_f64( + hmath_context *context, + ptrdiff_t n, + double x, + double *out0); +/* HMath.Special.wigner3j; float64 specialization. */ +HMATH_API hmath_status hmath_special_wigner3j_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t j2, + ptrdiff_t j3, + ptrdiff_t m1, + ptrdiff_t m2, + ptrdiff_t m3, + double *out0); +/* HMath.Special.wigner6j; float64 specialization. */ +HMATH_API hmath_status hmath_special_wigner6j_f64( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t c, + ptrdiff_t d, + ptrdiff_t e, + ptrdiff_t f, + double *out0); +/* HMath.Special.wigner9j; float64 specialization. */ +HMATH_API hmath_status hmath_special_wigner9j_f64( + hmath_context *context, + ptrdiff_t const *js, + size_t js_count, + double *out0); +/* HMath.Special.clebschGordan; float64 specialization. */ +HMATH_API hmath_status hmath_special_clebsch_gordan_f64( + hmath_context *context, + ptrdiff_t j1, + ptrdiff_t m1, + ptrdiff_t j2, + ptrdiff_t m2, + ptrdiff_t j, + ptrdiff_t m, + double *out0); +/* HMath.Complex.toPolar; float64 specialization. */ +HMATH_API hmath_status hmath_complex_to_polar_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Probability.gammaPoissonUpdate; float64 specialization. */ +HMATH_API hmath_status hmath_probability_gamma_poisson_update_f64( + hmath_context *context, + double shapePrior, + double ratePrior, + ptrdiff_t const *xs, + size_t xs_count, + double *out0, + double *out1); +/* HMath.Probability.normalNormalUpdate; float64 specialization. */ +HMATH_API hmath_status hmath_probability_normal_normal_update_f64( + hmath_context *context, + double mu, + double priorVariance, + double observationVariance, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +/* HMath.Probability.conditionalProbability; float64 specialization. */ +HMATH_API hmath_status hmath_probability_conditional_probability_f64( + hmath_context *context, + double joint, + double given, + double *out0); +/* HMath.Probability.bayes; owned array result. */ +HMATH_API hmath_status hmath_probability_bayes_f64( + hmath_context *context, + const double *priors, + size_t priors_count, + const double *likelihoods, + size_t likelihoods_count, + double **out_data, + size_t *out_count); +/* HMath.Probability.multinomialPMF; float64 specialization. */ +HMATH_API hmath_status hmath_probability_multinomial_p_m_f_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + ptrdiff_t const *counts, + size_t counts_count, + double *out0); +/* HMath.Probability.dirichletDensity; float64 specialization. */ +HMATH_API hmath_status hmath_probability_dirichlet_density_f64( + hmath_context *context, + const double *as, + size_t as_count, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Complex.complex; float64 specialization. */ +HMATH_API hmath_status hmath_complex_complex_f64( + hmath_context *context, + double real, + double imaginary, + double *out0, + double *out1); +/* HMath.Complex.reciprocal; float64 specialization. */ +HMATH_API hmath_status hmath_complex_reciprocal_f64( + hmath_context *context, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Complex.add; float64 specialization. */ +HMATH_API hmath_status hmath_complex_add_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Complex.subtractComplex; float64 specialization. */ +HMATH_API hmath_status hmath_complex_subtract_complex_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Complex.multiply; float64 specialization. */ +HMATH_API hmath_status hmath_complex_multiply_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Complex.divide; float64 specialization. */ +HMATH_API hmath_status hmath_complex_divide_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Complex.power; float64 specialization. */ +HMATH_API hmath_status hmath_complex_power_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double *out0, + double *out1); +/* HMath.Complex.fromPolar; float64 specialization. */ +HMATH_API hmath_status hmath_complex_from_polar_f64( + hmath_context *context, + double radius, + double angle, + double *out0, + double *out1); +/* HMath.Complex.rotate; float64 specialization. */ +HMATH_API hmath_status hmath_complex_rotate_f64( + hmath_context *context, + double angle, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.Special.hankel; float64 specialization. */ +HMATH_API hmath_status hmath_special_hankel_f64( + hmath_context *context, + ptrdiff_t kind, + ptrdiff_t order, + double x, + double *out0, + double *out1); +/* HMath.Special.sphericalHarmonic; float64 specialization. */ +HMATH_API hmath_status hmath_special_spherical_harmonic_f64( + hmath_context *context, + ptrdiff_t degree, + ptrdiff_t order, + double theta, + double phi, + double *out0, + double *out1); +/* HMath.Special.complex1F1; float64 specialization. */ +HMATH_API hmath_status hmath_special_complex1_f1_f64( + hmath_context *context, + double a_0, + double a_1, + double b_0, + double b_1, + double z_0, + double z_1, + double *out0, + double *out1); +/* HMath.API.Algebra.innerProduct; float32 specialization. */ +HMATH_API hmath_status hmath_api_algebra_inner_product_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + float *out0); +/* HMath.API.Algebra.innerProduct; float64 specialization. */ +HMATH_API hmath_status hmath_api_algebra_inner_product_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +/* HMath.Algorithms.lowerBound; float32 specialization. */ +HMATH_API hmath_status hmath_algorithms_lower_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +/* HMath.Algorithms.lowerBound; float64 specialization. */ +HMATH_API hmath_status hmath_algorithms_lower_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +/* HMath.Algorithms.upperBound; float32 specialization. */ +HMATH_API hmath_status hmath_algorithms_upper_bound_f32( + hmath_context *context, + float x, + const float *xs, + size_t xs_count, + ptrdiff_t *out0); +/* HMath.Algorithms.upperBound; float64 specialization. */ +HMATH_API hmath_status hmath_algorithms_upper_bound_f64( + hmath_context *context, + double x, + const double *xs, + size_t xs_count, + ptrdiff_t *out0); +/* HMath.Algorithms.quickselect; float32 specialization. */ +HMATH_API hmath_status hmath_algorithms_quickselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +/* HMath.Algorithms.quickselect; float64 specialization. */ +HMATH_API hmath_status hmath_algorithms_quickselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Algorithms.introselect; float32 specialization. */ +HMATH_API hmath_status hmath_algorithms_introselect_f32( + hmath_context *context, + ptrdiff_t k, + const float *xs, + size_t xs_count, + float *out0); +/* HMath.Algorithms.introselect; float64 specialization. */ +HMATH_API hmath_status hmath_algorithms_introselect_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Algorithms.partialSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_partial_sort_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.partialSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_partial_sort_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.mergeSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_merge_sort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.mergeSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_merge_sort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.quicksort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_quicksort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.quicksort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_quicksort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.heapsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_heapsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.heapsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_heapsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.introsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_introsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.introsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_introsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.countingSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_counting_sort( + hmath_context *context, + ptrdiff_t budget, + ptrdiff_t const *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Algorithms.radixSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_radix_sort( + hmath_context *context, + const char * const *argument1, + size_t argument1_count, + char * **out_data, + size_t *out_count); +/* HMath.Algorithms.bucketSort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_bucket_sort_f64( + hmath_context *context, + ptrdiff_t buckets, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.argsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_argsort_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Algorithms.argsort; owned array result. */ +HMATH_API hmath_status hmath_algorithms_argsort_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Algorithms.topK; owned array result. */ +HMATH_API hmath_status hmath_algorithms_top_k_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.topK; owned array result. */ +HMATH_API hmath_status hmath_algorithms_top_k_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.quantileSelect; float64 specialization. */ +HMATH_API hmath_status hmath_algorithms_quantile_select_f64( + hmath_context *context, + double q, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Algorithms.deduplicate; owned array result. */ +HMATH_API hmath_status hmath_algorithms_deduplicate_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.deduplicate; owned array result. */ +HMATH_API hmath_status hmath_algorithms_deduplicate_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.prefixSums; owned array result. */ +HMATH_API hmath_status hmath_algorithms_prefix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.prefixSums; owned array result. */ +HMATH_API hmath_status hmath_algorithms_prefix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.suffixSums; owned array result. */ +HMATH_API hmath_status hmath_algorithms_suffix_sums_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.suffixSums; owned array result. */ +HMATH_API hmath_status hmath_algorithms_suffix_sums_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.differenceArray; owned array result. */ +HMATH_API hmath_status hmath_algorithms_difference_array_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.differenceArray; owned array result. */ +HMATH_API hmath_status hmath_algorithms_difference_array_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.applyDifferences; owned array result. */ +HMATH_API hmath_status hmath_algorithms_apply_differences_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float **out_data, + size_t *out_count); +/* HMath.Algorithms.applyDifferences; owned array result. */ +HMATH_API hmath_status hmath_algorithms_apply_differences_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.Algorithms.binaryLift; fixed specialization. */ +HMATH_API hmath_status hmath_algorithms_binary_lift( + hmath_context *context, + ptrdiff_t const *next, + size_t next_count, + const char *steps, + ptrdiff_t start, + ptrdiff_t *out0); +/* HMath.Algorithms.polynomialHash; fixed specialization. */ +HMATH_API hmath_status hmath_algorithms_polynomial_hash( + hmath_context *context, + const char *base, + const char *modulus, + const char * const *xs, + size_t xs_count, + char **out0); +/* HMath.Algorithms.rollingHashes; owned array result. */ +HMATH_API hmath_status hmath_algorithms_rolling_hashes( + hmath_context *context, + const char *base, + const char *modulus, + ptrdiff_t width, + const char * const *xs, + size_t xs_count, + char * **out_data, + size_t *out_count); +/* HMath.DataStructure.monotonicMinima; owned array result. */ +HMATH_API hmath_status hmath_datastructure_monotonic_minima_f32( + hmath_context *context, + ptrdiff_t argument1, + const float *argument2, + size_t argument2_count, + float **out_data, + size_t *out_count); +/* HMath.DataStructure.monotonicMinima; owned array result. */ +HMATH_API hmath_status hmath_datastructure_monotonic_minima_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.DeepLearning.Core.logSoftmax; owned array result. */ +HMATH_API hmath_status hmath_deeplearning_core_log_softmax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.DeepLearning.Core.softmax; owned array result. */ +HMATH_API hmath_status hmath_deeplearning_core_softmax_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.DeepLearning.Core.sparsemax; owned array result. */ +HMATH_API hmath_status hmath_deeplearning_core_sparsemax_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double **out_data, + size_t *out_count); +/* HMath.DeepLearning.Core.gatedLinearUnit; owned array result. */ +HMATH_API hmath_status hmath_deeplearning_core_gated_linear_unit_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *gate, + size_t gate_count, + double **out_data, + size_t *out_count); +/* HMath.DeepLearning.Core.categoricalCrossEntropyLogits; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_categorical_cross_entropy_logits_f64( + hmath_context *context, + const double *target, + size_t target_count, + const double *logits, + size_t logits_count, + double *out0); +/* HMath.DeepLearning.Core.regularization; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_regularization_f64( + hmath_context *context, + double l1, + double l2, + const double *weights, + size_t weights_count, + double *out0); +/* HMath.DeepLearning.Core.contrastiveLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_contrastive_loss_f64( + hmath_context *context, + double margin, + int similar, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +/* HMath.DeepLearning.Core.tripletLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_triplet_loss_f64( + hmath_context *context, + double margin, + const double *anchor, + size_t anchor_count, + const double *positive, + size_t positive_count, + const double *negative, + size_t negative_count, + double *out0); +/* HMath.DeepLearning.Core.focalLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_focal_loss_f64( + hmath_context *context, + double alpha, + double gamma, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +/* HMath.DeepLearning.Core.diceLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_dice_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +/* HMath.DeepLearning.Core.iouLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_core_iou_loss_f64( + hmath_context *context, + double smooth, + const double *target, + size_t target_count, + const double *prediction, + size_t prediction_count, + double *out0); +/* HMath.DeepLearning.Metrics.perplexity; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_metrics_perplexity_f64( + hmath_context *context, + const double *logs, + size_t logs_count, + double *out0); +/* HMath.DeepLearning.Metrics.marginRankingLoss; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_metrics_margin_ranking_loss_f64( + hmath_context *context, + double margin, + const double *labels, + size_t labels_count, + const double *left, + size_t left_count, + const double *right, + size_t right_count, + double *out0); +/* HMath.DeepLearning.Precision.gradientNorm; float64 specialization. */ +HMATH_API hmath_status hmath_deeplearning_precision_gradient_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.DeepLearning.Precision.clipGradients; owned array result. */ +HMATH_API hmath_status hmath_deeplearning_precision_clip_gradients_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Discrete.setUnion; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_union_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +/* HMath.Discrete.setUnion; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_union_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +/* HMath.Discrete.setIntersection; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_intersection_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +/* HMath.Discrete.setIntersection; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_intersection_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +/* HMath.Discrete.setDifference; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +/* HMath.Discrete.setDifference; owned array result. */ +HMATH_API hmath_status hmath_discrete_set_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +/* HMath.Discrete.symmetricDifference; owned array result. */ +HMATH_API hmath_status hmath_discrete_symmetric_difference_f32( + hmath_context *context, + const float *a, + size_t a_count, + const float *b, + size_t b_count, + float **out_data, + size_t *out_count); +/* HMath.Discrete.symmetricDifference; owned array result. */ +HMATH_API hmath_status hmath_discrete_symmetric_difference_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.frequencies; owned array result. */ +HMATH_API hmath_status hmath_fourier_frequencies_f64( + hmath_context *context, + ptrdiff_t n, + double spacing, + double **out_data, + size_t *out_count); +/* HMath.Fourier.fftShift; owned array result. */ +HMATH_API hmath_status hmath_fourier_fft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.ifftShift; owned array result. */ +HMATH_API hmath_status hmath_fourier_ifft_shift_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.hartley; owned array result. */ +HMATH_API hmath_status hmath_fourier_hartley_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.periodogram; owned array result. */ +HMATH_API hmath_status hmath_fourier_periodogram_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.welch; owned array result. */ +HMATH_API hmath_status hmath_fourier_welch_f64( + hmath_context *context, + double rate, + const double *window, + size_t window_count, + ptrdiff_t hop, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.cepstrum; owned array result. */ +HMATH_API hmath_status hmath_fourier_cepstrum_f64( + hmath_context *context, + double floorValue, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Fourier.hilbert; owned array result. */ +HMATH_API hmath_status hmath_fourier_hilbert_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Geometry.Primitives.hammingDistance; float32 specialization. */ +HMATH_API hmath_status hmath_geometry_primitives_hamming_distance_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + const float *argument2, + size_t argument2_count, + ptrdiff_t *out0); +/* HMath.Geometry.Primitives.hammingDistance; float64 specialization. */ +HMATH_API hmath_status hmath_geometry_primitives_hamming_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + ptrdiff_t *out0); +/* HMath.Geometry.Primitives.jaccardDistance; float64 specialization. */ +HMATH_API hmath_status hmath_geometry_primitives_jaccard_distance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double *out0); +/* HMath.Graph.Core.finite; float64 specialization. */ +HMATH_API hmath_status hmath_graph_core_finite_f64( + hmath_context *context, + double x, + int *out0); +/* HMath.Image.Color.srgbToLinear; float64 specialization. */ +HMATH_API hmath_status hmath_image_color_srgb_to_linear_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Image.Color.linearToSrgb; float64 specialization. */ +HMATH_API hmath_status hmath_image_color_linear_to_srgb_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Interpolation.evaluateChebyshev; float64 specialization. */ +HMATH_API hmath_status hmath_interpolation_evaluate_chebyshev_f64( + hmath_context *context, + const double *cs, + size_t cs_count, + double a, + double b, + double x, + double *out0); +/* HMath.Numeric.nextAfter; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_next_after_f32( + hmath_context *context, + float argument1, + float argument2, + float *out0); +/* HMath.Numeric.nextAfter; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_next_after_f64( + hmath_context *context, + double argument1, + double argument2, + double *out0); +/* HMath.Numeric.ldexp; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_ldexp_f32( + hmath_context *context, + float argument1, + ptrdiff_t argument2, + float *out0); +/* HMath.Numeric.ldexp; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_ldexp_f64( + hmath_context *context, + double argument1, + ptrdiff_t argument2, + double *out0); +/* HMath.Numeric.ulpDistance; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_ulp_distance_f64( + hmath_context *context, + double a, + double b, + char **out0); +/* HMath.Numeric.withinULPs; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_within_u_l_ps_f64( + hmath_context *context, + const char *n, + double a, + double b, + int *out0); +/* HMath.Numeric.kahanSum; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_kahan_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Numeric.kahanSum; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_kahan_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Numeric.neumaierSum; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_neumaier_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Numeric.neumaierSum; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_neumaier_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Numeric.pairwiseSum; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_pairwise_sum_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Numeric.pairwiseSum; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_pairwise_sum_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Numeric.logsumexp; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_logsumexp_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Numeric.logsumexp; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_logsumexp_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Numeric.sumErrorBound; float32 specialization. */ +HMATH_API hmath_status hmath_numeric_sum_error_bound_f32( + hmath_context *context, + const float *argument1, + size_t argument1_count, + float *out0); +/* HMath.Numeric.sumErrorBound; float64 specialization. */ +HMATH_API hmath_status hmath_numeric_sum_error_bound_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Optimization.Common.dot; float64 specialization. */ +HMATH_API hmath_status hmath_optimization_common_dot_f64( + hmath_context *context, + const double *a, + size_t a_count, + const double *b, + size_t b_count, + double *out0); +/* HMath.Optimization.Common.norm; float64 specialization. */ +HMATH_API hmath_status hmath_optimization_common_norm_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Optimization.Common.add; owned array result. */ +HMATH_API hmath_status hmath_optimization_common_add_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Optimization.Common.sub; owned array result. */ +HMATH_API hmath_status hmath_optimization_common_sub_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Optimization.Common.scale; owned array result. */ +HMATH_API hmath_status hmath_optimization_common_scale_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Random.importance; float64 specialization. */ +HMATH_API hmath_status hmath_random_importance_f64( + hmath_context *context, + const double *values, + size_t values_count, + const double *weights, + size_t weights_count, + double *out0); +/* HMath.Random.halton; owned array result. */ +HMATH_API hmath_status hmath_random_halton_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +/* HMath.Random.sobol; owned array result. */ +HMATH_API hmath_status hmath_random_sobol_f64( + hmath_context *context, + ptrdiff_t dimension, + ptrdiff_t index, + double **out_data, + size_t *out_count); +/* HMath.Random.faure; owned array result. */ +HMATH_API hmath_status hmath_random_faure_f64( + hmath_context *context, + ptrdiff_t d, + ptrdiff_t ix, + double **out_data, + size_t *out_count); +/* HMath.Signal.convolution; owned array result. */ +HMATH_API hmath_status hmath_signal_convolution_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.circularConvolution; owned array result. */ +HMATH_API hmath_status hmath_signal_circular_convolution_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.correlation; owned array result. */ +HMATH_API hmath_status hmath_signal_correlation_f64( + hmath_context *context, + const double *x, + size_t x_count, + const double *y, + size_t y_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.autocorrelation; owned array result. */ +HMATH_API hmath_status hmath_signal_autocorrelation_f64( + hmath_context *context, + const double *x, + size_t x_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.overlapAdd; owned array result. */ +HMATH_API hmath_status hmath_signal_overlap_add_f64( + hmath_context *context, + ptrdiff_t block, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.overlapSave; owned array result. */ +HMATH_API hmath_status hmath_signal_overlap_save_f64( + hmath_context *context, + ptrdiff_t fftLength, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.movingAverage; owned array result. */ +HMATH_API hmath_status hmath_signal_moving_average_f64( + hmath_context *context, + ptrdiff_t count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.medianFilter; owned array result. */ +HMATH_API hmath_status hmath_signal_median_filter_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.gaussianFilter; owned array result. */ +HMATH_API hmath_status hmath_signal_gaussian_filter_f64( + hmath_context *context, + ptrdiff_t width, + double sigma, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.savitzkyGolay; owned array result. */ +HMATH_API hmath_status hmath_signal_savitzky_golay_f64( + hmath_context *context, + ptrdiff_t width, + ptrdiff_t degree, + ptrdiff_t derivative, + double spacing, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.downsample; owned array result. */ +HMATH_API hmath_status hmath_signal_downsample_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t offset, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.upsample; owned array result. */ +HMATH_API hmath_status hmath_signal_upsample_f64( + hmath_context *context, + ptrdiff_t factor, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.resamplePolyphase; owned array result. */ +HMATH_API hmath_status hmath_signal_resample_polyphase_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + const double *kernel, + size_t kernel_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.resample; owned array result. */ +HMATH_API hmath_status hmath_signal_resample_f64( + hmath_context *context, + ptrdiff_t up, + ptrdiff_t down, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.antiAlias; owned array result. */ +HMATH_API hmath_status hmath_signal_anti_alias_f64( + hmath_context *context, + ptrdiff_t factor, + ptrdiff_t taps, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.zeroCrossings; owned array result. */ +HMATH_API hmath_status hmath_signal_zero_crossings_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.envelope; owned array result. */ +HMATH_API hmath_status hmath_signal_envelope_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.unwrapPhase; owned array result. */ +HMATH_API hmath_status hmath_signal_unwrap_phase_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.detrend; owned array result. */ +HMATH_API hmath_status hmath_signal_detrend_f64( + hmath_context *context, + int linear, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.normalize; owned array result. */ +HMATH_API hmath_status hmath_signal_normalize_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.smooth; owned array result. */ +HMATH_API hmath_status hmath_signal_smooth_f64( + hmath_context *context, + ptrdiff_t argument1, + const double *argument2, + size_t argument2_count, + double **out_data, + size_t *out_count); +/* HMath.Signal.noiseEstimate; float64 specialization. */ +HMATH_API hmath_status hmath_signal_noise_estimate_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Signal.signalToNoise; float64 specialization. */ +HMATH_API hmath_status hmath_signal_signal_to_noise_f64( + hmath_context *context, + const double *signal, + size_t signal_count, + const double *noise, + size_t noise_count, + double *out0); +/* HMath.Signal.rms; float64 specialization. */ +HMATH_API hmath_status hmath_signal_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.arithmeticMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_arithmetic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.weightedMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_weighted_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ws, + size_t ws_count, + double *out0); +/* HMath.Statistics.Advanced.geometricMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_geometric_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.harmonicMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_harmonic_mean_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.rms; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_rms_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.trimmedMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_trimmed_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.winsorizedMean; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_winsorized_mean_f64( + hmath_context *context, + double fraction, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.quantile; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_quantile_f64( + hmath_context *context, + double p, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.median; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_median_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Statistics.Advanced.percentile; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_percentile_f64( + hmath_context *context, + double argument1, + const double *argument2, + size_t argument2_count, + double *out0); +/* HMath.Statistics.Advanced.modes; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_modes_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.interquartileRange; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_interquartile_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.medianAbsoluteDeviation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_median_absolute_deviation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.dataRange; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_data_range_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.centralMoment; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_central_moment_f64( + hmath_context *context, + ptrdiff_t k, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.populationVariance; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_population_variance_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Statistics.Advanced.sampleVariance; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_sample_variance_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.populationSD; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_population_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Statistics.Advanced.sampleSD; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_sample_s_d_f64( + hmath_context *context, + const double *argument1, + size_t argument1_count, + double *out0); +/* HMath.Statistics.Advanced.coefficientOfVariation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_coefficient_of_variation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.skewness; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_skewness_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.kurtosis; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_kurtosis_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.covariance; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_covariance_f64( + hmath_context *context, + int sampleCorrection, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.correlation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_correlation_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.spearman; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_spearman_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.kendall; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_kendall_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.autocorrelation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.crossCorrelation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.movingAverage; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_moving_average_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.movingVariance; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_moving_variance_f64( + hmath_context *context, + ptrdiff_t window, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.exponentialMovingAverage; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_exponential_moving_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.entropy; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_entropy_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double *out0); +/* HMath.Statistics.Advanced.klDivergence; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_kl_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +/* HMath.Statistics.Advanced.jsDivergence; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_js_divergence_f64( + hmath_context *context, + const double *p, + size_t p_count, + const double *q, + size_t q_count, + double *out0); +/* HMath.Statistics.Advanced.zScores; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_z_scores_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.standardError; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_standard_error_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Statistics.Advanced.confidenceInterval; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_confidence_interval_f64( + hmath_context *context, + double level, + const double *xs, + size_t xs_count, + double *out0, + double *out1); +/* HMath.Statistics.Advanced.bonferroni; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_bonferroni_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.benjaminiHochberg; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_benjamini_hochberg_f64( + hmath_context *context, + const double *ps, + size_t ps_count, + double **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.cohensD; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_cohens_d_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.Statistics.Advanced.normalTestPower; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_normal_test_power_f64( + hmath_context *context, + double alpha, + double standardizedEffect, + ptrdiff_t n, + double *out0); +/* HMath.Statistics.Advanced.normalSampleSize; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_normal_sample_size_f64( + hmath_context *context, + double alpha, + double power, + double effect, + ptrdiff_t *out0); +/* HMath.Statistics.Advanced.tukeyOutliers; owned array result. */ +HMATH_API hmath_status hmath_statistics_advanced_tukey_outliers_f64( + hmath_context *context, + double multiplier, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Statistics.Advanced.huberLocation; float64 specialization. */ +HMATH_API hmath_status hmath_statistics_advanced_huber_location_f64( + hmath_context *context, + double tuning, + const double *xs, + size_t xs_count, + double *out0); +/* HMath.Tensor.shapeSize; fixed specialization. */ +HMATH_API hmath_status hmath_tensor_shape_size( + hmath_context *context, + ptrdiff_t const *dims, + size_t dims_count, + ptrdiff_t *out0); +/* HMath.Tensor.inferBroadcast; owned array result. */ +HMATH_API hmath_status hmath_tensor_infer_broadcast( + hmath_context *context, + ptrdiff_t const *as, + size_t as_count, + ptrdiff_t const *bs, + size_t bs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.exponentialAverage; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_exponential_average_f64( + hmath_context *context, + double alpha, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.weightedAverage; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_weighted_average_f64( + hmath_context *context, + const double *ws, + size_t ws_count, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.cumulativeReturns; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_cumulative_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.logarithmicReturns; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_logarithmic_returns_f64( + hmath_context *context, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.difference; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_difference_f64( + hmath_context *context, + ptrdiff_t order, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.autocorrelation; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_autocorrelation_f64( + hmath_context *context, + ptrdiff_t lags, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Core.crossCorrelation; float64 specialization. */ +HMATH_API hmath_status hmath_timeseries_core_cross_correlation_f64( + hmath_context *context, + ptrdiff_t lag, + const double *xs, + size_t xs_count, + const double *ys, + size_t ys_count, + double *out0); +/* HMath.TimeSeries.Core.partialAutocorrelation; owned array result. */ +HMATH_API hmath_status hmath_timeseries_core_partial_autocorrelation_f64( + hmath_context *context, + ptrdiff_t order, + const double *xs, + size_t xs_count, + double **out_data, + size_t *out_count); +/* HMath.TimeSeries.Diagnostics.changePoints; owned array result. */ +HMATH_API hmath_status hmath_timeseries_diagnostics_change_points_f64( + hmath_context *context, + double penalty, + ptrdiff_t minSegment, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.TimeSeries.Diagnostics.cusum; owned array result. */ +HMATH_API hmath_status hmath_timeseries_diagnostics_cusum_f64( + hmath_context *context, + double mean, + double sd, + double drift, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.TimeSeries.Diagnostics.anomalies; owned array result. */ +HMATH_API hmath_status hmath_timeseries_diagnostics_anomalies_f64( + hmath_context *context, + double threshold, + const double *xs, + size_t xs_count, + ptrdiff_t **out_data, + size_t *out_count); +/* HMath.Units.radiansToDegrees; float32 specialization. */ +HMATH_API hmath_status hmath_units_radians_to_degrees_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Units.radiansToDegrees; float64 specialization. */ +HMATH_API hmath_status hmath_units_radians_to_degrees_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Units.degreesToRadians; float32 specialization. */ +HMATH_API hmath_status hmath_units_degrees_to_radians_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Units.degreesToRadians; float64 specialization. */ +HMATH_API hmath_status hmath_units_degrees_to_radians_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Units.radiansToGradians; float32 specialization. */ +HMATH_API hmath_status hmath_units_radians_to_gradians_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Units.radiansToGradians; float64 specialization. */ +HMATH_API hmath_status hmath_units_radians_to_gradians_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Units.gradiansToRadians; float32 specialization. */ +HMATH_API hmath_status hmath_units_gradians_to_radians_f32( + hmath_context *context, + float x, + float *out0); +/* HMath.Units.gradiansToRadians; float64 specialization. */ +HMATH_API hmath_status hmath_units_gradians_to_radians_f64( + hmath_context *context, + double x, + double *out0); +/* HMath.Scalar.saturatingAdd; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.saturatingAdd; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.saturatingAdd; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.saturatingAdd; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.saturatingAdd; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.saturatingAdd; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.saturatingAdd; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.saturatingAdd; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.saturatingAdd; intp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.saturatingAdd; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.saturatingSubtract; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.saturatingSubtract; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.saturatingSubtract; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.saturatingSubtract; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.saturatingSubtract; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.saturatingSubtract; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.saturatingSubtract; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.saturatingSubtract; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.saturatingSubtract; intp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.saturatingSubtract; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.saturatingMultiply; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.saturatingMultiply; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.saturatingMultiply; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.saturatingMultiply; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.saturatingMultiply; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.saturatingMultiply; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.saturatingMultiply; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.saturatingMultiply; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.saturatingMultiply; intp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.saturatingMultiply; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.checkedAdd; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.checkedAdd; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.checkedAdd; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.checkedAdd; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.checkedAdd; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.checkedAdd; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.checkedAdd; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.checkedAdd; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.checkedAdd; intp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.checkedAdd; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_add_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.checkedSubtract; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.checkedSubtract; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.checkedSubtract; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.checkedSubtract; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.checkedSubtract; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.checkedSubtract; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.checkedSubtract; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.checkedSubtract; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.checkedSubtract; intp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.checkedSubtract; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +/* HMath.Scalar.checkedMultiply; int8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_i8( + hmath_context *context, + int8_t a, + int8_t b, + int8_t *out0); +/* HMath.Scalar.checkedMultiply; int16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_i16( + hmath_context *context, + int16_t a, + int16_t b, + int16_t *out0); +/* HMath.Scalar.checkedMultiply; int32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_i32( + hmath_context *context, + int32_t a, + int32_t b, + int32_t *out0); +/* HMath.Scalar.checkedMultiply; int64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_i64( + hmath_context *context, + int64_t a, + int64_t b, + int64_t *out0); +/* HMath.Scalar.checkedMultiply; uint8 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_u8( + hmath_context *context, + uint8_t a, + uint8_t b, + uint8_t *out0); +/* HMath.Scalar.checkedMultiply; uint16 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_u16( + hmath_context *context, + uint16_t a, + uint16_t b, + uint16_t *out0); +/* HMath.Scalar.checkedMultiply; uint32 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_u32( + hmath_context *context, + uint32_t a, + uint32_t b, + uint32_t *out0); +/* HMath.Scalar.checkedMultiply; uint64 specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_u64( + hmath_context *context, + uint64_t a, + uint64_t b, + uint64_t *out0); +/* HMath.Scalar.checkedMultiply; intp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_int( + hmath_context *context, + ptrdiff_t a, + ptrdiff_t b, + ptrdiff_t *out0); +/* HMath.Scalar.checkedMultiply; uintp specialization. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_word( + hmath_context *context, + size_t a, + size_t b, + size_t *out0); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_numeric_objects.h b/include/hmath_numeric_objects.h new file mode 100644 index 0000000..eec72b0 --- /dev/null +++ b/include/hmath_numeric_objects.h @@ -0,0 +1,92 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_numeric_objects.py. */ +#ifndef HMATH_NUMERIC_OBJECTS_H +#define HMATH_NUMERIC_OBJECTS_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Additional type instances of existing source functions; no new source + * coverage is claimed. Actual Coefficient witnesses retain Float/Double, exact + * Integer/Rational, bounded/native integers, Complex, nested Numeric.Dual and + * Num-only Numeric.Quaternion. Original AD.Dual (including nested supported + * leaves) and AD.Expr use distinct original Num/Fractional/Floating instances. + * Eq/Ord/Integral/Bounded are required only where the original signature needs + * them. AD.Expr has no Eq/Ord; Numeric.Dual/Quaternion have no Ord. Unsupported + * instances return UNSUPPORTED; no ordering or arithmetic instance is invented. + * clamp/min/max use actual native Ord dictionaries, including supported public + * labels and recursively typed lists/tuples/Maybe. All inputs are borrowed; + * outputs own one reference and remain untouched on failure. The prototype + * selects the actual numeric type (required for empty lists), and all numeric + * values must have that same actual type. Source exceptions/MathErrors remain + * unchanged. Arbitrary user-defined Haskell instances need compiled adapters. */ +/* HMath.Basic.clamp; original typeclass constraints. */ +HMATH_API hmath_status hmath_basic_clamp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *low, const hmath_value *high, const hmath_value *value, hmath_value **out); +/* HMath.Basic.lerp; original typeclass constraints. */ +HMATH_API hmath_status hmath_basic_lerp_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, const hmath_value *t, hmath_value **out); +/* HMath.Scalar.add; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.subtractScalar; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_subtract_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.multiply; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.minimumScalar; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_minimum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.maximumScalar; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_maximum_scalar_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.absolute; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_absolute_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out); +/* HMath.Scalar.sign; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_sign_value(hmath_context *context, const hmath_value *prototype, const hmath_value *x, hmath_value **out); +/* HMath.Scalar.positiveModulo; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_positive_modulo_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *modulus, hmath_value **out); +/* HMath.Scalar.cumulativeSum; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_cumulative_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Scalar.cumulativeProduct; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_cumulative_product_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Scalar.prefixSum; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_prefix_sum_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Statistics.mean; original typeclass constraints. */ +HMATH_API hmath_status hmath_statistics_mean_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Statistics.variance; original typeclass constraints. */ +HMATH_API hmath_status hmath_statistics_variance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Statistics.standardDeviation; original typeclass constraints. */ +HMATH_API hmath_status hmath_statistics_standard_deviation_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Statistics.median; original typeclass constraints. */ +HMATH_API hmath_status hmath_statistics_median_value(hmath_context *context, const hmath_value *prototype, const hmath_value *values, hmath_value **out); +/* HMath.Linear.dot; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_dot_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Linear.dotChecked; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_dot_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Linear.magnitude; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_magnitude_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out); +/* HMath.Linear.normalize; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_normalize_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, hmath_value **out); +/* HMath.Linear.add; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Linear.addChecked; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_add_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Linear.subtractChecked; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_subtract_checked_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Linear.scale; original typeclass constraints. */ +HMATH_API hmath_status hmath_linear_scale_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Scalar.saturatingAdd; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_saturating_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.saturatingSubtract; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_saturating_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.saturatingMultiply; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_saturating_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.checkedAdd; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_checked_add_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.checkedSubtract; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_checked_subtract_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Scalar.checkedMultiply; original typeclass constraints. */ +HMATH_API hmath_status hmath_scalar_checked_multiply_value(hmath_context *context, const hmath_value *prototype, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Geometry.Primitives.hammingDistance; original typeclass constraints. */ +HMATH_API hmath_status hmath_geometry_primitives_hamming_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +/* HMath.Geometry.Primitives.jaccardDistance; original typeclass constraints. */ +HMATH_API hmath_status hmath_geometry_primitives_jaccard_distance_value(hmath_context *context, const hmath_value *prototype, const hmath_value *argument1, const hmath_value *argument2, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_numeric_types.h b/include/hmath_numeric_types.h new file mode 100644 index 0000000..44ed727 --- /dev/null +++ b/include/hmath_numeric_types.h @@ -0,0 +1,149 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_numeric_types.py. */ +#ifndef HMATH_NUMERIC_TYPES_H +#define HMATH_NUMERIC_TYPES_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +typedef hmath_value hmath_numeric_value; +typedef hmath_status (*hmath_numeric_callback)(const hmath_numeric_value *input, void *userdata, hmath_numeric_value **out); +typedef enum hmath_rounding_mode { + HMATH_NEAREST_EVEN=0, HMATH_TOWARD_ZERO=1, HMATH_TOWARD_POSITIVE=2, HMATH_TOWARD_NEGATIVE=3 +} hmath_rounding_mode; +typedef enum hmath_numeric_exception { + HMATH_INVALID_OPERATION=0, HMATH_DIVISION_BY_ZERO=1, HMATH_NUMERIC_OVERFLOW=2, + HMATH_NUMERIC_UNDERFLOW=3, HMATH_INEXACT=4 +} hmath_numeric_exception; +typedef enum hmath_ieee_class { + HMATH_NOT_A_NUMBER=0, HMATH_POSITIVE_INFINITY=1, HMATH_NEGATIVE_INFINITY=2, + HMATH_POSITIVE_ZERO=3, HMATH_NEGATIVE_ZERO=4, HMATH_SUBNORMAL=5, HMATH_NORMAL=6 +} hmath_ieee_class; +/* Handles are immutable and own an RTS reservation. Hold a reference throughout + * every call; final shutdown is BUSY while any handle is live. Release is a NULL + * no-op. Outputs are untouched on failure. Original MathError uses status11. + * Strings use length-delimited Unicode code points (including embedded NUL and + * surrogates), exactly matching Haskell Char. All code points must be <=0x10ffff. + * Synchronous derivative callbacks borrow input; out transfers one reference. + * Retain input first if returning it. Callbacks may reenter checked APIs, must + * not unwind through C, and must be deterministic. Cancellation is before entry. + * Independent calls may share immutable values; own a reference on each thread. + * Primitive dtypes follow shared Coefficient codes: Double0,Float1,Integer2, + * Rational3,ComplexDouble4,ComplexFloat5,Int8..Int64=6..9,Word8..Word64=10..13, + * native Int14,Word15; Numeric.Dual20,Quaternion21. + */ +HMATH_API void hmath_numeric_types_retain(hmath_numeric_value *value); +HMATH_API void hmath_numeric_types_release(hmath_numeric_value *value); +HMATH_API void hmath_numeric_types_buffer_free(void *value); +HMATH_API int hmath_numeric_types_kind(const hmath_numeric_value *value); +HMATH_API hmath_status hmath_numeric_types_type_name(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_binary(hmath_context *context, int operation, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_unary(hmath_context *context, int operation, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_literal_integer(hmath_context *context, const hmath_numeric_value *like, const char *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_literal_rational(hmath_context *context, const hmath_numeric_value *like, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_integer_power(hmath_context *context, const hmath_numeric_value *value, const char *power, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_equal(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_sequence_get(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_round_rational(hmath_context *context, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_classify(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_frexp(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_numeric_limits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_integer_limits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_float16_limits(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_bfloat16_limits(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_numeric_limits_record(hmath_context *context, const hmath_numeric_value *normal, const hmath_numeric_value *subnormal, const hmath_numeric_value *maximum_value, const hmath_numeric_value *epsilon, ptrdiff_t digits, ptrdiff_t low, ptrdiff_t high, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_minimum_normal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_minimum_subnormal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_maximum_finite(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_machine_epsilon(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_significand_digits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_minimum_exponent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_maximum_exponent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_safe_integral_cast(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_saturating_cast(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_real_to_integral(hmath_context *context, int mode, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_narrow_float(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_float16(hmath_context *context, int mode, double value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_bfloat16(hmath_context *context, int mode, double value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_float16_from_bits(hmath_context *context, uint16_t bits, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_bfloat16_from_bits(hmath_context *context, uint16_t bits, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_float16_bits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_bfloat16_bits(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_from_float16(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_from_bfloat16(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_rounded(hmath_context *context, const hmath_numeric_value *value, const int *flags, size_t flags_count, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_rounded_value(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_numerical_exceptions(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_float(hmath_context *context, ptrdiff_t precision, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_extended(hmath_context *context, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_precision(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_to_double(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_subtract(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_divide(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_sqrt(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_exp(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_big_log(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_mixed_add(hmath_context *context, const hmath_numeric_value *a, double b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_mixed_multiply(hmath_context *context, const hmath_numeric_value *a, double b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed(hmath_context *context, ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_multiply(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_divide(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_decimal(hmath_context *context, ptrdiff_t scale, int mode, const char *value_numerator, const char *value_denominator, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_decimal_rational(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_decimal_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_decimal_multiply(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_decimal_divide(hmath_context *context, int mode, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_scale(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_fixed_coefficient(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval(hmath_context *context, double low, double high, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_bounds(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_contains(hmath_context *context, const hmath_numeric_value *value, double point, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_add(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_subtract(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_interval_divide(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_dual(hmath_context *context, const hmath_numeric_value *primal_value, const hmath_numeric_value *tangent_value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_primal(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_tangent(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_derivative(hmath_context *context, hmath_numeric_callback function, void *function_userdata, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_quaternion(hmath_context *context, const hmath_numeric_value *real, const hmath_numeric_value *i, const hmath_numeric_value *j, const hmath_numeric_value *k, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_quaternion_conjugate(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_quaternion_norm(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_quaternion_inverse(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_quaternion_component(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_dual_quaternion(hmath_context *context, const hmath_numeric_value *real, const hmath_numeric_value *dual, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_dual_quaternion_component(hmath_context *context, const hmath_numeric_value *value, ptrdiff_t index, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_dual_quaternion_multiply(hmath_context *context, const hmath_numeric_value *a, const hmath_numeric_value *b, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_dual_quaternion_inverse(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_rotate_vector(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_rigid_transform(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_transform_point(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *x, const hmath_numeric_value *y, const hmath_numeric_value *z, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant(hmath_context *context, const uint32_t *name, size_t name_count, const char *value_numerator, const char *value_denominator, const char *uncertainty_numerator, const char *uncertainty_denominator, const char *approximation_numerator, const char *approximation_denominator, const uint32_t *unit, size_t unit_count, const uint32_t *source, size_t source_count, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_name(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_value(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_standard_uncertainty(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_approximation_bound(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_unit(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_source(hmath_context *context, const hmath_numeric_value *value, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_as(hmath_context *context, const hmath_numeric_value *value, int dtype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_constant_as_like(hmath_context *context, const hmath_numeric_value *value, const hmath_numeric_value *prototype, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_mathematical_constants(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_physical_constants(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_speed_of_light(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_planck_constant(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_elementary_charge(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_boltzmann_constant(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_avogadro_constant(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_gravitational_constant(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_electron_mass(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_astronomical_unit(hmath_context *context, hmath_numeric_value **out); +HMATH_API hmath_status hmath_numeric_types_enum_value(hmath_context *context,const hmath_numeric_value *value,int *out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_numerical.h b/include/hmath_numerical.h new file mode 100644 index 0000000..31afaaa --- /dev/null +++ b/include/hmath_numerical.h @@ -0,0 +1,414 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_numerical_bindings.py. */ +#ifndef HMATH_NUMERICAL_H +#define HMATH_NUMERICAL_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original checked numerical solvers and diagnostics. All arguments are + * borrowed Value handles; success transfers one output reference. Outputs + * remain untouched on failure. Function arguments use kind101 callbacks from + * hmath_linear_callback, with a tuple of positional arguments. Keep callback + * function/userdata valid while any object retaining it remains alive. + * Source formulas, defaults, finite checks, limits and error variants are + * preserved. Source Left MathError returns status11. Inputs/outputs may share + * immutable handles; output addresses must be distinct from input storage. + * Independent readers keep references alive, contexts remain per-call. */ +typedef hmath_value hmath_calculus_estimate_object; /* kind200 */ +typedef hmath_value hmath_calculus_tolerance_object; /* kind201 */ +typedef hmath_value hmath_calculus_difference_object; /* kind202 */ +typedef hmath_value hmath_calculus_quadrature_object; /* kind203 */ +typedef hmath_value hmath_root_root_options_object; /* kind204 */ +typedef hmath_value hmath_root_root_result_object; /* kind205 */ +typedef hmath_value hmath_root_bracket_object; /* kind206 */ +typedef hmath_value hmath_root_bracket_method_object; /* kind207 */ +typedef hmath_value hmath_root_derivative_method_object; /* kind208 */ +typedef hmath_value hmath_root_fixed_point_method_object; /* kind209 */ +typedef hmath_value hmath_root_system_method_object; /* kind210 */ +typedef hmath_value hmath_root_system_root_result_object; /* kind211 */ +typedef hmath_value hmath_ode_method_object; /* kind212 */ +typedef hmath_value hmath_ode_ode_options_object; /* kind213 */ +typedef hmath_value hmath_ode_trajectory_object; /* kind214 */ +typedef hmath_value hmath_ode_event_direction_object; /* kind215 */ +typedef hmath_value hmath_ode_event_object; /* kind216 */ +typedef hmath_value hmath_ode_hamiltonian_method_object; /* kind217 */ +typedef hmath_value hmath_pde_grid_object; /* kind218 */ +typedef hmath_value hmath_pde_boundary_object; /* kind219 */ +typedef hmath_value hmath_pde_discretization_object; /* kind220 */ +typedef hmath_value hmath_pde_pde_operator_object; /* kind221 */ +typedef hmath_value hmath_pde_pde_result_object; /* kind222 */ +/* HMath.Calculus.Estimate :: a -> Double -> Int -> Estimate a */ +HMATH_API hmath_status hmath_calculus_estimate(hmath_context *context, const hmath_value *value, const hmath_value *error, const hmath_value *evaluations, hmath_value **out); +/* HMath.Calculus.estimateValue :: Estimate a -> a */ +HMATH_API hmath_status hmath_calculus_estimate_value(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.estimateError :: Estimate a -> Double */ +HMATH_API hmath_status hmath_calculus_estimate_error(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.evaluations :: Estimate a -> Int */ +HMATH_API hmath_status hmath_calculus_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.Tolerance :: Double -> Double -> Int -> Tolerance */ +HMATH_API hmath_status hmath_calculus_tolerance(hmath_context *context, const hmath_value *absolute_tolerance, const hmath_value *relative_tolerance, const hmath_value *maximum_evaluations, hmath_value **out); +/* HMath.Calculus.absoluteTolerance :: Tolerance -> Double */ +HMATH_API hmath_status hmath_calculus_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.relativeTolerance :: Tolerance -> Double */ +HMATH_API hmath_status hmath_calculus_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.maximumEvaluations :: Tolerance -> Int */ +HMATH_API hmath_status hmath_calculus_maximum_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.defaultTolerance :: Tolerance */ +HMATH_API hmath_status hmath_calculus_default_tolerance(hmath_context *context, hmath_value **out); +/* HMath.Calculus.Forward :: Difference */ +HMATH_API hmath_status hmath_calculus_forward(hmath_context *context, hmath_value **out); +/* HMath.Calculus.Backward :: Difference */ +HMATH_API hmath_status hmath_calculus_backward(hmath_context *context, hmath_value **out); +/* HMath.Calculus.Central :: Difference */ +HMATH_API hmath_status hmath_calculus_central(hmath_context *context, hmath_value **out); +/* HMath.Calculus.Trapezoidal :: Quadrature */ +HMATH_API hmath_status hmath_calculus_trapezoidal(hmath_context *context, hmath_value **out); +/* HMath.Calculus.Simpson :: Quadrature */ +HMATH_API hmath_status hmath_calculus_simpson(hmath_context *context, hmath_value **out); +/* HMath.Calculus.ThreeEighths :: Quadrature */ +HMATH_API hmath_status hmath_calculus_three_eighths(hmath_context *context, hmath_value **out); +/* HMath.Calculus.derivative :: Difference -> Double -> (Double -> Double) -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_derivative(hmath_context *context, const hmath_value *method, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.derivativeN :: Int -> Double -> (Double -> Double) -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_derivative_n(hmath_context *context, const hmath_value *order, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.complexDerivative :: Double -> (Complex Double -> Complex Double) -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_complex_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.richardson :: Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_richardson(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.ridders :: Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_ridders(hmath_context *context, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.limit :: Difference -> Tolerance -> Double -> (Double -> Double) -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_limit(hmath_context *context, const hmath_value *side, const hmath_value *tol, const hmath_value *initial, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.partialDerivative :: Int -> Double -> ([Double] -> Double) -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_partial_derivative(hmath_context *context, const hmath_value *i, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +/* HMath.Calculus.gradient :: Double -> ([Double] -> Double) -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_gradient(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +/* HMath.Calculus.jacobian :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_calculus_jacobian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +/* HMath.Calculus.hessian :: Double -> ([Double] -> Double) -> [Double] -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_calculus_hessian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *xs, hmath_value **out); +/* HMath.Calculus.directionalDerivative :: Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_directional_derivative(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +/* HMath.Calculus.jvp :: Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_jvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +/* HMath.Calculus.vjp :: Double -> ([Double] -> [Double]) -> [Double] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_vjp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +/* HMath.Calculus.hvp :: Double -> ([Double] -> Double) -> [Double] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_hvp(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, const hmath_value *v, hmath_value **out); +/* HMath.Calculus.divergence :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_divergence(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.curl :: Double -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_curl(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.laplacian :: Double -> ([Double] -> Double) -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_laplacian(hmath_context *context, const hmath_value *h, const hmath_value *f, const hmath_value *x, hmath_value **out); +/* HMath.Calculus.integrateComposite :: Quadrature -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_integrate_composite(hmath_context *context, const hmath_value *method, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.romberg :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_romberg(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.gaussLegendre :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_gauss_legendre(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.gaussHermite :: Int -> (Double -> Double) -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_gauss_hermite(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Calculus.gaussLaguerre :: Int -> (Double -> Double) -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_gauss_laguerre(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Calculus.gaussChebyshev :: Int -> (Double -> Double) -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_gauss_chebyshev(hmath_context *context, const hmath_value *n, const hmath_value *f, hmath_value **out); +/* HMath.Calculus.gaussKronrod :: (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_gauss_kronrod(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.adaptiveIntegrate :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_adaptive_integrate(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.clenshawCurtis :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_clenshaw_curtis(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.tanhSinh :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_tanh_sinh(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.integrateInfinite :: Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_integrate_infinite(hmath_context *context, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.integrateOscillatory :: Bool -> Double -> Tolerance -> (Double -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_integrate_oscillatory(hmath_context *context, const hmath_value *sine, const hmath_value *omega, const hmath_value *tol, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.integrateND :: Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_integrate_nd(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +/* HMath.Calculus.monteCarlo :: Integer -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_monte_carlo(hmath_context *context, const hmath_value *seed, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +/* HMath.Calculus.quasiMonteCarlo :: Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_quasi_monte_carlo(hmath_context *context, const hmath_value *n, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +/* HMath.Calculus.cumulativeIntegral :: [(Double, Double)] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_calculus_cumulative_integral(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Calculus.pathIntegral :: Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> Double) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_path_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.lineIntegral :: Tolerance -> (Double -> [Double]) -> (Double -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> Either MathError (Estimate Double) */ +HMATH_API hmath_status hmath_calculus_line_integral(hmath_context *context, const hmath_value *tol, const hmath_value *curve, const hmath_value *tangent, const hmath_value *field, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Calculus.surfaceIntegral :: Int -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_surface_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *surface, const hmath_value *du, const hmath_value *dv, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +/* HMath.Calculus.volumeIntegral :: Int -> Int -> ([Double] -> Double) -> [(Double, Double)] -> Either MathError Double */ +HMATH_API hmath_status hmath_calculus_volume_integral(hmath_context *context, const hmath_value *panels, const hmath_value *budget, const hmath_value *f, const hmath_value *bounds, hmath_value **out); +/* HMath.Root.RootOptions :: Int -> Int -> Double -> Double -> RootOptions */ +HMATH_API hmath_status hmath_root_root_options(hmath_context *context, const hmath_value *root_max_iterations, const hmath_value *root_max_evaluations, const hmath_value *root_tolerance, const hmath_value *root_step_tolerance, hmath_value **out); +/* HMath.Root.rootMaxIterations :: RootOptions -> Int */ +HMATH_API hmath_status hmath_root_root_max_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootMaxEvaluations :: RootOptions -> Int */ +HMATH_API hmath_status hmath_root_root_max_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootTolerance :: RootOptions -> Double */ +HMATH_API hmath_status hmath_root_root_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootStepTolerance :: RootOptions -> Double */ +HMATH_API hmath_status hmath_root_root_step_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.defaultRootOptions :: RootOptions */ +HMATH_API hmath_status hmath_root_default_root_options(hmath_context *context, hmath_value **out); +/* HMath.Root.RootResult :: Double -> Double -> Maybe Double -> Int -> Int -> RootResult */ +HMATH_API hmath_status hmath_root_root_result(hmath_context *context, const hmath_value *root_value, const hmath_value *root_residual, const hmath_value *root_error_bound, const hmath_value *root_iterations, const hmath_value *root_evaluations, hmath_value **out); +/* HMath.Root.rootValue :: RootResult -> Double */ +HMATH_API hmath_status hmath_root_root_value(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootResidual :: RootResult -> Double */ +HMATH_API hmath_status hmath_root_root_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootErrorBound :: RootResult -> Maybe Double */ +HMATH_API hmath_status hmath_root_root_error_bound(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootIterations :: RootResult -> Int */ +HMATH_API hmath_status hmath_root_root_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.rootEvaluations :: RootResult -> Int */ +HMATH_API hmath_status hmath_root_root_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.Bisection :: BracketMethod */ +HMATH_API hmath_status hmath_root_bisection(hmath_context *context, hmath_value **out); +/* HMath.Root.RegulaFalsi :: BracketMethod */ +HMATH_API hmath_status hmath_root_regula_falsi(hmath_context *context, hmath_value **out); +/* HMath.Root.Illinois :: BracketMethod */ +HMATH_API hmath_status hmath_root_illinois(hmath_context *context, hmath_value **out); +/* HMath.Root.Brent :: BracketMethod */ +HMATH_API hmath_status hmath_root_brent(hmath_context *context, hmath_value **out); +/* HMath.Root.Ridder :: BracketMethod */ +HMATH_API hmath_status hmath_root_ridder(hmath_context *context, hmath_value **out); +/* HMath.Root.Newton :: DerivativeMethod */ +HMATH_API hmath_status hmath_root_newton(hmath_context *context, hmath_value **out); +/* HMath.Root.Halley :: DerivativeMethod */ +HMATH_API hmath_status hmath_root_halley(hmath_context *context, hmath_value **out); +/* HMath.Root.Householder3 :: DerivativeMethod */ +HMATH_API hmath_status hmath_root_householder3(hmath_context *context, hmath_value **out); +/* HMath.Root.Picard :: FixedPointMethod */ +HMATH_API hmath_status hmath_root_picard(hmath_context *context, hmath_value **out); +/* HMath.Root.Aitken :: FixedPointMethod */ +HMATH_API hmath_status hmath_root_aitken(hmath_context *context, hmath_value **out); +/* HMath.Root.SteffensenFixed :: FixedPointMethod */ +HMATH_API hmath_status hmath_root_steffensen_fixed(hmath_context *context, hmath_value **out); +/* HMath.Root.MultivariateNewton :: SystemMethod */ +HMATH_API hmath_status hmath_root_multivariate_newton(hmath_context *context, hmath_value **out); +/* HMath.Root.NewtonTrustRegion :: Double -> SystemMethod */ +HMATH_API hmath_status hmath_root_newton_trust_region(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.Broyden :: SystemMethod */ +HMATH_API hmath_status hmath_root_broyden(hmath_context *context, hmath_value **out); +/* HMath.Root.SystemRootResult :: [Double] -> Double -> Int -> Int -> SystemRootResult */ +HMATH_API hmath_status hmath_root_system_root_result(hmath_context *context, const hmath_value *system_root, const hmath_value *system_residual, const hmath_value *system_iterations, const hmath_value *system_evaluations, hmath_value **out); +/* HMath.Root.systemRoot :: SystemRootResult -> [Double] */ +HMATH_API hmath_status hmath_root_system_root(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.systemResidual :: SystemRootResult -> Double */ +HMATH_API hmath_status hmath_root_system_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.systemIterations :: SystemRootResult -> Int */ +HMATH_API hmath_status hmath_root_system_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.systemEvaluations :: SystemRootResult -> Int */ +HMATH_API hmath_status hmath_root_system_evaluations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Root.bracket :: (Double -> Double) -> Double -> Double -> Either MathError Bracket */ +HMATH_API hmath_status hmath_root_bracket(hmath_context *context, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Root.solveBracket :: BracketMethod -> RootOptions -> (Double -> Double) -> Bracket -> Either MathError RootResult */ +HMATH_API hmath_status hmath_root_solve_bracket(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.Root.bracketScan :: RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [Bracket] */ +HMATH_API hmath_status hmath_root_bracket_scan(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out); +/* HMath.Root.isolateIntervals :: RootOptions -> (Double -> Double) -> Double -> Double -> Int -> Either MathError [RootResult] */ +HMATH_API hmath_status hmath_root_isolate_intervals(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, const hmath_value *cells, hmath_value **out); +/* HMath.Root.solveDerivative :: DerivativeMethod -> RootOptions -> (Double -> Double) -> [Double -> Double] -> Double -> Either MathError RootResult */ +HMATH_API hmath_status hmath_root_solve_derivative(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *derivatives, const hmath_value *x0, hmath_value **out); +/* HMath.Root.secant :: RootOptions -> (Double -> Double) -> Double -> Double -> Either MathError RootResult */ +HMATH_API hmath_status hmath_root_secant(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Root.steffensen :: RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult */ +HMATH_API hmath_status hmath_root_steffensen(hmath_context *context, const hmath_value *o, const hmath_value *f, const hmath_value *x0, hmath_value **out); +/* HMath.Root.fixedPoint :: FixedPointMethod -> RootOptions -> (Double -> Double) -> Double -> Either MathError RootResult */ +HMATH_API hmath_status hmath_root_fixed_point(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out); +/* HMath.Root.anderson :: Int -> Double -> RootOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError SystemRootResult */ +HMATH_API hmath_status hmath_root_anderson(hmath_context *context, const hmath_value *depth, const hmath_value *regularization, const hmath_value *o, const hmath_value *g, const hmath_value *x0, hmath_value **out); +/* HMath.Root.solveSystem :: SystemMethod -> RootOptions -> ([Double] -> [Double]) -> ([Double] -> [[Double]]) -> [Double] -> Either MathError SystemRootResult */ +HMATH_API hmath_status hmath_root_solve_system(hmath_context *context, const hmath_value *method, const hmath_value *o, const hmath_value *f, const hmath_value *jac, const hmath_value *x0, hmath_value **out); +/* HMath.Root.polynomialRoots :: RootOptions -> P.Polynomial (Complex Double) -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_root_polynomial_roots(hmath_context *context, const hmath_value *o, const hmath_value *p, hmath_value **out); +/* HMath.Root.realPolynomialRoots :: Int -> Rational -> P.Polynomial Rational -> Either MathError [(Rational, Rational, Int)] */ +HMATH_API hmath_status hmath_root_real_polynomial_roots(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *p, hmath_value **out); +/* HMath.ODE.Euler :: Method */ +HMATH_API hmath_status hmath_ode_euler(hmath_context *context, hmath_value **out); +/* HMath.ODE.Heun :: Method */ +HMATH_API hmath_status hmath_ode_heun(hmath_context *context, hmath_value **out); +/* HMath.ODE.Midpoint :: Method */ +HMATH_API hmath_status hmath_ode_midpoint(hmath_context *context, hmath_value **out); +/* HMath.ODE.RK2 :: Method */ +HMATH_API hmath_status hmath_ode_rk2(hmath_context *context, hmath_value **out); +/* HMath.ODE.RK4 :: Method */ +HMATH_API hmath_status hmath_ode_rk4(hmath_context *context, hmath_value **out); +/* HMath.ODE.RK23 :: Method */ +HMATH_API hmath_status hmath_ode_rk23(hmath_context *context, hmath_value **out); +/* HMath.ODE.RK45 :: Method */ +HMATH_API hmath_status hmath_ode_rk45(hmath_context *context, hmath_value **out); +/* HMath.ODE.DormandPrince :: Method */ +HMATH_API hmath_status hmath_ode_dormand_prince(hmath_context *context, hmath_value **out); +/* HMath.ODE.DOP853 :: Method */ +HMATH_API hmath_status hmath_ode_dop853(hmath_context *context, hmath_value **out); +/* HMath.ODE.AdamsBashforth :: Method */ +HMATH_API hmath_status hmath_ode_adams_bashforth(hmath_context *context, hmath_value **out); +/* HMath.ODE.AdamsMoulton :: Method */ +HMATH_API hmath_status hmath_ode_adams_moulton(hmath_context *context, hmath_value **out); +/* HMath.ODE.PredictorCorrector :: Method */ +HMATH_API hmath_status hmath_ode_predictor_corrector(hmath_context *context, hmath_value **out); +/* HMath.ODE.BackwardEuler :: Method */ +HMATH_API hmath_status hmath_ode_backward_euler(hmath_context *context, hmath_value **out); +/* HMath.ODE.BDF :: Method */ +HMATH_API hmath_status hmath_ode_bdf(hmath_context *context, hmath_value **out); +/* HMath.ODE.Radau :: Method */ +HMATH_API hmath_status hmath_ode_radau(hmath_context *context, hmath_value **out); +/* HMath.ODE.Rosenbrock :: Method */ +HMATH_API hmath_status hmath_ode_rosenbrock(hmath_context *context, hmath_value **out); +/* HMath.ODE.ODEOptions :: Double -> Double -> Double -> Double -> Double -> Int -> Int -> ODEOptions */ +HMATH_API hmath_status hmath_ode_ode_options(hmath_context *context, const hmath_value *ode_absolute_tolerance, const hmath_value *ode_relative_tolerance, const hmath_value *initial_step, const hmath_value *minimum_step, const hmath_value *maximum_step, const hmath_value *maximum_steps, const hmath_value *newton_iterations, hmath_value **out); +/* HMath.ODE.odeAbsoluteTolerance :: ODEOptions -> Double */ +HMATH_API hmath_status hmath_ode_ode_absolute_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.odeRelativeTolerance :: ODEOptions -> Double */ +HMATH_API hmath_status hmath_ode_ode_relative_tolerance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.initialStep :: ODEOptions -> Double */ +HMATH_API hmath_status hmath_ode_initial_step(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.minimumStep :: ODEOptions -> Double */ +HMATH_API hmath_status hmath_ode_minimum_step(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.maximumStep :: ODEOptions -> Double */ +HMATH_API hmath_status hmath_ode_maximum_step(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.maximumSteps :: ODEOptions -> Int */ +HMATH_API hmath_status hmath_ode_maximum_steps(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.newtonIterations :: ODEOptions -> Int */ +HMATH_API hmath_status hmath_ode_newton_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.defaultODEOptions :: ODEOptions */ +HMATH_API hmath_status hmath_ode_default_ode_options(hmath_context *context, hmath_value **out); +/* HMath.ODE.Trajectory :: [Double] -> [[Double]] -> [[Double]] -> Trajectory */ +HMATH_API hmath_status hmath_ode_trajectory(hmath_context *context, const hmath_value *trajectory_times, const hmath_value *trajectory_states, const hmath_value *trajectory_derivatives, hmath_value **out); +/* HMath.ODE.trajectoryTimes :: Trajectory -> [Double] */ +HMATH_API hmath_status hmath_ode_trajectory_times(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.trajectoryStates :: Trajectory -> [[Double]] */ +HMATH_API hmath_status hmath_ode_trajectory_states(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.trajectoryDerivatives :: Trajectory -> [[Double]] */ +HMATH_API hmath_status hmath_ode_trajectory_derivatives(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.solveIVP :: Method -> ODEOptions -> Int -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_ivp(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +/* HMath.ODE.solveAdaptive :: Method -> ODEOptions -> ODE -> Double -> Double -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_adaptive(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +/* HMath.ODE.interpolateTrajectory :: Trajectory -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ode_interpolate_trajectory(hmath_context *context, const hmath_value *trajectory, const hmath_value *t, hmath_value **out); +/* HMath.ODE.AnyDirection :: EventDirection */ +HMATH_API hmath_status hmath_ode_any_direction(hmath_context *context, hmath_value **out); +/* HMath.ODE.Rising :: EventDirection */ +HMATH_API hmath_status hmath_ode_rising(hmath_context *context, hmath_value **out); +/* HMath.ODE.Falling :: EventDirection */ +HMATH_API hmath_status hmath_ode_falling(hmath_context *context, hmath_value **out); +/* HMath.ODE.Event :: Double -> [Double] -> Event */ +HMATH_API hmath_status hmath_ode_event(hmath_context *context, const hmath_value *event_time, const hmath_value *event_state, hmath_value **out); +/* HMath.ODE.eventTime :: Event -> Double */ +HMATH_API hmath_status hmath_ode_event_time(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.eventState :: Event -> [Double] */ +HMATH_API hmath_status hmath_ode_event_state(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.ODE.locateEvents :: EventDirection -> Double -> (Double -> [Double] -> Double) -> Trajectory -> Either MathError [Event] */ +HMATH_API hmath_status hmath_ode_locate_events(hmath_context *context, const hmath_value *direction, const hmath_value *tolerance, const hmath_value *function, const hmath_value *trajectory, hmath_value **out); +/* HMath.ODE.solveBoundary :: Method -> ODEOptions -> Int -> ODE -> ([Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_boundary(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *f, const hmath_value *boundary, const hmath_value *start, const hmath_value *end, const hmath_value *guess, hmath_value **out); +/* HMath.ODE.solveDAE :: ODEOptions -> Int -> (Double -> [Double] -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_dae(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *residual, const hmath_value *start, const hmath_value *end, const hmath_value *initial, const hmath_value *initial_derivative, hmath_value **out); +/* HMath.ODE.SymplecticEuler :: HamiltonianMethod */ +HMATH_API hmath_status hmath_ode_symplectic_euler(hmath_context *context, hmath_value **out); +/* HMath.ODE.Verlet :: HamiltonianMethod */ +HMATH_API hmath_status hmath_ode_verlet(hmath_context *context, hmath_value **out); +/* HMath.ODE.Leapfrog :: HamiltonianMethod */ +HMATH_API hmath_status hmath_ode_leapfrog(hmath_context *context, hmath_value **out); +/* HMath.ODE.solveHamiltonian :: HamiltonianMethod -> Int -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_hamiltonian(hmath_context *context, const hmath_value *method, const hmath_value *panels, const hmath_value *velocity, const hmath_value *force, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *p0, hmath_value **out); +/* HMath.ODE.solveNystrom :: Int -> (Double -> [Double] -> [Double]) -> Double -> Double -> [Double] -> [Double] -> Either MathError Trajectory */ +HMATH_API hmath_status hmath_ode_solve_nystrom(hmath_context *context, const hmath_value *panels, const hmath_value *acceleration, const hmath_value *start, const hmath_value *end, const hmath_value *q0, const hmath_value *v0, hmath_value **out); +/* HMath.ODE.sensitivities :: Method -> ODEOptions -> Int -> Double -> ([Double] -> ODE) -> [Double] -> Double -> Double -> [Double] -> Either MathError (Matrix Double) */ +HMATH_API hmath_status hmath_ode_sensitivities(hmath_context *context, const hmath_value *method, const hmath_value *options, const hmath_value *panels, const hmath_value *h, const hmath_value *family, const hmath_value *parameters, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +/* HMath.ODE.equilibrium :: ODEOptions -> ([Double] -> [Double]) -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ode_equilibrium(hmath_context *context, const hmath_value *options, const hmath_value *field, const hmath_value *guess, hmath_value **out); +/* HMath.ODE.phaseTrajectories :: Method -> ODEOptions -> Int -> ([Double] -> [Double]) -> Double -> Double -> [[Double]] -> Either MathError [Trajectory] */ +HMATH_API hmath_status hmath_ode_phase_trajectories(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, const hmath_value *value7, hmath_value **out); +/* HMath.ODE.lyapunovExponents :: ODEOptions -> Int -> Double -> ODE -> Double -> Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_ode_lyapunov_exponents(hmath_context *context, const hmath_value *options, const hmath_value *panels, const hmath_value *difference_step, const hmath_value *f, const hmath_value *start, const hmath_value *end, const hmath_value *initial, hmath_value **out); +/* HMath.PDE.Dirichlet :: Double -> Boundary */ +HMATH_API hmath_status hmath_pde_dirichlet(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.Neumann :: Double -> Boundary */ +HMATH_API hmath_status hmath_pde_neumann(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.Robin :: Double -> Double -> Double -> Boundary */ +HMATH_API hmath_status hmath_pde_robin(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.PDE.Periodic :: Boundary */ +HMATH_API hmath_status hmath_pde_periodic(hmath_context *context, hmath_value **out); +/* HMath.PDE.FiniteDifference :: Discretization */ +HMATH_API hmath_status hmath_pde_finite_difference(hmath_context *context, hmath_value **out); +/* HMath.PDE.FiniteVolume :: Discretization */ +HMATH_API hmath_status hmath_pde_finite_volume(hmath_context *context, hmath_value **out); +/* HMath.PDE.FiniteElement :: Discretization */ +HMATH_API hmath_status hmath_pde_finite_element(hmath_context *context, hmath_value **out); +/* HMath.PDE.PDEResult :: [Double] -> Double -> Double -> PDEResult */ +HMATH_API hmath_status hmath_pde_pde_result(hmath_context *context, const hmath_value *pde_values, const hmath_value *pde_residual, const hmath_value *pde_error_estimate, hmath_value **out); +/* HMath.PDE.pdeValues :: PDEResult -> [Double] */ +HMATH_API hmath_status hmath_pde_pde_values(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.pdeResidual :: PDEResult -> Double */ +HMATH_API hmath_status hmath_pde_pde_residual(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.pdeErrorEstimate :: PDEResult -> Double */ +HMATH_API hmath_status hmath_pde_pde_error_estimate(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.grid :: [Int] -> [(Double, Double)] -> [Bool] -> Either MathError Grid */ +HMATH_API hmath_status hmath_pde_grid(hmath_context *context, const hmath_value *dims, const hmath_value *bounds, const hmath_value *periodic, hmath_value **out); +/* HMath.PDE.gridShape :: Grid -> [Int] */ +HMATH_API hmath_status hmath_pde_grid_shape(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.gridSpacing :: Grid -> [Double] */ +HMATH_API hmath_status hmath_pde_grid_spacing(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.flattenIndex :: Grid -> [Int] -> Either MathError Int */ +HMATH_API hmath_status hmath_pde_flatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.PDE.unflattenIndex :: Grid -> Int -> Either MathError [Int] */ +HMATH_API hmath_status hmath_pde_unflatten_index(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.PDE.gridCoordinates :: Grid -> [[Double]] */ +HMATH_API hmath_status hmath_pde_grid_coordinates(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.assemblePDE :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Double -> Either MathError PDEOperator */ +HMATH_API hmath_status hmath_pde_assemble_pde(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.PDE.pdeStiffness :: PDEOperator -> S.Sparse Double */ +HMATH_API hmath_status hmath_pde_pde_stiffness(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.pdeMass :: PDEOperator -> S.Sparse Double */ +HMATH_API hmath_status hmath_pde_pde_mass(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.pdeBoundaryLoad :: PDEOperator -> [Double] */ +HMATH_API hmath_status hmath_pde_pde_boundary_load(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.PDE.solveElliptic :: PDEOperator -> [Double] -> Either MathError PDEResult */ +HMATH_API hmath_status hmath_pde_solve_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.PDE.poisson :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError PDEResult */ +HMATH_API hmath_status hmath_pde_poisson(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *forcing, hmath_value **out); +/* HMath.PDE.laplace :: Discretization -> Grid -> [(Boundary, Boundary)] -> Either MathError PDEResult */ +HMATH_API hmath_status hmath_pde_laplace(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, hmath_value **out); +/* HMath.PDE.helmholtz :: Discretization -> Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> Either MathError PDEResult */ +HMATH_API hmath_status hmath_pde_helmholtz(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *k, const hmath_value *forcing, hmath_value **out); +/* HMath.PDE.spatialGradient :: Grid -> [Double] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_pde_spatial_gradient(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.PDE.laplacianStencil :: Grid -> [(Boundary, Boundary)] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_pde_laplacian_stencil(hmath_context *context, const hmath_value *g, const hmath_value *bc, const hmath_value *values, hmath_value **out); +/* HMath.PDE.spectralDerivative :: Grid -> Int -> Int -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_pde_spectral_derivative(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.PDE.spectralLaplacian :: Grid -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_pde_spectral_laplacian(hmath_context *context, const hmath_value *g, const hmath_value *values, hmath_value **out); +/* HMath.PDE.spectralPoisson :: Grid -> Double -> [Double] -> Either MathError PDEResult */ +HMATH_API hmath_status hmath_pde_spectral_poisson(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.PDE.pseudoSpectralDiffusion :: Grid -> [Double] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_pde_pseudo_spectral_diffusion(hmath_context *context, const hmath_value *g, const hmath_value *kappas, const hmath_value *values, hmath_value **out); +/* HMath.PDE.methodOfLines :: O.Method -> PDEOperator -> (Double -> [Double]) -> [Double] -> [Double] -> Either MathError O.Trajectory */ +HMATH_API hmath_status hmath_pde_method_of_lines(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.PDE.heat :: Grid -> [(Boundary, Boundary)] -> Double -> [Double] -> [Double] -> Either MathError O.Trajectory */ +HMATH_API hmath_status hmath_pde_heat(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.PDE.diffusion :: Discretization -> Grid -> [(Boundary, Boundary)] -> [Double] -> [Double] -> [Double] -> Either MathError O.Trajectory */ +HMATH_API hmath_status hmath_pde_diffusion(hmath_context *context, const hmath_value *method, const hmath_value *g, const hmath_value *bc, const hmath_value *kappas, const hmath_value *times, const hmath_value *initial, hmath_value **out); +/* HMath.PDE.wave :: Grid -> Double -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_pde_wave(hmath_context *context, const hmath_value *g, const hmath_value *speed, const hmath_value *times, const hmath_value *initial, const hmath_value *velocity, hmath_value **out); +/* HMath.PDE.advection :: Grid -> [Double] -> [Double] -> [Double] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_pde_advection(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.PDE.advectionDiffusion :: Grid -> [Double] -> Double -> [Double] -> [Double] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_pde_advection_diffusion(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.PDE.stabilityLimit :: Grid -> Double -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_pde_stability_limit(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, hmath_value **out); +/* HMath.PDE.cflNumber :: Grid -> Double -> [Double] -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_pde_cfl_number(hmath_context *context, const hmath_value *g, const hmath_value *diffusivity, const hmath_value *velocity, const hmath_value *dt, hmath_value **out); +/* HMath.PDE.manufacturedError :: Grid -> ([Double] -> Double) -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_pde_manufactured_error(hmath_context *context, const hmath_value *g, const hmath_value *exact, const hmath_value *values, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_optimization.h b/include/hmath_optimization.h new file mode 100644 index 0000000..d81113e --- /dev/null +++ b/include/hmath_optimization.h @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_OPTIMIZATION_H +#define HMATH_OPTIMIZATION_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum hmath_gradient_method { + HMATH_GRADIENT_DESCENT = 0, + HMATH_MOMENTUM = 1, + HMATH_NESTEROV = 2, + HMATH_ADAGRAD = 3, + HMATH_RMSPROP = 4, + HMATH_ADADELTA = 5, + HMATH_ADAM = 6, + HMATH_ADAMW = 7, + HMATH_AMSGRAD = 8, + HMATH_ADAMAX = 9, + HMATH_NADAM = 10, + HMATH_RADAM = 11 +} hmath_gradient_method; + +typedef struct hmath_optimizer_state hmath_optimizer_state; + +/* HMath.Optimization.FirstOrder.initializeOptimizer. Negative dimension is + * passed to Haskell and returns its original InvalidArgument MathError. + * Each state is immutable and owns one runtime reservation. Final shutdown + * returns BUSY until all states are released. Outputs are untouched on error. */ +HMATH_API hmath_status hmath_initialize_optimizer(hmath_context *context, ptrdiff_t dimension, + hmath_optimizer_state **out); +HMATH_API void hmath_optimizer_state_retain(hmath_optimizer_state *state); +HMATH_API void hmath_optimizer_state_release(hmath_optimizer_state *state); + +/* HMath.Optimization.FirstOrder.optimizerStep, with the same defaults: + * beta1=.9, beta2=.999, epsilon=1e-8; RMSProp/AdaDelta rho=.9; + * AdamW weight decay=.01. No new mathematical options or defaults are added. + * Nesterov is this function's corrected-momentum update, not the look-ahead + * objective evaluation performed by minimizeGradient. + * Preserve the original state; return new parameters and a new independent + * state. Input/state/gradient length mismatches retain the original MathError. + * Inputs are borrowed during the call. All output regions must be disjoint + * from inputs and each other. out_capacity >= parameter_count. On failure + * both outputs are untouched. The caller holds a state reference for the call. + * Sharing states between threads is safe; output buffers must be independent. + * Cancellation is checked before entry. Release returned states explicitly. */ +HMATH_API hmath_status hmath_optimizer_step(hmath_context *context, hmath_gradient_method method, + double rate, const hmath_optimizer_state *state, + const double *parameters, size_t parameter_count, + const double *gradient, size_t gradient_count, + double *out_parameters, size_t out_capacity, + hmath_optimizer_state **out_state); + +#ifdef __cplusplus +} +#endif +#include "hmath_optimization_all.h" +#endif diff --git a/include/hmath_optimization_all.h b/include/hmath_optimization_all.h new file mode 100644 index 0000000..0bea806 --- /dev/null +++ b/include/hmath_optimization_all.h @@ -0,0 +1,467 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_OPTIMIZATION_ALL_H +#define HMATH_OPTIMIZATION_ALL_H +#include "hmath_error.h" +#include "hmath_optimization.h" +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Typed immutable values represent original records, methods, ragged lists and + * callbacks. All solver arithmetic is the original Double implementation. + * Each output owns one Value reference; release it with hmath_value_release. + * Inputs are borrowed for each call; concurrent immutable sharing is allowed. + * Callback/userdata must remain live while any derived function/constraint may + * invoke them. Returned callback values transfer one owned reference; retain a + * borrowed input before returning it. status11 fills MathError wire and becomes + * a genuine Haskell Left, allowing original solver recovery/backtracking. + * Unexpected failures return another status and abort after native cleanup. + * Output pointers remain untouched on errors; buffers must not overlap inputs. + * Original options, budgets, diagnostics and explicit Word64 seeds are retained. + * Callback roles:0Objective(vector->Double),1Gradient/projection(vector->vector), + * 2Hessian/Jacobian(vector->ragged matrix),3prox((rate,point)->vector), + * 4monitor(OptimizeResult->Bool). Scalar minimization Objective input is [x]. */ +typedef hmath_status (*hmath_optimization_callback_fn)(const hmath_value *argument, void *userdata, + hmath_value **out, hmath_math_error *error); +HMATH_API hmath_status hmath_optimization_callback(hmath_context *context, int role, + hmath_optimization_callback_fn function, + void *userdata, hmath_value **out); +HMATH_API hmath_status hmath_optimization_function_apply(hmath_context *context, + const hmath_value *function, + const hmath_value *const *arguments, + size_t count, hmath_value **out); +HMATH_API hmath_status hmath_optimization_state_import(hmath_context *context, + const hmath_optimizer_state *state, + hmath_value **out); +HMATH_API hmath_status hmath_optimization_state_export(hmath_context *context, + const hmath_value *value, + hmath_optimizer_state **out); +/* HMath.Optimization.Common.OptimizeOptions (Int, Int, Double, Double) -> Options. */ +HMATH_API hmath_status hmath_optimization_optimize_options_create( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Optimization.Common.defaultOptimizeOptions () -> Options. */ +HMATH_API hmath_status hmath_optimization_default_optimize_options(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Common.OptimizeResult (Vector, Double, Double, Int, Int, Bool) -> Result. */ +HMATH_API hmath_status hmath_optimization_optimize_result_create( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Common.EarlyStopping (MaybeDouble, Int, Bool) -> EarlyStopping. */ +HMATH_API hmath_status hmath_optimization_early_stopping_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Optimization.Common.ConstantRate (Double) -> LearningRate. */ +HMATH_API hmath_status hmath_optimization_constant_rate_create(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.StepDecay (Double, Int, Double) -> LearningRate. */ +HMATH_API hmath_status hmath_optimization_step_decay_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Optimization.Common.ExponentialDecay (Double, Double) -> LearningRate. */ +HMATH_API hmath_status hmath_optimization_exponential_decay_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Optimization.Common.CosineAnnealing (Double, Double, Int) -> LearningRate. */ +HMATH_API hmath_status hmath_optimization_cosine_annealing_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + hmath_value **out); +/* HMath.Optimization.Common.Warmup (Int, LearningRate) -> LearningRate. */ +HMATH_API hmath_status hmath_optimization_warmup_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.Armijo () -> LineSearch. */ +HMATH_API hmath_status hmath_optimization_armijo_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Common.StrongWolfe () -> LineSearch. */ +HMATH_API hmath_status hmath_optimization_strong_wolfe_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Common.checkedOptions (Options) -> Unit. */ +HMATH_API hmath_status hmath_optimization_checked_options(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.checkedPoint (Vector) -> Unit. */ +HMATH_API hmath_status hmath_optimization_checked_point(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.checkedValue (Objective, Vector) -> Double. */ +HMATH_API hmath_status hmath_optimization_checked_value(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.checkedGradient (Gradient, Vector) -> Vector. */ +HMATH_API hmath_status hmath_optimization_checked_gradient(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Optimization.Common.checkBudget (Options, Int) -> Unit. */ +HMATH_API hmath_status hmath_optimization_check_budget(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + hmath_value **out); +/* HMath.Optimization.Common.dot (Vector, Vector) -> Value. */ +HMATH_API hmath_status hmath_optimization_dot(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.add (Vector, Vector) -> Value. */ +HMATH_API hmath_status hmath_optimization_add(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.sub (Vector, Vector) -> Value. */ +HMATH_API hmath_status hmath_optimization_sub(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.outer (Vector, Vector) -> Value. */ +HMATH_API hmath_status hmath_optimization_outer(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.norm (Vector) -> Double. */ +HMATH_API hmath_status hmath_optimization_norm(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.scale (Double, Vector) -> Vector. */ +HMATH_API hmath_status hmath_optimization_scale(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.identity (Int) -> Matrix. */ +HMATH_API hmath_status hmath_optimization_identity(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.matVec (Matrix, Vector) -> Vector. */ +HMATH_API hmath_status hmath_optimization_mat_vec(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.matMul (Matrix, Matrix) -> Matrix. */ +HMATH_API hmath_status hmath_optimization_mat_mul(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.transpose (GenericMatrix) -> GenericMatrix. */ +HMATH_API hmath_status hmath_optimization_transpose(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.solveDense (Matrix, Vector) -> Vector. */ +HMATH_API hmath_status hmath_optimization_solve_dense(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.result (Int, Int, Bool, Objective, Gradient, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_result(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Common.learningRate (LearningRate, Int) -> Double. */ +HMATH_API hmath_status hmath_optimization_learning_rate(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Common.earlyStopping (Int, Double, Double, EarlyStopping) -> EarlyStopping. */ +HMATH_API hmath_status hmath_optimization_early_stopping(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Optimization.Common.lineSearch (LineSearch, Int, Objective, Gradient, Vector, Vector, + * Double, Vector) -> Tuple. */ +HMATH_API hmath_status hmath_optimization_line_search(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, const hmath_value *a6, + const hmath_value *a7, hmath_value **out); +/* HMath.Optimization.Common.optMaxIterations (Options) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_max_iterations(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optMaxEvaluations (Options) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_max_evaluations(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optTolerance (Options) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_tolerance(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.optLearningRate (Options) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_learning_rate(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optPoint (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_point(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optValue (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_value(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optGradientNorm (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_gradient_norm(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.optIterations (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_iterations(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.optEvaluations (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_evaluations(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.optConverged (Result) -> Value. */ +HMATH_API hmath_status hmath_optimization_opt_converged(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Common.bestScore (EarlyStopping) -> Value. */ +HMATH_API hmath_status hmath_optimization_best_score(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.staleSteps (EarlyStopping) -> Value. */ +HMATH_API hmath_status hmath_optimization_stale_steps(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Common.stopped (EarlyStopping) -> Value. */ +HMATH_API hmath_status hmath_optimization_stopped(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.FirstOrder.GradientDescent () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_gradient_descent_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.Momentum () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_momentum_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.Nesterov () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_nesterov_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.AdaGrad () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_ada_grad_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.RMSProp () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_rms_prop_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.AdaDelta () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_ada_delta_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.Adam () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_adam_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.FirstOrder.AdamW () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_adam_w_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.FirstOrder.AMSGrad () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_ams_grad_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.FirstOrder.AdaMax () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_ada_max_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.FirstOrder.Nadam () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_nadam_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.FirstOrder.RAdam () -> GradientMethod. */ +HMATH_API hmath_status hmath_optimization_r_adam_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.FirstOrder.initializeOptimizer (Int) -> State. */ +HMATH_API hmath_status hmath_optimization_initialize_optimizer(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.FirstOrder.optimizerStep (GradientMethod, Double, State, Vector, Vector) -> + * Tuple. */ +HMATH_API hmath_status hmath_optimization_optimizer_step( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.FirstOrder.minimizeGradient (GradientMethod, Options, Objective, Gradient, + * Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_minimize_gradient( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.FirstOrder.minimizeGradientWithCallback (Monitor, GradientMethod, Options, + * Objective, Gradient, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_minimize_gradient_with_callback( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.FirstOrder.stochasticGradient (GradientMethod, Double, Gradients, Vector) -> + * Tuple. */ +HMATH_API hmath_status hmath_optimization_stochastic_gradient( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Optimization.FirstOrder.miniBatchGradient (Gradients) -> Function. */ +HMATH_API hmath_status hmath_optimization_mini_batch_gradient(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.FirstOrder.projectedGradient (Options, Objective, Gradient, Gradient, Vector) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_projected_gradient( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.FirstOrder.proximalGradient (Options, Objective, Gradient, Prox, Vector) -> + * Result. */ +HMATH_API hmath_status hmath_optimization_proximal_gradient( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.FirstOrder.fista (Options, Objective, Gradient, Prox, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_fista(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out); +/* HMath.Optimization.FirstOrder.coordinateDescent (Blocks, Options, Objective, Gradient, Vector) -> + * Result. */ +HMATH_API hmath_status hmath_optimization_coordinate_descent( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.Local.GoldenSection () -> ScalarMethod. */ +HMATH_API hmath_status hmath_optimization_golden_section_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Local.TernarySearch () -> ScalarMethod. */ +HMATH_API hmath_status hmath_optimization_ternary_search_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Local.BrentSearch () -> ScalarMethod. */ +HMATH_API hmath_status hmath_optimization_brent_search_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Local.minimizeScalar (ScalarMethod, Options, ScalarObjective, Double, Double) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_minimize_scalar( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.Local.BFGS () -> QuasiNewton. */ +HMATH_API hmath_status hmath_optimization_bfgs_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Local.DFP () -> QuasiNewton. */ +HMATH_API hmath_status hmath_optimization_dfp_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Local.SR1 () -> QuasiNewton. */ +HMATH_API hmath_status hmath_optimization_sr1_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Local.LBFGS (Int) -> QuasiNewton. */ +HMATH_API hmath_status hmath_optimization_lbfgs_create(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Local.minimizeQuasiNewton (QuasiNewton, Options, Objective, Gradient, Vector) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_minimize_quasi_newton( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.Local.Newton () -> NewtonMethod. */ +HMATH_API hmath_status hmath_optimization_newton_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Local.NewtonCG () -> NewtonMethod. */ +HMATH_API hmath_status hmath_optimization_newton_cg_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Local.TrustRegion (Double) -> NewtonMethod. */ +HMATH_API hmath_status hmath_optimization_trust_region_create(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Local.Dogleg (Double) -> NewtonMethod. */ +HMATH_API hmath_status hmath_optimization_dogleg_create(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Local.minimizeNewton (NewtonMethod, Options, Objective, Gradient, Hessian, + * Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_minimize_newton( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Local.nonlinearCG (Options, Objective, Gradient, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_nonlinear_cg(hmath_context *context, + const hmath_value *a0, const hmath_value *a1, + const hmath_value *a2, const hmath_value *a3, + hmath_value **out); +/* HMath.Optimization.Local.SquaredLoss () -> Loss. */ +HMATH_API hmath_status hmath_optimization_squared_loss_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Local.HuberLoss (Double) -> Loss. */ +HMATH_API hmath_status hmath_optimization_huber_loss_create(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Local.CauchyLoss (Double) -> Loss. */ +HMATH_API hmath_status hmath_optimization_cauchy_loss_create(hmath_context *context, + const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Local.SoftL1 (Double) -> Loss. */ +HMATH_API hmath_status hmath_optimization_soft_l1_create(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Local.leastSquares (Loss, Double, Options, Gradient, Hessian, Vector) -> + * Result. */ +HMATH_API hmath_status hmath_optimization_least_squares( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Local.nelderMead (Options, Objective, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_nelder_mead(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + hmath_value **out); +/* HMath.Optimization.Local.powell (Double, Options, Objective, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_powell(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Optimization.Constrained.Equality (Objective, Gradient) -> Constraint. */ +HMATH_API hmath_status hmath_optimization_equality_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Constrained.LessEqual (Objective, Gradient) -> Constraint. */ +HMATH_API hmath_status hmath_optimization_less_equal_create(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Optimization.Constrained.feasibility (Constraints, Vector) -> Double. */ +HMATH_API hmath_status hmath_optimization_feasibility(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, hmath_value **out); +/* HMath.Optimization.Constrained.QuadraticPenalty () -> PenaltyMethod. */ +HMATH_API hmath_status hmath_optimization_quadratic_penalty_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Constrained.LogBarrier () -> PenaltyMethod. */ +HMATH_API hmath_status hmath_optimization_log_barrier_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Constrained.InteriorPoint () -> PenaltyMethod. */ +HMATH_API hmath_status hmath_optimization_interior_point_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Constrained.AugmentedLagrangian () -> PenaltyMethod. */ +HMATH_API hmath_status hmath_optimization_augmented_lagrangian_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Constrained.constrainedMinimize (PenaltyMethod, Options, Objective, Gradient, + * Constraints, Vector) -> Result. */ +HMATH_API hmath_status hmath_optimization_constrained_minimize( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Constrained.LPResult (Vector, Double, Indices, Int) -> LPResult. */ +HMATH_API hmath_status hmath_optimization_lp_result_create( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, hmath_value **out); +/* HMath.Optimization.Constrained.linearProgramming (Int, Double, Vector, Matrix, Vector) -> + * LPResult. */ +HMATH_API hmath_status hmath_optimization_linear_programming( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Optimization.Constrained.revisedSimplex (Int, Double, Vector, Matrix, Vector, Indices) -> + * LPResult. */ +HMATH_API hmath_status hmath_optimization_revised_simplex( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Constrained.quadraticProgramming (Int, Double, Matrix, Vector, Matrix, Vector) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_quadratic_programming( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Constrained.slsqp (Options, Objective, Gradient, Hessian, Constraints, Vector) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_slsqp(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Constrained.cobyla (Double, Options, Objective, Objectives, Vector) -> Result. + */ +HMATH_API hmath_status hmath_optimization_cobyla(hmath_context *context, const hmath_value *a0, + const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, + hmath_value **out); +/* HMath.Optimization.Constrained.weightedObjective (Vector, Objectives) -> Function. */ +HMATH_API hmath_status hmath_optimization_weighted_objective(hmath_context *context, + const hmath_value *a0, + const hmath_value *a1, + hmath_value **out); +/* HMath.Optimization.Constrained.paretoFront (Matrix) -> Indices. */ +HMATH_API hmath_status hmath_optimization_pareto_front(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Constrained.lpPoint (LPResult) -> Value. */ +HMATH_API hmath_status hmath_optimization_lp_point(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Constrained.lpValue (LPResult) -> Value. */ +HMATH_API hmath_status hmath_optimization_lp_value(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Constrained.lpBasis (LPResult) -> Value. */ +HMATH_API hmath_status hmath_optimization_lp_basis(hmath_context *context, const hmath_value *a0, + hmath_value **out); +/* HMath.Optimization.Constrained.lpIterations (LPResult) -> Value. */ +HMATH_API hmath_status hmath_optimization_lp_iterations(hmath_context *context, + const hmath_value *a0, hmath_value **out); +/* HMath.Optimization.Global.SimulatedAnnealing () -> GlobalMethod. */ +HMATH_API hmath_status hmath_optimization_simulated_annealing_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Global.DifferentialEvolution () -> GlobalMethod. */ +HMATH_API hmath_status hmath_optimization_differential_evolution_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Global.GeneticAlgorithm () -> GlobalMethod. */ +HMATH_API hmath_status hmath_optimization_genetic_algorithm_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Global.ParticleSwarm () -> GlobalMethod. */ +HMATH_API hmath_status hmath_optimization_particle_swarm_create(hmath_context *context, + hmath_value **out); +/* HMath.Optimization.Global.CMAES () -> GlobalMethod. */ +HMATH_API hmath_status hmath_optimization_cmaes_create(hmath_context *context, hmath_value **out); +/* HMath.Optimization.Global.globalMinimize (GlobalMethod, Int, Word64, Options, Bounds, Objective) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_global_minimize( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, hmath_value **out); +/* HMath.Optimization.Global.basinHopping (Word64, Double, Int, Options, Bounds, Objective, Vector) + * -> Result. */ +HMATH_API hmath_status hmath_optimization_basin_hopping( + hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, + const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, const hmath_value *a6, + hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_polynomial.h b/include/hmath_polynomial.h new file mode 100644 index 0000000..e1a76ff --- /dev/null +++ b/include/hmath_polynomial.h @@ -0,0 +1,78 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_polynomial_bindings.py. */ +#ifndef HMATH_POLYNOMIAL_H +#define HMATH_POLYNOMIAL_H +#include "hmath_value.h" +#include "hmath_error.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Every successful output is an owned immutable hmath_value. Release it with + * hmath_value_release. Inputs are borrowed only for the call. Scalar and object + * coefficient types must match; no implicit numerical conversion occurs. + * prototype is a typed scalar selecting the coefficient type even for empty + * input. Lists and tuples use the common Value transport. MathError returns + * HMATH_MATH_ERROR with full hmath_last_math_error data. Failure leaves the + * output pointer untouched. Same source budgets/defaults/normalization apply. */ +HMATH_API hmath_status hmath_polynomial_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_coefficients(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_polynomial_degree(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_evaluate_polynomial(hmath_context *context, const hmath_value *polynomial, const hmath_value *x, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_add_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_subtract_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_scale_polynomial(hmath_context *context, const hmath_value *scalar, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_multiply_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_compose_polynomial(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_divide_polynomial(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_monic_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_gcd_polynomial(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_differentiate_polynomial(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_integrate_polynomial(hmath_context *context, const hmath_value *constant, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_square_free_factors(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_rational_roots(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_factor_rational_polynomial(hmath_context *context, const hmath_value *budget, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_sturm_sequence(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_count_real_roots(hmath_context *context, const hmath_value *polynomial, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_isolate_real_roots(hmath_context *context, const hmath_value *depth, const hmath_value *width, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_durand_kerner(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_aberth_ehrlich(hmath_context *context, const hmath_value *iterations, const hmath_value *tolerance, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_companion_matrix(hmath_context *context, const hmath_value *polynomial, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_lagrange_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_newton_interpolation(hmath_context *context, const hmath_value *prototype, const hmath_value *points, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_chebyshev_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_legendre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_hermite_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_laguerre_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_bernstein_polynomial(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *index, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_polynomial_regression(hmath_context *context, const hmath_value *prototype, const hmath_value *degree, const hmath_value *points, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_power_series(hmath_context *context, const hmath_value *prototype, const hmath_value *coefficients, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_series_coefficients(hmath_context *context, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_add_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_multiply_series(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_reciprocal_series(hmath_context *context, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_divide_series(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_compose_series(hmath_context *context, const hmath_value *outer, const hmath_value *inner, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_differentiate_series(hmath_context *context, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_integrate_series(hmath_context *context, const hmath_value *constant, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_exp_series(hmath_context *context, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_log_series(hmath_context *context, const hmath_value *series, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_rational_function(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_rational_numerator(hmath_context *context, const hmath_value *function, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_rational_denominator(hmath_context *context, const hmath_value *function, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_evaluate_rational_function(hmath_context *context, const hmath_value *function, const hmath_value *x, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_add_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_multiply_rational_function(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_partial_fractions(hmath_context *context, const hmath_value *budget, const hmath_value *function, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_polynomial_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_series_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_polynomial_rational_function_equal(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +/* Callback is synchronous, called exactly according to source sampling. Set + * out only on success. HMATH_MATH_ERROR reads the structured error wire; + * other failure codes abort with its length-delimited message. Userdata/error + * payload storage must remain live until this enclosing call returns. */ +typedef hmath_status (*hmath_polynomial_callback)(double input,double *out,void *userdata,hmath_math_error *error); +HMATH_API hmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context,ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_rotations.h b/include/hmath_rotations.h new file mode 100644 index 0000000..c9d8f95 --- /dev/null +++ b/include/hmath_rotations.h @@ -0,0 +1,75 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_rotation_bindings.py. */ +#ifndef HMATH_ROTATIONS_H +#define HMATH_ROTATIONS_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Actual HMath.Quaternion/HMath.Rotation objects, distinct from Numeric types. + * Owned immutable common Value handles use kinds72 Quaternion,73 SO3,74 SE3, + *75 Rotation.DualQuaternion. Inputs are borrowed for the call; outputs transfer + *one owned reference and remain untouched on failure. Release with + *hmath_value_release. Every live reference pins the runtime. Independent calls + *can share immutable values while retaining a reference per participating thread. + *All scalar/vector/matrix coefficients are original Double. Lists and tuples + *retain their source structure. Vectors are shared list handles; twists are + *tuples of two lists. Matrix conversions consume/return shared Dense handles. + *Original validation, NaN/Inf, normalization, sign, angle, error and interpolation + *policies apply unchanged. Source MathError uses status11 with full payload. + *Active right-handed column-vector rotations use radians. compose(a,b) applies + *b first; Euler angles are intrinsic ZYX, passed as roll,pitch,yaw. + */ +HMATH_API hmath_status hmath_quaternion_quaternion(hmath_context *context, const hmath_value *w, const hmath_value *x, const hmath_value *y, const hmath_value *z, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_components(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_norm(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_normalize(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_inverse(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_conjugate(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_multiply(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_add(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_scale(hmath_context *context, const hmath_value *factor, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_rotate_vector(hmath_context *context, const hmath_value *value, const hmath_value *vector, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_axis_angle(hmath_context *context, const hmath_value *axis, const hmath_value *angle, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_to_axis_angle(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_from_euler(hmath_context *context, const hmath_value *roll, const hmath_value *pitch, const hmath_value *yaw, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_to_euler(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_to_matrix(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_from_matrix(hmath_context *context, const hmath_value *matrix, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_nlerp(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_slerp(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_squad(hmath_context *context, const hmath_value *fraction, const hmath_value *q0, const hmath_value *q1, const hmath_value *q2, const hmath_value *q3, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_exponential(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_logarithm(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_quaternion_swing_twist(hmath_context *context, const hmath_value *axis, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_so3(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_rotation_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_identity_rotation(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_rotation_compose_rotation(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_rotation_inverse_rotation(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_rotate(hmath_context *context, const hmath_value *value, const hmath_value *vector, hmath_value **out); +HMATH_API hmath_status hmath_rotation_exp_so3(hmath_context *context, const hmath_value *omega, hmath_value **out); +HMATH_API hmath_status hmath_rotation_log_so3(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_se3(hmath_context *context, const hmath_value *rotation, const hmath_value *translation, hmath_value **out); +HMATH_API hmath_status hmath_rotation_rotation_part(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_translation_part(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_identity_transform(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_rotation_compose(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_rotation_inverse(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_transform_point(hmath_context *context, const hmath_value *value, const hmath_value *point, hmath_value **out); +HMATH_API hmath_status hmath_rotation_exp_se3(hmath_context *context, const hmath_value *twist, hmath_value **out); +HMATH_API hmath_status hmath_rotation_log_se3(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_to_homogeneous(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_from_homogeneous(hmath_context *context, const hmath_value *matrix, hmath_value **out); +HMATH_API hmath_status hmath_rotation_dual_quaternion(hmath_context *context, const hmath_value *real, const hmath_value *dual, hmath_value **out); +HMATH_API hmath_status hmath_rotation_dual_parts(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_to_dual_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_from_dual_quaternion(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_multiply_dual(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_rotation_inverse_dual(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_rotation_interpolate_dual(hmath_context *context, const hmath_value *fraction, const hmath_value *a, const hmath_value *b, hmath_value **out); +HMATH_API hmath_status hmath_rotations_equal(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_scalar_extras.h b/include/hmath_scalar_extras.h new file mode 100644 index 0000000..d96b95b --- /dev/null +++ b/include/hmath_scalar_extras.h @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_scalar_extras.py. */ +#ifndef HMATH_SCALAR_EXTRAS_H +#define HMATH_SCALAR_EXTRAS_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Borrowed immutable inputs; outputs transfer one Value owner on success and + * remain untouched on failure. Release with hmath_value_release. Selector + * objects use actual Elementary(kind352)/ComplexFunction(kind353) payloads. + * Complex arithmetic/FFT/matrices and SFResult use original Double precision; + * trigonometric complexFunction retains either actual Complex Float or Double + * input/output, without intermediate widening. Exact integer transport never + * uses floating point; nested tuple/list/Maybe results retain source shape. + * Source bounds, budgets, principal branches, flags and MathError/status11 are + * unchanged. Independent readers retain references per participating thread. */ +typedef hmath_value hmath_complex_elementary_object; +typedef hmath_value hmath_trigonometry_complex_function_object; +typedef hmath_value hmath_special_sf_result_value; /* tuple(Double,Double) */ +/* HMath.Complex.Exp :: Elementary */ +HMATH_API hmath_status hmath_complex_exp(hmath_context *context, hmath_value **out); +/* HMath.Complex.Log :: Elementary */ +HMATH_API hmath_status hmath_complex_log(hmath_context *context, hmath_value **out); +/* HMath.Complex.Sqrt :: Elementary */ +HMATH_API hmath_status hmath_complex_sqrt(hmath_context *context, hmath_value **out); +/* HMath.Complex.Sin :: Elementary */ +HMATH_API hmath_status hmath_complex_sin(hmath_context *context, hmath_value **out); +/* HMath.Complex.Cos :: Elementary */ +HMATH_API hmath_status hmath_complex_cos(hmath_context *context, hmath_value **out); +/* HMath.Complex.Tan :: Elementary */ +HMATH_API hmath_status hmath_complex_tan(hmath_context *context, hmath_value **out); +/* HMath.Complex.Sinh :: Elementary */ +HMATH_API hmath_status hmath_complex_sinh(hmath_context *context, hmath_value **out); +/* HMath.Complex.Cosh :: Elementary */ +HMATH_API hmath_status hmath_complex_cosh(hmath_context *context, hmath_value **out); +/* HMath.Complex.Tanh :: Elementary */ +HMATH_API hmath_status hmath_complex_tanh(hmath_context *context, hmath_value **out); +/* HMath.Complex.Asin :: Elementary */ +HMATH_API hmath_status hmath_complex_asin(hmath_context *context, hmath_value **out); +/* HMath.Complex.Acos :: Elementary */ +HMATH_API hmath_status hmath_complex_acos(hmath_context *context, hmath_value **out); +/* HMath.Complex.Atan :: Elementary */ +HMATH_API hmath_status hmath_complex_atan(hmath_context *context, hmath_value **out); +/* HMath.Complex.Asinh :: Elementary */ +HMATH_API hmath_status hmath_complex_asinh(hmath_context *context, hmath_value **out); +/* HMath.Complex.Acosh :: Elementary */ +HMATH_API hmath_status hmath_complex_acosh(hmath_context *context, hmath_value **out); +/* HMath.Complex.Atanh :: Elementary */ +HMATH_API hmath_status hmath_complex_atanh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CSin :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_sin(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCos :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_cos(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CTan :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_tan(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAsin :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_asin(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAcos :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_acos(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAtan :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_atan(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CSinh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_sinh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCosh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_cosh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CTanh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_tanh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAsinh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_asinh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAcosh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_acosh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CAtanh :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_atanh(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CSec :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_sec(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCsc :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_csc(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCot :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_cot(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CSech :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_sech(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCsch :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_csch(hmath_context *context, hmath_value **out); +/* HMath.Trigonometry.CCoth :: ComplexFunction */ +HMATH_API hmath_status hmath_trigonometry_c_coth(hmath_context *context, hmath_value **out); +/* HMath.Complex.elementary :: Elementary -> Complex Double -> Either MathError (Complex Double) */ +HMATH_API hmath_status hmath_complex_elementary(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out); +/* HMath.Complex.complexMatrix :: Int -> Int -> [Complex Double] -> Either MathError (Matrix (Complex Double)) */ +HMATH_API hmath_status hmath_complex_complex_matrix(hmath_context *context, const hmath_value *rows, const hmath_value *columns, const hmath_value *values, hmath_value **out); +/* HMath.Complex.multiplyMatrices :: Matrix (Complex Double) -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)) */ +HMATH_API hmath_status hmath_complex_multiply_matrices(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Complex.conjugateTranspose :: Matrix (Complex Double) -> Either MathError (Matrix (Complex Double)) */ +HMATH_API hmath_status hmath_complex_conjugate_transpose(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Complex.complexFFT :: [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_complex_complex_fft(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Complex.complexIFFT :: [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_complex_complex_ifft(hmath_context *context, const hmath_value *values, hmath_value **out); +/* HMath.Trigonometry.complexFunction :: RealFloat a => ComplexFunction -> Complex a -> Either MathError (Complex a) */ +HMATH_API hmath_status hmath_trigonometry_complex_function(hmath_context *context, const hmath_value *operation, const hmath_value *value, hmath_value **out); +/* HMath.NumberTheory.chineseRemainder :: [(Integer,Integer)] -> Either MathError (Integer,Integer) */ +HMATH_API hmath_status hmath_numbertheory_chinese_remainder(hmath_context *context, const hmath_value *congruences, hmath_value **out); +/* HMath.NumberTheory.linearDiophantine :: Integer -> Integer -> Integer -> Either MathError (Integer,Integer,Integer,Integer) */ +HMATH_API hmath_status hmath_numbertheory_linear_diophantine(hmath_context *context, const hmath_value *a, const hmath_value *b, const hmath_value *c, hmath_value **out); +/* HMath.NumberTheory.perfectPower :: Integer -> Maybe (Integer,Int) */ +HMATH_API hmath_status hmath_numbertheory_perfect_power(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.NumberTheory.primeFactorization :: Int -> Integer -> Either MathError [(Integer,Int)] */ +HMATH_API hmath_status hmath_numbertheory_prime_factorization(hmath_context *context, const hmath_value *budget, const hmath_value *value, hmath_value **out); +/* HMath.NumberTheory.partitions :: Int -> Either MathError [[Int]] */ +HMATH_API hmath_status hmath_numbertheory_partitions(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Special.SFResult :: Double -> Double -> SFResult */ +HMATH_API hmath_status hmath_special_sf_result(hmath_context *context, const hmath_value *value, const hmath_value *error, hmath_value **out); +/* HMath.Special.sfValue :: SFResult -> Double */ +HMATH_API hmath_status hmath_special_sf_value(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Special.sfError :: SFResult -> Double */ +HMATH_API hmath_status hmath_special_sf_error(hmath_context *context, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_scalar_selector_name(hmath_context *context,const hmath_value *value0,hmath_value **out); +HMATH_API hmath_status hmath_scalar_selector_equal(hmath_context *context,const hmath_value *value0,const hmath_value *value1,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_shape.h b/include/hmath_shape.h new file mode 100644 index 0000000..4399937 --- /dev/null +++ b/include/hmath_shape.h @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_SHAPE_H +#define HMATH_SHAPE_H +#include "hmath_foundation.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original runtime and nominal type-indexed shapes. Implicit Haskell Nat + * indices become explicit nonnegative Integer Values; KnownNat/KnownShape + * dictionaries are reified, never coerced. Source Int overflow and dimension + * checks remain. Shape patterns are read-only views. Matrix/Tensor results + * interoperate with their ordinary public APIs. Inputs borrow; outputs own a + * Value; failure leaves *out untouched. */ +/* HMath.API.Shape.shapeDimensions */ +HMATH_API hmath_status hmath_shape_shape_dimensions(hmath_context *context, + const hmath_value *shape, hmath_value **out); +/* HMath.API.Shape.shapeElements */ +HMATH_API hmath_status hmath_shape_shape_elements(hmath_context *context, const hmath_value *shape, + hmath_value **out); +/* HMath.API.Shape.makeShape */ +HMATH_API hmath_status hmath_shape_make_shape(hmath_context *context, const hmath_value *dimensions, + hmath_value **out); +/* HMath.API.Shape.ScalarShape */ +HMATH_API hmath_status hmath_shape_scalar_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out); +/* HMath.API.Shape.VectorShape */ +HMATH_API hmath_status hmath_shape_vector_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out); +/* HMath.API.Shape.MatrixShape */ +HMATH_API hmath_status hmath_shape_matrix_shape(hmath_context *context, const hmath_value *shape, + hmath_value **out); +/* HMath.API.Shape.staticMatrix */ +HMATH_API hmath_status hmath_shape_static_matrix(hmath_context *context, const hmath_value *rows, + const hmath_value *columns, + const hmath_value *matrix, hmath_value **out); +/* HMath.API.Shape.dynamicMatrix */ +HMATH_API hmath_status hmath_shape_dynamic_matrix(hmath_context *context, const hmath_value *matrix, + hmath_value **out); +/* HMath.API.Shape.staticMultiply */ +HMATH_API hmath_status hmath_shape_static_multiply(hmath_context *context, const hmath_value *left, + const hmath_value *right, hmath_value **out); +/* HMath.API.Shape.staticTranspose */ +HMATH_API hmath_status hmath_shape_static_transpose(hmath_context *context, + const hmath_value *matrix, hmath_value **out); +/* HMath.API.Shape.reflectedShape */ +HMATH_API hmath_status hmath_shape_reflected_shape(hmath_context *context, + const hmath_value *dimensions, + hmath_value **out); +/* HMath.API.Shape.staticTensor */ +HMATH_API hmath_status hmath_shape_static_tensor(hmath_context *context, + const hmath_value *dimensions, + const hmath_value *tensor, hmath_value **out); +/* HMath.API.Shape.dynamicTensor */ +HMATH_API hmath_status hmath_shape_dynamic_tensor(hmath_context *context, const hmath_value *tensor, + hmath_value **out); +/* HMath.API.Shape.coordinates */ +HMATH_API hmath_status hmath_shape_coordinates(hmath_context *context, const hmath_value *prototype, + const hmath_value *count, const hmath_value *values, + hmath_value **out); +/* HMath.API.Shape.coordinateValues */ +HMATH_API hmath_status hmath_shape_coordinate_values(hmath_context *context, + const hmath_value *coordinates, + hmath_value **out); +/* HMath.API.Shape.coordinatesToVector */ +HMATH_API hmath_status hmath_shape_coordinates_to_vector(hmath_context *context, + const hmath_value *coordinates, + hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_spectral.h b/include/hmath_spectral.h new file mode 100644 index 0000000..a4b9a63 --- /dev/null +++ b/include/hmath_spectral.h @@ -0,0 +1,358 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_spectral_bindings.py. */ +#ifndef HMATH_SPECTRAL_H +#define HMATH_SPECTRAL_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original checked numerical solvers and diagnostics. All arguments are + * borrowed Value handles; success transfers one output reference. Outputs + * remain untouched on failure. Function arguments use kind101 callbacks from + * hmath_linear_callback, with a tuple of positional arguments. Keep callback + * function/userdata valid while any object retaining it remains alive. + * Source formulas, defaults, finite checks, limits and error variants are + * preserved. Source Left MathError returns status11. Inputs/outputs may share + * immutable handles; output addresses must be distinct from input storage. + * Independent readers keep references alive, contexts remain per-call. */ +typedef hmath_value hmath_signal_value_filter_object; /* kind360 */ +typedef hmath_value hmath_signal_value_filter_family_object; /* kind361 */ +typedef hmath_value hmath_signal_value_filter_band_object; /* kind362 */ +typedef hmath_value hmath_signal_value_window_object; /* kind363 */ +typedef hmath_value hmath_signal_value_peak_object; /* kind364 */ +typedef hmath_value hmath_signal_value_wavelet_object; /* kind365 */ +typedef hmath_value hmath_signal_value_wavelet_tree_object; /* kind366 */ +typedef hmath_value hmath_signal_value_mother_wavelet_object; /* kind367 */ +typedef hmath_value hmath_signal_value_wavelet_packet_object; /* kind368 */ +typedef hmath_value hmath_interpolation_value_extrapolation_object; /* kind369 */ +typedef hmath_value hmath_interpolation_value_interpolation_method_object; /* kind370 */ +typedef hmath_value hmath_interpolation_value_spline_boundary_object; /* kind371 */ +typedef hmath_value hmath_interpolation_value_piecewise_polynomial_object; /* kind372 */ +typedef hmath_value hmath_interpolation_value_b_spline_object; /* kind373 */ +typedef hmath_value hmath_interpolation_value_radial_kernel_object; /* kind374 */ +typedef hmath_value hmath_interpolation_value_rbf_object; /* kind375 */ +typedef hmath_value hmath_interpolation_value_approximation_object; /* kind376 */ +typedef hmath_value hmath_fourier_value_direction_object; /* kind377 */ +typedef hmath_value hmath_fourier_value_fft_algorithm_object; /* kind378 */ +typedef hmath_value hmath_fourier_value_fft_plan_object; /* kind379 */ +typedef hmath_value hmath_fourier_value_transform_type_object; /* kind380 */ +typedef hmath_value hmath_fourier_value_stft_object; /* kind381 */ +/* HMath.Signal.iir :: [Double] -> [Double] -> Either MathError Filter */ +HMATH_API hmath_status hmath_signal_value_iir(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +/* HMath.Signal.fir :: [Double] -> Either MathError Filter */ +HMATH_API hmath_status hmath_signal_value_fir(hmath_context *context, const hmath_value *b, hmath_value **out); +/* HMath.Signal.filterCoefficients :: Filter -> ([Double], [Double]) */ +HMATH_API hmath_status hmath_signal_value_filter_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.filterState :: Filter -> [Double] */ +HMATH_API hmath_status hmath_signal_value_filter_state(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.resetFilter :: Filter -> Filter */ +HMATH_API hmath_status hmath_signal_value_reset_filter(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.filterSignal :: Filter -> [Double] -> Either MathError ([Double], Filter) */ +HMATH_API hmath_status hmath_signal_value_filter_signal(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Signal.frequencyResponse :: Filter -> Double -> Either MathError (Complex Double) */ +HMATH_API hmath_status hmath_signal_value_frequency_response(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Signal.Butterworth :: FilterFamily */ +HMATH_API hmath_status hmath_signal_value_butterworth(hmath_context *context, hmath_value **out); +/* HMath.Signal.ChebyshevI :: Double -> FilterFamily */ +HMATH_API hmath_status hmath_signal_value_chebyshev_i(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.ChebyshevII :: Double -> FilterFamily */ +HMATH_API hmath_status hmath_signal_value_chebyshev_ii(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Elliptic :: Double -> Double -> FilterFamily */ +HMATH_API hmath_status hmath_signal_value_elliptic(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Signal.Bessel :: FilterFamily */ +HMATH_API hmath_status hmath_signal_value_bessel(hmath_context *context, hmath_value **out); +/* HMath.Signal.Lowpass :: Double -> FilterBand */ +HMATH_API hmath_status hmath_signal_value_lowpass(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Highpass :: Double -> FilterBand */ +HMATH_API hmath_status hmath_signal_value_highpass(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Bandpass :: Double -> Double -> FilterBand */ +HMATH_API hmath_status hmath_signal_value_bandpass(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Signal.Bandstop :: Double -> Double -> FilterBand */ +HMATH_API hmath_status hmath_signal_value_bandstop(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Signal.designIIR :: FilterFamily -> FilterBand -> Int -> Double -> Either MathError Filter */ +HMATH_API hmath_status hmath_signal_value_design_iir(hmath_context *context, const hmath_value *family, const hmath_value *band, const hmath_value *order, const hmath_value *rate, hmath_value **out); +/* HMath.Signal.notch :: Double -> Double -> Either MathError Filter */ +HMATH_API hmath_status hmath_signal_value_notch(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out); +/* HMath.Signal.allPass :: Double -> Double -> Either MathError Filter */ +HMATH_API hmath_status hmath_signal_value_all_pass(hmath_context *context, const hmath_value *omega, const hmath_value *quality, hmath_value **out); +/* HMath.Signal.wiener :: Int -> Maybe Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_wiener(hmath_context *context, const hmath_value *width, const hmath_value *noise, const hmath_value *xs, hmath_value **out); +/* HMath.Signal.Hann :: Window */ +HMATH_API hmath_status hmath_signal_value_hann(hmath_context *context, hmath_value **out); +/* HMath.Signal.Hamming :: Window */ +HMATH_API hmath_status hmath_signal_value_hamming(hmath_context *context, hmath_value **out); +/* HMath.Signal.Blackman :: Window */ +HMATH_API hmath_status hmath_signal_value_blackman(hmath_context *context, hmath_value **out); +/* HMath.Signal.Bartlett :: Window */ +HMATH_API hmath_status hmath_signal_value_bartlett(hmath_context *context, hmath_value **out); +/* HMath.Signal.Kaiser :: Double -> Window */ +HMATH_API hmath_status hmath_signal_value_kaiser(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Gaussian :: Double -> Window */ +HMATH_API hmath_status hmath_signal_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Tukey :: Double -> Window */ +HMATH_API hmath_status hmath_signal_value_tukey(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.FlatTop :: Window */ +HMATH_API hmath_status hmath_signal_value_flat_top(hmath_context *context, hmath_value **out); +/* HMath.Signal.DolphChebyshev :: Double -> Window */ +HMATH_API hmath_status hmath_signal_value_dolph_chebyshev(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.window :: Window -> Int -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_window(hmath_context *context, const hmath_value *kind, const hmath_value *n, hmath_value **out); +/* HMath.Signal.windowedSinc :: Window -> Int -> Double -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_windowed_sinc(hmath_context *context, const hmath_value *kind, const hmath_value *taps, const hmath_value *cutoff, const hmath_value *rate, hmath_value **out); +/* HMath.Signal.Peak :: Int -> Double -> Double -> Double -> Peak */ +HMATH_API hmath_status hmath_signal_value_peak(hmath_context *context, const hmath_value *peak_index, const hmath_value *peak_height, const hmath_value *peak_prominence, const hmath_value *peak_width, hmath_value **out); +/* HMath.Signal.peakIndex :: Peak -> Int */ +HMATH_API hmath_status hmath_signal_value_peak_index(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.peakHeight :: Peak -> Double */ +HMATH_API hmath_status hmath_signal_value_peak_height(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.peakProminence :: Peak -> Double */ +HMATH_API hmath_status hmath_signal_value_peak_prominence(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.peakWidth :: Peak -> Double */ +HMATH_API hmath_status hmath_signal_value_peak_width(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.peaks :: Double -> Int -> [Double] -> Either MathError [Peak] */ +HMATH_API hmath_status hmath_signal_value_peaks(hmath_context *context, const hmath_value *minimum_prominence, const hmath_value *minimum_distance, const hmath_value *xs, hmath_value **out); +/* HMath.Signal.kalman :: [[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState */ +HMATH_API hmath_status hmath_signal_value_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +/* HMath.Signal.extendedKalman :: ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState */ +HMATH_API hmath_status hmath_signal_value_extended_kalman(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, const hmath_value *value6, hmath_value **out); +/* HMath.Signal.unscentedKalman :: Double -> Double -> Double -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState */ +HMATH_API hmath_status hmath_signal_value_unscented_kalman(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, const hmath_value *kappa, const hmath_value *transition, const hmath_value *measurement, const hmath_value *q, const hmath_value *r, const hmath_value *measured, const hmath_value *state, hmath_value **out); +/* HMath.Signal.Haar :: Wavelet */ +HMATH_API hmath_status hmath_signal_value_haar(hmath_context *context, hmath_value **out); +/* HMath.Signal.Daubechies2 :: Wavelet */ +HMATH_API hmath_status hmath_signal_value_daubechies2(hmath_context *context, hmath_value **out); +/* HMath.Signal.Daubechies4 :: Wavelet */ +HMATH_API hmath_status hmath_signal_value_daubechies4(hmath_context *context, hmath_value **out); +/* HMath.Signal.Biorthogonal53 :: Wavelet */ +HMATH_API hmath_status hmath_signal_value_biorthogonal53(hmath_context *context, hmath_value **out); +/* HMath.Signal.waveletApproximation :: WaveletTree -> [Double] */ +HMATH_API hmath_status hmath_signal_value_wavelet_approximation(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.waveletDetails :: WaveletTree -> [[Double]] */ +HMATH_API hmath_status hmath_signal_value_wavelet_details(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.dwt :: Wavelet -> Int -> [Double] -> Either MathError WaveletTree */ +HMATH_API hmath_status hmath_signal_value_dwt(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out); +/* HMath.Signal.idwt :: WaveletTree -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_idwt(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.Morlet :: Double -> MotherWavelet */ +HMATH_API hmath_status hmath_signal_value_morlet(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.MexicanHat :: MotherWavelet */ +HMATH_API hmath_status hmath_signal_value_mexican_hat(hmath_context *context, hmath_value **out); +/* HMath.Signal.GaussianDerivative :: MotherWavelet */ +HMATH_API hmath_status hmath_signal_value_gaussian_derivative(hmath_context *context, hmath_value **out); +/* HMath.Signal.cwt :: MotherWavelet -> Double -> [Double] -> [Double] -> Either MathError [[Complex Double]] */ +HMATH_API hmath_status hmath_signal_value_cwt(hmath_context *context, const hmath_value *mother, const hmath_value *spacing, const hmath_value *scales, const hmath_value *xs, hmath_value **out); +/* HMath.Signal.waveletPackets :: Wavelet -> Int -> [Double] -> Either MathError WaveletPacket */ +HMATH_API hmath_status hmath_signal_value_wavelet_packets(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *xs, hmath_value **out); +/* HMath.Signal.inverseWaveletPackets :: WaveletPacket -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_inverse_wavelet_packets(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.packetBands :: WaveletPacket -> [[Double]] */ +HMATH_API hmath_status hmath_signal_value_packet_bands(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.waveletDenoise :: Wavelet -> Int -> Maybe Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_signal_value_wavelet_denoise(hmath_context *context, const hmath_value *family, const hmath_value *levels, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +/* HMath.Interpolation.Reject :: Extrapolation */ +HMATH_API hmath_status hmath_interpolation_value_reject(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Clamp :: Extrapolation */ +HMATH_API hmath_status hmath_interpolation_value_clamp(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Extrapolate :: Extrapolation */ +HMATH_API hmath_status hmath_interpolation_value_extrapolate(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Nearest :: InterpolationMethod */ +HMATH_API hmath_status hmath_interpolation_value_nearest(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Linear :: InterpolationMethod */ +HMATH_API hmath_status hmath_interpolation_value_linear(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Lagrange :: InterpolationMethod */ +HMATH_API hmath_status hmath_interpolation_value_lagrange(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Newton :: InterpolationMethod */ +HMATH_API hmath_status hmath_interpolation_value_newton(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Barycentric :: InterpolationMethod */ +HMATH_API hmath_status hmath_interpolation_value_barycentric(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Natural :: SplineBoundary */ +HMATH_API hmath_status hmath_interpolation_value_natural(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Clamped :: Double -> Double -> SplineBoundary */ +HMATH_API hmath_status hmath_interpolation_value_clamped(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Interpolation.Periodic :: SplineBoundary */ +HMATH_API hmath_status hmath_interpolation_value_periodic(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Gaussian :: Double -> RadialKernel */ +HMATH_API hmath_status hmath_interpolation_value_gaussian(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.Multiquadric :: Double -> RadialKernel */ +HMATH_API hmath_status hmath_interpolation_value_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.InverseMultiquadric :: Double -> RadialKernel */ +HMATH_API hmath_status hmath_interpolation_value_inverse_multiquadric(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.ThinPlate :: RadialKernel */ +HMATH_API hmath_status hmath_interpolation_value_thin_plate(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Cubic :: RadialKernel */ +HMATH_API hmath_status hmath_interpolation_value_cubic(hmath_context *context, hmath_value **out); +/* HMath.Interpolation.Approximation :: [Double] -> Double -> Int -> Approximation */ +HMATH_API hmath_status hmath_interpolation_value_approximation(hmath_context *context, const hmath_value *approximation_coefficients, const hmath_value *approximation_error, const hmath_value *approximation_iterations, hmath_value **out); +/* HMath.Interpolation.approximationCoefficients :: Approximation -> [Double] */ +HMATH_API hmath_status hmath_interpolation_value_approximation_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.approximationError :: Approximation -> Double */ +HMATH_API hmath_status hmath_interpolation_value_approximation_error(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.approximationIterations :: Approximation -> Int */ +HMATH_API hmath_status hmath_interpolation_value_approximation_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.interpolate :: InterpolationMethod -> Extrapolation -> [(Double, Double)] -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *points, const hmath_value *x0, hmath_value **out); +/* HMath.Interpolation.hermite :: [(Double, Double, Double)] -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_hermite(hmath_context *context, const hmath_value *triples, const hmath_value *x, hmath_value **out); +/* HMath.Interpolation.piecewisePolynomial :: [Double] -> [[Double]] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_piecewise_polynomial(hmath_context *context, const hmath_value *knots, const hmath_value *coefficients, hmath_value **out); +/* HMath.Interpolation.piecewiseKnots :: PiecewisePolynomial -> [Double] */ +HMATH_API hmath_status hmath_interpolation_value_piecewise_knots(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.evaluatePiecewise :: Extrapolation -> PiecewisePolynomial -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_evaluate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interpolation.differentiatePiecewise :: PiecewisePolynomial -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_differentiate_piecewise(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.integratePiecewise :: PiecewisePolynomial -> Double -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_integrate_piecewise(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interpolation.cubicHermite :: [(Double, Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_cubic_hermite(hmath_context *context, const hmath_value *triples, hmath_value **out); +/* HMath.Interpolation.cubicSpline :: SplineBoundary -> [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_cubic_spline(hmath_context *context, const hmath_value *boundary, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.pchip :: [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_pchip(hmath_context *context, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.akima :: [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_akima(hmath_context *context, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.smoothingSpline :: Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_smoothing_spline(hmath_context *context, const hmath_value *lambda_, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.bSpline :: Int -> [Double] -> [[Double]] -> [Double] -> Either MathError BSpline */ +HMATH_API hmath_status hmath_interpolation_value_b_spline(hmath_context *context, const hmath_value *degree, const hmath_value *knots, const hmath_value *controls, const hmath_value *weights, hmath_value **out); +/* HMath.Interpolation.evaluateBSpline :: BSpline -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_interpolation_value_evaluate_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out); +/* HMath.Interpolation.derivativeBSpline :: BSpline -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_interpolation_value_derivative_b_spline(hmath_context *context, const hmath_value *s, const hmath_value *x, hmath_value **out); +/* HMath.Interpolation.insertKnot :: BSpline -> Double -> Either MathError BSpline */ +HMATH_API hmath_status hmath_interpolation_value_insert_knot(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Interpolation.rationalBezier :: [[Double]] -> [Double] -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_interpolation_value_rational_bezier(hmath_context *context, const hmath_value *controls, const hmath_value *ws, const hmath_value *t, hmath_value **out); +/* HMath.Interpolation.bezier :: [[Double]] -> Double -> Either MathError [Double] */ +HMATH_API hmath_status hmath_interpolation_value_bezier(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Interpolation.kochanekBartels :: Double -> Double -> Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_kochanek_bartels(hmath_context *context, const hmath_value *tension, const hmath_value *continuity, const hmath_value *bias, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.cardinalSpline :: Double -> [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_cardinal_spline(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Interpolation.catmullRom :: [(Double, Double)] -> Either MathError PiecewisePolynomial */ +HMATH_API hmath_status hmath_interpolation_value_catmull_rom(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Interpolation.curveIntegral :: C.Tolerance -> BSpline -> Double -> Double -> Either MathError [C.Estimate Double] */ +HMATH_API hmath_status hmath_interpolation_value_curve_integral(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.Interpolation.arcLength :: C.Tolerance -> BSpline -> Double -> Double -> Either MathError (C.Estimate Double) */ +HMATH_API hmath_status hmath_interpolation_value_arc_length(hmath_context *context, const hmath_value *tolerance, const hmath_value *spline, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Interpolation.gridInterpolate :: InterpolationMethod -> Extrapolation -> [[Double]] -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_grid_interpolate(hmath_context *context, const hmath_value *method, const hmath_value *policy, const hmath_value *axes, const hmath_value *values, const hmath_value *point, hmath_value **out); +/* HMath.Interpolation.fitRBF :: RadialKernel -> Double -> [[Double]] -> [Double] -> Either MathError RBF */ +HMATH_API hmath_status hmath_interpolation_value_fit_rbf(hmath_context *context, const hmath_value *method, const hmath_value *smoothing, const hmath_value *nodes, const hmath_value *ys, hmath_value **out); +/* HMath.Interpolation.evaluateRBF :: RBF -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_evaluate_rbf(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Interpolation.inverseDistance :: Double -> [[Double]] -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_inverse_distance(hmath_context *context, const hmath_value *power, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out); +/* HMath.Interpolation.shepard :: [[Double]] -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_shepard(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.Interpolation.kriging :: Double -> Double -> [[Double]] -> [Double] -> [Double] -> Either MathError (Double, Double) */ +HMATH_API hmath_status hmath_interpolation_value_kriging(hmath_context *context, const hmath_value *range, const hmath_value *nugget, const hmath_value *nodes, const hmath_value *ys, const hmath_value *point, hmath_value **out); +/* HMath.Interpolation.polynomialFit :: Int -> [(Double, Double)] -> Either MathError Approximation */ +HMATH_API hmath_status hmath_interpolation_value_polynomial_fit(hmath_context *context, const hmath_value *degree, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.chebyshevApproximate :: Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation */ +HMATH_API hmath_status hmath_interpolation_value_chebyshev_approximate(hmath_context *context, const hmath_value *degree, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Interpolation.pade :: Int -> Int -> [Double] -> Either MathError ([Double], [Double]) */ +HMATH_API hmath_status hmath_interpolation_value_pade(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *series, hmath_value **out); +/* HMath.Interpolation.rationalFit :: Int -> Int -> [(Double, Double)] -> Either MathError ([Double], [Double], Double) */ +HMATH_API hmath_status hmath_interpolation_value_rational_fit(hmath_context *context, const hmath_value *m, const hmath_value *n, const hmath_value *points, hmath_value **out); +/* HMath.Interpolation.remez :: Int -> Int -> Double -> Int -> (Double -> Double) -> Double -> Double -> Either MathError Approximation */ +HMATH_API hmath_status hmath_interpolation_value_remez(hmath_context *context, const hmath_value *degree, const hmath_value *grid_count, const hmath_value *tolerance, const hmath_value *budget, const hmath_value *f, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Interpolation.nonlinearFit :: Int -> Double -> (Double -> [Double] -> Double) -> [(Double, Double)] -> [Double] -> Either MathError Approximation */ +HMATH_API hmath_status hmath_interpolation_value_nonlinear_fit(hmath_context *context, const hmath_value *budget, const hmath_value *tolerance, const hmath_value *model, const hmath_value *points, const hmath_value *initial, hmath_value **out); +/* HMath.Interpolation.interpolationError :: (Double -> Double) -> [(Double, Double)] -> Either MathError Double */ +HMATH_API hmath_status hmath_interpolation_value_interpolation_error(hmath_context *context, const hmath_value *f, const hmath_value *points, hmath_value **out); +/* HMath.Fourier.Forward :: Direction */ +HMATH_API hmath_status hmath_fourier_value_forward(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Inverse :: Direction */ +HMATH_API hmath_status hmath_fourier_value_inverse(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Automatic :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_automatic(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Direct :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_direct(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Radix2 :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_radix2(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Radix4 :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_radix4(hmath_context *context, hmath_value **out); +/* HMath.Fourier.MixedRadix :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_mixed_radix(hmath_context *context, hmath_value **out); +/* HMath.Fourier.SplitRadix :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_split_radix(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Bluestein :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_bluestein(hmath_context *context, hmath_value **out); +/* HMath.Fourier.Rader :: FFTAlgorithm */ +HMATH_API hmath_status hmath_fourier_value_rader(hmath_context *context, hmath_value **out); +/* HMath.Fourier.TypeI :: TransformType */ +HMATH_API hmath_status hmath_fourier_value_type_i(hmath_context *context, hmath_value **out); +/* HMath.Fourier.TypeII :: TransformType */ +HMATH_API hmath_status hmath_fourier_value_type_ii(hmath_context *context, hmath_value **out); +/* HMath.Fourier.TypeIII :: TransformType */ +HMATH_API hmath_status hmath_fourier_value_type_iii(hmath_context *context, hmath_value **out); +/* HMath.Fourier.TypeIV :: TransformType */ +HMATH_API hmath_status hmath_fourier_value_type_iv(hmath_context *context, hmath_value **out); +/* HMath.Fourier.planFFT :: Direction -> FFTAlgorithm -> Int -> Either MathError FFTPlan */ +HMATH_API hmath_status hmath_fourier_value_plan_fft(hmath_context *context, const hmath_value *direction, const hmath_value *method, const hmath_value *n, hmath_value **out); +/* HMath.Fourier.executeFFT :: FFTPlan -> [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_execute_fft(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.fft :: [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_fft(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.ifft :: [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_ifft(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.dft :: [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_dft(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.realFFT :: [Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_real_fft(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.inverseRealFFT :: Double -> [Complex Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_inverse_real_fft(hmath_context *context, const hmath_value *tolerance, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.fftBatch :: FFTPlan -> [[Complex Double]] -> Either MathError [[Complex Double]] */ +HMATH_API hmath_status hmath_fourier_value_fft_batch(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.fftND :: Direction -> [Int] -> [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_fft_nd(hmath_context *context, const hmath_value *direction, const hmath_value *dims, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.dct :: TransformType -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_dct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.idct :: TransformType -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_idct(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.dst :: TransformType -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_dst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.idst :: TransformType -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_idst(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.Fourier.stftFrames :: STFT -> [[Complex Double]] */ +HMATH_API hmath_status hmath_fourier_value_stft_frames(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.stft :: [Double] -> Int -> [Double] -> Either MathError STFT */ +HMATH_API hmath_status hmath_fourier_value_stft(hmath_context *context, const hmath_value *window, const hmath_value *hop, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.istft :: STFT -> Either MathError [Double] */ +HMATH_API hmath_status hmath_fourier_value_istft(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.magnitudeSpectrum :: [Complex Double] -> [Double] */ +HMATH_API hmath_status hmath_fourier_value_magnitude_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.phaseSpectrum :: [Complex Double] -> [Double] */ +HMATH_API hmath_status hmath_fourier_value_phase_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.powerSpectrum :: [Complex Double] -> [Double] */ +HMATH_API hmath_status hmath_fourier_value_power_spectrum(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Fourier.crossSpectrum :: Double -> [Double] -> [Double] -> [Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_cross_spectrum(hmath_context *context, const hmath_value *rate, const hmath_value *window, const hmath_value *x, const hmath_value *y, hmath_value **out); +/* HMath.Fourier.spectrogram :: [Double] -> Int -> [Double] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_fourier_value_spectrogram(hmath_context *context, const hmath_value *w, const hmath_value *h, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.analyticSignal :: [Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_analytic_signal(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.chirpZ :: Int -> Complex Double -> Complex Double -> [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_chirp_z(hmath_context *context, const hmath_value *count, const hmath_value *a, const hmath_value *w, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.goertzel :: Double -> [Double] -> Either MathError (Complex Double) */ +HMATH_API hmath_status hmath_fourier_value_goertzel(hmath_context *context, const hmath_value *omega, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.fftConvolve :: [Complex Double] -> [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_fft_convolve(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Fourier.fftCorrelate :: [Complex Double] -> [Complex Double] -> Either MathError [Complex Double] */ +HMATH_API hmath_status hmath_fourier_value_fft_correlate(hmath_context *context, const hmath_value *a, const hmath_value *b, hmath_value **out); +/* HMath.Fourier.fftShift :: [a] -> [a] */ +HMATH_API hmath_status hmath_fourier_value_fft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.Fourier.ifftShift :: [a] -> [a] */ +HMATH_API hmath_status hmath_fourier_value_ifft_shift(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* Original fftInPlace: borrowed writable interleaved real/imaginary Double + * storage for count complex values, aligned for Double. The original checks + * NULL/count/finite values and changes storage only after successful execution. + * No wrapper copy; caller keeps storage alive and excludes concurrent writers. */ +HMATH_API hmath_status hmath_fourier_value_fft_in_place(hmath_context *context,const hmath_value *plan,double *interleaved,ptrdiff_t count); +/* Original Show representation as an owned codepoint String value. */ +HMATH_API hmath_status hmath_spectral_describe(hmath_context *context,const hmath_value *value,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_stochastic.h b/include/hmath_stochastic.h new file mode 100644 index 0000000..28e1b48 --- /dev/null +++ b/include/hmath_stochastic.h @@ -0,0 +1,312 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_stochastic_bindings.py. */ +#ifndef HMATH_STOCHASTIC_H +#define HMATH_STOCHASTIC_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original immutable RNG240,Generator241,AliasTable242,Distribution243, + * Markov244,HMM245,Streaming246,TestResult247. Every output owns one Value; + * retain inputs during the call and release each output. Errors leave out + * untouched and preserve MathError. Seeds/words are exact Word64 scalars. + * Polymorphic sample elements transport arbitrary Values without coercion. + * Callbacks use hmath_linear_callback(kind101). Checked callbacks return true + * source Left on status11; pure callbacks abort. No generator, distribution, + * algorithm, default, proposal/evaluation budget or buffered state is replaced. */ +HMATH_API hmath_status hmath_stochastic_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_stochastic_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out); +/* HMath.Random.cloneRNG :: RNG -> RNG */ +HMATH_API hmath_status hmath_stochastic_random_clone_rng(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.seedRNG :: Generator -> Word64 -> RNG */ +HMATH_API hmath_status hmath_stochastic_random_seed_rng(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.nextWord64 :: RNG -> (Word64, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_next_word64(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.splitRNG :: RNG -> (RNG, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_split_rng(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.serializeRNG :: RNG -> String */ +HMATH_API hmath_status hmath_stochastic_random_serialize_rng(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.restoreRNG :: String -> Either MathError RNG */ +HMATH_API hmath_status hmath_stochastic_random_restore_rng(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.uniform :: RNG -> (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_uniform(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.uniformOpen :: RNG -> (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_uniform_open(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.uniformInt :: Int -> Int -> RNG -> Either MathError (Int, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_uniform_int(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.sampleN :: Int -> (RNG -> Either MathError (a, RNG)) -> RNG -> Either MathError ([a], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_sample_n(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.boxMuller :: RNG -> (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_box_muller(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.marsagliaNormal :: RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_marsaglia_normal(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.zigguratNormal :: RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_ziggurat_normal(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.normal :: Double -> Double -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.exponential :: Double -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_exponential(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.gamma :: Double -> Double -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_gamma(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.beta :: Double -> Double -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_beta(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.poisson :: Double -> RNG -> Either MathError (Int, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_poisson(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.binomial :: Int -> Double -> RNG -> Either MathError (Int, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.weighted :: [Double] -> RNG -> Either MathError (Int, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_weighted(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.aliasTable :: [Double] -> Either MathError AliasTable */ +HMATH_API hmath_status hmath_stochastic_random_alias_table(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Random.aliasSample :: AliasTable -> RNG -> Either MathError (Int, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_alias_sample(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.shuffle :: [a] -> RNG -> Either MathError ([a], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_shuffle(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.withReplacement :: Int -> [a] -> RNG -> Either MathError ([a], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_with_replacement(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.withoutReplacement :: Int -> [a] -> RNG -> Either MathError ([a], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_without_replacement(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.reservoir :: Int -> [a] -> RNG -> Either MathError ([a], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_reservoir(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.stratified :: Int -> RNG -> Either MathError ([Double], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_stratified(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.rejection :: Int -> (Double -> Double) -> (RNG -> Either MathError (Double, RNG)) -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_rejection(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Random.inverseTransform :: (Double -> Either MathError Double) -> RNG -> Either MathError (Double, RNG) */ +HMATH_API hmath_status hmath_stochastic_random_inverse_transform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.metropolisHastings :: Int -> Double -> (Double -> Double) -> Double -> RNG -> Either MathError ([Double], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_metropolis_hastings(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Random.gibbs :: Int -> [([Double] -> RNG -> Either MathError (Double, RNG))] -> [Double] -> RNG -> Either MathError ([[Double]], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_gibbs(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Random.hamiltonianMonteCarlo :: Int -> Int -> Double -> ([Double] -> Double) -> ([Double] -> [Double]) -> [Double] -> RNG -> Either MathError ([[Double]], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_hamiltonian_monte_carlo(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, const hmath_value *a5, const hmath_value *a6, hmath_value **out); +/* HMath.Random.monteCarlo :: (Double -> Double) -> Int -> RNG -> Either MathError ((Double, Double), RNG) */ +HMATH_API hmath_status hmath_stochastic_random_monte_carlo(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.latinHypercube :: Int -> Int -> RNG -> Either MathError ([[Double]], RNG) */ +HMATH_API hmath_status hmath_stochastic_random_latin_hypercube(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Random.randomQuality :: Int -> RNG -> Either MathError ((Double, Double, Double), RNG) */ +HMATH_API hmath_status hmath_stochastic_random_random_quality(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Random.entropySeed :: IO Word64 */ +HMATH_API hmath_status hmath_stochastic_random_entropy_seed(hmath_context *context, hmath_value **out); +/* HMath.Random.PCG32 :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_pcg32(hmath_context *context, hmath_value **out); +/* HMath.Random.Xoshiro256StarStar :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_xoshiro256_star_star(hmath_context *context, hmath_value **out); +/* HMath.Random.Xoroshiro128Plus :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_xoroshiro128_plus(hmath_context *context, hmath_value **out); +/* HMath.Random.MT19937 :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_mt19937(hmath_context *context, hmath_value **out); +/* HMath.Random.Philox4x32 :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_philox4x32(hmath_context *context, hmath_value **out); +/* HMath.Random.Threefry2x64 :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_threefry2x64(hmath_context *context, hmath_value **out); +/* HMath.Random.ChaCha20 :: constructor */ +HMATH_API hmath_status hmath_stochastic_random_new_cha_cha20(hmath_context *context, hmath_value **out); +/* HMath.Probability.validateDistribution :: Distribution -> Either MathError () */ +HMATH_API hmath_status hmath_stochastic_probability_validate_distribution(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.logDensity :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.density :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.cdf :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_cdf(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.survival :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_survival(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.quantile :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_quantile(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.hazard :: Distribution -> Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_hazard(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.logLikelihood :: Distribution -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_log_likelihood(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.moments :: Distribution -> Either MathError (Double, Double) */ +HMATH_API hmath_status hmath_stochastic_probability_moments(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.entropy :: Distribution -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_entropy(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.expectation :: Distribution -> (Double -> Double) -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_expectation(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.sample :: Distribution -> R.RNG -> Either MathError (Double, R.RNG) */ +HMATH_API hmath_status hmath_stochastic_probability_sample(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.fitNormal :: [Double] -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_fit_normal(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.fitExponential :: [Double] -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_fit_exponential(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.fitBernoulli :: [Double] -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_fit_bernoulli(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.fitMLEGrid :: [Distribution] -> [Double] -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_fit_mle_grid(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.fitMAPGrid :: [Distribution] -> [Double] -> (Distribution -> Double) -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_fit_map_grid(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.betaBernoulliUpdate :: Double -> Double -> [Bool] -> Either MathError (Double, Double) */ +HMATH_API hmath_status hmath_stochastic_probability_beta_bernoulli_update(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.goodnessOfFit :: Distribution -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_goodness_of_fit(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.gaussianKDE :: Double -> [Double] -> Either MathError Distribution */ +HMATH_API hmath_status hmath_stochastic_probability_gaussian_kde(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.multivariateNormalLogDensity :: [Double] -> Matrix Double -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_multivariate_normal_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.sampleMultivariateNormal :: [Double] -> Matrix Double -> R.RNG -> Either MathError ([Double], R.RNG) */ +HMATH_API hmath_status hmath_stochastic_probability_sample_multivariate_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.wishartLogDensity :: Double -> Matrix Double -> Matrix Double -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_probability_wishart_log_density(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.sampleWishart :: Int -> Matrix Double -> R.RNG -> Either MathError (Matrix Double, R.RNG) */ +HMATH_API hmath_status hmath_stochastic_probability_sample_wishart(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.markov :: [[Double]] -> Either MathError Markov */ +HMATH_API hmath_status hmath_stochastic_probability_markov(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.transition :: Markov -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_stochastic_probability_transition(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.stationary :: Int -> Double -> Markov -> Either MathError [Double] */ +HMATH_API hmath_status hmath_stochastic_probability_stationary(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.hmm :: [Double] -> [[Double]] -> [[Double]] -> Either MathError HMM */ +HMATH_API hmath_status hmath_stochastic_probability_hmm(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.forward :: HMM -> [Int] -> Either MathError (Double, [[Double]], [Double]) */ +HMATH_API hmath_status hmath_stochastic_probability_forward(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.backward :: HMM -> [Int] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_stochastic_probability_backward(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.posteriorStates :: HMM -> [Int] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_stochastic_probability_posterior_states(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.viterbi :: HMM -> [Int] -> Either MathError ([Int], Double) */ +HMATH_API hmath_status hmath_stochastic_probability_viterbi(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.baumWelch :: Int -> Double -> HMM -> [Int] -> Either MathError HMM */ +HMATH_API hmath_status hmath_stochastic_probability_baum_welch(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Probability.Bernoulli :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_bernoulli(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Binomial :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.NegativeBinomial :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_negative_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Geometric :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_geometric(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Hypergeometric :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_hypergeometric(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.Poisson :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_poisson(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Categorical :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_categorical(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.DiscreteUniform :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_discrete_uniform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Uniform :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_uniform(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Normal :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.LogNormal :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_log_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Exponential :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_exponential(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Gamma :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_gamma(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Beta :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_beta(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.ChiSquare :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_chi_square(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.StudentT :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_student_t(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.FisherF :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_fisher_f(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Cauchy :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_cauchy(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Laplace :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_laplace(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Logistic :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_logistic(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Weibull :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_weibull(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Pareto :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_pareto(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Rayleigh :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_rayleigh(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Maxwell :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_maxwell(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Gumbel :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_gumbel(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.GeneralizedExtremeValue :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_generalized_extreme_value(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.BetaBinomial :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_beta_binomial(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.Skellam :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_skellam(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.VonMises :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_von_mises(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Probability.Triangular :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_triangular(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Probability.TruncatedNormal :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_truncated_normal(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Probability.Mixture :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_mixture(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.Empirical :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_empirical(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Probability.GaussianKDE :: constructor */ +HMATH_API hmath_status hmath_stochastic_probability_new_gaussian_kde(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.covarianceMatrix :: Bool -> [[Double]] -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_covariance_matrix(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.partialCorrelation :: [[Double]] -> Int -> Int -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_partial_correlation(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Statistics.Advanced.emptyStreaming :: Streaming */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_empty_streaming(hmath_context *context, hmath_value **out); +/* HMath.Statistics.Advanced.updateStreaming :: Streaming -> Double -> Either MathError Streaming */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_update_streaming(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.combineStreaming :: Streaming -> Streaming -> Either MathError Streaming */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_combine_streaming(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.streamingResult :: Bool -> Streaming -> Either MathError (Integer, Double, Double) */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_streaming_result(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.histogramND :: [[Double]] -> [[Double]] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_histogram_nd(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Statistics.Advanced.mutualInformation :: [[Double]] -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_mutual_information(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.bootstrap :: Int -> ([Double] -> Either MathError Double) -> [Double] -> R.RNG -> Either MathError ([Double], R.RNG) */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_bootstrap(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Statistics.Advanced.jackknife :: ([Double] -> Either MathError Double) -> [Double] -> Either MathError (Double, Double) */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_jackknife(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.oneSampleT :: Double -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_one_sample_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.twoSampleT :: Bool -> [Double] -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_two_sample_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Statistics.Advanced.pairedT :: [Double] -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_paired_t(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.zTest :: Double -> Double -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_z_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Statistics.Advanced.chiSquareTest :: Int -> [Double] -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_chi_square_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +/* HMath.Statistics.Advanced.varianceFTest :: [Double] -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_variance_f_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.anova :: [[Double]] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_anova(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.welchAnova :: [[Double]] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_welch_anova(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.kruskalWallis :: [[Double]] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_kruskal_wallis(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.mannWhitney :: [Double] -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_mann_whitney(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.wilcoxon :: [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_wilcoxon(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.kolmogorovSmirnov :: P.Distribution -> [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_kolmogorov_smirnov(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.shapiroWilk :: [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_shapiro_wilk(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.andersonDarling :: [Double] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_anderson_darling(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.levene :: Bool -> [[Double]] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_levene(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.bartlett :: [[Double]] -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_bartlett(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.fisherExact :: Int -> Int -> Int -> Int -> Either MathError TestResult */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_fisher_exact(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, hmath_value **out); +/* HMath.Statistics.Advanced.permutationTest :: Int -> ([Double] -> [Double] -> Either MathError Double) -> [Double] -> [Double] -> R.RNG -> Either MathError (TestResult, R.RNG) */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_permutation_test(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, const hmath_value *a3, const hmath_value *a4, hmath_value **out); +/* HMath.Statistics.Advanced.etaSquared :: [[Double]] -> Either MathError Double */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_eta_squared(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.grubbs :: Double -> [Double] -> Either MathError (Int, Double, Bool) */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_grubbs(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.masked :: [Bool] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_masked(hmath_context *context, const hmath_value *a0, const hmath_value *a1, hmath_value **out); +/* HMath.Statistics.Advanced.testStatistic :: TestResult -> field */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_test_statistic(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.pValue :: TestResult -> field */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_p_value(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.degreesOfFreedom :: TestResult -> field */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_degrees_of_freedom(hmath_context *context, const hmath_value *a0, hmath_value **out); +/* HMath.Statistics.Advanced.TestResult :: constructor */ +HMATH_API hmath_status hmath_stochastic_statistics_advanced_new_test_result(hmath_context *context, const hmath_value *a0, const hmath_value *a1, const hmath_value *a2, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_tensor_bindings.h b/include/hmath_tensor_bindings.h new file mode 100644 index 0000000..8983b52 --- /dev/null +++ b/include/hmath_tensor_bindings.h @@ -0,0 +1,785 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_TENSOR_BINDINGS_H +#define HMATH_TENSOR_BINDINGS_H +#include "hmath_value.h" +#include "hmath_error.h" +#include "hmath_callback.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Actual original typed boxed tensors (Value161 Double,270 other element + * witnesses), lazy TensorGraph271, pinned MutableTensor272. No legacy C tensor + * rank/element cap is imposed; original shape and byte overflow checks apply. + * Prototype scalars select element types explicitly; Bool and String permit + * structural APIs, and numerical APIs require their original class instance. */ +typedef enum hmath_tensor_layout_kind { + HMATH_TENSOR_LAYOUT_ROW_MAJOR=0, + HMATH_TENSOR_LAYOUT_COLUMN_MAJOR=1, + HMATH_TENSOR_LAYOUT_STRIDED=2 +} hmath_tensor_layout_kind; +typedef enum hmath_tensor_device_kind { HMATH_TENSOR_DEVICE_CPU=0 } hmath_tensor_device_kind; +/* Scalar arguments are a borrowed tuple of exact typed values. Successful + * callbacks transfer one owned Value result. MathError wire fields live until + * consumed. Function/userdata live until every derived lazy graph is released. + * Callbacks are synchronous, may reenter HMath, and must not request shutdown. */ +typedef hmath_status (*hmath_tensor_scalar_callback_fn)(const hmath_value *arguments,void *userdata,hmath_value **out,hmath_math_error *error); +/* Buffer pointer is valid only during the call; metadata=(prototype,shape, + * signed element strides,Storable element byte size,Storable alignment). + * Synchronize concurrent writes and honor actual shape/strides. Do not retain + * pointer or access memory outside this view. Result may be any shared Value. */ +typedef hmath_status (*hmath_tensor_buffer_callback_fn)(void *pointer,const hmath_value *metadata,void *userdata,hmath_value **out,hmath_math_error *error); +HMATH_API hmath_status hmath_tensor_object_callback(hmath_context *,hmath_tensor_scalar_callback_fn,void *,hmath_value **); +HMATH_API hmath_status hmath_tensor_object_buffer_callback(hmath_context *,hmath_tensor_buffer_callback_fn,void *,hmath_value **); +HMATH_API hmath_status hmath_tensor_object_prototype(hmath_context *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_tensor_object_graph_prototype(hmath_context *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_tensor_object_mutable_prototype(hmath_context *,const hmath_value *,hmath_value **); +HMATH_API hmath_status hmath_tensor_object_equal_instance(hmath_context *,const hmath_value *,const hmath_value *,hmath_value **); +/* Explicit type token permits structural scalar types whose provider has no + * Num instance. This calls original tensorFull without numeric conversion. */ +HMATH_API hmath_status hmath_tensor_object_full_typed(hmath_context *,const hmath_value *element_type,const hmath_value *shape,const hmath_value *fill,hmath_value **out); +/* BEGIN GENERATED */ +/* HMath.Tensor.RowMajor -> Layout. */ +HMATH_API hmath_status hmath_tensor_object_row_major_create( + hmath_context *context, + hmath_value **out); + +/* HMath.Tensor.ColumnMajor -> Layout. */ +HMATH_API hmath_status hmath_tensor_object_column_major_create( + hmath_context *context, + hmath_value **out); + +/* HMath.Tensor.Strided -> Layout. */ +HMATH_API hmath_status hmath_tensor_object_strided_create( + hmath_context *context, + hmath_value **out); + +/* HMath.Tensor.CPU -> Device. */ +HMATH_API hmath_status hmath_tensor_object_cpu_create( + hmath_context *context, + hmath_value **out); + +/* HMath.Tensor.tensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + const hmath_value *xs, + hmath_value **out); + +/* HMath.Tensor.tensorColumnMajor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_column_major( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + const hmath_value *xs, + hmath_value **out); + +/* HMath.Tensor.tensorFull -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_full( + hmath_context *context, + const hmath_value *shape, + const hmath_value *fill_value, + hmath_value **out); + +/* HMath.Tensor.tensorZeros -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_zeros( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + hmath_value **out); + +/* HMath.Tensor.tensorOnes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_ones( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *shape, + hmath_value **out); + +/* HMath.Tensor.tensorArange -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_arange( + hmath_context *context, + const hmath_value *start, + const hmath_value *end, + const hmath_value *step, + hmath_value **out); + +/* HMath.Tensor.tensorLinspace -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_linspace( + hmath_context *context, + const hmath_value *start, + const hmath_value *end, + const hmath_value *count, + hmath_value **out); + +/* HMath.Tensor.tensorLogspace -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_logspace( + hmath_context *context, + const hmath_value *base, + const hmath_value *start, + const hmath_value *end, + const hmath_value *count, + hmath_value **out); + +/* HMath.Tensor.tensorRandom -> (Tensor,Integer). */ +HMATH_API hmath_status hmath_tensor_object_tensor_random( + hmath_context *context, + const hmath_value *seed, + const hmath_value *shape, + hmath_value **out); + +/* HMath.Tensor.tensorValues -> Elements. */ +HMATH_API hmath_status hmath_tensor_object_tensor_values( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorShape -> [Int]. */ +HMATH_API hmath_status hmath_tensor_object_tensor_shape( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorStrides -> [Int]. */ +HMATH_API hmath_status hmath_tensor_object_tensor_strides( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorOffset -> Int. */ +HMATH_API hmath_status hmath_tensor_object_tensor_offset( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorDType -> String. */ +HMATH_API hmath_status hmath_tensor_object_tensor_d_type( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorDevice -> Device. */ +HMATH_API hmath_status hmath_tensor_object_tensor_device( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensorLayout -> Layout. */ +HMATH_API hmath_status hmath_tensor_object_tensor_layout( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.numel -> Int. */ +HMATH_API hmath_status hmath_tensor_object_numel( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.isContiguous -> Bool. */ +HMATH_API hmath_status hmath_tensor_object_is_contiguous( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.shapeSize -> Int. */ +HMATH_API hmath_status hmath_tensor_object_shape_size( + hmath_context *context, + const hmath_value *shape, + hmath_value **out); + +/* HMath.Tensor.inferBroadcast -> [Int]. */ +HMATH_API hmath_status hmath_tensor_object_infer_broadcast( + hmath_context *context, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.Tensor.contiguous -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_contiguous( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.indexTensor -> Element. */ +HMATH_API hmath_status hmath_tensor_object_index_tensor( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + hmath_value **out); + +/* HMath.Tensor.sliceTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_slice_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *start, + const hmath_value *count, + const hmath_value *step, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.fancyIndex -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_fancy_index( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.gather -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_gather( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.booleanIndex -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_boolean_index( + hmath_context *context, + const hmath_value *mask, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.scatter -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_scatter( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *updates, + const hmath_value *target, + hmath_value **out); + +/* HMath.Tensor.scatterAdd -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_scatter_add( + hmath_context *context, + const hmath_value *axis, + const hmath_value *indices, + const hmath_value *updates, + const hmath_value *target, + hmath_value **out); + +/* HMath.Tensor.reshapeTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_reshape_tensor( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.flattenTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_flatten_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.squeeze -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_squeeze( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.unsqueeze -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_unsqueeze( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.expand -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_expand( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.permute -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_permute( + hmath_context *context, + const hmath_value *axes, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.transposeTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_transpose_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.moveAxis -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_move_axis( + hmath_context *context, + const hmath_value *from_axis, + const hmath_value *to_axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.swapAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_swap_axes( + hmath_context *context, + const hmath_value *from_axis, + const hmath_value *to_axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.broadcastTo -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_broadcast_to( + hmath_context *context, + const hmath_value *shape, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.repeatTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_repeat_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tile -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tile( + hmath_context *context, + const hmath_value *counts, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.concatenate -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_concatenate( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *axis, + const hmath_value *inputs, + hmath_value **out); + +/* HMath.Tensor.stack -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_stack( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *axis, + const hmath_value *inputs, + hmath_value **out); + +/* HMath.Tensor.splitTensor -> [Tensor]. */ +HMATH_API hmath_status hmath_tensor_object_split_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *segments, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.chunkTensor -> [Tensor]. */ +HMATH_API hmath_status hmath_tensor_object_chunk_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.padTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_pad_tensor( + hmath_context *context, + const hmath_value *padding, + const hmath_value *fill_value, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.roll -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_roll( + hmath_context *context, + const hmath_value *axis, + const hmath_value *shift, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.flipTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_flip_tensor( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.rotate -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_rotate( + hmath_context *context, + const hmath_value *first, + const hmath_value *second, + const hmath_value *turns, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.sortTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_sort_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.unique -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_unique( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.argsort -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_argsort( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.topk -> (Tensor,Tensor). */ +HMATH_API hmath_status hmath_tensor_object_topk( + hmath_context *context, + const hmath_value *count, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.nonzero -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_nonzero( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.whereTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_where_tensor( + hmath_context *context, + const hmath_value *mask, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.Tensor.maskedFill -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_masked_fill( + hmath_context *context, + const hmath_value *mask, + const hmath_value *fill_value, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.maskedSelect -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_masked_select( + hmath_context *context, + const hmath_value *mask, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.mapTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_map_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.zipTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_zip_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.Tensor.tensorAdd -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_add( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorSubtract -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_subtract( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorMultiply -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_multiply( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorDivide -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_divide( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorEqual -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_equal( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorLess -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_less( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorAnd -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_and( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorOr -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_or( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorNot -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_not( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.promoteTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_promote_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.sumAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_sum_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.productAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_product_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.meanAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_mean_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.varianceAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_variance_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.normAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_norm_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.minAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_min_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.maxAxes -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_max_axes( + hmath_context *context, + const hmath_value *axes, + const hmath_value *keep_dimensions, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.argmin -> Int. */ +HMATH_API hmath_status hmath_tensor_object_argmin( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.argmax -> Int. */ +HMATH_API hmath_status hmath_tensor_object_argmax( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.cumulativeSum -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_cumulative_sum( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.cumulativeProduct -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_cumulative_product( + hmath_context *context, + const hmath_value *axis, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.tensordot -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensordot( + hmath_context *context, + const hmath_value *left_axes, + const hmath_value *right_axes, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.Tensor.einsum -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_einsum( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *labels, + const hmath_value *output_labels, + const hmath_value *inputs, + hmath_value **out); + +/* HMath.Tensor.batchedMatmul -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_batched_matmul( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.tensorKronecker -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_tensor_kronecker( + hmath_context *context, + const hmath_value *a, + const hmath_value *b, + hmath_value **out); + +/* HMath.Tensor.serializeTensor -> String. */ +HMATH_API hmath_status hmath_tensor_object_serialize_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.deserializeTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_deserialize_tensor( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *text, + hmath_value **out); + +/* HMath.Tensor.inputGraph -> TensorGraph. */ +HMATH_API hmath_status hmath_tensor_object_input_graph( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.mapGraph -> TensorGraph. */ +HMATH_API hmath_status hmath_tensor_object_map_graph( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.zipGraph -> TensorGraph. */ +HMATH_API hmath_status hmath_tensor_object_zip_graph( + hmath_context *context, + const hmath_value *element_type, + const hmath_value *cb, + const hmath_value *left, + const hmath_value *right, + hmath_value **out); + +/* HMath.Tensor.evaluateGraph -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_evaluate_graph( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.newMutable -> MutableTensor. */ +HMATH_API hmath_status hmath_tensor_object_new_mutable( + hmath_context *context, + const hmath_value *shape, + const hmath_value *fill_value, + hmath_value **out); + +/* HMath.Tensor.Mutable.thawTensor -> MutableTensor. */ +HMATH_API hmath_status hmath_tensor_object_thaw_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.freezeTensor -> Tensor. */ +HMATH_API hmath_status hmath_tensor_object_freeze_tensor( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.mutableShape -> [Int]. */ +HMATH_API hmath_status hmath_tensor_object_mutable_shape( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.readMutable -> Element. */ +HMATH_API hmath_status hmath_tensor_object_read_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + hmath_value **out); + +/* HMath.Tensor.Mutable.writeMutable -> Unit. */ +HMATH_API hmath_status hmath_tensor_object_write_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + const hmath_value *fill_value, + hmath_value **out); + +/* HMath.Tensor.Mutable.modifyMutable -> Unit. */ +HMATH_API hmath_status hmath_tensor_object_modify_mutable( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *index, + const hmath_value *cb, + hmath_value **out); + +/* HMath.Tensor.Mutable.sliceMutable -> MutableTensor. */ +HMATH_API hmath_status hmath_tensor_object_slice_mutable( + hmath_context *context, + const hmath_value *axis, + const hmath_value *start, + const hmath_value *count, + const hmath_value *step, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.transposeMutable -> MutableTensor. */ +HMATH_API hmath_status hmath_tensor_object_transpose_mutable( + hmath_context *context, + const hmath_value *input_tensor, + hmath_value **out); + +/* HMath.Tensor.Mutable.mutableAlignment -> Int. */ +HMATH_API hmath_status hmath_tensor_object_mutable_alignment( + hmath_context *context, + const hmath_value *element_type, + hmath_value **out); + +/* HMath.Tensor.Mutable.withMutableBuffer -> Generic. */ +HMATH_API hmath_status hmath_tensor_object_with_mutable_buffer( + hmath_context *context, + const hmath_value *input_tensor, + const hmath_value *cb, + hmath_value **out); +/* END GENERATED */ +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_timeseries.h b/include/hmath_timeseries.h new file mode 100644 index 0000000..205b46e --- /dev/null +++ b/include/hmath_timeseries.h @@ -0,0 +1,239 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_timeseries_bindings.py. */ +#ifndef HMATH_TIMESERIES_H +#define HMATH_TIMESERIES_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Borrowed immutable inputs; successful outputs own one Value reference. + * Error outputs are untouched. Original binary64 arithmetic, time ordering, + * missingness, model fitting, diagnostics, budgets and seeds are preserved. + * OptimizeOptions accepts original kind20 objects from the optimization API. + * Source MathError returns status11 and hmath_last_math_error payload. + * Cancellation is checked before entry, source budgets govern evaluation. */ +typedef hmath_value hmath_timeseries_series_object; /* kind120 */ +typedef hmath_value hmath_timeseries_alignment_object; /* kind121 */ +typedef hmath_value hmath_timeseries_fill_object; /* kind122 */ +typedef hmath_value hmath_timeseries_resampling_object; /* kind123 */ +typedef hmath_value hmath_timeseries_rolling_object; /* kind124 */ +typedef hmath_value hmath_timeseries_dtw_result_object; /* kind125 */ +typedef hmath_value hmath_timeseries_deterministic_object; /* kind126 */ +typedef hmath_value hmath_timeseries_forecast_metric_object; /* kind127 */ +typedef hmath_value hmath_timeseries_stationarity_object; /* kind128 */ +typedef hmath_value hmath_timeseries_arima_model_object; /* kind129 */ +typedef hmath_value hmath_timeseries_ar_model_object; /* kind130 */ +typedef hmath_value hmath_timeseries_decomposition_object; /* kind131 */ +typedef hmath_value hmath_timeseries_sarima_order_object; /* kind132 */ +typedef hmath_value hmath_timeseries_stl_config_object; /* kind133 */ +typedef hmath_value hmath_timeseries_smoothing_object; /* kind134 */ +typedef hmath_value hmath_timeseries_var_model_object; /* kind135 */ +typedef hmath_value hmath_timeseries_gaussian_state_object; /* kind140 */ +/* Return the original Show representation as an owned String Value. */ +HMATH_API hmath_status hmath_timeseries_describe(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Core.BackwardFill :: Fill */ +HMATH_API hmath_status hmath_timeseries_backward_fill(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.BinLast :: Resampling */ +HMATH_API hmath_status hmath_timeseries_bin_last(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.BinMean :: Resampling */ +HMATH_API hmath_status hmath_timeseries_bin_mean(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.ForwardFill :: Fill */ +HMATH_API hmath_status hmath_timeseries_forward_fill(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.Inner :: Alignment */ +HMATH_API hmath_status hmath_timeseries_inner(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.LeftAligned :: Alignment */ +HMATH_API hmath_status hmath_timeseries_left_aligned(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.LinearFill :: Fill */ +HMATH_API hmath_status hmath_timeseries_linear_fill(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.LinearSamples :: Resampling */ +HMATH_API hmath_status hmath_timeseries_linear_samples(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.MovingMaximum :: Rolling */ +HMATH_API hmath_status hmath_timeseries_moving_maximum(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.MovingMean :: Rolling */ +HMATH_API hmath_status hmath_timeseries_moving_mean(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.MovingMinimum :: Rolling */ +HMATH_API hmath_status hmath_timeseries_moving_minimum(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.MovingSD :: Rolling */ +HMATH_API hmath_status hmath_timeseries_moving_sd(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.MovingVariance :: Rolling */ +HMATH_API hmath_status hmath_timeseries_moving_variance(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.Outer :: Alignment */ +HMATH_API hmath_status hmath_timeseries_outer(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Core.align :: Alignment -> Series -> Series -> Either MathError (Series, Series) */ +HMATH_API hmath_status hmath_timeseries_align(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.TimeSeries.Core.autocorrelation :: Int -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_autocorrelation(hmath_context *context, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.crossCorrelation :: Int -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_timeseries_cross_correlation(hmath_context *context, const hmath_value *lag, const hmath_value *xs, const hmath_value *ys, hmath_value **out); +/* HMath.TimeSeries.Core.cumulativeReturns :: [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_cumulative_returns(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.difference :: Int -> Int -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_difference(hmath_context *context, const hmath_value *order, const hmath_value *lag, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.durbinLevinson :: [Double] -> Either MathError ([Double], Double, [Double]) */ +HMATH_API hmath_status hmath_timeseries_durbin_levinson(hmath_context *context, const hmath_value *covariance, hmath_value **out); +/* HMath.TimeSeries.Core.exponentialAverage :: Double -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_exponential_average(hmath_context *context, const hmath_value *alpha, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.fillMissing :: Fill -> Series -> Either MathError Series */ +HMATH_API hmath_status hmath_timeseries_fill_missing(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.TimeSeries.Core.isRegular :: Double -> Series -> Either MathError Bool */ +HMATH_API hmath_status hmath_timeseries_is_regular(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.TimeSeries.Core.logarithmicReturns :: [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_logarithmic_returns(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.observations :: Series -> [(Double, Maybe Double)] */ +HMATH_API hmath_status hmath_timeseries_observations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Core.partialAutocorrelation :: Int -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_partial_autocorrelation(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.regularSeries :: Double -> Double -> [Maybe Double] -> Either MathError Series */ +HMATH_API hmath_status hmath_timeseries_regular_series(hmath_context *context, const hmath_value *start, const hmath_value *step, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.resample :: Resampling -> Double -> Double -> Int -> Series -> Either MathError Series */ +HMATH_API hmath_status hmath_timeseries_resample(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.TimeSeries.Core.rolling :: Rolling -> Int -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_rolling(hmath_context *context, const hmath_value *method, const hmath_value *width, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.series :: [(Double, Maybe Double)] -> Either MathError Series */ +HMATH_API hmath_status hmath_timeseries_series(hmath_context *context, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.seriesValues :: Series -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_series_values(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Core.weightedAverage :: [Double] -> [Double] -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_weighted_average(hmath_context *context, const hmath_value *ws, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Core.yuleWalker :: Int -> [Double] -> Either MathError ([Double], Double, Double) */ +HMATH_API hmath_status hmath_timeseries_yule_walker(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.DTWResult :: Double -> [(Int, Int)] -> DTWResult */ +HMATH_API hmath_status hmath_timeseries_dtw_result(hmath_context *context, const hmath_value *distance, const hmath_value *path, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.Level :: Deterministic */ +HMATH_API hmath_status hmath_timeseries_level(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.LinearTrend :: Deterministic */ +HMATH_API hmath_status hmath_timeseries_linear_trend(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.MAE :: ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_mae(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.MAPE :: ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_mape(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.MASE :: Int -> [Double] -> ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_mase(hmath_context *context, const hmath_value *period, const hmath_value *training, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.MSE :: ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_mse(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.RMSE :: ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_rmse(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.SMAPE :: ForecastMetric */ +HMATH_API hmath_status hmath_timeseries_smape(hmath_context *context, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.Stationarity :: Double -> [(Double, Double)] -> Int -> String -> Stationarity */ +HMATH_API hmath_status hmath_timeseries_stationarity(hmath_context *context, const hmath_value *statistic, const hmath_value *critical_values, const hmath_value *observations, const hmath_value *null_hypothesis, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.anomalies :: Double -> [Double] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_timeseries_anomalies(hmath_context *context, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.augmentedDickeyFuller :: Deterministic -> Int -> [Double] -> Either MathError Stationarity */ +HMATH_API hmath_status hmath_timeseries_augmented_dickey_fuller(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.changePoints :: Double -> Int -> [Double] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_timeseries_change_points(hmath_context *context, const hmath_value *penalty, const hmath_value *min_segment, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.cusum :: Double -> Double -> Double -> Double -> [Double] -> Either MathError [Int] */ +HMATH_API hmath_status hmath_timeseries_cusum(hmath_context *context, const hmath_value *mean, const hmath_value *sd, const hmath_value *drift, const hmath_value *threshold, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.dtwDistance :: DTWResult -> Double */ +HMATH_API hmath_status hmath_timeseries_dtw_distance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.dtwPath :: DTWResult -> [(Int, Int)] */ +HMATH_API hmath_status hmath_timeseries_dtw_path(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.dynamicTimeWarping :: Int -> [Double] -> [Double] -> Either MathError DTWResult */ +HMATH_API hmath_status hmath_timeseries_dynamic_time_warping(hmath_context *context, const hmath_value *radius, const hmath_value *xs, const hmath_value *ys, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.forecastError :: ForecastMetric -> [Double] -> [Double] -> Either MathError Double */ +HMATH_API hmath_status hmath_timeseries_forecast_error(hmath_context *context, const hmath_value *metric, const hmath_value *actual, const hmath_value *predicted, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.kpss :: Deterministic -> Int -> [Double] -> Either MathError Stationarity */ +HMATH_API hmath_status hmath_timeseries_kpss(hmath_context *context, const hmath_value *deterministic, const hmath_value *lags, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.spectrum :: Double -> [Double] -> Either MathError [(Double, Double)] */ +HMATH_API hmath_status hmath_timeseries_spectrum(hmath_context *context, const hmath_value *sample_rate, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.stationarityCriticalValues :: Stationarity -> [(Double, Double)] */ +HMATH_API hmath_status hmath_timeseries_stationarity_critical_values(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.stationarityNull :: Stationarity -> String */ +HMATH_API hmath_status hmath_timeseries_stationarity_null(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.stationarityObservations :: Stationarity -> Int */ +HMATH_API hmath_status hmath_timeseries_stationarity_observations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Diagnostics.stationarityStatistic :: Stationarity -> Double */ +HMATH_API hmath_status hmath_timeseries_stationarity_statistic(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.Decomposition :: [Double] -> [Double] -> [Double] -> Decomposition */ +HMATH_API hmath_status hmath_timeseries_decomposition(hmath_context *context, const hmath_value *trend, const hmath_value *seasonal, const hmath_value *remainder, hmath_value **out); +/* HMath.TimeSeries.Models.Holt :: Double -> Double -> Smoothing */ +HMATH_API hmath_status hmath_timeseries_holt(hmath_context *context, const hmath_value *alpha, const hmath_value *beta, hmath_value **out); +/* HMath.TimeSeries.Models.HoltWinters :: Int -> Double -> Double -> Double -> Smoothing */ +HMATH_API hmath_status hmath_timeseries_holt_winters(hmath_context *context, const hmath_value *period, const hmath_value *alpha, const hmath_value *beta, const hmath_value *gamma, hmath_value **out); +/* HMath.TimeSeries.Models.SARIMAOrder :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> SARIMAOrder */ +HMATH_API hmath_status hmath_timeseries_sarima_order(hmath_context *context, const hmath_value *ar, const hmath_value *difference, const hmath_value *ma, const hmath_value *seasonal_ar, const hmath_value *seasonal_difference, const hmath_value *seasonal_ma, const hmath_value *period, hmath_value **out); +/* HMath.TimeSeries.Models.STLConfig :: Int -> Int -> Int -> Int -> Int -> Int -> STLConfig */ +HMATH_API hmath_status hmath_timeseries_stl_config(hmath_context *context, const hmath_value *period, const hmath_value *seasonal_window, const hmath_value *trend_window, const hmath_value *low_pass_window, const hmath_value *inner_iterations, const hmath_value *robust_iterations, hmath_value **out); +/* HMath.TimeSeries.Models.Simple :: Double -> Smoothing */ +HMATH_API hmath_status hmath_timeseries_simple(hmath_context *context, const hmath_value *alpha, hmath_value **out); +/* HMath.TimeSeries.Models.arCoefficients :: ARModel -> [Double] */ +HMATH_API hmath_status hmath_timeseries_ar_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.arOrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.arimaInnovationVariance :: ARIMAModel -> Double */ +HMATH_API hmath_status hmath_timeseries_arima_innovation_variance(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.arimaParameters :: ARIMAModel -> [Double] */ +HMATH_API hmath_status hmath_timeseries_arima_parameters(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.arimaResiduals :: ARIMAModel -> [Double] */ +HMATH_API hmath_status hmath_timeseries_arima_residuals(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.decompose :: Int -> [Double] -> Either MathError Decomposition */ +HMATH_API hmath_status hmath_timeseries_decompose(hmath_context *context, const hmath_value *period, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.defaultSTLConfig :: Int -> STLConfig */ +HMATH_API hmath_status hmath_timeseries_default_stl_config(hmath_context *context, const hmath_value *period, hmath_value **out); +/* HMath.TimeSeries.Models.differenceOrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.fitAR :: Int -> [Double] -> Either MathError ARModel */ +HMATH_API hmath_status hmath_timeseries_fit_ar(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.fitARIMA :: OptimizeOptions -> Int -> Int -> Int -> [Double] -> Either MathError ARIMAModel */ +HMATH_API hmath_status hmath_timeseries_fit_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, const hmath_value *value5, hmath_value **out); +/* HMath.TimeSeries.Models.fitARMA :: OptimizeOptions -> Int -> Int -> [Double] -> Either MathError ARIMAModel */ +HMATH_API hmath_status hmath_timeseries_fit_arma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, const hmath_value *value4, hmath_value **out); +/* HMath.TimeSeries.Models.fitMA :: OptimizeOptions -> Int -> [Double] -> Either MathError ARIMAModel */ +HMATH_API hmath_status hmath_timeseries_fit_ma(hmath_context *context, const hmath_value *value, const hmath_value *value2, const hmath_value *value3, hmath_value **out); +/* HMath.TimeSeries.Models.fitSARIMA :: OptimizeOptions -> SARIMAOrder -> [Double] -> Either MathError ARIMAModel */ +HMATH_API hmath_status hmath_timeseries_fit_sarima(hmath_context *context, const hmath_value *options, const hmath_value *order, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.fitVAR :: Int -> [[Double]] -> Either MathError VARModel */ +HMATH_API hmath_status hmath_timeseries_fit_var(hmath_context *context, const hmath_value *order, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.forecastAR :: Int -> ARModel -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_forecast_ar(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.TimeSeries.Models.forecastARIMA :: Int -> ARIMAModel -> Either MathError [Double] */ +HMATH_API hmath_status hmath_timeseries_forecast_arima(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.TimeSeries.Models.forecastVAR :: Int -> VARModel -> Either MathError [[Double]] */ +HMATH_API hmath_status hmath_timeseries_forecast_var(hmath_context *context, const hmath_value *value, const hmath_value *value2, hmath_value **out); +/* HMath.TimeSeries.Models.kalmanSeries :: [[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> GaussianState -> [[Double]] -> Either MathError [GaussianState] */ +HMATH_API hmath_status hmath_timeseries_kalman_series(hmath_context *context, const hmath_value *transition, const hmath_value *observation, const hmath_value *q, const hmath_value *r, const hmath_value *initial, const hmath_value *measured, hmath_value **out); +/* HMath.TimeSeries.Models.maOrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.remainderComponent :: Decomposition -> [Double] */ +HMATH_API hmath_status hmath_timeseries_remainder_component(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.seasonalAROrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_seasonal_ar_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.seasonalComponent :: Decomposition -> [Double] */ +HMATH_API hmath_status hmath_timeseries_seasonal_component(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.seasonalDifferenceOrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_seasonal_difference_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.seasonalMAOrder :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_seasonal_ma_order(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.seasonalPeriod :: SARIMAOrder -> Int */ +HMATH_API hmath_status hmath_timeseries_seasonal_period(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.smoothForecast :: Smoothing -> Int -> [Double] -> Either MathError ([Double], [Double]) */ +HMATH_API hmath_status hmath_timeseries_smooth_forecast(hmath_context *context, const hmath_value *method, const hmath_value *horizon, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.stl :: STLConfig -> [Double] -> Either MathError Decomposition */ +HMATH_API hmath_status hmath_timeseries_stl(hmath_context *context, const hmath_value *config, const hmath_value *xs, hmath_value **out); +/* HMath.TimeSeries.Models.stlInnerIterations :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_inner_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.stlLowPassWindow :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_low_pass_window(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.stlPeriod :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_period(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.stlRobustIterations :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_robust_iterations(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.stlSeasonalWindow :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_seasonal_window(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.stlTrendWindow :: STLConfig -> Int */ +HMATH_API hmath_status hmath_timeseries_stl_trend_window(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.trendComponent :: Decomposition -> [Double] */ +HMATH_API hmath_status hmath_timeseries_trend_component(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.TimeSeries.Models.varCoefficients :: VARModel -> [[Double]] */ +HMATH_API hmath_status hmath_timeseries_var_coefficients(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.gaussianState :: [Double] -> [[Double]] -> Either MathError GaussianState */ +HMATH_API hmath_status hmath_timeseries_gaussian_state(hmath_context *context, const hmath_value *mean, const hmath_value *covariance, hmath_value **out); +/* HMath.Signal.stateMean :: GaussianState -> [Double] */ +HMATH_API hmath_status hmath_timeseries_state_mean(hmath_context *context, const hmath_value *value, hmath_value **out); +/* HMath.Signal.stateCovariance :: GaussianState -> [[Double]] */ +HMATH_API hmath_status hmath_timeseries_state_covariance(hmath_context *context, const hmath_value *value, hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_units.h b/include/hmath_units.h new file mode 100644 index 0000000..971c291 --- /dev/null +++ b/include/hmath_units.h @@ -0,0 +1,96 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_units_bindings.py. */ +#ifndef HMATH_UNITS_H +#define HMATH_UNITS_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Exact original Units API. Unit/Quantity scalar inputs must be Rational + * Values; dimension and power exponents use arbitrary Integer Values. + * Prefix exponents use Haskell Int. Objects are immutable and independently + * owned; release every result with hmath_value_release. Inputs are borrowed + * for this call only. All errors preserve the original MathError; output + * pointers remain untouched on failure. Catalog getters return owned handles. */ +HMATH_API hmath_status hmath_units_value_dimension(hmath_context *context, const hmath_value *exponents, hmath_value **out); +HMATH_API hmath_status hmath_units_value_dimension_exponents(hmath_context *context, const hmath_value *dimension, hmath_value **out); +HMATH_API hmath_status hmath_units_value_dimensionless(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_length_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_mass_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_time_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_temperature_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_angle_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_data_dimension(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit(hmath_context *context, const hmath_value *name, const hmath_value *dimension, const hmath_value *scale, const hmath_value *offset, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_name(hmath_context *context, const hmath_value *unit, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_dimension(hmath_context *context, const hmath_value *unit, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_scale(hmath_context *context, const hmath_value *unit, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_offset(hmath_context *context, const hmath_value *unit, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_product(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_quotient(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +HMATH_API hmath_status hmath_units_value_unit_power(hmath_context *context, const hmath_value *unit, const hmath_value *exponent, hmath_value **out); +HMATH_API hmath_status hmath_units_value_quantity(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_units_value_temperature_difference(hmath_context *context, const hmath_value *unit, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_units_value_quantity_dimension(hmath_context *context, const hmath_value *quantity, hmath_value **out); +HMATH_API hmath_status hmath_units_value_si_value(hmath_context *context, const hmath_value *quantity, hmath_value **out); +HMATH_API hmath_status hmath_units_value_in_unit(hmath_context *context, const hmath_value *unit, const hmath_value *quantity, hmath_value **out); +HMATH_API hmath_status hmath_units_value_convert(hmath_context *context, const hmath_value *source, const hmath_value *destination, const hmath_value *value, hmath_value **out); +HMATH_API hmath_status hmath_units_value_add_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_units_value_subtract_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_units_value_multiply_quantity(hmath_context *context, const hmath_value *left, const hmath_value *right, hmath_value **out); +HMATH_API hmath_status hmath_units_value_divide_quantity(hmath_context *context, const hmath_value *numerator, const hmath_value *denominator, hmath_value **out); +HMATH_API hmath_status hmath_units_value_si_prefix(hmath_context *context, const hmath_value *name, const hmath_value *symbol, const hmath_value *exponent, hmath_value **out); +HMATH_API hmath_status hmath_units_value_si_prefixes(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_prefixed(hmath_context *context, const hmath_value *prefix, const hmath_value *unit, hmath_value **out); +HMATH_API hmath_status hmath_units_value_metre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_kilometre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_centimetre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_millimetre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_inch(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_foot(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_yard(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_mile(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_nautical_mile(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_square_metre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_hectare(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_cubic_metre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_litre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_millilitre(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_kilogram(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_gram(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_tonne(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_pound(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_second(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_minute(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_hour(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_day(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_metres_per_second(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_kilometres_per_hour(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_miles_per_hour(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_metres_per_second_squared(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_newton(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_joule(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_watt(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_pascal(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_bar(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_atmosphere(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_kelvin(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_celsius(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_fahrenheit(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_hertz(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_bit(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_byte(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_kibibyte(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_mebibyte(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_gigabyte(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_radian(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_degree(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_gradian(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_units_value_prefix_name(hmath_context *context, const hmath_value *prefix, hmath_value **out); +HMATH_API hmath_status hmath_units_value_prefix_symbol(hmath_context *context, const hmath_value *prefix, hmath_value **out); +HMATH_API hmath_status hmath_units_value_prefix_exponent(hmath_context *context, const hmath_value *prefix, hmath_value **out); +HMATH_API hmath_status hmath_units_value_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/hmath_value.h b/include/hmath_value.h new file mode 100644 index 0000000..a53cad1 --- /dev/null +++ b/include/hmath_value.h @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_VALUE_H +#define HMATH_VALUE_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Lossless owned values shared by structured mathematical APIs. Each owned + * handle pins the runtime; release every reference before final shutdown. + * Inputs are borrowed for each synchronous call. Outputs remain untouched on + * errors. Containers retain their Haskell values independently of input owners. + * Exact integer/rational text is signed ASCII decimal, not a floating encoding. */ +typedef struct hmath_value hmath_value; +typedef enum hmath_coefficient_type { + HMATH_COEFFICIENT_FLOAT64 = 0, + HMATH_COEFFICIENT_FLOAT32 = 1, + HMATH_COEFFICIENT_INTEGER = 2, + HMATH_COEFFICIENT_RATIONAL = 3, + HMATH_COEFFICIENT_COMPLEX128 = 4, + HMATH_COEFFICIENT_COMPLEX64 = 5, + HMATH_COEFFICIENT_INT8 = 6, + HMATH_COEFFICIENT_INT16 = 7, + HMATH_COEFFICIENT_INT32 = 8, + HMATH_COEFFICIENT_INT64 = 9, + HMATH_COEFFICIENT_UINT8 = 10, + HMATH_COEFFICIENT_UINT16 = 11, + HMATH_COEFFICIENT_UINT32 = 12, + HMATH_COEFFICIENT_UINT64 = 13, + HMATH_COEFFICIENT_INTP = 14, + HMATH_COEFFICIENT_UINTP = 15 +} hmath_coefficient_type; +/* Kinds: 0 None, 1 scalar coefficient, 2 Haskell Int, 3 Boolean, + * 4 list, 5 tuple, 6 polynomial, 7 power series, 8 rational function, + * 9 dense matrix, 10 String (Unicode codepoints); other documented domains reserve additional + * opaque kinds. dtype=-1 means not a coefficient-bearing object. count is logical length. info is a + * metadata query and does not alter last-error state. */ +HMATH_API hmath_status hmath_value_info(const hmath_value *value, int *kind, int *dtype, + size_t *count); +HMATH_API void hmath_value_retain(hmath_value *value); +HMATH_API void hmath_value_release(hmath_value *value); +HMATH_API hmath_status hmath_value_f32(hmath_context *context, float value, hmath_value **out); +HMATH_API hmath_status hmath_value_f64(hmath_context *context, double value, hmath_value **out); +HMATH_API hmath_status hmath_value_complex_f32(hmath_context *context, float real, float imaginary, + hmath_value **out); +HMATH_API hmath_status hmath_value_complex_f64(hmath_context *context, double real, + double imaginary, hmath_value **out); +HMATH_API hmath_status hmath_value_integer(hmath_context *context, const char *decimal, + hmath_value **out); +HMATH_API hmath_status hmath_value_integral(hmath_context *context, hmath_coefficient_type dtype, + const char *decimal, hmath_value **out); +HMATH_API hmath_status hmath_value_rational(hmath_context *context, const char *numerator, + const char *denominator, hmath_value **out); +HMATH_API hmath_status hmath_value_index(hmath_context *context, ptrdiff_t value, + hmath_value **out); +HMATH_API hmath_status hmath_value_boolean(hmath_context *context, int value, hmath_value **out); +HMATH_API hmath_status hmath_value_none(hmath_context *context, hmath_value **out); +HMATH_API hmath_status hmath_value_list(hmath_context *context, const hmath_value *const *items, + size_t count, hmath_value **out); +HMATH_API hmath_status hmath_value_tuple(hmath_context *context, const hmath_value *const *items, + size_t count, hmath_value **out); +HMATH_API hmath_status hmath_value_item(hmath_context *context, const hmath_value *sequence, + ptrdiff_t index, hmath_value **out); +/* Typed scalar accessors reject mismatched coefficient types; no narrowing. + * Real scalar getters set imaginary to zero. Both output pointers are required. + * Exact getter returns two owned decimal strings (denominator=1 for integers). + * Release returned strings with hmath_value_string_free. */ +HMATH_API hmath_status hmath_value_get_f32(const hmath_value *value, float *real, float *imaginary); +HMATH_API hmath_status hmath_value_get_f64(const hmath_value *value, double *real, + double *imaginary); +HMATH_API hmath_status hmath_value_get_exact(const hmath_value *value, char **numerator, + char **denominator); +HMATH_API hmath_status hmath_value_get_index(const hmath_value *value, ptrdiff_t *out); +HMATH_API hmath_status hmath_value_get_boolean(const hmath_value *value, int *out); +/* String uses Unicode codepoints, not UTF-8 bytes: preserves embedded NUL and + * every Haskell Char, including surrogate codepoints, without normalization. */ +HMATH_API hmath_status hmath_value_text(hmath_context *context, const uint32_t *codepoints, + size_t count, hmath_value **out); +HMATH_API hmath_status hmath_value_get_text(const hmath_value *value, uint32_t *out, + size_t capacity); +HMATH_API void hmath_value_string_free(char *value); +#ifdef __cplusplus +} +#endif +#endif diff --git a/meson.build b/meson.build index 5c9d7d2..a2a6abb 100644 --- a/meson.build +++ b/meson.build @@ -33,17 +33,89 @@ if get_option('offline') build_args += ['--offline'] endif hmath_sources = files( - 'hmath.cabal', 'cabal.project', + 'cbits/algebra.c', + 'cbits/autodiff_bindings.c', 'cbits/backend.c', + 'cbits/buffer.c', + 'cbits/bytes.c', + 'cbits/deeplearning.c', + 'cbits/error_wire.c', + 'cbits/execution.c', + 'cbits/expression.c', + 'cbits/foundation.c', + 'cbits/geometry.c', + 'cbits/graph_bindings.c', + 'cbits/image.c', + 'cbits/interchange.c', 'cbits/interchange_io.c', + 'cbits/linear.c', + 'cbits/machinelearning.c', + 'cbits/matrix_bindings.c', + 'cbits/matrix_internal.h', + 'cbits/matrix_value.c', 'cbits/native.c', 'cbits/native_dlpack.c', 'cbits/native_internal.h', + 'cbits/numeric_generated.c', + 'cbits/numeric_internal.h', + 'cbits/numeric_objects.c', + 'cbits/numeric_types.c', + 'cbits/numerical.c', + 'cbits/optimization.c', + 'cbits/optimization_all.c', + 'cbits/polynomial.c', + 'cbits/rotations.c', 'cbits/runtime.c', + 'cbits/scalar_extras.c', + 'cbits/shape.c', + 'cbits/spectral.c', + 'cbits/stochastic.c', + 'cbits/tensor_bindings.c', + 'cbits/timeseries.c', + 'cbits/units.c', + 'cbits/value.c', + 'cbits/value_internal.h', + 'hmath.cabal', 'include/hmath.h', + 'include/hmath_algebra.h', + 'include/hmath_autodiff.h', 'include/hmath_backend.h', + 'include/hmath_buffer.h', + 'include/hmath_bytes.h', + 'include/hmath_callback.h', + 'include/hmath_deeplearning.h', 'include/hmath_dlpack.h', + 'include/hmath_error.h', + 'include/hmath_execution.h', + 'include/hmath_expression.h', + 'include/hmath_expression_error.h', + 'include/hmath_foundation.h', + 'include/hmath_geometry.h', + 'include/hmath_graph.h', + 'include/hmath_image.h', + 'include/hmath_interchange.h', + 'include/hmath_interchange_error.h', + 'include/hmath_linear.h', + 'include/hmath_machinelearning.h', + 'include/hmath_matrix.h', + 'include/hmath_matrix_value.h', + 'include/hmath_numeric.h', + 'include/hmath_numeric_objects.h', + 'include/hmath_numeric_types.h', + 'include/hmath_numerical.h', + 'include/hmath_optimization.h', + 'include/hmath_optimization_all.h', + 'include/hmath_polynomial.h', + 'include/hmath_rotations.h', + 'include/hmath_scalar_extras.h', + 'include/hmath_shape.h', + 'include/hmath_spectral.h', + 'include/hmath_stochastic.h', + 'include/hmath_tensor_bindings.h', + 'include/hmath_timeseries.h', + 'include/hmath_units.h', + 'include/hmath_value.h', 'src/HMath.hs', 'src/HMath/API.hs', 'src/HMath/API/Algebra.hs', @@ -69,6 +141,59 @@ hmath_sources = files( 'src/HMath/Error.hs', 'src/HMath/Expression.hs', 'src/HMath/FFI.hs', + 'src/HMath/FFI/AlgebraAll.hs', + 'src/HMath/FFI/AlgebraCodec.hs', + 'src/HMath/FFI/Autodiff.hs', + 'src/HMath/FFI/AutodiffChecked.hs', + 'src/HMath/FFI/AutodiffValue.hs', + 'src/HMath/FFI/Boundary.hs', + 'src/HMath/FFI/Buffer.hs', + 'src/HMath/FFI/Buffer/Codec.hs', + 'src/HMath/FFI/Bytes.hs', + 'src/HMath/FFI/Coefficient.hs', + 'src/HMath/FFI/DeepLearning.hs', + 'src/HMath/FFI/Execution.hs', + 'src/HMath/FFI/Expression.hs', + 'src/HMath/FFI/Foundation.hs', + 'src/HMath/FFI/FoundationCodec.hs', + 'src/HMath/FFI/Geometry.hs', + 'src/HMath/FFI/Graph.hs', + 'src/HMath/FFI/GraphCodec.hs', + 'src/HMath/FFI/Image.hs', + 'src/HMath/FFI/InterchangeAll.hs', + 'src/HMath/FFI/InterchangeCodec.hs', + 'src/HMath/FFI/InterchangeElement.hs', + 'src/HMath/FFI/InterchangeError.hs', + 'src/HMath/FFI/LinearAll.hs', + 'src/HMath/FFI/LinearCodec.hs', + 'src/HMath/FFI/MachineLearning.hs', + 'src/HMath/FFI/MachineLearning/Codec.hs', + 'src/HMath/FFI/MachineLearning/Types.hs', + 'src/HMath/FFI/MathError.hs', + 'src/HMath/FFI/Matrix.hs', + 'src/HMath/FFI/MatrixValue.hs', + 'src/HMath/FFI/Numeric.hs', + 'src/HMath/FFI/NumericObjects.hs', + 'src/HMath/FFI/NumericTypes.hs', + 'src/HMath/FFI/NumericTypes/Core.hs', + 'src/HMath/FFI/NumericalAll.hs', + 'src/HMath/FFI/NumericalCodec.hs', + 'src/HMath/FFI/OptimizationAll.hs', + 'src/HMath/FFI/Optimizer.hs', + 'src/HMath/FFI/Ordering.hs', + 'src/HMath/FFI/Polynomial.hs', + 'src/HMath/FFI/RandomCodec.hs', + 'src/HMath/FFI/Rotations.hs', + 'src/HMath/FFI/ScalarExtras.hs', + 'src/HMath/FFI/ShapeAll.hs', + 'src/HMath/FFI/ShapeCodec.hs', + 'src/HMath/FFI/SpectralAll.hs', + 'src/HMath/FFI/Stochastic.hs', + 'src/HMath/FFI/TensorAll.hs', + 'src/HMath/FFI/TensorCodec.hs', + 'src/HMath/FFI/TimeSeries.hs', + 'src/HMath/FFI/Units.hs', + 'src/HMath/FFI/Value.hs', 'src/HMath/Fourier.hs', 'src/HMath/Geometry.hs', 'src/HMath/Geometry/Collision.hs', @@ -149,6 +274,7 @@ hmath_sources = files( 'src/HMath/Trigonometry.hs', 'src/HMath/Units.hs', 'src/HMath/Vector.hs', + ) # The ABI epoch is independent of the package release version. @@ -164,7 +290,7 @@ hmath = custom_target('hmath', output: library_names, input: hmath_sources, build_by_default: true, console: true, install: true, install_dir: get_option('libdir'), install_tag: 'runtime') hmath_library = hmath[0] -install_headers('include/hmath.h', 'include/hmath_dlpack.h') +install_headers('include/hmath.h', 'include/hmath_algebra.h', 'include/hmath_autodiff.h', 'include/hmath_buffer.h', 'include/hmath_bytes.h', 'include/hmath_callback.h', 'include/hmath_deeplearning.h', 'include/hmath_dlpack.h', 'include/hmath_error.h', 'include/hmath_execution.h', 'include/hmath_expression.h', 'include/hmath_expression_error.h', 'include/hmath_foundation.h', 'include/hmath_geometry.h', 'include/hmath_graph.h', 'include/hmath_image.h', 'include/hmath_interchange.h', 'include/hmath_interchange_error.h', 'include/hmath_linear.h', 'include/hmath_machinelearning.h', 'include/hmath_matrix.h', 'include/hmath_matrix_value.h', 'include/hmath_numeric.h', 'include/hmath_numeric_objects.h', 'include/hmath_numeric_types.h', 'include/hmath_numerical.h', 'include/hmath_optimization.h', 'include/hmath_optimization_all.h', 'include/hmath_polynomial.h', 'include/hmath_rotations.h', 'include/hmath_scalar_extras.h', 'include/hmath_shape.h', 'include/hmath_spectral.h', 'include/hmath_stochastic.h', 'include/hmath_tensor_bindings.h', 'include/hmath_timeseries.h', 'include/hmath_units.h', 'include/hmath_value.h') install_data('LICENSE', install_dir: get_option('datadir') / 'licenses/hmath') hmath_dep = declare_dependency(link_with: hmath_library, include_directories: include_directories('include')) meson.override_dependency('hmath', hmath_dep) @@ -203,6 +329,132 @@ if get_option('tests') dependencies: hmath_dep, override_options: ['c_std=c99'], build_rpath: meson.current_build_dir()) test('hmath-c99-header', header_test) + numeric_contracts = executable('hmath-numeric-contracts', 'test/native/numeric_contracts.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-numeric-contracts', numeric_contracts) + matrix_contracts = executable('hmath-matrix-contracts', 'test/native/matrix_contracts.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-matrix-contracts', matrix_contracts) + ad_contracts = executable('hmath-autodiff-contracts', 'test/native/autodiff_contracts.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-autodiff-contracts', ad_contracts) + storage_contracts = executable('hmath-kernel-storage', + ['test/native/kernel_storage.c', 'cbits/native.c', 'cbits/error_wire.c'], + dependencies: dependency('threads'), + include_directories: include_directories('include', 'cbits')) + test('hmath-kernel-storage', storage_contracts) + + if add_languages('cpp', required: false) + numeric_cpp = executable('hmath-numeric-cpp', 'test/native/numeric_contracts.cpp', + dependencies: hmath_dep, override_options: ['cpp_std=c++17'], + build_rpath: meson.current_build_dir()) + test('hmath-numeric-cpp', numeric_cpp) + foreach contract : ['tensor_contracts', 'deeplearning_contracts', 'autodiff_checked_contracts', 'foundation_contracts', 'interchange_contracts'] + cpp_client = executable('hmath-' + contract + '-cpp', 'test/native/' + contract + '.cpp', + dependencies: hmath_dep, override_options: ['cpp_std=c++17'], + build_rpath: meson.current_build_dir()) + test('hmath-' + contract + '-cpp', cpp_client) + endforeach + endif + test('hmath-generated-bindings', python, + args: [files('tools/generate_numeric_bindings.py'), '--check']) + foreach domain : ['graph', 'matrix', 'matrix_value', 'polynomial', 'units', 'optimization', 'timeseries', 'rotation', 'image', 'expression', 'linear', 'numerical', 'geometry', 'stochastic', 'spectral', 'foundation', 'algebra', 'shape', 'tensor', 'deeplearning', 'machinelearning', 'interchange'] + test('hmath-generated-' + domain, python, + args: [files('tools/generate_' + domain + '_bindings.py'), '--check']) + endforeach + foreach domain : ['matrix_value', 'polynomial', 'numeric_types', 'graph', 'optimization', 'units', 'rotation', 'timeseries', 'image', 'expression', 'linear', 'geometry', 'stochastic', 'numerical', 'spectral', 'structural_matrix', 'foundation', 'algebra', 'shape', 'machinelearning', 'tensor', 'deeplearning'] + test('hmath-' + domain + '-equivalence', python, + args: [files('tools/check_' + domain + '_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + endforeach + test('hmath-interchange-bindings-equivalence', python, + args: [files('tools/check_interchange_bindings_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + foreach domain : ['value', 'polynomial', 'optimization', 'units', 'expression', 'linear', 'stochastic', 'numerical', 'spectral', 'foundation', 'tensor', 'deeplearning', 'interchange'] + test('hmath-' + domain + '-python', python, + args: [files('test/native/' + domain + '_bindings.py')], + env: {'HMATH_LIBRARY': hmath_library.full_path(), 'PYTHONPATH': meson.current_source_dir() / 'bindings/python'}, depends: hmath) + endforeach + foreach contract : ['numeric_variants', 'polynomial_contracts', 'execution_smoke', 'numeric_types', 'rotations', 'optimization_contracts', 'structured_contracts', 'image', 'expression_contracts', 'geometry', 'stochastic_contracts', 'linear_contracts', 'foundation_contracts', 'structural_matrix_contracts', 'machinelearning', 'tensor_contracts', 'deeplearning_contracts', 'autodiff_checked_contracts', 'spectral_contracts', 'scalar_extras', 'interchange_contracts'] + client = executable('hmath-' + contract, 'test/native/' + contract + '.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-' + contract, client) + endforeach + test('hmath-callback-errors', python, + args: [files('test/native/callback_errors.py')], + env: {'HMATH_LIBRARY': hmath_library.full_path(), 'PYTHONPATH': meson.current_source_dir() / 'bindings/python'}, depends: hmath) + test('hmath-release-candidate', python, args: [files('test/release_candidate.py')]) + test('hmath-release-publishing', python, args: [files('test/release_publishing.py')]) + test('hmath-scalar-extras', python, args: [files('tools/check_scalar_extras.py'), '--library', hmath_library.full_path()], depends: hmath, timeout: 300) + test('hmath-generated-scalar-extras', python, args: [files('tools/generate_scalar_extras.py'), '--check']) + test('hmath-generated-numeric-types', python, args: [files('tools/generate_numeric_types.py'), '--check']) + test('hmath-generated-numeric-objects', python, + args: [files('tools/generate_numeric_objects.py'), '--check']) + test('hmath-numeric-objects-equivalence', python, + args: [files('tools/check_numeric_objects_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + test('hmath-numeric-equality-equivalence', python, + args: [files('tools/check_numeric_equality.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + numeric_objects_client = executable('hmath-numeric-objects-contracts', 'test/native/numeric_objects_contracts.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-numeric-objects-contracts', numeric_objects_client) + if add_languages('cpp', required: false) + numeric_objects_cpp = executable('hmath-numeric-objects-contracts-cpp', 'test/native/numeric_objects_contracts.cpp', + dependencies: hmath_dep, override_options: ['cpp_std=c++17'], + build_rpath: meson.current_build_dir()) + test('hmath-numeric-objects-contracts-cpp', numeric_objects_cpp) + endif + + test('hmath-generated-buffer', python, + args: [files('tools/generate_buffer_bindings.py'), '--check']) + test('hmath-buffer-equivalence', python, + args: [files('tools/check_buffer_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + buffer_client = executable('hmath-buffer-contracts', 'test/native/buffer_contracts.c', + dependencies: hmath_dep, override_options: ['c_std=c99'], + build_rpath: meson.current_build_dir()) + test('hmath-buffer-contracts', buffer_client) + if add_languages('cpp', required: false) + buffer_cpp = executable('hmath-buffer-contracts-cpp', 'test/native/buffer_contracts.cpp', + dependencies: hmath_dep, override_options: ['cpp_std=c++17'], + build_rpath: meson.current_build_dir()) + test('hmath-buffer-contracts-cpp', buffer_cpp) + endif + + test('hmath-binding-coverage', python, + args: [files('tools/check_binding_coverage.py')]) + test('hmath-expanded-python', python, + args: [files('test/native/expanded_bindings.py')], + env: {'HMATH_LIBRARY': hmath_library.full_path()}, depends: hmath) + oracle_optimization = '2' + if buildtype == 'debug' + oracle_optimization = '0' + elif buildtype == 'minsize' + oracle_optimization = '1' + endif + test('hmath-numeric-equivalence', python, + args: [files('tools/check_numeric_equivalence.py'), '--library', hmath_library.full_path(), '--oracle-builddir', meson.current_build_dir() / 'numeric-oracle', '--optimization', oracle_optimization], + depends: hmath, timeout: 300) + test('hmath-matrix-equivalence', python, + args: [files('tools/check_matrix_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + test('hmath-autodiff-equivalence', python, + args: [files('tools/check_autodiff_equivalence.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + test('hmath-autodiff-coefficients', python, + args: [files('tools/check_autodiff_coefficients.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 300) + test('hmath-autodiff-python', python, + args: [files('test/native/autodiff_bindings.py')], + env: {'HMATH_LIBRARY': hmath_library.full_path()}, depends: hmath) + + if host_machine.system() != 'windows' contract_test = executable('hmath-native-contracts', 'test/native/contracts.c', dependencies: [hmath_dep, dependency('threads')], @@ -216,6 +468,11 @@ if get_option('tests') if not get_option('python_bindings').disabled() python_modules = run_command(python, '-c', 'import numpy, cffi', check: false) if python_modules.returncode() == 0 + if get_option('native_backend') and host_machine.system() == 'linux' + test('hmath-execution', python, + args: [files('tools/check_execution.py'), '--library', hmath_library.full_path()], + depends: hmath, timeout: 180) + endif test('hmath-python-bindings', python, args: [files('bindings/python/test_bindings.py')], env: {'HMATH_LIBRARY': hmath_library.full_path()}, depends: hmath) test('hmath-numpy-dlpack', python, args: [files('test/native/dlpack_numpy.py')], diff --git a/mkdocs.yml b/mkdocs.yml index 5ffadb1..8c6d2ed 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -67,9 +67,42 @@ nav: - Numerical conventions: explanation/numerical-conventions.md - Compatibility and releases: explanation/releases.md - Contributing: contributing.md + - Release process: guides/releasing.md - API Reference: - Python API: reference/python.md - C ABI: reference/c.md + - Exact numeric types: reference/numeric-types.md + - Numeric type functions: reference/numeric-type-functions.md + - Exact units: reference/units-values.md + - Error contracts: reference/errors.md + - Quaternions and rotations: reference/rotations.md + - Time series: reference/timeseries-bindings.md + - Structured values: reference/values.md + - Polynomial bindings: reference/polynomial.md + - Generic matrix values: reference/matrix-values.md + - Image bindings: reference/image-bindings.md + - Expressions and symbolic algebra: reference/expression-bindings.md + - Extended linear algebra: reference/linear-bindings.md + - Probability and random generators: reference/stochastic.md + - Signal, Fourier and interpolation: reference/spectral-bindings.md + - Geometry: reference/geometry-bindings.md + - Numerical solvers: reference/numerical-solvers.md + - Graph bindings: reference/graph-bindings.md + - Numeric bindings: reference/numeric-bindings.md + - Generic numeric instances: reference/numeric-objects.md + - Foundation collections: reference/foundation.md + - Algebra and exact domains: reference/algebra-values.md + - Static shapes: reference/shapes.md + - Typed tensor operations: reference/tensor-bindings.md + - Deep learning: reference/deeplearning-bindings.md + - Machine learning: reference/machinelearning-bindings.md + - Complex and special functions: reference/scalar-extras.md + - Array and file interchange: reference/interchange-bindings.md + - Matrix bindings: reference/matrix-bindings.md + - Autodiff bindings: reference/autodiff-bindings.md + - Buffer execution: reference/execution.md + - Typed storage buffers: reference/buffer-bindings.md + - Optimizer bindings: reference/optimization-bindings.md - Wave API: reference/wave.md - Haskell API: reference/haskell.md - QR contracts (Haskell): reference/qr.md diff --git a/src/HMath/FFI/AlgebraAll.hs b/src/HMath/FFI/AlgebraAll.hs new file mode 100644 index 0000000..f2639a7 --- /dev/null +++ b/src/HMath/FFI/AlgebraAll.hs @@ -0,0 +1,248 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated direct calls into the two distinct original algebra interfaces. +module HMath.FFI.AlgebraAll where +import Prelude hiding(readList) +import Foreign +import Foreign.C +import qualified HMath.Algebra as A +import qualified HMath.API.Algebra as P +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec +import HMath.FFI.AlgebraCodec +import qualified HMath.FFI.TensorCodec as TensorCodec +apply :: Int -> [V.Value] -> IO V.Value +apply operation args=case(operation,args) of + (0,[prototype,a0,a1]) -> withModule prototype $ \wire -> do + zeroVector <- readList(readWire wire)a0;terms <- readList(\v -> V.asTuple 2 v >>= \parts -> case parts of {[s,x] -> (,) <$>readWire wire s <*>readList(readWire wire)x;_ -> V.invalid "module term arity differs"})a1;source(A.linearCombination zeroVector terms) >>= list(writeWire wire) + (1,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readList(\x -> readWire wire x) a0 + list(\x -> (\(field1,field2) -> V.Tuple <$> sequence [pure(V.Text field1),pure(V.Boolean field2)]) x) (A.semiringLaws x0) + (2,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readList(\x -> readWire wire x) a0 + list(\x -> (\(field3,field4) -> V.Tuple <$> sequence [pure(V.Text field3),pure(V.Boolean field4)]) x) (A.ringLaws x0) + (3,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readList(\x -> readWire wire x) a0 + oldField domain $ list(\x -> (\(field5,field6) -> V.Tuple <$> sequence [pure(V.Text field5),pure(V.Boolean field6)]) x) (A.fieldLaws x0) + (4,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readList(\x -> asAdditiveWire wire x) a0 + pairs(A.groupLaws x0) + (5,[prototype,a0,a1]) -> withModule prototype $ \wire -> do + xs <- readList(readWire wire)a0;ys <- readList(readList(readWire wire))a1;pairs(A.moduleLaws xs ys) + (6,[a0,a1]) -> do + x0 <- V.asScalar a0 + x1 <- V.asScalar a1 + source (A.modular x0 x1) >>= \result -> pure(modular result) + (7,[a0]) -> do + x0 <- asModular a0 + pure(V.Scalar SInteger (A.modularValue x0)) + (8,[a0]) -> do + x0 <- asModular a0 + pure(V.Scalar SInteger (A.modularModulus x0)) + (9,[a0,a1]) -> do + x0 <- asModular a0 + x1 <- asModular a1 + source (A.addModular x0 x1) >>= \result -> pure(modular result) + (10,[a0,a1]) -> do + x0 <- asModular a0 + x1 <- asModular a1 + source (A.subtractModular x0 x1) >>= \result -> pure(modular result) + (11,[a0,a1]) -> do + x0 <- asModular a0 + x1 <- asModular a1 + source (A.multiplyModular x0 x1) >>= \result -> pure(modular result) + (12,[a0]) -> do + x0 <- asModular a0 + source (A.inverseModular x0) >>= \result -> pure(modular result) + (13,[a0,a1]) -> do + x0 <- asModular a0 + x1 <- V.asScalar a1 + source (A.powerModular x0 x1) >>= \result -> pure(modular result) + (14,[a0,a1,a2]) -> do + x0 <- V.asIndex a0 + x1 <- V.asScalar a1 + x2 <- readList(\x -> V.asScalar x) a2 + source (A.finiteField x0 x1 x2) >>= \result -> pure(finiteField result) + (15,[a0,a1]) -> do + x0 <- V.asIndex a0 + x1 <- V.asScalar a1 + source (A.primeField x0 x1) >>= \result -> pure(finiteField result) + (16,[a0]) -> do + x0 <- asFiniteField a0 + pure(V.Scalar SInteger (A.fieldCharacteristic x0)) + (17,[a0]) -> do + x0 <- asFiniteField a0 + pure(V.Index (A.fieldDegree x0)) + (18,[a0]) -> do + x0 <- asFiniteField a0 + pure(V.Scalar SInteger (A.fieldCardinality x0)) + (19,[a0]) -> do + x0 <- asFiniteField a0 + list(\x -> pure(V.Scalar SInteger x)) (A.fieldModulus x0) + (20,[a0,a1]) -> do + x0 <- asFiniteField a0 + x1 <- readList(\x -> V.asScalar x) a1 + pure(fieldElement (A.fieldElement x0 x1)) + (21,[a0]) -> do + x0 <- asFieldElement a0 + list(\x -> pure(V.Scalar SInteger x)) (A.fieldElementCoefficients x0) + (22,[a0,a1]) -> do + x0 <- V.asIndex a0 + x1 <- asFiniteField a1 + source (A.fieldElements x0 x1) >>= \result -> list(\x -> pure(fieldElement x)) result + (23,[a0,a1]) -> do + x0 <- asFieldElement a0 + x1 <- asFieldElement a1 + source (A.addField x0 x1) >>= \result -> pure(fieldElement result) + (24,[a0]) -> do + x0 <- asFieldElement a0 + pure(fieldElement (A.negateField x0)) + (25,[a0,a1]) -> do + x0 <- asFieldElement a0 + x1 <- asFieldElement a1 + source (A.subtractField x0 x1) >>= \result -> pure(fieldElement result) + (26,[a0,a1]) -> do + x0 <- asFieldElement a0 + x1 <- asFieldElement a1 + source (A.multiplyField x0 x1) >>= \result -> pure(fieldElement result) + (27,[a0]) -> do + x0 <- asFieldElement a0 + source (A.inverseFieldElement x0) >>= \result -> pure(fieldElement result) + (28,[a0,a1]) -> do + x0 <- asFieldElement a0 + x1 <- V.asScalar a1 + source (A.powerField x0 x1) >>= \result -> pure(fieldElement result) + (29,[a0,a1]) -> do + x0 <- V.asIndex a0 + x1 <- asFiniteField a1 + source (A.finiteFieldLaws x0 x1) >>= \result -> list(\x -> (\(field9,field10) -> V.Tuple <$> sequence [pure(V.Text field9),pure(V.Boolean field10)]) x) result + (30,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- asAdditiveWire wire a0 + writeWire wire (A.getAdditive x0) + (31,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readWire wire a0 + pure(additive domain (A.Additive x0)) + (32,[prototype,a0,a1]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readList(\x -> readWire wire x) a0 + x1 <- readWire wire a1 + writeWire wire (P.horner x0 x1) + (33,[prototype,a0,a1]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readList(\x -> readWire wire x) a0 + x1 <- readList(\x -> readWire wire x) a1 + source (P.innerProduct x0 x1) >>= \result -> writeWire wire result + (34,[a0]) -> do + x0 <- unbox "HMath.API.Algebra.Exact" a0 + pure(V.Scalar SRational (P.getExact x0)) + (35,[a0]) -> do + x0 <- V.asScalar a0 + pure(exact (P.Exact x0)) + (36,[prototype]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + writeWire wire (A.zero) + (37,[prototype]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + writeWire wire (A.one) + (38,[prototype,a0,a1]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readWire wire a0 + x1 <- readWire wire a1 + writeWire wire (A.plus x0 x1) + (39,[prototype,a0,a1]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readWire wire a0 + x1 <- readWire wire a1 + writeWire wire (A.times x0 x1) + (40,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readWire wire a0 + writeWire wire (A.negateRing x0) + (41,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- readWire wire a0 + oldField domain $ source (A.inverseField x0) >>= \result -> writeWire wire result + (42,[prototype]) -> withOld prototype $ \domain -> do + pure(additive domain A.groupIdentity) + (43,[prototype,a0,a1]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- asAdditiveWire wire a0 + x1 <- asAdditiveWire wire a1 + pure(additive domain (A.groupCombine x0 x1)) + (44,[prototype,a0]) -> withOld prototype $ \domain -> do + let wire=oldWire domain + x0 <- asAdditiveWire wire a0 + pure(additive domain (A.groupInverse x0)) + (45,[prototype,a0,a1]) -> withModule prototype $ \wire -> do + x <- readWire wire a0;xs <- readList(readWire wire)a1;list(writeWire wire)(A.moduleScale x xs) + (46,[prototype,a0,a1]) -> withModule prototype $ \wire -> do + xs <- readList(readWire wire)a0;ys <- readList(readWire wire)a1;source(A.moduleAdd xs ys) >>= list(writeWire wire) + (47,[prototype]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + writeWire wire (P.zero) + (48,[prototype]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + writeWire wire (P.one) + (49,[prototype,a0,a1]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + x1 <- readWire wire a1 + writeWire wire (P.plus x0 x1) + (50,[prototype,a0,a1]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + x1 <- readWire wire a1 + writeWire wire (P.times x0 x1) + (51,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + writeWire wire (P.negative x0) + (52,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- V.asScalar a0 + writeWire wire (P.integer x0) + (53,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + apiField domain $ source (P.invert x0) >>= \result -> writeWire wire result + (54,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + writeWire wire (P.conjugateScalar x0) + (55,[prototype]) -> withAPI prototype $ \domain -> do + apiFloating domain $ pure(V.Scalar SDouble (apiEpsilon domain)) + (56,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- readWire wire a0 + apiFloating domain $ pure(V.Boolean (P.finiteScalar x0)) + (57,[prototype,a0]) -> withAPI prototype $ \domain -> do + let wire=apiWire domain + x0 <- V.asScalar a0 + source (P.rational x0) >>= \result -> writeWire wire result + (58,[a0]) -> withMatrix a0 $ \_ matrixValue -> pure(\(r,c) -> V.Tuple[V.Index r,V.Index c]) <*> pure(P.matrixDimensions matrixValue) + (59,[a0]) -> withMatrix a0 $ \wire matrixValue -> list(writeWire wire)(P.matrixElements matrixValue) + (60,[prototype,a0,a1,a2]) -> do {r <- V.asIndex a0;c <- V.asIndex a1;xs <- V.asList a2;matrixConstruct prototype r c xs} + (61,[a0]) -> tensorDimensions a0 + (62,[a0]) -> tensorElements a0 + (63,[prototype,a0,a1]) -> do {ds <- V.asList a0 >>= mapM V.asIndex;xs <- V.asList a1;tensorConstruct prototype ds xs} + (64,[prototype,a0,a1]) -> vectorPlus prototype a0 a1 + (65,[prototype,a0,a1]) -> vectorScale prototype a0 a1 + (66,[a0]) -> differential a0 + (-1,[]) -> pure(TensorCodec.prototype exactElement) + _ -> V.invalid "invalid algebra operation/arity" +foreign export ccall "hm_algebra_apply" ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(V.publish value out)) diff --git a/src/HMath/FFI/AlgebraCodec.hs b/src/HMath/FFI/AlgebraCodec.hs new file mode 100644 index 0000000..aba8c64 --- /dev/null +++ b/src/HMath/FFI/AlgebraCodec.hs @@ -0,0 +1,191 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE FlexibleContexts #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Actual original algebra dictionaries and lossless foreign representations. +module HMath.FFI.AlgebraCodec where + +import Control.Exception (evaluate) +import Data.Typeable (Typeable,cast) +import Data.Proxy (Proxy(..)) +import qualified HMath.Algebra as A +import qualified HMath.API.Algebra as P +import qualified HMath.Polynomial as Poly +import qualified HMath.FFI.Polynomial as Polynomial +import qualified HMath.FFI.Value as V +import qualified HMath.Matrix as Matrix +import qualified HMath.Vector as Vector +import qualified HMath.Autodiff as AD +import qualified HMath.Error as E +import qualified HMath.FFI.Autodiff as ADWire +import qualified HMath.FFI.AutodiffValue as ADValue +import qualified HMath.FFI.LinearCodec as Linear +import qualified HMath.FFI.TensorCodec as Tensor +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec + +data Wire a=Wire (a -> IO V.Value) (V.Value -> IO a) (a -> IO ()) Int +writeWire :: Wire a -> a -> IO V.Value +writeWire(Wire write _ _ _)=write +readWire :: Wire a -> V.Value -> IO a +readWire(Wire _ readValue _ _)=readValue +forceWire :: Wire a -> a -> IO () +forceWire(Wire _ _ force _)=force +wireCode :: Wire a -> Int +wireCode(Wire _ _ _ code)=code +coefficientWire :: Coefficient a => ScalarType a -> Wire a +coefficientWire w=Wire(pure . V.Scalar w)V.asScalar forceCoefficient(scalarTypeCode w) +polynomialWire :: Coefficient a => ScalarType a -> Wire(Poly.Polynomial a) +polynomialWire w=Wire(pure . Polynomial.poly w)Polynomial.asPolynomial(mapM_ forceCoefficient . Poly.coefficients)(scalarTypeCode w) +exactWire :: Wire P.Exact +exactWire=Wire(pure . exact)(unbox "HMath.API.Algebra.Exact")(forceCoefficient . P.getExact)18 +exact :: P.Exact -> V.Value +exact value=opaqueEq "HMath.API.Algebra.Exact" 18 value(forceCoefficient(P.getExact value))(pure(V.Tuple[V.Text "Exact",V.Tuple[V.Scalar SRational(P.getExact value)]])) + +data OldWire a where + OldWire :: (Typeable a,Eq a,A.Ring a) => Wire a -> Maybe(Dict(A.Field a)) -> OldWire a +withOld :: V.Value -> (forall a. (Typeable a,Eq a,A.Ring a) => OldWire a -> IO V.Value) -> IO V.Value +withOld value action=case value of + V.Scalar SInteger _ -> action(OldWire(coefficientWire SInteger)Nothing) + V.Scalar SRational _ -> action(OldWire(coefficientWire SRational)(Just Dict)) + V.Opaque 6 _ _ _ _ -> Polynomial.withPolynomial value $ \w _ -> action(OldWire(polynomialWire w)Nothing) + V.Opaque 400 _ _ _ _ -> do + name <- objectName value + if name=="HMath.Algebra.Additive" then do + AdditiveBox wire _ <- unbox name value + case wire of OldWire _ _ -> action wire + else V.unsupported "original HMath.Algebra instances are Integer, Rational and Polynomial; Group uses Additive" + _ -> V.unsupported "original HMath.Algebra instances are Integer, Rational and Polynomial" +oldWire :: OldWire a -> Wire a +oldWire(OldWire wire _)=wire +oldField :: OldWire a -> (A.Field a => IO V.Value) -> IO V.Value +oldField(OldWire _ (Just Dict)) action=action +oldField _ _=V.unsupported "original HMath.Algebra.Field instance is Rational" +withModule :: V.Value -> (forall a. (Typeable a,Eq a,A.Module a [a]) => Wire a -> IO V.Value) -> IO V.Value +withModule (V.Scalar SInteger _) action=action(coefficientWire SInteger) +withModule (V.Scalar SRational _) action=action(coefficientWire SRational) +withModule _ _=V.unsupported "original Module instances are Integer/Rational lists" +data AdditiveBox where + AdditiveBox :: (Typeable a,Eq a,A.Ring a) => OldWire a -> A.Additive a -> AdditiveBox +instance Eq AdditiveBox where + AdditiveBox _ left == AdditiveBox _ right=maybe False(left==)(cast right) +additive :: (Typeable a,Eq a,A.Ring a) => OldWire a -> A.Additive a -> V.Value +additive wire value=opaqueEq "HMath.Algebra.Additive" (wireCode(oldWire wire))(AdditiveBox wire value) force view + where + force=forceWire(oldWire wire)(A.getAdditive value) + view=do x <- writeWire(oldWire wire)(A.getAdditive value);pure(V.Tuple[V.Text "Additive",V.Tuple[x]]) +asAdditive :: forall a. Typeable a => V.Value -> IO(A.Additive a) +asAdditive value=do + AdditiveBox _ payload <- unbox "HMath.Algebra.Additive" value + maybe(V.invalid "Additive ring types differ")pure(cast payload) +asAdditiveWire :: Typeable a => Wire a -> V.Value -> IO(A.Additive a) +asAdditiveWire _=asAdditive + +data APIWire a where + APIWire :: (Typeable a,Eq a,P.Numeric a,P.Scalar a) => Wire a -> Maybe(Dict(P.Field a)) -> Maybe(Dict(P.FloatingPoint a)) -> APIWire a +withAPI :: V.Value -> (forall a. (Typeable a,Eq a,P.Numeric a,P.Scalar a) => APIWire a -> IO V.Value) -> IO V.Value +withAPI value action=case value of + V.Scalar SInteger _ -> action(APIWire(coefficientWire SInteger)Nothing Nothing) + V.Scalar SRational _ -> action(APIWire(coefficientWire SRational)(Just Dict)Nothing) + V.Scalar SFloat _ -> action(APIWire(coefficientWire SFloat)(Just Dict)(Just Dict)) + V.Scalar SDouble _ -> action(APIWire(coefficientWire SDouble)(Just Dict)(Just Dict)) + V.Scalar SComplexDouble _ -> action(APIWire(coefficientWire SComplexDouble)(Just Dict)(Just Dict)) + V.Opaque 400 _ _ _ _ -> do + name <- objectName value + if name=="HMath.API.Algebra.Exact" then action(APIWire exactWire(Just Dict)Nothing) + else V.unsupported "original API.Algebra instance required" + _ -> V.unsupported "original API.Algebra instances are Integer/Rational/Float/Double/Complex Double/Exact" +apiWire :: APIWire a -> Wire a +apiWire(APIWire wire _ _)=wire +apiField :: APIWire a -> (P.Field a => IO V.Value) -> IO V.Value +apiField(APIWire _ (Just Dict) _) action=action +apiField _ _=V.unsupported "original API.Algebra.Field does not include Integer" +apiFloating :: APIWire a -> (P.FloatingPoint a => IO V.Value) -> IO V.Value +apiFloating(APIWire _ _ (Just Dict)) action=action +apiFloating _ _=V.unsupported "original FloatingPoint instances are Float,Double,Complex Double" + +modular :: A.Modular -> V.Value +modular value=opaqueEq "HMath.Algebra.Modular" (-1)value(evaluate value >> pure())(V.unsupported "original abstract Modular has no public constructor fields") +finiteField :: A.FiniteField -> V.Value +finiteField value=opaqueEq "HMath.Algebra.FiniteField" (-1)value(evaluate value >> pure())(V.unsupported "original abstract FiniteField has no public constructor fields") +fieldElement :: A.FieldElement -> V.Value +fieldElement value=opaqueEq "HMath.Algebra.FieldElement" (-1)value(evaluate value >> pure())(V.unsupported "original abstract FieldElement has no public constructor fields") +asModular :: V.Value -> IO A.Modular +asModular=unbox "HMath.Algebra.Modular" +asFiniteField :: V.Value -> IO A.FiniteField +asFiniteField=unbox "HMath.Algebra.FiniteField" +asFieldElement :: V.Value -> IO A.FieldElement +asFieldElement=unbox "HMath.Algebra.FieldElement" + +list :: (a -> IO V.Value) -> [a] -> IO V.Value +list write values=V.List <$> mapM write values +readList :: (V.Value -> IO a) -> V.Value -> IO[a] +readList readValue value=V.asList value >>= mapM readValue +pairs :: [(String,Bool)] -> IO V.Value +pairs values=pure(V.List[V.Tuple[V.Text name,V.Boolean result]|(name,result)<-values]) +apiEpsilon :: forall a. P.FloatingPoint a => APIWire a -> Double +apiEpsilon _=P.machineEpsilon(Proxy::Proxy a) + +matrix :: Typeable a => Wire a -> Matrix.Matrix a -> V.Value +matrix wire value=V.Dense(V.StructuralMatrix(wireCode wire)(writeWire wire)(readWire wire)(forceWire wire)value) +withMatrix :: V.Value -> (forall a. Typeable a => Wire a -> Matrix.Matrix a -> IO V.Value) -> IO V.Value +withMatrix (V.Dense(V.SomeMatrix w value)) action=action(coefficientWire w)value +withMatrix (V.Dense(V.StructuralMatrix code write readValue force value)) action=action(Wire write readValue force code)value +withMatrix _ _=V.invalid "expected Matrix" +matrixConstruct :: V.Value -> Int -> Int -> [V.Value] -> IO V.Value +matrixConstruct prototype rows columns values=case prototype of + V.Scalar w _ -> V.Dense . V.SomeMatrix w <$> (mapM V.asScalar values >>= source . P.matrixConstruct rows columns) + V.Boolean _ -> V.booleanMatrix <$> (mapM V.asBoolean values >>= source . P.matrixConstruct rows columns) + V.Text _ -> V.stringMatrix <$> (mapM V.asText values >>= source . P.matrixConstruct rows columns) + _ -> withAPI prototype $ \wire -> matrix(apiWire wire) <$> (mapM(readWire(apiWire wire))values >>= source . P.matrixConstruct rows columns) +tensorConstruct :: V.Value -> [Int] -> [V.Value] -> IO V.Value +tensorConstruct prototype dimensions values=do + Tensor.SomeElement kind <- algebraElement prototype + Tensor.fromTensor kind <$> (mapM(Tensor.asElement kind)values >>= source . P.tensorConstruct dimensions) +exactElement :: Tensor.Element P.Exact +exactElement=Tensor.Structural Tensor.StructuralCodec + { Tensor.structuralCode=18 + , Tensor.structuralEncode=exact + , Tensor.structuralDecode=unbox "HMath.API.Algebra.Exact" + , Tensor.structuralForce=forceCoefficient . P.getExact + , Tensor.structuralOrdering=Just Dict + , Tensor.structuralRead=Nothing + , Tensor.structuralStorable=Nothing + } +algebraElement :: V.Value -> IO Tensor.SomeElement +algebraElement value@(V.Opaque 400 _ _ _ _)=do + name <- objectName value + if name=="HMath.API.Algebra.Exact" then pure(Tensor.SomeElement exactElement) else Tensor.element value +algebraElement value=Tensor.element value +tensorDimensions :: V.Value -> IO V.Value +tensorDimensions value=do Tensor.SomeTensor _ tensor <- Tensor.asTensor value;pure(V.List(map V.Index(P.tensorDimensions tensor))) +tensorElements :: V.Value -> IO V.Value +tensorElements value=do Tensor.SomeTensor kind tensor <- Tensor.asTensor value;pure(V.List(map(Tensor.scalar kind)(P.tensorElements tensor))) +differential :: V.Value -> IO V.Value +differential value=do + ADWire.Tower original <- ADValue.asADTower value + case ADWire.components original of + Just(ADWire.Tower(_::a),_) -> case cast original of + Just dual -> pure(ADValue.fromADTower(ADWire.Tower(P.differential(dual::AD.Dual a)))) + Nothing -> V.invalid "invalid original Dual witness" + Nothing -> V.unsupported "original Differentiable instance requires Autodiff.Dual" +vectorPlus :: V.Value -> V.Value -> V.Value -> IO V.Value +vectorPlus prototype left right=Linear.withWitness prototype $ \(w::ScalarType a) -> case left of + V.Dense _ -> do + a <- V.asMatrix left;b <- V.asMatrix right + V.Dense . V.SomeMatrix w <$> source(P.vectorPlus a b) + _ -> do + a <- Linear.unbox "HMath.Vector.Vector" left + b <- Linear.unbox "HMath.Vector.Vector" right + source(P.vectorPlus a b::Either E.MathError(Vector.Vector a)) >>= Linear.encodeVector w +vectorScale :: V.Value -> V.Value -> V.Value -> IO V.Value +vectorScale prototype scalar value=case value of + V.Dense _ -> Linear.withWitness prototype $ \w -> do + a <- V.asMatrix value; x <- V.asScalar scalar + pure(V.Dense(V.SomeMatrix w(P.vectorScale x a))) + _ -> Linear.withWitness prototype $ \(w::ScalarType a) -> do + a <- Linear.unbox "HMath.Vector.Vector" value + x <- V.asScalar scalar + Linear.encodeVector w(P.vectorScale x (a::Vector.Vector a)) diff --git a/src/HMath/FFI/Autodiff.hs b/src/HMath/FFI/Autodiff.hs new file mode 100644 index 0000000..7bae028 --- /dev/null +++ b/src/HMath/FFI/Autodiff.hs @@ -0,0 +1,462 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE ExistentialQuantification #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE UndecidableInstances #-} + +-- SPDX-License-Identifier: MPL-2.0 +-- | Representation adapters only; all mathematical operations call HMath.Autodiff. +module HMath.FFI.Autodiff where + +import Control.Exception (Exception, bracket, bracketOnError, catch, evaluate, throwIO) +import Data.Coerce (coerce) +import Data.Typeable (Typeable, cast) +import Data.Proxy (Proxy (..)) +import Data.Kind (Constraint) +import Data.Ratio (numerator, denominator, (%)) +import GHC.Float (float2Double) +import Data.Complex (Complex ((:+)), imagPart, realPart) +import Foreign +import Foreign.C +import qualified HMath.Autodiff as A +import qualified HMath.FFI.Coefficient as C +import HMath.Error (MathError (..)) +import HMath.FFI.Boundary hiding (boundary) +import qualified HMath.FFI.Boundary as Boundary +import System.IO.Unsafe (unsafePerformIO) + +-- Existential towers retain the original Dual instance at every nesting depth. +-- No derivative arithmetic or finite check is implemented in the adapter. +data Dict (constraint :: Constraint) where + Dict :: constraint => Dict constraint +class (Typeable a, Eq a, Num a) => TowerValue a where + depth :: a -> Int + baseKind :: a -> CInt + components :: a -> Maybe (Tower,Tower) + fractionalDict :: proxy a -> Maybe (Dict (Fractional a)) + floatingDict :: proxy a -> Maybe (Dict (Floating a)) + orderingDict :: proxy a -> Maybe (Dict (Ord a)) + coefficientLeaf :: a -> Maybe C.SomeCoefficient + coefficientLeaf _ = Nothing +instance {-# OVERLAPPABLE #-} forall a. (Typeable a, Eq a, Num a, C.Coefficient a) => TowerValue a where + depth _ = 0 + baseKind _ = fromIntegral (C.scalarTypeCode (C.scalarType :: C.ScalarType a)) + components _ = Nothing + fractionalDict _ = case C.fractionalDict (Proxy :: Proxy a) of + Just C.Dict -> Just Dict + Nothing -> Nothing + floatingDict _ = case C.floatingDict (Proxy :: Proxy a) of + Just C.Dict -> Just Dict + Nothing -> Nothing + orderingDict _ = case C.orderingDict (Proxy :: Proxy a) of + Just C.Dict -> Just Dict + Nothing -> Nothing + coefficientLeaf value = Just (C.SomeCoefficient C.scalarType value) +instance forall a. (TowerValue a) => TowerValue (A.Dual a) where + depth value = 1 + depth (A.primal value) + baseKind value = baseKind (A.primal value) + components value = Just (Tower (A.primal value),Tower (A.tangent value)) + fractionalDict _ = case fractionalDict (Proxy :: Proxy a) of + Just Dict -> Just Dict + Nothing -> Nothing + floatingDict _ = case floatingDict (Proxy :: Proxy a) of + Just Dict -> Just Dict + Nothing -> Nothing + orderingDict _ = case orderingDict (Proxy :: Proxy a) of + Just Dict -> Just Dict + Nothing -> Nothing +data Tower = forall a. (TowerValue a) => Tower a + +unaryValue :: forall a. (TowerValue a) => Int -> a -> Either MathError a +unaryValue operation value = case operation of + 0 -> Right (negate value) + 1 -> Right (abs value) + 2 -> Right (signum value) + 3 -> case fractionalDict (Proxy :: Proxy a) of + Just Dict -> Right (recip value) + Nothing -> Left (InvalidArgument "Dual scalar type has no Fractional instance") + _ -> case floatingDict (Proxy :: Proxy a) of + Just Dict -> Right (unary operation value) + Nothing -> Left (InvalidArgument "Dual scalar type has no Floating instance") +binaryValue :: forall a. (TowerValue a) => Int -> a -> a -> Either MathError a +binaryValue operation left right = case operation of + 0 -> Right (left+right) + 1 -> Right (left-right) + 2 -> Right (left*right) + 3 -> case fractionalDict (Proxy :: Proxy a) of + Just Dict -> Right (left/right) + Nothing -> Left (InvalidArgument "Dual scalar type has no Fractional instance") + _ -> case floatingDict (Proxy :: Proxy a) of + Just Dict -> Right (binary operation left right) + Nothing -> Left (InvalidArgument "Dual scalar type has no Floating instance") +unaryTower :: Int -> Tower -> Either MathError Tower +unaryTower operation (Tower value) = Tower <$> unaryValue operation value +binaryTower :: Int -> Tower -> Tower -> Either MathError Tower +binaryTower operation (Tower left) (Tower right) = case cast right of + Just other -> Tower <$> binaryValue operation left other + Nothing -> Left (InvalidArgument "mismatched Dual scalar types") +nestTower :: Tower -> Tower -> Either MathError Tower +nestTower (Tower left) (Tower right) = case cast right of + Just other -> Right (Tower (A.Dual left other)) + Nothing -> Left (InvalidArgument "mismatched Dual component types") +flatDual :: Tower -> Either MathError (A.Dual Double) +flatDual (Tower value) = maybe (Left (InvalidArgument "expected Dual Double")) Right (cast value) +towerData :: Tower -> [Double] +towerData (Tower value) = case cast value of + Just number -> [number] + Nothing -> case cast value of + Just dual -> [A.primal (dual :: A.Dual Double),A.tangent dual] + Nothing -> case cast value of + Just number -> [float2Double number] + Nothing -> case cast value of + Just dual -> [float2Double (A.primal (dual :: A.Dual Float)),float2Double (A.tangent dual)] + Nothing -> [] + +-- One stable-pointer type prevents accidental casts between differently typed +-- Haskell heaps. The C facade checks the public kind before every operation. +data Value + = Expression A.Expr + | Graph A.CompiledGraph + | Gradients A.GradientState + | Tensor A.ADTensor + | Dual Tower + +expression :: Value -> Either MathError A.Expr +expression (Expression x) = Right x +expression _ = Left (InvalidArgument "expected AD expression") + +gradients :: Value -> Either MathError A.GradientState +gradients (Gradients x) = Right x +gradients _ = Left (InvalidArgument "expected gradient state") + +tensor :: Value -> Either MathError A.ADTensor +tensor (Tensor x) = Right x +tensor _ = Left (InvalidArgument "expected AD tensor") + +unary :: (Floating a) => Int -> a -> a +unary operation = case operation of + 0 -> negate; 1 -> abs; 2 -> signum; 3 -> recip + 4 -> exp; 5 -> log; 6 -> sqrt; 7 -> sin; 8 -> cos; 9 -> tan + 10 -> asin; 11 -> acos; 12 -> atan; 13 -> sinh; 14 -> cosh + 15 -> tanh; 16 -> asinh; 17 -> acosh; 18 -> atanh + _ -> error "invalid AD unary operation" + +binary :: (Floating a) => Int -> a -> a -> a +binary operation = case operation of + 0 -> (+); 1 -> (-); 2 -> (*); 3 -> (/); 4 -> (**) + _ -> error "invalid AD binary operation" + +foreign export ccall "hm_ad_free" release :: StablePtr Value -> IO () +release :: StablePtr Value -> IO () +release = freeStablePtr + +foreign export ccall "hm_ad_make" + make :: CInt -> Ptr (StablePtr Value) -> CSize -> CPtrdiff -> CDouble -> + Ptr CDouble -> CSize -> Ptr CPtrdiff -> CSize -> Ptr CPtrdiff -> CSize -> + Ptr (StablePtr Value) -> IO CInt +make :: CInt -> Ptr (StablePtr Value) -> CSize -> CPtrdiff -> CDouble -> + Ptr CDouble -> CSize -> Ptr CPtrdiff -> CSize -> Ptr CPtrdiff -> CSize -> + Ptr (StablePtr Value) -> IO CInt +make operation inputs inputCount index scalar xs valueCount dimensions rank axes axisCount out = boundary $ do + arguments <- peekArray (fromIntegral inputCount) inputs >>= mapM deRefStablePtr + values <- peekArray (fromIntegral valueCount) (castPtr xs :: Ptr Double) + shape <- map fromIntegral <$> peekArray (fromIntegral rank) dimensions + otherAxes <- map fromIntegral <$> peekArray (fromIntegral axisCount) axes + let i = fromIntegral index + r = coerce scalar :: Double + result = case (operation, arguments) of + (0, []) -> Right (Expression (A.variable i)) + (1, []) -> Right (Expression (A.constant r)) + (2, []) -> case values of + [a,b] -> Right (Dual (Tower (A.Dual a b))) + _ -> Left (InvalidArgument "dual pair") + (3, [Expression e]) -> Right (Expression (if i == 19 then A.detach e else if i == 20 then A.stopGradient e else unary i e)) + (3, [Dual e]) -> Dual <$> unaryTower i e + (4, [Expression a,Expression b]) -> Right (Expression (binary i a b)) + (4, [Dual a,Dual b]) -> Dual <$> binaryTower i a b + (5, [Expression e]) -> Graph <$> A.compileGraph i e + (6, [Expression e]) -> Expression <$> A.differentiate i e + (7, []) -> Gradients <$> A.zeroGradients i + (8, [Gradients g]) -> Gradients <$> A.accumulateGradients g values + (9, [Gradients g]) -> Right (Gradients (A.resetGradients g)) + (10, []) -> Gradients . A.GradientState <$> A.clipGradient r values + (11, es) -> Tensor <$> (mapM expression es >>= A.adTensor shape) + (12, [Tensor t]) -> Tensor <$> A.adBroadcast shape t + (13, [Tensor a,Tensor b]) -> Tensor <$> A.adAdd a b + (14, [Tensor a,Tensor b]) -> Tensor <$> A.adMultiply a b + (15, [Tensor a,Tensor b]) -> Tensor <$> A.adMatmul a b + (16, [Tensor a,Tensor b]) -> Tensor <$> A.adContract shape otherAxes a b + (17, [Tensor t]) -> Right (Expression (A.adSum t)) + (18, Expression e : es) -> do + points <- mapM expression es + next <- A.differentiableStep r (const e) points + Tensor <$> A.adTensor [length next] next + (19, [Gradients g]) -> Gradients <$> A.gradientHook (const (Right values)) g + (20, []) -> Right (Gradients (A.GradientState values)) + (21, [Dual a,Dual b]) -> Dual <$> nestTower a b + _ -> Left (InvalidArgument "invalid AD representation or operation") + checked result $ \value -> + bracketOnError (newStablePtr value) freeStablePtr (poke out) + +foreign export ccall "hm_ad_metadata" + metadata :: StablePtr Value -> Ptr CSize -> Ptr CSize -> IO CInt +metadata :: StablePtr Value -> Ptr CSize -> Ptr CSize -> IO CInt +metadata pointer outCount outRank = boundary $ do + value <- deRefStablePtr pointer + let (count,rank) = case value of + Tensor t -> (length (A.adValues t),length (A.adShape t)) + Gradients g -> (length (A.accumulatedGradient g),0) + Dual t -> (length (towerData t),0) + _ -> (0,0) + strictCount <- evaluate count + strictRank <- evaluate rank + poke outCount (fromIntegral strictCount) + poke outRank (fromIntegral strictRank) + pure 0 + +foreign export ccall "hm_ad_data" + copyData :: StablePtr Value -> Ptr CDouble -> Ptr CPtrdiff -> IO CInt +copyData :: StablePtr Value -> Ptr CDouble -> Ptr CPtrdiff -> IO CInt +copyData pointer outValues outShape = boundary $ do + value <- deRefStablePtr pointer + let values = case value of + Gradients g -> A.accumulatedGradient g + Dual d -> towerData d + _ -> [] + shape = case value of { Tensor t -> A.adShape t; _ -> [] } + strictValues <- mapM evaluate values + strictShape <- mapM evaluate shape + pokeArray (castPtr outValues) strictValues + pokeArray outShape (map fromIntegral strictShape) + pure 0 + +foreign export ccall "hm_ad_tensor_values" + tensorValues :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +tensorValues :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +tensorValues pointer out = boundary $ do + value <- deRefStablePtr pointer + checked (tensor value) $ \t -> allocate (A.adValues t) [] + where + allocate [] pointers = pokeArray out (reverse pointers) + allocate (e:es) pointers = bracketOnError (newStablePtr (Expression e)) freeStablePtr $ \p -> allocate es (p:pointers) + +foreign export ccall "hm_ad_run" + run :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr CDouble -> CSize -> + Ptr CDouble -> CSize -> CDouble -> Ptr CDouble -> IO CInt +run :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr CDouble -> CSize -> + Ptr CDouble -> CSize -> CDouble -> Ptr CDouble -> IO CInt +run operation pointers count xs n ds directionCount scalar out = boundary $ do + arguments <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + values <- peekArray (fromIntegral n) (castPtr xs :: Ptr Double) + directions <- peekArray (fromIntegral directionCount) (castPtr ds :: Ptr Double) + let result = case (operation,arguments) of + (0,[Graph g]) -> (:[]) <$> A.evaluateGraph g values + (1,[Expression e]) -> (\(y,g) -> y:g) <$> A.valueAndGradient (const e) values + (2,[Expression e]) -> A.gradient (const e) values + (3,[Expression e]) -> concat <$> A.hessian (const e) values + (4,es) -> concat <$> (mapM expression es >>= \outputs -> A.jacobian (const outputs) values) + (5,es) -> mapM expression es >>= \outputs -> A.jvp (const outputs) values directions + (6,es) -> mapM expression es >>= \outputs -> A.vjp (const outputs) values directions + (7,[Expression e]) -> A.hvp (const e) values directions + (8,[Expression e]) -> (:[]) <$> A.gradientCheck (coerce scalar) (const e) values + (9,[Expression e]) -> case values of + [a,b] -> (\z -> [realPart z,imagPart z]) <$> A.complexGradient (const e) (a :+ b) + _ -> Left (InvalidArgument "complex coordinate pair") + (10,outputs) -> do + duals <- mapM (\v -> case v of { Dual d -> flatDual d; _ -> Left (InvalidArgument "expected dual output") }) outputs + (primals,tangents) <- A.forwardJVP (const duals) values directions + Right (primals ++ tangents) + _ -> Left (InvalidArgument "invalid AD evaluation operation") + checked result $ \resultValues -> do + strict <- mapM evaluate resultValues + pokeArray (castPtr out) strict + + +-- Callbacks return a status and borrowed error text. Relaying this exception at +-- the C boundary has the same short-circuit effect as Left MathError, preserving +-- the original constructor/payload without parsing or rewriting its Show form. +data CallbackFailure = CallbackFailure CInt String deriving (Show) +instance Exception CallbackFailure +foreign import ccall unsafe "hm_error" setCallbackError :: CInt -> CString -> IO CInt +boundary :: IO CInt -> IO CInt +boundary action = Boundary.boundary (action `catch` relay) + where + relay (CallbackFailure code message) = withCString message (setCallbackError code) + +type RuleCallback = Ptr CDouble -> CSize -> Ptr () -> Ptr CDouble -> Ptr CDouble -> CSize -> Ptr CSize -> Ptr CString -> IO CInt +type UnaryCallback = CDouble -> Ptr () -> Ptr CDouble -> Ptr CString -> IO CInt +foreign import ccall safe "dynamic" callRule :: FunPtr RuleCallback -> RuleCallback +foreign import ccall safe "dynamic" callUnary :: FunPtr UnaryCallback -> UnaryCallback +foreign import ccall safe "hm_ad_invoke_builder" + callBuilder :: FunPtr () -> Ptr () -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> Ptr CString -> IO CInt + +callbackStatus :: CInt -> Ptr CString -> IO () +callbackStatus status messagePointer + | status == 0 = pure () + | otherwise = do + pointer <- peek messagePointer + message <- if pointer == nullPtr then pure "AD callback failed" else peekCString pointer + throwIO (CallbackFailure (if status > 0 && status <= 11 then status else 1) message) + +{-# NOINLINE customRule #-} +customRule :: FunPtr RuleCallback -> Ptr () -> [Double] -> Either MathError (Double,[Double]) +customRule callback userdata values = unsafePerformIO $ + withArray (map coerce values :: [CDouble]) $ \inputs -> + alloca $ \outValue -> allocaArray (max 1 (length values)) $ \partials -> + alloca $ \outCount -> alloca $ \outError -> do + poke outError nullPtr + poke outCount (fromIntegral (length values)) + poke outValue (0/0) + status <- callRule callback inputs (fromIntegral (length values)) userdata outValue partials (fromIntegral (length values)) outCount outError + callbackStatus status outError + n <- peek outCount + if toInteger n > toInteger (maxBound :: Int) + then throwIO (CallbackFailure 3 "custom derivative count exceeds Haskell Int") + else do + value <- coerce <$> peek outValue + -- Preserve value-only evaluation even when derivative arity is + -- wrong: runValue ignores partials, runTape checks their length. + derivatives <- if fromIntegral n == length values + then map coerce <$> peekArray (fromIntegral n) partials + else pure (replicate (fromIntegral n) 0) + pure (Right (value,derivatives)) + +{-# NOINLINE customScalar #-} +customScalar :: FunPtr UnaryCallback -> Ptr () -> Double -> Double +customScalar callback userdata value = unsafePerformIO $ + alloca $ \out -> alloca $ \outError -> do + poke outError nullPtr + poke out (0/0) + status <- callUnary callback (coerce value) userdata out outError + callbackStatus status outError + coerce <$> peek out + +{-# NOINLINE checkpointRecipe #-} +checkpointRecipe :: FunPtr () -> Ptr () -> [A.Expr] -> A.Expr +checkpointRecipe callback userdata values = unsafePerformIO $ temporary values [] + where + temporary [] pointers = withArray (reverse pointers) $ \inputs -> + alloca $ \out -> alloca $ \outError -> do + poke outError nullPtr + status <- callBuilder callback userdata inputs (fromIntegral (length values)) out outError + callbackStatus status outError + pointer <- peek out + bracket (pure pointer) freeStablePtr $ \stable -> do + result <- deRefStablePtr stable + either (throwIO . CallbackFailure 1 . show) pure (expression result) + temporary (e:es) pointers = bracket (newStablePtr (Expression e)) freeStablePtr $ \pointer -> temporary es (pointer:pointers) + +foreign export ccall "hm_ad_clone" + clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone pointer out = boundary $ do + value <- deRefStablePtr pointer + bracketOnError (newStablePtr value) freeStablePtr (poke out) + pure 0 + +foreign export ccall "hm_ad_callbacks" + callbacks :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr RuleCallback -> FunPtr UnaryCallback -> FunPtr UnaryCallback -> FunPtr () -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +callbacks :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr RuleCallback -> FunPtr UnaryCallback -> FunPtr UnaryCallback -> FunPtr () -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +callbacks operation pointers count rule valueCallback derivativeCallback builder userdata out = boundary $ do + values <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + checked (mapM expression values) $ \expressions -> do + let result = case operation of + 0 -> A.customOperation (customRule rule userdata) expressions + 1 -> case expressions of + [e] -> A.customUnary (customScalar valueCallback userdata) (customScalar derivativeCallback userdata) e + _ -> error "invalid custom unary arity" + 2 -> A.checkpoint (checkpointRecipe builder userdata) expressions + _ -> error "invalid AD callback operation" + bracketOnError (newStablePtr (Expression result)) freeStablePtr (poke out) + + +foreign export ccall "hm_ad_dual_depth" + dualDepth :: StablePtr Value -> Ptr CSize -> IO CInt +dualDepth :: StablePtr Value -> Ptr CSize -> IO CInt +dualDepth pointer out = boundary $ do + value <- deRefStablePtr pointer + checked (case value of { Dual (Tower number) -> Right (depth number); _ -> Left (InvalidArgument "expected Dual") }) $ \n -> poke out (fromIntegral n) + +foreign export ccall "hm_ad_dual_parts" + dualParts :: StablePtr Value -> Ptr (StablePtr Value) -> Ptr (StablePtr Value) -> IO CInt +dualParts :: StablePtr Value -> Ptr (StablePtr Value) -> Ptr (StablePtr Value) -> IO CInt +dualParts pointer outPrimal outTangent = boundary $ do + value <- deRefStablePtr pointer + let result = case value of + Dual (Tower number) -> maybe (Left (InvalidArgument "scalar has no Dual components")) Right (components number) + _ -> Left (InvalidArgument "expected Dual") + checked result $ \(primalPart,tangentPart) -> + bracketOnError (newStablePtr (Dual primalPart)) freeStablePtr $ \primalPointer -> + bracketOnError (newStablePtr (Dual tangentPart)) freeStablePtr $ \tangentPointer -> do + poke outPrimal primalPointer + poke outTangent tangentPointer + + +foreign export ccall "hm_ad_dual_f32" + dualFloat :: CFloat -> CFloat -> Ptr (StablePtr Value) -> IO CInt +dualFloat :: CFloat -> CFloat -> Ptr (StablePtr Value) -> IO CInt +dualFloat primalValue tangentValue out = boundary $ + bracketOnError (newStablePtr (Dual (Tower (A.Dual (coerce primalValue :: Float) (coerce tangentValue))))) freeStablePtr $ \pointer -> poke out pointer >> pure 0 + +foreign export ccall "hm_ad_dual_exact" + dualExact :: CInt -> CString -> CString -> CString -> CString -> Ptr (StablePtr Value) -> IO CInt +dualExact :: CInt -> CString -> CString -> CString -> CString -> Ptr (StablePtr Value) -> IO CInt +dualExact kind primalNumerator primalDenominator tangentNumerator tangentDenominator out = boundary $ do + primalValue <- readInteger primalNumerator + tangentValue <- readInteger tangentNumerator + value <- if kind == 2 + then pure (Dual (Tower (A.Dual primalValue tangentValue))) + else do + primalDivisor <- readInteger primalDenominator + tangentDivisor <- readInteger tangentDenominator + pure (Dual (Tower (A.Dual (primalValue % primalDivisor) (tangentValue % tangentDivisor)))) + bracketOnError (newStablePtr value) freeStablePtr $ \pointer -> poke out pointer >> pure 0 + +foreign export ccall "hm_ad_dual_kind" + dualKind :: StablePtr Value -> Ptr CInt -> IO CInt +dualKind :: StablePtr Value -> Ptr CInt -> IO CInt +dualKind pointer out = boundary $ do + value <- deRefStablePtr pointer + checked (case value of { Dual (Tower number) -> Right (baseKind number); _ -> Left (InvalidArgument "expected Dual") }) (poke out) + +foreign export ccall "hm_ad_scalar_text" + scalarText :: StablePtr Value -> Ptr CString -> Ptr CString -> IO CInt +scalarText :: StablePtr Value -> Ptr CString -> Ptr CString -> IO CInt +scalarText pointer outNumerator outDenominator = boundary $ do + value <- deRefStablePtr pointer + let result = case value of + Dual (Tower number) -> case cast number of + Just integer -> Right (show (integer :: Integer),"1") + Nothing -> case cast number of + Just rational -> Right (show (numerator (rational :: Rational)),show (denominator rational)) + Nothing -> Left (InvalidArgument "expected Integer or Rational scalar leaf") + _ -> Left (InvalidArgument "expected exact scalar leaf") + checked result $ \(n,d) -> writeStrings [n,d] $ \texts -> do + poke outNumerator (texts !! 0) + poke outDenominator (texts !! 1) + + +relationValue :: forall a. (TowerValue a) => Int -> a -> a -> Either MathError Bool +relationValue operation left right + | operation == 0 = Right (left == right) + | otherwise = case orderingDict (Proxy :: Proxy a) of + Nothing -> Left (InvalidArgument "Dual scalar type has no Ord instance") + Just Dict -> Right (case operation of { 1 -> left < right; 2 -> left <= right; 3 -> left > right; _ -> left >= right }) +relationTower :: Int -> Tower -> Tower -> Either MathError Bool +relationTower operation (Tower left) (Tower right) = case cast right of + Nothing -> Left (InvalidArgument "mismatched Dual scalar types") + Just other -> relationValue operation left other +foreign export ccall "hm_ad_dual_relation" + dualRelation :: CInt -> StablePtr Value -> StablePtr Value -> Ptr CInt -> IO CInt +dualRelation :: CInt -> StablePtr Value -> StablePtr Value -> Ptr CInt -> IO CInt +dualRelation operation leftPointer rightPointer out = boundary $ do + left <- deRefStablePtr leftPointer + right <- deRefStablePtr rightPointer + let result = case (left,right) of + (Dual a,Dual b) -> relationTower (fromIntegral operation) a b + _ -> Left (InvalidArgument "expected Dual operands") + checked result $ \value -> poke out (if value then 1 else 0) diff --git a/src/HMath/FFI/AutodiffChecked.hs b/src/HMath/FFI/AutodiffChecked.hs new file mode 100644 index 0000000..a098a47 --- /dev/null +++ b/src/HMath/FFI/AutodiffChecked.hs @@ -0,0 +1,81 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Additive structured callbacks; original AD formulas and laziness stay in Autodiff. +module HMath.FFI.AutodiffChecked where + +import Control.Exception (bracket,bracketOnError,throwIO) +import Data.Coerce (coerce) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Autodiff as A +import qualified HMath.FFI.Autodiff as D +import HMath.Error (MathError) +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError (CallbackFailure(..),withMathErrorWire,readCallbackFailure) + +type Rule = Ptr CDouble -> CSize -> Ptr () -> Ptr CDouble -> Ptr CDouble -> CSize -> Ptr CSize -> Ptr () -> IO CInt +type Unary = CDouble -> Ptr () -> Ptr CDouble -> Ptr () -> IO CInt +foreign import ccall safe "dynamic" callRule :: FunPtr Rule -> Rule +foreign import ccall safe "dynamic" callUnary :: FunPtr Unary -> Unary +foreign import ccall safe "hm_ad_invoke_builder_checked" + callBuilder :: FunPtr () -> Ptr () -> Ptr(StablePtr D.Value) -> CSize -> Ptr(StablePtr D.Value) -> Ptr () -> IO CInt + +{-# NOINLINE rule #-} +rule :: FunPtr Rule -> Ptr () -> [Double] -> Either MathError(Double,[Double]) +rule callback userdata values = unsafePerformIO $ + withArray(map coerce values::[CDouble]) $ \inputs -> + alloca $ \value -> allocaArray(max 1(length values)) $ \partials -> + alloca $ \written -> withMathErrorWire $ \errorWire -> do + poke value (0/0) + poke written (fromIntegral(length values)) + status<-callRule callback inputs (fromIntegral(length values)) userdata value partials (fromIntegral(length values)) written errorWire + if status/=0 then do + failure<-readCallbackFailure status errorWire + case failure of + CallbackMathError err -> pure(Left err) + _ -> throwIO failure + else do + count<-peek written + if toInteger count>toInteger(maxBound::Int) + then throwIO(CallbackFailure 3 "custom derivative count exceeds Haskell Int") + else do + result<-coerce <$> peek value + derivatives<-if fromIntegral count==length values + then map coerce <$> peekArray(fromIntegral count)partials + else pure(replicate(fromIntegral count)0) + pure(Right(result,derivatives)) + +{-# NOINLINE unary #-} +unary :: FunPtr Unary -> Ptr () -> Double -> Double +unary callback userdata input = unsafePerformIO $ alloca $ \out -> withMathErrorWire $ \errorWire -> do + poke out (0/0) + status<-callUnary callback (coerce input) userdata out errorWire + if status/=0 then readCallbackFailure status errorWire >>= throwIO else coerce <$> peek out + +{-# NOINLINE builder #-} +builder :: FunPtr () -> Ptr () -> [A.Expr] -> A.Expr +builder callback userdata values = unsafePerformIO $ temporary values [] + where + temporary [] pointers = withArray(reverse pointers) $ \inputs -> alloca $ \out -> withMathErrorWire $ \errorWire -> do + status<-callBuilder callback userdata inputs (fromIntegral(length values)) out errorWire + if status/=0 then readCallbackFailure status errorWire >>= throwIO else do + pointer<-peek out + bracket(pure pointer)freeStablePtr $ \stable -> do + value<-deRefStablePtr stable + case D.expression value of + Left err -> throwIO(CallbackMathError err) + Right expression -> pure expression + temporary (value:rest) pointers = bracket(newStablePtr(D.Expression value))freeStablePtr $ \pointer -> temporary rest(pointer:pointers) + +foreign export ccall "hm_ad_custom_checked" create :: CInt -> FunPtr () -> FunPtr () -> Ptr () -> Ptr(StablePtr D.Value) -> CSize -> Ptr(StablePtr D.Value) -> IO CInt +create :: CInt -> FunPtr () -> FunPtr () -> Ptr () -> Ptr(StablePtr D.Value) -> CSize -> Ptr(StablePtr D.Value) -> IO CInt +create operation callback derivative userdata inputs count out = B.boundary $ do + arguments<-peekArray(fromIntegral count)inputs >>= mapM deRefStablePtr + B.checked(mapM D.expression arguments) $ \expressions -> do + result<-case (operation,expressions) of + (0,_) -> pure(A.customOperation(rule(castFunPtr callback)userdata)expressions) + (1,[expression]) -> pure(A.customUnary(unary(castFunPtr callback)userdata)(unary(castFunPtr derivative)userdata)expression) + (2,_) -> pure(A.checkpoint(builder callback userdata)expressions) + _ -> throwIO(CallbackFailure 1 "invalid checked AD callback operation") + bracketOnError(newStablePtr(D.Expression result))freeStablePtr(poke out) diff --git a/src/HMath/FFI/AutodiffValue.hs b/src/HMath/FFI/AutodiffValue.hs new file mode 100644 index 0000000..5fb1dfe --- /dev/null +++ b/src/HMath/FFI/AutodiffValue.hs @@ -0,0 +1,64 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Lossless interoperability with the existing Autodiff handles and sum type. +module HMath.FFI.AutodiffValue where + +import Control.Exception (bracketOnError,evaluate) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Autodiff as A +import qualified HMath.FFI.Autodiff as D +import qualified HMath.FFI.Boundary as B +import HMath.FFI.Coefficient (SomeCoefficient(..)) +import qualified HMath.FFI.Value as V + +fromADExpr :: A.Expr -> V.Value +fromADExpr value = V.Opaque 287 0 0 (evaluate value >> pure ()) value +asADExpr :: V.Value -> IO A.Expr +asADExpr (V.Opaque 287 _ _ _ payload) = maybe (V.invalid "invalid original AD Expr payload") pure (cast payload) +asADExpr _ = V.invalid "expected original AD Expr" +fromADTensor :: A.ADTensor -> V.Value +fromADTensor value = V.Opaque 288 0 (length(A.adValues value)) (evaluate value >> pure ()) value +asADTensor :: V.Value -> IO A.ADTensor +asADTensor (V.Opaque 288 _ _ _ payload) = maybe (V.invalid "invalid original ADTensor payload") pure (cast payload) +asADTensor _ = V.invalid "expected original ADTensor" + +-- Coefficient leaves remain ordinary exact typed scalars; each actual A.Dual +-- tower remains separate from HMath.Numeric.Dual's Coefficient representation. +fromADTower :: D.Tower -> V.Value +fromADTower tower@(D.Tower value) = case D.coefficientLeaf value of + Just (SomeCoefficient witness number) -> V.Scalar witness number + Nothing -> V.Opaque 289 (-1) (D.depth value) (evaluate value >> pure ()) tower +asADTower :: V.Value -> IO D.Tower +asADTower (V.Opaque 289 _ _ _ payload) = maybe (V.invalid "invalid original Autodiff Dual tower") pure (cast payload) +asADTower (V.Scalar _ value) = pure(D.Tower value) +asADTower _ = V.invalid "expected original Autodiff Dual or coefficient scalar leaf" +adDual :: D.TowerValue a => A.Dual a -> V.Value +adDual = fromADTower . D.Tower +asADDual :: forall a. Typeable a => V.Value -> IO(A.Dual a) +asADDual input = do + D.Tower value <- asADTower input + maybe (V.invalid "original Autodiff Dual component types differ") pure (cast value) + +foreign export ccall "hm_ad_value_import" importValue :: StablePtr D.Value -> Ptr(StablePtr V.Value) -> IO CInt +importValue :: StablePtr D.Value -> Ptr(StablePtr V.Value) -> IO CInt +importValue input out = B.boundary $ do + value<-deRefStablePtr input + result<-case value of + D.Expression expression -> pure(fromADExpr expression) + D.Tensor tensor -> pure(fromADTensor tensor) + D.Dual tower -> pure(fromADTower tower) + _ -> V.invalid "AD Value interchange supports expressions, symbolic tensors and original Duals" + B.checked(Right())(\_ -> V.publish result out) +foreign export ccall "hm_ad_value_export" exportValue :: StablePtr V.Value -> Ptr(StablePtr D.Value) -> Ptr CInt -> IO CInt +exportValue :: StablePtr V.Value -> Ptr(StablePtr D.Value) -> Ptr CInt -> IO CInt +exportValue input out kindOut = B.boundary $ do + value<-deRefStablePtr input + (kind,result)<-case value of + V.Opaque 287 _ _ _ _ -> do expression<-asADExpr value;pure(0,D.Expression expression) + V.Opaque 288 _ _ _ _ -> do tensor<-asADTensor value;pure(3,D.Tensor tensor) + _ -> do tower<-asADTower value;pure(4,D.Dual tower) + B.checked(Right()) $ \_ -> bracketOnError(newStablePtr result)freeStablePtr(\pointer -> poke kindOut kind >> poke out pointer) diff --git a/src/HMath/FFI/Boundary.hs b/src/HMath/FFI/Boundary.hs new file mode 100644 index 0000000..6536456 --- /dev/null +++ b/src/HMath/FFI/Boundary.hs @@ -0,0 +1,53 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE ScopedTypeVariables #-} + +-- SPDX-License-Identifier: MPL-2.0 +-- | Marshaling only: mathematical validation belongs to the original function. +module HMath.FFI.Boundary (boundary, checked, readInteger, writeStrings) where + +import Control.Exception (SomeException, bracketOnError, catch, displayException, evaluate) +import Foreign +import Foreign.C +import HMath.Error (MathError) +import HMath.FFI.MathError (callbackBoundary, recordMathError) + +foreign import ccall unsafe "hm_error" setError :: CInt -> CString -> IO CInt + +report :: CInt -> String -> IO CInt +report code message = withCString message (setError code) + +-- The caller reserves the RTS for the entire call. Every result is forced +-- before writing caller memory; Haskell exceptions never cross the C boundary. +boundary :: IO CInt -> IO CInt +boundary action = + callbackBoundary mathFailure action + `catch` (\(e :: SomeException) -> report 6 (displayException e)) + +mathFailure :: MathError -> IO CInt +mathFailure err = do + status <- report 11 (show err) + recorded <- recordMathError err + if recorded == 0 + then pure status + else report recorded "unable to record structured MathError" + +checked :: Either MathError a -> (a -> IO ()) -> IO CInt +checked result write = case result of + Left err -> mathFailure err + Right value -> write value >> report 0 "" + +-- C validates the decimal grammar before this parser is called. No bounded +-- integer or floating-point intermediate is involved. +readInteger :: CString -> IO Integer +readInteger pointer = peekCString pointer >>= evaluate . read + +-- Force and allocate all text outputs before publishing any pointers. A later +-- allocation failure releases earlier allocations and leaves outputs untouched. +writeStrings :: [String] -> ([CString] -> IO ()) -> IO () +writeStrings values write = do + mapM_ (evaluate . length) values + allocate values [] + where + allocate [] pointers = write (reverse pointers) + allocate (value : rest) pointers = + bracketOnError (newCString value) free (\pointer -> allocate rest (pointer : pointers)) diff --git a/src/HMath/FFI/Buffer.hs b/src/HMath/FFI/Buffer.hs new file mode 100644 index 0000000..7b801eb --- /dev/null +++ b/src/HMath/FFI/Buffer.hs @@ -0,0 +1,47 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Named Buffer calls and checked scope/borrow representation helpers. +module HMath.FFI.Buffer where +import Foreign +import Foreign.C +import qualified HMath.API.Buffer as B +import qualified HMath.FFI.Buffer.Codec as C +import qualified HMath.FFI.FoundationCodec as F +import qualified HMath.FFI.Value as V +import HMath.FFI.Coefficient (ScalarType(SDouble)) +foreign export ccall "hm_buffer_apply" apply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +apply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +apply operation input arity out=F.foundationBoundary $ do + values <- peekArray(fromIntegral arity) input >>= mapM deRefStablePtr + result <- case(operation,values)of + (0,[xs]) -> C.boxed . B.lazyBoxed <$> V.asList xs + (1,[xs]) -> C.boxed . B.strictBoxed <$> V.asList xs + (2,[value]) -> V.List . B.boxedValues <$> C.asBoxed value + (3,[value]) -> V.Index . B.boxedLength <$> C.asBoxed value + (4,[callback,value]) -> C.asBoxed value >>= C.mapStrict callback + (5,[xs]) -> V.asList xs >>= mapM V.asScalar >>= pure . C.unboxed . B.unboxedDouble + (6,[value]) -> V.List . map(V.Scalar SDouble) . B.unboxedValues <$> C.asUnboxed value + (7,[value,callback]) -> C.asBoxed value >>= \inputBox -> C.runBuffer inputBox callback + (8,[region,value]) -> do scope <- C.asSTBox region;inputBox <- C.asBoxed value;C.thawST scope inputBox + (9,[value]) -> C.asSTBox value >>= C.freezeST + (10,[value,index]) -> do buffer <- C.asSTBox value;i <- V.asIndex index;C.readST buffer i + (11,[value,index,element]) -> do buffer <- C.asSTBox value;i <- V.asIndex index;C.writeST buffer i element + (12,[count,value]) -> V.asIndex count >>= \n -> C.newIO n value + (13,[prototype,value]) -> C.asBoxed value >>= C.thawIO prototype + (14,[value]) -> C.asIOBox value >>= C.freezeIO + (15,[value]) -> V.Index . C.ioLength <$> C.asIOBox value + (16,[value,index]) -> do buffer <- C.asIOBox value;i <- V.asIndex index;C.readIO buffer i + (17,[value,index,element]) -> do buffer <- C.asIOBox value;i <- V.asIndex index;C.writeIO buffer i element + (18,[value,callback]) -> C.asIOBox value >>= \buffer -> C.withIO buffer callback + (19,[value]) -> do raw <- C.asUnboxed value;pure(C.boxed(fmap(V.Scalar SDouble)(B.unboxedToBoxed raw))) + (20,[value]) -> do raw <- C.asBoxed value;xs <- mapM V.asScalar(B.boxedValues raw);pure(C.unboxed(B.boxedToUnboxed(B.lazyBoxed xs))) + (21,[value]) -> C.storageInfo <$> C.asIOBox value + (22,[value]) -> C.asBorrowed value >>= C.pointerInfo + (23,[value,index]) -> do pointer <- C.asBorrowed value;i <- V.asIndex index;C.pointerRead pointer i + (24,[value,index,element]) -> do pointer <- C.asBorrowed value;i <- V.asIndex index;C.pointerWrite pointer i element + (25,[value]) -> C.asBorrowed value >>= C.pointerAddress + (26,[value]) -> do C.STBox scope _ <- C.asSTBox value;V.Boolean <$> C.scopeActive scope + (27,[value]) -> do C.Borrowed scope _ _ _ <- C.asBorrowed value;V.Boolean <$> C.scopeActive scope + _ -> V.invalid "Buffer adapter argument shape differs" + V.publish result out + pure 0 diff --git a/src/HMath/FFI/Buffer/Codec.hs b/src/HMath/FFI/Buffer/Codec.hs new file mode 100644 index 0000000..f8f3325 --- /dev/null +++ b/src/HMath/FFI/Buffer/Codec.hs @@ -0,0 +1,188 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Original containers with foreign scope and storage witnesses. No alternate +-- array implementation is used: every named operation delegates to API.Buffer. +module HMath.FFI.Buffer.Codec where +import Control.Concurrent.MVar +import Control.Exception (bracket_,evaluate,finally,throwIO) +import Control.Monad.ST.Unsafe (unsafeIOToST,unsafeSTToIO) +import Data.IORef +import Data.Typeable (Typeable) +import Foreign.Ptr (Ptr,ptrToWordPtr) +import Foreign.Storable (Storable,sizeOf,alignment,peekElemOff,pokeElemOff) +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.API.Buffer as B +import qualified HMath.Error as E +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.FoundationCodec as F +import qualified HMath.FFI.LinearCodec as LC +import HMath.FFI.Coefficient +import HMath.FFI.MathError (CallbackFailure(..)) + +foreign import ccall unsafe "hm_buffer_thread_token" threadToken :: IO (Ptr ()) + +source :: Either E.MathError a -> IO a +source=F.source +boxed :: B.Boxed V.Value -> V.Value +boxed value=F.opaque "HMath.API.Buffer.Boxed" (-1) value (evaluate value >> pure()) (pure(V.List(B.boxedValues value))) +asBoxed :: V.Value -> IO(B.Boxed V.Value) +asBoxed=F.unbox "HMath.API.Buffer.Boxed" +unboxed :: B.UnboxedDouble -> V.Value +unboxed value=F.opaqueEq "HMath.API.Buffer.UnboxedDouble" 0 value (evaluate value >> pure()) (pure(V.List(map(V.Scalar SDouble)(B.unboxedValues value)))) +asUnboxed :: V.Value -> IO B.UnboxedDouble +asUnboxed=F.unbox "HMath.API.Buffer.UnboxedDouble" + +-- Scope guards are serialized and tied to the native caller thread. A retained +-- ST or borrowed-pointer owner can be released later, but cannot execute after +-- its callback or from another thread. Invalidation waits for in-flight access. +data Scope=Scope (Ptr ()) (MVar Bool) +newScope :: IO Scope +newScope=Scope <$> threadToken <*> newMVar True +withScope :: Scope -> IO a -> IO a +withScope(Scope owner active) action=withMVar active $ \alive -> do + if not alive then V.invalid "buffer callback scope has ended" else pure() + current <- threadToken + if current/=owner then V.invalid "buffer callback scope belongs to another thread" else action +endScope :: Scope -> IO () +endScope(Scope _ active)=modifyMVar_ active(const(pure False)) +scopeActive :: Scope -> IO Bool +scopeActive(Scope _ active)=readMVar active + +data STBox where + STBox :: Scope -> B.STBuffer s V.Value -> STBox +stBox :: STBox -> V.Value +stBox value=F.opaque "HMath.API.Buffer.STBuffer" (-1) value (evaluate value >> pure()) (V.invalid "ST buffer has no immutable constructor fields") +asSTBox :: V.Value -> IO STBox +asSTBox=F.unbox "HMath.API.Buffer.STBuffer" +runBuffer :: B.Boxed V.Value -> V.Value -> IO V.Value +runBuffer input callback=do + scope <- newScope + let result=B.runSTBuffer input $ \buffer -> unsafeIOToST(LC.callbackValue callback(V.Tuple[stBox(STBox scope buffer)])) + evaluate result `finally` endScope scope +thawST :: STBox -> B.Boxed V.Value -> IO V.Value +thawST(STBox scope _) input=withScope scope $ stBox . STBox scope <$> unsafeSTToIO(B.thawSTBuffer input) +freezeST :: STBox -> IO V.Value +freezeST(STBox scope buffer)=withScope scope $ boxed <$> unsafeSTToIO(B.freezeSTBuffer buffer) +readST :: STBox -> Int -> IO V.Value +readST(STBox scope buffer) index=withScope scope $ unsafeSTToIO(B.readSTBuffer buffer index) >>= source +writeST :: STBox -> Int -> V.Value -> IO V.Value +writeST(STBox scope buffer) index value=withScope scope $ do + unsafeSTToIO(B.writeSTBuffer buffer index value) >>= source + pure V.None +mapValue :: V.Value -> V.Value -> V.Value +mapValue callback value=unsafePerformIO(LC.callbackValue callback(V.Tuple[value])) +{-# NOINLINE mapValue #-} +mapStrict :: V.Value -> B.Boxed V.Value -> IO V.Value +mapStrict callback input=boxed <$> evaluate(B.mapStrict(mapValue callback) input) + +-- Storable is exposed only for actual existing standard instances. Integer, +-- Rational, Numeric.Dual and Quaternion have no such instance and are rejected. +data Storage a=Storage Int (a -> V.Value) (V.Value -> IO a) +storableDict :: ScalarType a -> Maybe(Dict(Storable a)) +storableDict witness=case witness of + SDouble -> Just Dict + SFloat -> Just Dict + SComplexDouble -> Just Dict + SComplexFloat -> Just Dict + SInt8 -> Just Dict + SInt16 -> Just Dict + SInt32 -> Just Dict + SInt64 -> Just Dict + SWord8 -> Just Dict + SWord16 -> Just Dict + SWord32 -> Just Dict + SWord64 -> Just Dict + SInt -> Just Dict + SWord -> Just Dict + _ -> Nothing +withStorage :: V.Value -> (forall a. (Typeable a,Storable a) => Storage a -> IO r) -> IO r +withStorage prototype action=case prototype of + V.Scalar witness _ -> case storableDict witness of + Just Dict -> action(Storage(scalarTypeCode witness)(V.Scalar witness)V.asScalar) + Nothing -> V.unsupported "coefficient has no original Storable instance" + V.Index _ -> action(Storage 14 V.Index V.asIndex) + V.Boolean _ -> action(Storage 16 V.Boolean readBool) + V.Text [_] -> action(Storage 17 (\c -> V.Text[c]) readChar) + _ -> V.unsupported "IO buffer requires a standard Storable numeric, Bool or Char prototype" + where + readBool(V.Boolean x)=pure x + readBool _=V.invalid "Bool storage requires a Boolean" + readChar(V.Text[c])=pure c + readChar _=V.invalid "Char storage requires one Haskell character" + +data IOBox where + IOBox :: (Typeable a,Storable a) => Storage a -> B.IOBuffer a -> IORef(Maybe(Ptr())) -> IOBox +ioBox :: IOBox -> V.Value +ioBox value@(IOBox(Storage code _ _) _ _)=F.opaque "HMath.API.Buffer.IOBuffer" code value (evaluate value >> pure()) (V.invalid "mutable IO storage has no immutable constructor fields") +asIOBox :: V.Value -> IO IOBox +asIOBox=F.unbox "HMath.API.Buffer.IOBuffer" +newIO :: Int -> V.Value -> IO V.Value +newIO count initial=withStorage initial $ \store@(Storage _ _ readValue) -> do + x <- readValue initial + buffer <- B.newIOBuffer count x >>= source + borrowed <- newIORef Nothing + pure(ioBox(IOBox store buffer borrowed)) +thawIO :: V.Value -> B.Boxed V.Value -> IO V.Value +thawIO prototype input=do + let fields=B.boxedValues input + selected <- case(prototype,fields)of + (V.None,first:_) -> pure first + (V.None,[]) -> V.invalid "empty IO storage needs an explicit element prototype" + _ -> pure prototype + withStorage selected $ \store@(Storage _ _ readValue) -> do + values <- mapM readValue fields + buffer <- B.thawIOBuffer(B.lazyBoxed values) >>= source + borrowed <- newIORef Nothing + pure(ioBox(IOBox store buffer borrowed)) +guardReentry :: IORef(Maybe(Ptr())) -> IO a -> IO a +guardReentry borrowed action=do + owner <- readIORef borrowed + current <- threadToken + if owner==Just current then throwIO(CallbackFailure 9 "cannot reenter locking operations on a borrowed IO buffer") else action +freezeIO :: IOBox -> IO V.Value +freezeIO(IOBox(Storage _ write _) buffer borrowed)=guardReentry borrowed $ do + values <- B.freezeIOBuffer buffer + pure(boxed(B.lazyBoxed(map write(B.boxedValues values)))) +readIO :: IOBox -> Int -> IO V.Value +readIO(IOBox(Storage _ write _) buffer borrowed) index=guardReentry borrowed $ B.readIOBuffer buffer index >>= source >>= pure . write +writeIO :: IOBox -> Int -> V.Value -> IO V.Value +writeIO(IOBox(Storage _ _ readValue) buffer borrowed) index value=guardReentry borrowed $ do + x <- readValue value + B.writeIOBuffer buffer index x >>= source + pure V.None +ioLength :: IOBox -> Int +ioLength(IOBox _ buffer _)=B.ioBufferLength buffer + +data Borrowed where + Borrowed :: (Typeable a,Storable a) => Scope -> Storage a -> Ptr a -> Int -> Borrowed +borrowedValue :: Borrowed -> V.Value +borrowedValue value@(Borrowed _ (Storage code _ _) _ _)=F.opaque "HMath.API.Buffer.BorrowedPointer" code value (evaluate value >> pure()) (V.invalid "borrowed pointer has no persistent fields") +asBorrowed :: V.Value -> IO Borrowed +asBorrowed=F.unbox "HMath.API.Buffer.BorrowedPointer" +withIO :: IOBox -> V.Value -> IO V.Value +withIO(IOBox store buffer borrowed) callback=guardReentry borrowed $ B.withIOBuffer buffer $ \pointer count -> do + scope <- newScope + owner <- threadToken + bracket_(writeIORef borrowed(Just owner))(writeIORef borrowed Nothing) $ + LC.callbackValue callback(V.Tuple[borrowedValue(Borrowed scope store pointer count),V.Index count]) `finally` endScope scope +pointerRead :: Borrowed -> Int -> IO V.Value +pointerRead(Borrowed scope(Storage _ write _) pointer count) index=withScope scope $ do + pointerIndex count index + write <$> peekElemOff pointer index +pointerWrite :: Borrowed -> Int -> V.Value -> IO V.Value +pointerWrite(Borrowed scope(Storage _ _ readValue) pointer count) index value=withScope scope $ do + pointerIndex count index + x <- readValue value + pokeElemOff pointer index x + pure V.None +pointerIndex :: Int -> Int -> IO () +pointerIndex count index=source(if index<0 || index>=count then Left(E.InvalidArgument "buffer index out of bounds") else Right()) +pointerAddress :: Borrowed -> IO V.Value +pointerAddress(Borrowed scope _ pointer _)=withScope scope $ pure(V.Scalar SInteger(toInteger(ptrToWordPtr pointer))) +storageInfo :: IOBox -> V.Value +storageInfo(IOBox(Storage code _ _) (buffer::B.IOBuffer a) _)=V.Tuple[V.Index code,V.Index(sizeOf(undefined::a)),V.Index(alignment(undefined::a)),V.Index(B.ioBufferLength buffer)] +pointerInfo :: Borrowed -> IO V.Value +pointerInfo(Borrowed scope(Storage code _ _) (_::Ptr a) count)=withScope scope $ pure(V.Tuple[V.Index code,V.Index(sizeOf(undefined::a)),V.Index(alignment(undefined::a)),V.Index count]) diff --git a/src/HMath/FFI/Bytes.hs b/src/HMath/FFI/Bytes.hs new file mode 100644 index 0000000..d5503f0 --- /dev/null +++ b/src/HMath/FFI/Bytes.hs @@ -0,0 +1,37 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Owned strict bytes with stable, read-only ForeignPtr-backed spans. +module HMath.FFI.Bytes where + +import Control.Exception (evaluate) +import qualified Data.ByteString as BS +import qualified Data.ByteString.Internal as BI +import Data.Typeable (cast) +import Foreign hiding (copyBytes) +import Foreign.C +import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) +import qualified HMath.FFI.Boundary as B +import qualified HMath.FFI.Value as V + +bytes :: BS.ByteString -> V.Value +bytes value = V.Opaque 450 (-1) (BS.length value) (evaluate (BS.length value) >> pure ()) value +asBytes :: V.Value -> IO BS.ByteString +asBytes (V.Opaque 450 _ _ _ value) = maybe (V.invalid "ByteString payload differs") pure (cast value) +asBytes _ = V.invalid "expected an immutable ByteString" + +foreign export ccall "hm_bytes_copy" copyBytes :: Ptr Word8 -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +copyBytes :: Ptr Word8 -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +copyBytes pointer count out = B.boundary $ do + value <- if count == 0 then pure BS.empty else BS.packCStringLen (castPtr pointer,fromIntegral count) + B.checked (Right ()) (const (V.publish (bytes value) out)) + +foreign export ccall "hm_bytes_data" byteSpan :: StablePtr V.Value -> Ptr (Ptr Word8) -> Ptr CSize -> IO CInt +byteSpan :: StablePtr V.Value -> Ptr (Ptr Word8) -> Ptr CSize -> IO CInt +byteSpan input out count = B.boundary $ do + value <- deRefStablePtr input >>= asBytes + let (owner,offset,size)=BI.toForeignPtr value + pointer=unsafeForeignPtrToPtr owner `plusPtr` offset + poke out pointer + poke count (fromIntegral size) + touchForeignPtr owner + pure 0 diff --git a/src/HMath/FFI/Coefficient.hs b/src/HMath/FFI/Coefficient.hs new file mode 100644 index 0000000..29a3599 --- /dev/null +++ b/src/HMath/FFI/Coefficient.hs @@ -0,0 +1,233 @@ +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeSynonymInstances #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Concrete standard numeric witnesses. Dictionaries expose only instances +-- already implemented by the original Haskell types; no arithmetic lives here. +module HMath.FFI.Coefficient where + +import Control.Exception (evaluate) +import Data.Complex (Complex, imagPart, realPart) +import Data.Int +import Data.Kind (Constraint) +import Data.Proxy (Proxy (..)) +import Data.Ratio (denominator, numerator) +import Data.Typeable (Typeable) +import Data.Word +import qualified HMath.Numeric as N + +data Dict (constraint :: Constraint) where + Dict :: constraint => Dict constraint + +data ScalarType a where + SDouble :: ScalarType Double + SFloat :: ScalarType Float + SInteger :: ScalarType Integer + SRational :: ScalarType Rational + SComplexDouble :: ScalarType (Complex Double) + SComplexFloat :: ScalarType (Complex Float) + SInt8 :: ScalarType Int8 + SInt16 :: ScalarType Int16 + SInt32 :: ScalarType Int32 + SInt64 :: ScalarType Int64 + SWord8 :: ScalarType Word8 + SWord16 :: ScalarType Word16 + SWord32 :: ScalarType Word32 + SWord64 :: ScalarType Word64 + SInt :: ScalarType Int + SWord :: ScalarType Word + SDual :: ScalarType a -> ScalarType (N.Dual a) + SQuaternion :: (Coefficient a, RealFloat a) => ScalarType a -> ScalarType (N.Quaternion a) + +class (Typeable a, Eq a, Show a, Num a) => Coefficient a where + scalarType :: ScalarType a + fractionalDict :: proxy a -> Maybe (Dict (Fractional a)) + fractionalDict _ = Nothing + floatingDict :: proxy a -> Maybe (Dict (Floating a)) + floatingDict _ = Nothing + orderingDict :: proxy a -> Maybe (Dict (Ord a)) + orderingDict _ = Nothing + realFloatDict :: proxy a -> Maybe (Dict (RealFloat a)) + realFloatDict _ = Nothing + realFracDict :: proxy a -> Maybe (Dict (RealFrac a)) + realFracDict _ = Nothing + realDict :: proxy a -> Maybe (Dict (Real a)) + realDict _ = Nothing + integralDict :: proxy a -> Maybe (Dict (Integral a)) + integralDict _ = Nothing + boundedDict :: proxy a -> Maybe (Dict (Bounded a)) + boundedDict _ = Nothing + forceCoefficient :: a -> IO () + forceCoefficient value = evaluate value >> pure () + +instance Coefficient Double where + scalarType = SDouble + fractionalDict _ = Just Dict + floatingDict _ = Just Dict + orderingDict _ = Just Dict + realFloatDict _ = Just Dict + realFracDict _ = Just Dict + realDict _ = Just Dict +instance Coefficient Float where + scalarType = SFloat + fractionalDict _ = Just Dict + floatingDict _ = Just Dict + orderingDict _ = Just Dict + realFloatDict _ = Just Dict + realFracDict _ = Just Dict + realDict _ = Just Dict +instance Coefficient Integer where + scalarType = SInteger + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict +instance Coefficient Rational where + scalarType = SRational + fractionalDict _ = Just Dict + orderingDict _ = Just Dict + realFracDict _ = Just Dict + realDict _ = Just Dict + forceCoefficient value = evaluate (numerator value) >> evaluate (denominator value) >> pure () +instance Coefficient (Complex Double) where + scalarType = SComplexDouble + fractionalDict _ = Just Dict + floatingDict _ = Just Dict + forceCoefficient value = evaluate (realPart value) >> evaluate (imagPart value) >> pure () +instance Coefficient (Complex Float) where + scalarType = SComplexFloat + fractionalDict _ = Just Dict + floatingDict _ = Just Dict + forceCoefficient value = evaluate (realPart value) >> evaluate (imagPart value) >> pure () + +instance Coefficient Int8 where + scalarType = SInt8 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Int16 where + scalarType = SInt16 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Int32 where + scalarType = SInt32 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Int64 where + scalarType = SInt64 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Word8 where + scalarType = SWord8 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Word16 where + scalarType = SWord16 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Word32 where + scalarType = SWord32 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Word64 where + scalarType = SWord64 + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Int where + scalarType = SInt + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance Coefficient Word where + scalarType = SWord + orderingDict _ = Just Dict + realDict _ = Just Dict + integralDict _ = Just Dict + boundedDict _ = Just Dict + +instance forall a. Coefficient a => Coefficient (N.Dual a) where + scalarType = SDual (scalarType :: ScalarType a) + fractionalDict _ = case fractionalDict (Proxy :: Proxy a) of + Just Dict -> Just Dict + Nothing -> Nothing + floatingDict _ = case floatingDict (Proxy :: Proxy a) of + Just Dict -> Just Dict + Nothing -> Nothing + forceCoefficient value = forceCoefficient (N.primal value) >> forceCoefficient (N.tangent value) + +instance forall a. (Coefficient a, RealFloat a) => Coefficient (N.Quaternion a) where + scalarType = SQuaternion (scalarType :: ScalarType a) + forceCoefficient (N.Quaternion a b c d) = + forceCoefficient a >> forceCoefficient b >> forceCoefficient c >> forceCoefficient d + +data SomeCoefficient where + SomeCoefficient :: Coefficient a => ScalarType a -> a -> SomeCoefficient + +coefficientDict :: ScalarType a -> Dict (Coefficient a) +coefficientDict witness = case witness of + SDouble -> Dict + SFloat -> Dict + SInteger -> Dict + SRational -> Dict + SComplexDouble -> Dict + SComplexFloat -> Dict + SInt8 -> Dict + SInt16 -> Dict + SInt32 -> Dict + SInt64 -> Dict + SWord8 -> Dict + SWord16 -> Dict + SWord32 -> Dict + SWord64 -> Dict + SInt -> Dict + SWord -> Dict + SDual child -> case coefficientDict child of Dict -> Dict + SQuaternion _ -> Dict + +scalarTypeCode :: ScalarType a -> Int +scalarTypeCode witness = case witness of + SDouble -> 0 + SFloat -> 1 + SInteger -> 2 + SRational -> 3 + SComplexDouble -> 4 + SComplexFloat -> 5 + SInt8 -> 6 + SInt16 -> 7 + SInt32 -> 8 + SInt64 -> 9 + SWord8 -> 10 + SWord16 -> 11 + SWord32 -> 12 + SWord64 -> 13 + SInt -> 14 + SWord -> 15 + SDual _ -> 20 + SQuaternion _ -> 21 diff --git a/src/HMath/FFI/DeepLearning.hs b/src/HMath/FFI/DeepLearning.hs new file mode 100644 index 0000000..6a2f2f4 --- /dev/null +++ b/src/HMath/FFI/DeepLearning.hs @@ -0,0 +1,261 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Original checked neural functions, records and AD/RNG/Tensor interoperability. +module HMath.FFI.DeepLearning where + +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import HMath.Error (MathError) +import HMath.FFI.Boundary +import HMath.FFI.MathError (CallbackFailure(..)) +import HMath.FFI.Coefficient (ScalarType(SDouble,SInt8)) +import HMath.FFI.Value (Value(..),asScalar,asIndex,asList,asTuple,asBoolean,invalid,publish,forceValue) +import HMath.FFI.TensorCodec (Element(Numeric),asTensorType,fromTensor) +import HMath.FFI.AutodiffValue (asADExpr,fromADExpr,asADTensor,fromADTensor) +import HMath.FFI.RandomCodec (asRNG,rng) +import qualified HMath.Autodiff as A +import qualified HMath.Random as R +import qualified HMath.Tensor as T +import qualified HMath.DeepLearning.Core as C +import qualified HMath.DeepLearning.Layers as L +import qualified HMath.DeepLearning.Precision as P +import qualified HMath.DeepLearning.Metrics as M + +class FromValue a where fromValue :: Value -> IO a +class ToValue a where toValue :: a -> IO Value +instance FromValue Double where fromValue = asScalar +instance ToValue Double where toValue = pure . Scalar SDouble +instance FromValue Int where fromValue = asIndex +instance ToValue Int where toValue = pure . Index +instance ToValue Int8 where toValue = pure . Scalar SInt8 +instance FromValue Bool where fromValue = asBoolean +instance ToValue Bool where toValue = pure . Boolean +instance FromValue a => FromValue [a] where fromValue value = asList value >>= mapM fromValue +instance ToValue a => ToValue [a] where toValue values = List <$> mapM toValue values +instance FromValue a => FromValue(Maybe a) where fromValue None = pure Nothing; fromValue value = Just <$> fromValue value +instance ToValue a => ToValue(Maybe a) where toValue = maybe(pure None)toValue +instance ToValue a => ToValue(Either MathError a) where + toValue(Left err) = throwIO(CallbackMathError err) + toValue(Right value) = toValue value +instance (FromValue a,FromValue b)=>FromValue(a,b) where + fromValue value = do [a,b]<-asTuple 2 value; (,) <$> fromValue a <*> fromValue b +instance (ToValue a,ToValue b)=>ToValue(a,b) where toValue(a,b) = Tuple <$> sequence[toValue a,toValue b] +instance (ToValue a,ToValue b,ToValue c)=>ToValue(a,b,c) where toValue(a,b,c) = Tuple <$> sequence[toValue a,toValue b,toValue c] +instance FromValue(T.Tensor Double) where fromValue = asTensorType +instance ToValue(T.Tensor Double) where toValue = pure . fromTensor(Numeric SDouble) +instance FromValue A.Expr where fromValue = asADExpr +instance ToValue A.Expr where toValue = pure . fromADExpr +instance FromValue A.ADTensor where fromValue = asADTensor +instance ToValue A.ADTensor where toValue = pure . fromADTensor +instance FromValue R.RNG where fromValue = asRNG +instance ToValue R.RNG where toValue = pure . rng + +opaque :: Typeable a => Int -> a -> IO () -> Value +opaque kind value force = Opaque kind (-1) 0 force value +unbox :: forall a. Typeable a => Int -> Value -> IO a +unbox expected(Opaque actual _ _ _ payload) | expected==actual = maybe(invalid "neural object type differs")pure(cast payload) +unbox _ _ = invalid "neural object kind differs" +forceFields :: [IO Value] -> IO () +forceFields actions = sequence actions >>= mapM_ forceValue + +instance FromValue C.Activation where fromValue = unbox 274 +instance ToValue C.Activation where toValue value = pure(opaque 274 value (evaluate value >> pure ())) + +instance FromValue C.Loss where fromValue = unbox 275 +instance ToValue C.Loss where toValue value = pure(opaque 275 value (evaluate value >> pure ())) + +instance FromValue C.Reduction where fromValue = unbox 276 +instance ToValue C.Reduction where toValue value = pure(opaque 276 value (evaluate value >> pure ())) + +instance FromValue L.Training where fromValue = unbox 277 +instance ToValue L.Training where toValue value = pure(opaque 277 value (evaluate value >> pure ())) + +instance FromValue L.BatchNormState where fromValue = unbox 278 +instance ToValue L.BatchNormState where toValue value = pure(opaque 278 value (forceFields [toValue((L.runningMean) value),toValue((L.runningVariance) value),toValue((L.batchesSeen) value)])) + +instance FromValue L.Initializer where fromValue = unbox 279 +instance ToValue L.Initializer where toValue value = pure(opaque 279 value (evaluate value >> pure ())) + +instance FromValue L.ConvOptions where fromValue = unbox 280 +instance ToValue L.ConvOptions where toValue value = pure(opaque 280 value (forceFields [toValue((L.convolutionStride) value),toValue((L.convolutionPadding) value),toValue((L.convolutionDilation) value),toValue((L.convolutionGroups) value)])) + +instance FromValue L.PoolMode where fromValue = unbox 281 +instance ToValue L.PoolMode where toValue value = pure(opaque 281 value (evaluate value >> pure ())) + +instance FromValue L.KVCache where fromValue = unbox 282 +instance ToValue L.KVCache where toValue value = pure(opaque 282 value (forceFields [toValue((fst . L.cacheValues) value),toValue((snd . L.cacheValues) value)])) + +instance FromValue P.Quantization where fromValue = unbox 283 +instance ToValue P.Quantization where toValue value = pure(opaque 283 value (evaluate value >> pure ())) + +instance FromValue P.Precision where fromValue = unbox 284 +instance ToValue P.Precision where toValue value = pure(opaque 284 value (evaluate value >> pure ())) + +instance FromValue P.QuantizedTensor where fromValue = unbox 285 +instance ToValue P.QuantizedTensor where toValue value = pure(opaque 285 value (forceFields [toValue((P.quantizedValues) value),toValue((P.quantizationScales) value),toValue((P.quantizationZeroPoints) value)])) + +instance FromValue P.LossScaler where fromValue = unbox 286 +instance ToValue P.LossScaler where toValue value = pure(opaque 286 value (forceFields [toValue((P.lossScale) value),toValue((P.scaleGrowthInterval) value),toValue((P.finiteSteps) value)])) + +instance FromValue M.ClassificationMetrics where fromValue = unbox 290 +instance ToValue M.ClassificationMetrics where toValue value = pure(opaque 290 value (forceFields [toValue((M.accuracy) value),toValue((M.precisionByClass) value),toValue((M.recallByClass) value),toValue((M.f1ByClass) value)])) + +class Apply a where apply :: a -> [Value] -> IO Value +instance {-# OVERLAPPABLE #-} ToValue a => Apply a where + apply value [] = toValue value + apply _ _ = invalid "too many neural arguments" +instance {-# OVERLAPPING #-} (FromValue a,Apply b)=>Apply(a -> b) where + apply function(value:rest) = fromValue value >>= \argument -> apply(function argument)rest + apply _ [] = invalid "missing neural argument" +foreign export ccall "hm_neural_apply" ffiApply :: CString -> Ptr(StablePtr Value) -> CSize -> Ptr(StablePtr Value) -> IO CInt +ffiApply :: CString -> Ptr(StablePtr Value) -> CSize -> Ptr(StablePtr Value) -> IO CInt +ffiApply namePointer inputs count out = boundary $ do + name<-peekCString namePointer + arguments<-peekArray(fromIntegral count)inputs >>= mapM deRefStablePtr + result<-dispatch name arguments + checked(Right())(\_ -> publish result out) +dispatch :: String -> [Value] -> IO Value +dispatch name arguments = case name of +-- BEGIN GENERATED + "HMath.DeepLearning.Core.Sigmoid" -> apply C.Sigmoid arguments + "HMath.DeepLearning.Core.Tanh" -> apply C.Tanh arguments + "HMath.DeepLearning.Core.ReLU" -> apply C.ReLU arguments + "HMath.DeepLearning.Core.SELU" -> apply C.SELU arguments + "HMath.DeepLearning.Core.GELU" -> apply C.GELU arguments + "HMath.DeepLearning.Core.SiLU" -> apply C.SiLU arguments + "HMath.DeepLearning.Core.Mish" -> apply C.Mish arguments + "HMath.DeepLearning.Core.Softplus" -> apply C.Softplus arguments + "HMath.DeepLearning.Core.Softsign" -> apply C.Softsign arguments + "HMath.DeepLearning.Core.HardSigmoid" -> apply C.HardSigmoid arguments + "HMath.DeepLearning.Core.HardSwish" -> apply C.HardSwish arguments + "HMath.DeepLearning.Core.LeakyReLU" -> apply C.LeakyReLU arguments + "HMath.DeepLearning.Core.PReLU" -> apply C.PReLU arguments + "HMath.DeepLearning.Core.ELU" -> apply C.ELU arguments + "HMath.DeepLearning.Core.Sum" -> apply C.Sum arguments + "HMath.DeepLearning.Core.Mean" -> apply C.Mean arguments + "HMath.DeepLearning.Core.MeanSquaredError" -> apply C.MeanSquaredError arguments + "HMath.DeepLearning.Core.MeanAbsoluteError" -> apply C.MeanAbsoluteError arguments + "HMath.DeepLearning.Core.BinaryCrossEntropy" -> apply C.BinaryCrossEntropy arguments + "HMath.DeepLearning.Core.CategoricalCrossEntropy" -> apply C.CategoricalCrossEntropy arguments + "HMath.DeepLearning.Core.NegativeLogLikelihood" -> apply C.NegativeLogLikelihood arguments + "HMath.DeepLearning.Core.KLDivergence" -> apply C.KLDivergence arguments + "HMath.DeepLearning.Core.CosineLoss" -> apply C.CosineLoss arguments + "HMath.DeepLearning.Core.Huber" -> apply C.Huber arguments + "HMath.DeepLearning.Core.SmoothL1" -> apply C.SmoothL1 arguments + "HMath.DeepLearning.Core.Hinge" -> apply C.Hinge arguments + "HMath.DeepLearning.Core.activation" -> apply C.activation arguments + "HMath.DeepLearning.Core.activationDerivative" -> apply C.activationDerivative arguments + "HMath.DeepLearning.Core.activationExpr" -> apply C.activationExpr arguments + "HMath.DeepLearning.Core.softmax" -> apply C.softmax arguments + "HMath.DeepLearning.Core.logSoftmax" -> apply C.logSoftmax arguments + "HMath.DeepLearning.Core.sparsemax" -> apply C.sparsemax arguments + "HMath.DeepLearning.Core.gatedLinearUnit" -> apply C.gatedLinearUnit arguments + "HMath.DeepLearning.Core.softmaxExpr" -> apply C.softmaxExpr arguments + "HMath.DeepLearning.Core.logSoftmaxExpr" -> apply C.logSoftmaxExpr arguments + "HMath.DeepLearning.Core.sparsemaxExpr" -> apply C.sparsemaxExpr arguments + "HMath.DeepLearning.Core.loss" -> apply C.loss arguments + "HMath.DeepLearning.Core.lossGradient" -> apply C.lossGradient arguments + "HMath.DeepLearning.Core.lossExpr" -> apply C.lossExpr arguments + "HMath.DeepLearning.Core.binaryCrossEntropyLogits" -> apply C.binaryCrossEntropyLogits arguments + "HMath.DeepLearning.Core.categoricalCrossEntropyLogits" -> apply C.categoricalCrossEntropyLogits arguments + "HMath.DeepLearning.Core.regularization" -> apply C.regularization arguments + "HMath.DeepLearning.Core.contrastiveLoss" -> apply C.contrastiveLoss arguments + "HMath.DeepLearning.Core.tripletLoss" -> apply C.tripletLoss arguments + "HMath.DeepLearning.Core.focalLoss" -> apply C.focalLoss arguments + "HMath.DeepLearning.Core.diceLoss" -> apply C.diceLoss arguments + "HMath.DeepLearning.Core.iouLoss" -> apply C.iouLoss arguments + "HMath.DeepLearning.Core.ctcLoss" -> apply C.ctcLoss arguments + "HMath.DeepLearning.Core.ctcLossGradient" -> apply C.ctcLossGradient arguments + "HMath.DeepLearning.Core.ctcLossExpr" -> apply C.ctcLossExpr arguments + "HMath.DeepLearning.Layers.Training" -> apply L.Training arguments + "HMath.DeepLearning.Layers.Inference" -> apply L.Inference arguments + "HMath.DeepLearning.Layers.dropout" -> apply L.dropout arguments + "HMath.DeepLearning.Layers.spatialDropout" -> apply L.spatialDropout arguments + "HMath.DeepLearning.Layers.BatchNormState" -> apply L.BatchNormState arguments + "HMath.DeepLearning.Layers.runningMean" -> apply L.runningMean arguments + "HMath.DeepLearning.Layers.runningVariance" -> apply L.runningVariance arguments + "HMath.DeepLearning.Layers.batchesSeen" -> apply L.batchesSeen arguments + "HMath.DeepLearning.Layers.batchNorm" -> apply L.batchNorm arguments + "HMath.DeepLearning.Layers.layerNorm" -> apply L.layerNorm arguments + "HMath.DeepLearning.Layers.rmsNorm" -> apply L.rmsNorm arguments + "HMath.DeepLearning.Layers.instanceNorm" -> apply L.instanceNorm arguments + "HMath.DeepLearning.Layers.groupNorm" -> apply L.groupNorm arguments + "HMath.DeepLearning.Layers.weightNorm" -> apply L.weightNorm arguments + "HMath.DeepLearning.Layers.XavierUniform" -> apply L.XavierUniform arguments + "HMath.DeepLearning.Layers.XavierNormal" -> apply L.XavierNormal arguments + "HMath.DeepLearning.Layers.KaimingUniform" -> apply L.KaimingUniform arguments + "HMath.DeepLearning.Layers.KaimingNormal" -> apply L.KaimingNormal arguments + "HMath.DeepLearning.Layers.Orthogonal" -> apply L.Orthogonal arguments + "HMath.DeepLearning.Layers.TruncatedNormal" -> apply L.TruncatedNormal arguments + "HMath.DeepLearning.Layers.initializeWeights" -> apply L.initializeWeights arguments + "HMath.DeepLearning.Layers.embedding" -> apply L.embedding arguments + "HMath.DeepLearning.Layers.dense" -> apply L.dense arguments + "HMath.DeepLearning.Layers.denseAD" -> apply L.denseAD arguments + "HMath.DeepLearning.Layers.ConvOptions" -> apply L.ConvOptions arguments + "HMath.DeepLearning.Layers.convolutionStride" -> apply L.convolutionStride arguments + "HMath.DeepLearning.Layers.convolutionPadding" -> apply L.convolutionPadding arguments + "HMath.DeepLearning.Layers.convolutionDilation" -> apply L.convolutionDilation arguments + "HMath.DeepLearning.Layers.convolutionGroups" -> apply L.convolutionGroups arguments + "HMath.DeepLearning.Layers.convolution" -> apply L.convolution arguments + "HMath.DeepLearning.Layers.depthwiseConvolution" -> apply L.depthwiseConvolution arguments + "HMath.DeepLearning.Layers.convolutionAD" -> apply L.convolutionAD arguments + "HMath.DeepLearning.Layers.transposedConvolution" -> apply L.transposedConvolution arguments + "HMath.DeepLearning.Layers.MaxPool" -> apply L.MaxPool arguments + "HMath.DeepLearning.Layers.AveragePool" -> apply L.AveragePool arguments + "HMath.DeepLearning.Layers.pooling" -> apply L.pooling arguments + "HMath.DeepLearning.Layers.adaptivePooling" -> apply L.adaptivePooling arguments + "HMath.DeepLearning.Layers.globalPooling" -> apply L.globalPooling arguments + "HMath.DeepLearning.Layers.scaledDotProductAttention" -> apply L.scaledDotProductAttention arguments + "HMath.DeepLearning.Layers.multiheadAttention" -> apply L.multiheadAttention arguments + "HMath.DeepLearning.Layers.causalMask" -> apply L.causalMask arguments + "HMath.DeepLearning.Layers.rotaryEmbedding" -> apply L.rotaryEmbedding arguments + "HMath.DeepLearning.Layers.sinusoidalEncoding" -> apply L.sinusoidalEncoding arguments + "HMath.DeepLearning.Layers.alibiBias" -> apply L.alibiBias arguments + "HMath.DeepLearning.Layers.emptyCache" -> apply L.emptyCache arguments + "HMath.DeepLearning.Layers.appendCache" -> apply L.appendCache arguments + "HMath.DeepLearning.Layers.cacheValues" -> apply L.cacheValues arguments + "HMath.DeepLearning.Layers.transformerFeedForward" -> apply L.transformerFeedForward arguments + "HMath.DeepLearning.Layers.layerNormAD" -> apply L.layerNormAD arguments + "HMath.DeepLearning.Layers.rmsNormAD" -> apply L.rmsNormAD arguments + "HMath.DeepLearning.Layers.scaledDotProductAttentionAD" -> apply L.scaledDotProductAttentionAD arguments + "HMath.DeepLearning.Precision.Symmetric" -> apply P.Symmetric arguments + "HMath.DeepLearning.Precision.Asymmetric" -> apply P.Asymmetric arguments + "HMath.DeepLearning.Precision.quantize" -> apply P.quantize arguments + "HMath.DeepLearning.Precision.dequantize" -> apply P.dequantize arguments + "HMath.DeepLearning.Precision.quantizedValues" -> apply P.quantizedValues arguments + "HMath.DeepLearning.Precision.quantizationScales" -> apply P.quantizationScales arguments + "HMath.DeepLearning.Precision.quantizationZeroPoints" -> apply P.quantizationZeroPoints arguments + "HMath.DeepLearning.Precision.int8Gemm" -> apply P.int8Gemm arguments + "HMath.DeepLearning.Precision.FP16" -> apply P.FP16 arguments + "HMath.DeepLearning.Precision.BF16" -> apply P.BF16 arguments + "HMath.DeepLearning.Precision.reducedGemm" -> apply P.reducedGemm arguments + "HMath.DeepLearning.Precision.LossScaler" -> apply P.LossScaler arguments + "HMath.DeepLearning.Precision.lossScale" -> apply P.lossScale arguments + "HMath.DeepLearning.Precision.scaleGrowthInterval" -> apply P.scaleGrowthInterval arguments + "HMath.DeepLearning.Precision.finiteSteps" -> apply P.finiteSteps arguments + "HMath.DeepLearning.Precision.initialLossScaler" -> apply P.initialLossScaler arguments + "HMath.DeepLearning.Precision.scaleLoss" -> apply P.scaleLoss arguments + "HMath.DeepLearning.Precision.unscaleGradients" -> apply P.unscaleGradients arguments + "HMath.DeepLearning.Precision.updateLossScaler" -> apply P.updateLossScaler arguments + "HMath.DeepLearning.Precision.gradientNorm" -> apply P.gradientNorm arguments + "HMath.DeepLearning.Precision.clipGradients" -> apply P.clipGradients arguments + "HMath.DeepLearning.Metrics.ClassificationMetrics" -> apply M.ClassificationMetrics arguments + "HMath.DeepLearning.Metrics.accuracy" -> apply M.accuracy arguments + "HMath.DeepLearning.Metrics.precisionByClass" -> apply M.precisionByClass arguments + "HMath.DeepLearning.Metrics.recallByClass" -> apply M.recallByClass arguments + "HMath.DeepLearning.Metrics.f1ByClass" -> apply M.f1ByClass arguments + "HMath.DeepLearning.Metrics.confusionMatrix" -> apply M.confusionMatrix arguments + "HMath.DeepLearning.Metrics.classificationMetrics" -> apply M.classificationMetrics arguments + "HMath.DeepLearning.Metrics.topKAccuracy" -> apply M.topKAccuracy arguments + "HMath.DeepLearning.Metrics.rocAUC" -> apply M.rocAUC arguments + "HMath.DeepLearning.Metrics.prAUC" -> apply M.prAUC arguments + "HMath.DeepLearning.Metrics.perplexity" -> apply M.perplexity arguments + "HMath.DeepLearning.Metrics.cosineSimilarityMatrix" -> apply M.cosineSimilarityMatrix arguments + "HMath.DeepLearning.Metrics.marginRankingLoss" -> apply M.marginRankingLoss arguments +-- END GENERATED + _ -> invalid "invalid neural operation" diff --git a/src/HMath/FFI/Execution.hs b/src/HMath/FFI/Execution.hs new file mode 100644 index 0000000..de1fd54 --- /dev/null +++ b/src/HMath/FFI/Execution.hs @@ -0,0 +1,65 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Reference buffer execution delegates arithmetic to the existing matrices. +module HMath.FFI.Execution where +import Control.Exception (evaluate) +import Data.Coerce (coerce) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import qualified HMath.Matrix as M +import qualified HMath.Matrix.Internal as I + +readRows :: Storable a => Int -> Int -> Int -> Ptr a -> IO [a] +readRows rows columns stride pointer + | rows == 0 || columns == 0 = pure [] + | stride == columns = peekArray (rows * columns) pointer + | otherwise = concat <$> mapM (\row -> peekArray columns (advancePtr pointer (row * stride))) [0 .. rows-1] +writeRows :: Storable a => Int -> Int -> Int -> Ptr a -> [a] -> IO () +writeRows rows columns stride pointer values + | rows == 0 || columns == 0 = pure () + | stride == columns = pokeArray pointer values + | otherwise = go 0 values + where + go row remaining + | row == rows = pure () + | otherwise = let (chunk,rest)=splitAt columns remaining + in pokeArray (advancePtr pointer (row * stride)) chunk >> go (row+1) rest + +foreign export ccall "hm_execution_reference_f32" reference32 :: CSize -> CSize -> CSize -> CFloat -> Ptr CFloat -> CSize -> Ptr CFloat -> CSize -> CFloat -> Ptr CFloat -> CSize -> IO CInt +reference32 :: CSize -> CSize -> CSize -> CFloat -> Ptr CFloat -> CSize -> Ptr CFloat -> CSize -> CFloat -> Ptr CFloat -> CSize -> IO CInt +reference32 m n k alpha ap lda bp ldb beta cp ldc = boundary $ do + av <- readRows (fromIntegral m) (fromIntegral k) (fromIntegral lda) (castPtr ap :: Ptr Float) + bv <- readRows (fromIntegral k) (fromIntegral n) (fromIntegral ldb) (castPtr bp :: Ptr Float) + cv <- readRows (fromIntegral m) (fromIntegral n) (fromIntegral ldc) (castPtr cp :: Ptr Float) + let computation = do + a <- M.fromListChecked (fromIntegral m) (fromIntegral k) av + b <- M.fromListChecked (fromIntegral k) (fromIntegral n) bv + c <- M.fromListChecked (fromIntegral m) (fromIntegral n) cv + I.finiteValues ((coerce alpha :: Float) : (coerce beta :: Float) : av ++ bv ++ cv) + productM <- M.multiplyChecked a b + result <- M.addMatrixChecked (M.scaleMatrix (coerce alpha) productM) (M.scaleMatrix (coerce beta) c) + I.finiteValues (M.toList result) + Right (M.toList result) + checked computation $ \values -> do + strict <- mapM evaluate values + writeRows (fromIntegral m) (fromIntegral n) (fromIntegral ldc) (castPtr cp :: Ptr Float) strict + +foreign export ccall "hm_execution_reference_f64" reference64 :: CSize -> CSize -> CSize -> CDouble -> Ptr CDouble -> CSize -> Ptr CDouble -> CSize -> CDouble -> Ptr CDouble -> CSize -> IO CInt +reference64 :: CSize -> CSize -> CSize -> CDouble -> Ptr CDouble -> CSize -> Ptr CDouble -> CSize -> CDouble -> Ptr CDouble -> CSize -> IO CInt +reference64 m n k alpha ap lda bp ldb beta cp ldc = boundary $ do + av <- readRows (fromIntegral m) (fromIntegral k) (fromIntegral lda) (castPtr ap :: Ptr Double) + bv <- readRows (fromIntegral k) (fromIntegral n) (fromIntegral ldb) (castPtr bp :: Ptr Double) + cv <- readRows (fromIntegral m) (fromIntegral n) (fromIntegral ldc) (castPtr cp :: Ptr Double) + let computation = do + a <- M.fromListChecked (fromIntegral m) (fromIntegral k) av + b <- M.fromListChecked (fromIntegral k) (fromIntegral n) bv + c <- M.fromListChecked (fromIntegral m) (fromIntegral n) cv + I.finiteValues ((coerce alpha :: Double) : (coerce beta :: Double) : av ++ bv ++ cv) + productM <- M.multiplyChecked a b + result <- M.addMatrixChecked (M.scaleMatrix (coerce alpha) productM) (M.scaleMatrix (coerce beta) c) + I.finiteValues (M.toList result) + Right (M.toList result) + checked computation $ \values -> do + strict <- mapM evaluate values + writeRows (fromIntegral m) (fromIntegral n) (fromIntegral ldc) (castPtr cp :: Ptr Double) strict diff --git a/src/HMath/FFI/Expression.hs b/src/HMath/FFI/Expression.hs new file mode 100644 index 0000000..98195fd --- /dev/null +++ b/src/HMath/FFI/Expression.hs @@ -0,0 +1,430 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Lossless language adapters; every mathematical transformation calls source APIs. +module HMath.FFI.Expression where +import Control.Exception (Exception, catch, evaluate, throwIO) +import Data.Complex (Complex) +import Data.List (elemIndex) +import qualified Data.Map.Strict as Map +import Data.Typeable (Typeable, cast) +import Foreign +import Foreign.C +import qualified HMath.Expression as E +import qualified HMath.Symbolic as S +import qualified HMath.Polynomial as P +import qualified HMath.FFI.Polynomial as Poly +import HMath.FFI.Coefficient (ScalarType (SDouble,SRational,SWord64,SComplexDouble)) +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError (withEncodedMessage) +import HMath.FFI.Value (Value(..), asIndex, asList, asTuple, asText, asBoolean, asScalar, invalid, publish) + +class FromValue a where fromValue :: Value -> IO a +class ToValue a where toValue :: a -> IO Value +instance FromValue Value where fromValue = pure +instance ToValue Value where toValue = pure +instance FromValue Double where fromValue = asScalar +instance ToValue Double where toValue = pure . Scalar SDouble +instance FromValue Rational where fromValue = asScalar +instance ToValue Rational where toValue = pure . Scalar SRational +instance ToValue (Complex Double) where toValue = pure . Scalar SComplexDouble +instance FromValue Int where fromValue = asIndex +instance ToValue Int where toValue = pure . Index +instance ToValue Word64 where toValue = pure . Scalar SWord64 +instance FromValue Bool where fromValue = asBoolean +instance ToValue Bool where toValue = pure . Boolean +instance {-# OVERLAPPING #-} FromValue String where fromValue = asText +instance {-# OVERLAPPING #-} ToValue String where toValue = pure . Text +instance {-# OVERLAPPABLE #-} FromValue a => FromValue [a] where fromValue v = asList v >>= mapM fromValue +instance {-# OVERLAPPABLE #-} ToValue a => ToValue [a] where toValue xs = List <$> mapM toValue xs +instance FromValue a => FromValue (Maybe a) where fromValue None = pure Nothing; fromValue x = Just <$> fromValue x +instance ToValue a => ToValue (Maybe a) where toValue = maybe (pure None) toValue +instance ToValue () where toValue () = pure None +instance ToValue a => ToValue (Either E.ExprError a) where + toValue (Left err) = throwIO (ExpressionFailure err) + toValue (Right x) = toValue x +instance (FromValue a,FromValue b) => FromValue (a,b) where + fromValue v = do [a,b]<-asTuple 2 v; (,) <$> fromValue a <*> fromValue b +instance (ToValue a,ToValue b) => ToValue (a,b) where toValue (a,b) = Tuple <$> sequence [toValue a,toValue b] +instance (FromValue a,FromValue b,FromValue c) => FromValue (a,b,c) where + fromValue v = do [a,b,c]<-asTuple 3 v; (,,) <$> fromValue a <*> fromValue b <*> fromValue c +instance (ToValue a,ToValue b,ToValue c) => ToValue (a,b,c) where toValue (a,b,c) = Tuple <$> sequence [toValue a,toValue b,toValue c] + +unbox :: forall a. Typeable a => Int -> Value -> IO a +unbox kind (Opaque actual _ _ _ value) | actual==kind = maybe (invalid "expression object type differs") pure (cast value) +unbox _ _ = invalid "expression object kind differs" +boxed :: Typeable a => Int -> a -> Value +boxed kind value = Opaque kind (-1) 0 (evaluate value >> pure ()) value +fromEnumValue :: [a] -> Value -> IO a +fromEnumValue values value = do n<-asIndex value; if n<0 || n>=length values then invalid "expression enum representation is invalid" else pure (values!!n) +toEnumValue :: Eq a => [a] -> a -> IO Value +toEnumValue values value = maybe (invalid "unknown expression enum") (pure . Index) (elemIndex value values) + +instance FromValue E.SourcePos where + fromValue value = do [a,b,c]<-asTuple 3 value; E.SourcePos <$> fromValue a <*> fromValue b <*> fromValue c +instance ToValue E.SourcePos where toValue (E.SourcePos a b c) = toValue (a,b,c) +instance FromValue E.Limits where + fromValue value = do [a,b,c,d,e,f]<-asTuple 6 value; E.Limits <$> fromValue a <*> fromValue b <*> fromValue c <*> fromValue d <*> fromValue e <*> fromValue f +instance ToValue E.Limits where toValue value = Tuple <$> mapM toValue [E.maximumSteps value,E.maximumDepth value,E.maximumNodes value,E.maximumInputChars value,E.maximumIntegerBits value,E.maximumCacheEntries value] +instance FromValue E.ExprError where + fromValue value = do [a,b,c]<-asTuple 3 value; E.ExprError <$> fromValue a <*> fromValue b <*> fromValue c +instance ToValue E.ExprError where toValue (E.ExprError a b c) = toValue (a,b,c) +instance FromValue E.Value where + fromValue value = do + [tag,payload]<-asTuple 2 value + kind<-asIndex tag + case kind of { 0 -> E.ExactValue <$> fromValue payload; 1 -> E.FloatValue <$> fromValue payload; _ -> invalid "invalid expression Value constructor" } +instance ToValue E.Value where + toValue (E.ExactValue q) = Tuple <$> sequence [pure (Index 0),toValue q] + toValue (E.FloatValue x) = Tuple <$> sequence [pure (Index 1),toValue x] +instance FromValue E.Bindings where fromValue value = Map.fromList <$> fromValue value +instance ToValue E.Bindings where toValue = toValue . Map.toAscList +instance FromValue S.SymbolicOptions where + fromValue value = do [a,b]<-asTuple 2 value; S.SymbolicOptions <$> fromValue a <*> fromValue b +instance ToValue S.SymbolicOptions where toValue (S.SymbolicOptions a b) = toValue (a,b) +instance FromValue S.PolynomialFactorization where + fromValue value = do [a,b]<-asTuple 2 value; S.PolynomialFactorization <$> fromValue a <*> fromValue b +instance ToValue S.PolynomialFactorization where toValue (S.PolynomialFactorization a b) = toValue (a,b) +instance FromValue S.RewriteRule where + fromValue value = do [a,b,c]<-asTuple 3 value; S.RewriteRule <$> fromValue a <*> fromValue b <*> fromValue c +instance ToValue S.RewriteRule where toValue (S.RewriteRule a b c) = toValue (a,b,c) +instance FromValue S.Series where + fromValue value = do [a,b,c]<-asTuple 3 value; S.Series <$> fromValue a <*> fromValue b <*> fromValue c +instance ToValue S.Series where toValue (S.Series a b c) = toValue (a,b,c) +instance FromValue S.Relation where + fromValue value = do [a,b,c]<-asTuple 3 value; S.Relation <$> fromValue a <*> fromValue b <*> fromValue c +instance ToValue S.Relation where toValue (S.Relation a b c) = toValue (a,b,c) +instance FromValue S.RelationResult where + fromValue value = do + [tag,payload]<-asTuple 2 value; kind<-asIndex tag + case kind of {0 -> S.Truth <$> fromValue payload; 1 -> S.Unresolved <$> fromValue payload; _ -> invalid "invalid RelationResult constructor"} +instance ToValue S.RelationResult where + toValue (S.Truth x) = Tuple <$> sequence [pure (Index 0),toValue x] + toValue (S.Unresolved x) = Tuple <$> sequence [pure (Index 1),toValue x] +instance FromValue S.LimitResult where + fromValue (Tuple [Index 0,payload]) = S.FiniteLimit <$> fromValue payload + fromValue (Tuple [Index 1]) = pure S.PositiveInfinity + fromValue (Tuple [Index 2]) = pure S.NegativeInfinity + fromValue (Tuple [Index 3]) = pure S.DoesNotExist + fromValue _ = invalid "invalid LimitResult constructor" +instance ToValue S.LimitResult where + toValue (S.FiniteLimit x) = Tuple <$> sequence [pure (Index 0),toValue x] + toValue S.PositiveInfinity = pure (Tuple [Index 1]) + toValue S.NegativeInfinity = pure (Tuple [Index 2]) + toValue S.DoesNotExist = pure (Tuple [Index 3]) +instance FromValue S.LinearSolution where + fromValue (Tuple [Index 0]) = pure S.Inconsistent + fromValue (Tuple [Index 1,a,b]) = S.ParametricSolution <$> fromValue a <*> fromValue b + fromValue _ = invalid "invalid LinearSolution constructor" +instance ToValue S.LinearSolution where + toValue S.Inconsistent = pure (Tuple [Index 0]) + toValue (S.ParametricSolution a b) = Tuple <$> sequence [pure (Index 1),toValue a,toValue b] +instance FromValue (S.Guarded Value) where + fromValue value = do [a,b]<-asTuple 2 value; S.Guarded a <$> fromValue b +instance ToValue a => ToValue (S.Guarded a) where toValue (S.Guarded a b) = toValue (a,b) +instance FromValue (P.Polynomial Rational) where fromValue = Poly.asPolynomial +instance ToValue (P.Polynomial Rational) where toValue = pure . Poly.poly SRational +instance FromValue (P.PowerSeries Rational) where fromValue = Poly.asSeries +instance ToValue (P.PowerSeries Rational) where toValue = pure . Poly.series SRational + +instance FromValue E.UnaryOp where fromValue = fromEnumValue [E.Negate] +instance ToValue E.UnaryOp where toValue = toEnumValue [E.Negate] + +instance FromValue E.BinaryOp where fromValue = fromEnumValue [E.Add,E.Subtract,E.Multiply,E.Divide,E.Power] +instance ToValue E.BinaryOp where toValue = toEnumValue [E.Add,E.Subtract,E.Multiply,E.Divide,E.Power] + +instance FromValue E.NamedConstant where fromValue = fromEnumValue [E.Pi,E.Euler,E.Tau] +instance ToValue E.NamedConstant where toValue = toEnumValue [E.Pi,E.Euler,E.Tau] + +instance FromValue E.Precision where fromValue = fromEnumValue [E.ExactRational,E.Float64] +instance ToValue E.Precision where toValue = toEnumValue [E.ExactRational,E.Float64] + +instance FromValue E.ErrorKind where fromValue = fromEnumValue [E.SyntaxError,E.UnknownName,E.TypeMismatch,E.DomainFailure,E.NonFinite,E.StepLimit,E.DepthLimit,E.MemoryLimit,E.InvalidLimits,E.Unsupported] +instance ToValue E.ErrorKind where toValue = toEnumValue [E.SyntaxError,E.UnknownName,E.TypeMismatch,E.DomainFailure,E.NonFinite,E.StepLimit,E.DepthLimit,E.MemoryLimit,E.InvalidLimits,E.Unsupported] + +instance FromValue E.Builtin where fromValue = fromEnumValue [E.Sin,E.Cos,E.Tan,E.Exp,E.Log,E.Sqrt,E.Abs,E.Signum,E.Floor,E.Ceiling,E.Min,E.Max,E.Asin,E.Acos,E.Atan,E.Sinh,E.Cosh,E.Tanh] +instance ToValue E.Builtin where toValue = toEnumValue [E.Sin,E.Cos,E.Tan,E.Exp,E.Log,E.Sqrt,E.Abs,E.Signum,E.Floor,E.Ceiling,E.Min,E.Max,E.Asin,E.Acos,E.Atan,E.Sinh,E.Cosh,E.Tanh] + +instance FromValue S.Property where fromValue = fromEnumValue [S.Real,S.NonZero,S.Positive,S.NonNegative,S.Integral,S.Negative,S.NonPositive] +instance ToValue S.Property where toValue = toEnumValue [S.Real,S.NonZero,S.Positive,S.NonNegative,S.Integral,S.Negative,S.NonPositive] + +instance FromValue S.Direction where fromValue = fromEnumValue [S.FromLeft,S.FromRight,S.TwoSided] +instance ToValue S.Direction where toValue = toEnumValue [S.FromLeft,S.FromRight,S.TwoSided] + +instance FromValue S.RelationOp where fromValue = fromEnumValue [S.Equal,S.NotEqual,S.Less,S.LessEqual,S.Greater,S.GreaterEqual] +instance ToValue S.RelationOp where toValue = toEnumValue [S.Equal,S.NotEqual,S.Less,S.LessEqual,S.Greater,S.GreaterEqual] + +instance FromValue E.Expr where fromValue = unbox 80 +instance ToValue E.Expr where toValue = pure . boxed 80 + +instance FromValue E.ExprNode where fromValue = unbox 81 +instance ToValue E.ExprNode where toValue = pure . boxed 81 + +instance FromValue E.Registry where fromValue = unbox 82 +instance ToValue E.Registry where toValue = pure . boxed 82 + +instance FromValue E.Compiled where fromValue = unbox 83 +instance ToValue E.Compiled where toValue = pure . boxed 83 + +instance FromValue E.ExpressionCache where fromValue = unbox 84 +instance ToValue E.ExpressionCache where toValue = pure . boxed 84 + +instance FromValue S.Pattern where fromValue = unbox 85 +instance ToValue S.Pattern where toValue = pure . boxed 85 + +instance FromValue S.Assumptions where fromValue = unbox 86 +instance ToValue S.Assumptions where toValue = pure . boxed 86 + +instance FromValue S.SymbolicMatrix where fromValue = unbox 87 +instance ToValue S.SymbolicMatrix where toValue = pure . boxed 87 + +class Apply a where apply :: a -> [Value] -> IO Value +instance {-# OVERLAPPABLE #-} ToValue a => Apply a where + apply value [] = toValue value + apply _ _ = invalid "too many expression arguments" +instance {-# OVERLAPPING #-} (FromValue a,Apply b) => Apply (a -> b) where + apply function (value:rest) = fromValue value >>= \argument -> apply (function argument) rest + apply _ [] = invalid "missing expression argument" + +data ExpressionFailure = ExpressionFailure E.ExprError deriving Show +instance Exception ExpressionFailure +foreign import ccall unsafe "hm_error" report :: CInt -> CString -> IO CInt +foreign import ccall unsafe "hm_record_expression_error" recordError :: CInt -> Ptr CPtrdiff -> CString -> CSize -> IO CInt +expressionBoundary :: IO CInt -> IO CInt +expressionBoundary action = B.boundary (action `catch` failed) + where + failed (ExpressionFailure err) = do + _ <- withCString (show err) (report 12) + Index kind <- toValue (E.errorKind err) + let E.SourcePos offset line column = E.errorPosition err + code <- withArray (map fromIntegral [offset,line,column]) $ \position -> + withEncodedMessage (E.errorMessage err) (recordError (fromIntegral kind) position) + if code == 0 then pure 12 else withCString "unable to record ExprError" (report code) +foreign export ccall "hm_expression_apply" ffiApply :: CString -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +ffiApply :: CString -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +ffiApply namePointer arguments count out = expressionBoundary $ do + name<-peekCString namePointer + values<-peekArray (fromIntegral count) arguments >>= mapM deRefStablePtr + result<-dispatch name values + B.checked (Right ()) $ \_ -> publish result out +nodeFields :: E.ExprNode -> IO Value +nodeFields node = case node of + E.Literal q -> Tuple <$> sequence [pure (Index 0),toValue q] + E.Variable n -> Tuple <$> sequence [pure (Index 1),toValue n] + E.Constant c -> Tuple <$> sequence [pure (Index 2),toValue c] + E.Unary op child -> Tuple <$> sequence [pure (Index 3),toValue op,toValue child] + E.Binary op a b -> Tuple <$> sequence [pure (Index 4),toValue op,toValue a,toValue b] + E.Call name args -> Tuple <$> sequence [pure (Index 5),toValue name,toValue args] + E.Let name a b -> Tuple <$> sequence [pure (Index 6),toValue name,toValue a,toValue b] +patternFields :: S.Pattern -> IO Value +patternFields patternValue = case patternValue of + S.Any name -> Tuple <$> sequence [pure (Index 0),toValue name] + S.Exactly expr -> Tuple <$> sequence [pure (Index 1),toValue expr] + S.UnaryPattern op child -> Tuple <$> sequence [pure (Index 2),toValue op,toValue child] + S.BinaryPattern op a b -> Tuple <$> sequence [pure (Index 3),toValue op,toValue a,toValue b] + S.CallPattern name args -> Tuple <$> sequence [pure (Index 4),toValue name,toValue args] +dispatch :: String -> [Value] -> IO Value +dispatch name arguments = case name of +-- BEGIN GENERATED + "HMath.Expression.SourcePos" -> apply E.SourcePos arguments + "HMath.Expression.unknownPosition" -> apply E.unknownPosition arguments + "HMath.Expression.sourceOffset" -> apply E.sourceOffset arguments + "HMath.Expression.sourceLine" -> apply E.sourceLine arguments + "HMath.Expression.sourceColumn" -> apply E.sourceColumn arguments + "HMath.Expression.Negate" -> apply E.Negate arguments + "HMath.Expression.Add" -> apply E.Add arguments + "HMath.Expression.Subtract" -> apply E.Subtract arguments + "HMath.Expression.Multiply" -> apply E.Multiply arguments + "HMath.Expression.Divide" -> apply E.Divide arguments + "HMath.Expression.Power" -> apply E.Power arguments + "HMath.Expression.Pi" -> apply E.Pi arguments + "HMath.Expression.Euler" -> apply E.Euler arguments + "HMath.Expression.Tau" -> apply E.Tau arguments + "HMath.Expression.ExactRational" -> apply E.ExactRational arguments + "HMath.Expression.Float64" -> apply E.Float64 arguments + "HMath.Expression.SyntaxError" -> apply E.SyntaxError arguments + "HMath.Expression.UnknownName" -> apply E.UnknownName arguments + "HMath.Expression.TypeMismatch" -> apply E.TypeMismatch arguments + "HMath.Expression.DomainFailure" -> apply E.DomainFailure arguments + "HMath.Expression.NonFinite" -> apply E.NonFinite arguments + "HMath.Expression.StepLimit" -> apply E.StepLimit arguments + "HMath.Expression.DepthLimit" -> apply E.DepthLimit arguments + "HMath.Expression.MemoryLimit" -> apply E.MemoryLimit arguments + "HMath.Expression.InvalidLimits" -> apply E.InvalidLimits arguments + "HMath.Expression.Unsupported" -> apply E.Unsupported arguments + "HMath.Expression.Sin" -> apply E.Sin arguments + "HMath.Expression.Cos" -> apply E.Cos arguments + "HMath.Expression.Tan" -> apply E.Tan arguments + "HMath.Expression.Exp" -> apply E.Exp arguments + "HMath.Expression.Log" -> apply E.Log arguments + "HMath.Expression.Sqrt" -> apply E.Sqrt arguments + "HMath.Expression.Abs" -> apply E.Abs arguments + "HMath.Expression.Signum" -> apply E.Signum arguments + "HMath.Expression.Floor" -> apply E.Floor arguments + "HMath.Expression.Ceiling" -> apply E.Ceiling arguments + "HMath.Expression.Min" -> apply E.Min arguments + "HMath.Expression.Max" -> apply E.Max arguments + "HMath.Expression.Asin" -> apply E.Asin arguments + "HMath.Expression.Acos" -> apply E.Acos arguments + "HMath.Expression.Atan" -> apply E.Atan arguments + "HMath.Expression.Sinh" -> apply E.Sinh arguments + "HMath.Expression.Cosh" -> apply E.Cosh arguments + "HMath.Expression.Tanh" -> apply E.Tanh arguments + "HMath.Expression.Expr" -> apply E.Expr arguments + "HMath.Expression.expressionPosition" -> apply E.expressionPosition arguments + "HMath.Expression.expressionNode" -> apply E.expressionNode arguments + "HMath.Expression.Literal" -> apply E.Literal arguments + "HMath.Expression.Variable" -> apply E.Variable arguments + "HMath.Expression.Constant" -> apply E.Constant arguments + "HMath.Expression.Unary" -> apply E.Unary arguments + "HMath.Expression.Binary" -> apply E.Binary arguments + "HMath.Expression.Call" -> apply E.Call arguments + "HMath.Expression.Let" -> apply E.Let arguments + "HMath.Expression.literal" -> apply E.literal arguments + "HMath.Expression.variable" -> apply E.variable arguments + "HMath.Expression.constant" -> apply E.constant arguments + "HMath.Expression.unary" -> apply E.unary arguments + "HMath.Expression.binary" -> apply E.binary arguments + "HMath.Expression.call" -> apply E.call arguments + "HMath.Expression.letIn" -> apply E.letIn arguments + "HMath.Expression.Limits" -> apply E.Limits arguments + "HMath.Expression.defaultLimits" -> apply E.defaultLimits arguments + "HMath.Expression.maximumSteps" -> apply E.maximumSteps arguments + "HMath.Expression.maximumDepth" -> apply E.maximumDepth arguments + "HMath.Expression.maximumNodes" -> apply E.maximumNodes arguments + "HMath.Expression.maximumInputChars" -> apply E.maximumInputChars arguments + "HMath.Expression.maximumIntegerBits" -> apply E.maximumIntegerBits arguments + "HMath.Expression.maximumCacheEntries" -> apply E.maximumCacheEntries arguments + "HMath.Expression.ExprError" -> apply E.ExprError arguments + "HMath.Expression.errorKind" -> apply E.errorKind arguments + "HMath.Expression.errorPosition" -> apply E.errorPosition arguments + "HMath.Expression.errorMessage" -> apply E.errorMessage arguments + "HMath.Expression.validateLimits" -> apply E.validateLimits arguments + "HMath.Expression.validateExpression" -> apply E.validateExpression arguments + "HMath.Expression.parseExpression" -> apply E.parseExpression arguments + "HMath.Expression.prettyExpression" -> apply E.prettyExpression arguments + "HMath.Expression.freeVariables" -> apply E.freeVariables arguments + "HMath.Expression.ExactValue" -> apply E.ExactValue arguments + "HMath.Expression.FloatValue" -> apply E.FloatValue arguments + "HMath.Expression.defaultRegistry" -> apply E.defaultRegistry arguments + "HMath.Expression.emptyRegistry" -> apply E.emptyRegistry arguments + "HMath.Expression.registerFunction" -> apply E.registerFunction arguments + "HMath.Expression.allowedFunctions" -> apply E.allowedFunctions arguments + "HMath.Expression.typeCheckExpression" -> apply E.typeCheckExpression arguments + "HMath.Expression.evaluateExpression" -> apply E.evaluateExpression arguments + "HMath.Expression.evaluateText" -> apply E.evaluateText arguments + "HMath.Expression.evaluateCompiled" -> apply E.evaluateCompiled arguments + "HMath.Expression.compileExpression" -> apply E.compileExpression arguments + "HMath.Expression.compiledNodeCount" -> apply E.compiledNodeCount arguments + "HMath.Expression.optimizeExpression" -> apply E.optimizeExpression arguments + "HMath.Expression.emptyExpressionCache" -> apply E.emptyExpressionCache arguments + "HMath.Expression.cacheSize" -> apply E.cacheSize arguments + "HMath.Expression.cachedExpression" -> apply E.cachedExpression arguments + "HMath.Expression.formatScientific" -> apply E.formatScientific arguments + "HMath.Expression.formatRadix" -> apply E.formatRadix arguments + "HMath.Expression.serializeExpression" -> apply E.serializeExpression arguments + "HMath.Expression.deserializeExpression" -> apply E.deserializeExpression arguments + "HMath.Expression.expressionHash" -> apply E.expressionHash arguments + "HMath.Symbolic.Real" -> apply S.Real arguments + "HMath.Symbolic.NonZero" -> apply S.NonZero arguments + "HMath.Symbolic.Positive" -> apply S.Positive arguments + "HMath.Symbolic.NonNegative" -> apply S.NonNegative arguments + "HMath.Symbolic.Integral" -> apply S.Integral arguments + "HMath.Symbolic.Negative" -> apply S.Negative arguments + "HMath.Symbolic.NonPositive" -> apply S.NonPositive arguments + "HMath.Symbolic.FromLeft" -> apply S.FromLeft arguments + "HMath.Symbolic.FromRight" -> apply S.FromRight arguments + "HMath.Symbolic.TwoSided" -> apply S.TwoSided arguments + "HMath.Symbolic.Equal" -> apply S.Equal arguments + "HMath.Symbolic.NotEqual" -> apply S.NotEqual arguments + "HMath.Symbolic.Less" -> apply S.Less arguments + "HMath.Symbolic.LessEqual" -> apply S.LessEqual arguments + "HMath.Symbolic.Greater" -> apply S.Greater arguments + "HMath.Symbolic.GreaterEqual" -> apply S.GreaterEqual arguments + "HMath.Symbolic.assumptions" -> apply S.assumptions arguments + "HMath.Symbolic.noAssumptions" -> apply S.noAssumptions arguments + "HMath.Symbolic.proves" -> apply S.proves arguments + "HMath.Symbolic.SymbolicOptions" -> apply S.SymbolicOptions arguments + "HMath.Symbolic.defaultSymbolicOptions" -> apply S.defaultSymbolicOptions arguments + "HMath.Symbolic.symbolicLimits" -> apply S.symbolicLimits arguments + "HMath.Symbolic.symbolicAssumptions" -> apply S.symbolicAssumptions arguments + "HMath.Symbolic.normalize" -> apply S.normalize arguments + "HMath.Symbolic.simplify" -> apply S.simplify arguments + "HMath.Symbolic.expand" -> apply S.expand arguments + "HMath.Symbolic.collectTerms" -> apply S.collectTerms arguments + "HMath.Symbolic.trigonometricSimplify" -> apply S.trigonometricSimplify arguments + "HMath.Symbolic.logarithmicSimplify" -> apply S.logarithmicSimplify arguments + "HMath.Symbolic.factorPolynomial" -> apply S.factorPolynomial arguments + "HMath.Symbolic.rationalSimplify" -> apply S.rationalSimplify arguments + "HMath.Symbolic.differentiate" -> apply S.differentiate arguments + "HMath.Symbolic.integrateBasic" -> apply S.integrateBasic arguments + "HMath.Symbolic.toPolynomial" -> apply S.toPolynomial arguments + "HMath.Symbolic.exactPolynomialRoots" -> apply S.exactPolynomialRoots arguments + "HMath.Symbolic.numericalPolynomialRoots" -> apply S.numericalPolynomialRoots arguments + "HMath.Symbolic.PolynomialFactorization" -> apply S.PolynomialFactorization arguments + "HMath.Symbolic.factorLeading" -> apply S.factorLeading arguments + "HMath.Symbolic.factorTerms" -> apply S.factorTerms arguments + "HMath.Symbolic.substitute" -> apply S.substitute arguments + "HMath.Symbolic.Any" -> apply S.Any arguments + "HMath.Symbolic.Exactly" -> apply S.Exactly arguments + "HMath.Symbolic.UnaryPattern" -> apply S.UnaryPattern arguments + "HMath.Symbolic.BinaryPattern" -> apply S.BinaryPattern arguments + "HMath.Symbolic.CallPattern" -> apply S.CallPattern arguments + "HMath.Symbolic.matchPattern" -> apply S.matchPattern arguments + "HMath.Symbolic.RewriteRule" -> apply S.RewriteRule arguments + "HMath.Symbolic.rewritePattern" -> apply S.rewritePattern arguments + "HMath.Symbolic.rewriteReplacement" -> apply S.rewriteReplacement arguments + "HMath.Symbolic.rewriteRequirements" -> apply S.rewriteRequirements arguments + "HMath.Symbolic.applyRewrite" -> apply S.applyRewrite arguments + "HMath.Symbolic.gradient" -> apply S.gradient arguments + "HMath.Symbolic.hessian" -> apply S.hessian arguments + "HMath.Symbolic.jacobian" -> apply S.jacobian arguments + "HMath.Symbolic.integrateByParts" -> apply S.integrateByParts arguments + "HMath.Symbolic.integrateSubstitution" -> apply S.integrateSubstitution arguments + "HMath.Symbolic.integrateRational" -> apply S.integrateRational arguments + "HMath.Symbolic.FiniteLimit" -> apply S.FiniteLimit arguments + "HMath.Symbolic.PositiveInfinity" -> apply S.PositiveInfinity arguments + "HMath.Symbolic.NegativeInfinity" -> apply S.NegativeInfinity arguments + "HMath.Symbolic.DoesNotExist" -> apply S.DoesNotExist arguments + "HMath.Symbolic.symbolicLimit" -> apply S.symbolicLimit arguments + "HMath.Symbolic.Series" -> apply S.Series arguments + "HMath.Symbolic.seriesCenter" -> apply S.seriesCenter arguments + "HMath.Symbolic.seriesMinimumPower" -> apply S.seriesMinimumPower arguments + "HMath.Symbolic.seriesTerms" -> apply S.seriesTerms arguments + "HMath.Symbolic.taylorSeries" -> apply S.taylorSeries arguments + "HMath.Symbolic.laurentSeries" -> apply S.laurentSeries arguments + "HMath.Symbolic.maclaurinSeries" -> apply S.maclaurinSeries arguments + "HMath.Symbolic.formalPowerSeries" -> apply S.formalPowerSeries arguments + "HMath.Symbolic.multiplyFormalSeries" -> apply S.multiplyFormalSeries arguments + "HMath.Symbolic.reciprocalFormalSeries" -> apply S.reciprocalFormalSeries arguments + "HMath.Symbolic.fromPolynomial" -> apply S.fromPolynomial arguments + "HMath.Symbolic.Relation" -> apply S.Relation arguments + "HMath.Symbolic.Truth" -> apply S.Truth arguments + "HMath.Symbolic.Unresolved" -> apply S.Unresolved arguments + "HMath.Symbolic.simplifyRelation" -> apply S.simplifyRelation arguments + "HMath.Symbolic.solveLinearInequality" -> apply S.solveLinearInequality arguments + "HMath.Symbolic.Inconsistent" -> apply S.Inconsistent arguments + "HMath.Symbolic.ParametricSolution" -> apply S.ParametricSolution arguments + "HMath.Symbolic.solveLinearEquations" -> apply S.solveLinearEquations arguments + "HMath.Symbolic.symbolicMatrix" -> apply S.symbolicMatrix arguments + "HMath.Symbolic.matrixExpressions" -> apply S.matrixExpressions arguments + "HMath.Symbolic.matrixAdd" -> apply S.matrixAdd arguments + "HMath.Symbolic.matrixMultiply" -> apply S.matrixMultiply arguments + "HMath.Symbolic.symbolicDeterminant" -> apply S.symbolicDeterminant arguments + "HMath.Symbolic.Guarded" -> apply (S.Guarded :: Value -> [(E.Expr,S.Property)] -> S.Guarded Value) arguments + "HMath.Symbolic.guardedValue" -> apply (S.guardedValue :: S.Guarded Value -> Value) arguments + "HMath.Symbolic.requiredConditions" -> apply (S.requiredConditions :: S.Guarded Value -> [(E.Expr,S.Property)]) arguments + "HMath.Symbolic.symbolicEigenvalues" -> apply S.symbolicEigenvalues arguments + "HMath.Symbolic.numericalSubstitution" -> apply S.numericalSubstitution arguments + "HMath.Symbolic.toLaTeX" -> apply S.toLaTeX arguments + "HMath.Symbolic.toMathML" -> apply S.toMathML arguments +-- END GENERATED + "__node_fields" -> do [value]<-pure arguments; fromValue value >>= nodeFields + "__pattern_fields" -> do [value]<-pure arguments; fromValue value >>= patternFields + "__compare_expr" -> apply (\a b -> case compare (a::E.Expr) b of { LT -> -1::Int; EQ -> 0; GT -> 1 }) arguments + "__compare_node" -> apply (\a b -> case compare (a::E.ExprNode) b of { LT -> -1::Int; EQ -> 0; GT -> 1 }) arguments + "__equal_pattern" -> apply ((==)::S.Pattern -> S.Pattern -> Bool) arguments + _ -> invalid "invalid expression operation" diff --git a/src/HMath/FFI/Foundation.hs b/src/HMath/FFI/Foundation.hs new file mode 100644 index 0000000..3b3437e --- /dev/null +++ b/src/HMath/FFI/Foundation.hs @@ -0,0 +1,728 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated original-operation adapters. No algorithm implementation here. +module HMath.FFI.Foundation where +import Control.Exception (evaluate) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec +import HMath.FFI.Ordering +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import qualified HMath.DataStructure as D +import qualified HMath.Discrete as S +import qualified HMath.Algorithms as A +import qualified HMath.Combinatorics as C +import qualified HMath.API.Convergence as V + +encodeFenwick :: (D.Fenwick) -> IO X.Value +encodeFenwick value=pure(opaqueEq "HMath.DataStructure.Fenwick" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSegmentTree :: (D.SegmentTree) -> IO X.Value +encodeSegmentTree value=pure(opaqueEq "HMath.DataStructure.SegmentTree" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseTable :: (D.SparseTable) -> IO X.Value +encodeSparseTable value=pure(opaqueEq "HMath.DataStructure.SparseTable" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeDisjointSparseTable :: (D.DisjointSparseTable) -> IO X.Value +encodeDisjointSparseTable value=pure(opaqueEq "HMath.DataStructure.DisjointSparseTable" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeHeap :: HeapState -> IO X.Value +encodeHeap value=pure(opaqueEq "HMath.DataStructure.Heap" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeBinaryHeap :: (D.BinaryHeap) -> IO X.Value +encodeBinaryHeap value=pure(opaqueEq "HMath.DataStructure.BinaryHeap" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeIndexedHeap :: (D.IndexedHeap) -> IO X.Value +encodeIndexedHeap value=pure(opaqueEq "HMath.DataStructure.IndexedHeap" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeUnionFind :: (D.UnionFind) -> IO X.Value +encodeUnionFind value=pure(opaqueEq "HMath.DataStructure.UnionFind" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeBloom :: (D.Bloom) -> IO X.Value +encodeBloom value=pure(opaqueEq "HMath.DataStructure.Bloom" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeCountMin :: (D.CountMin) -> IO X.Value +encodeCountMin value=pure(opaqueEq "HMath.DataStructure.CountMin" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeHyperLogLog :: (D.HyperLogLog) -> IO X.Value +encodeHyperLogLog value=pure(opaqueEq "HMath.DataStructure.HyperLogLog" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeReservoir :: (D.Reservoir EqualityValue) -> IO X.Value +encodeReservoir value=pure(opaqueEq "HMath.DataStructure.Reservoir" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeOnlineQuantiles :: (D.OnlineQuantiles) -> IO X.Value +encodeOnlineQuantiles value=pure(opaqueEq "HMath.DataStructure.OnlineQuantiles" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeMultiSet :: MultiState -> IO X.Value +encodeMultiSet value=pure(opaqueEq "HMath.Discrete.MultiSet" (-1) value force view) + where + force=multisetEntries value >>= \xs -> forceFields [X.List <$>mapM(\item1 -> (\(part2,part3) -> X.Tuple <$> sequence [pure part2,pure(X.Scalar SInteger part3)]) item1) xs] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeBitSet :: (S.BitSet) -> IO X.Value +encodeBitSet value=pure(opaqueEq "HMath.Discrete.BitSet" (-1) value force view) + where + force=evaluate value >> pure() + view=X.unsupported "original abstract type has no public constructor fields" + +encodeProp :: (S.Prop) -> IO X.Value +encodeProp value=pure(opaqueEq "HMath.Discrete.Prop" (-1) value force view) + where + force=evaluate value >> pure() + view=case value of + S.Literal field4 -> do + values <- sequence [pure(X.Boolean field4)] + pure(X.Tuple[X.Text "Literal",X.Tuple values]) + S.Variable field5 -> do + values <- sequence [pure(X.Index field5)] + pure(X.Tuple[X.Text "Variable",X.Tuple values]) + S.Not field6 -> do + values <- sequence [encodeProp field6] + pure(X.Tuple[X.Text "Not",X.Tuple values]) + S.And field7 field8 -> do + values <- sequence [encodeProp field7,encodeProp field8] + pure(X.Tuple[X.Text "And",X.Tuple values]) + S.Or field9 field10 -> do + values <- sequence [encodeProp field9,encodeProp field10] + pure(X.Tuple[X.Text "Or",X.Tuple values]) + S.Xor field11 field12 -> do + values <- sequence [encodeProp field11,encodeProp field12] + pure(X.Tuple[X.Text "Xor",X.Tuple values]) + S.Implies field13 field14 -> do + values <- sequence [encodeProp field13,encodeProp field14] + pure(X.Tuple[X.Text "Implies",X.Tuple values]) + S.Iff field15 field16 -> do + values <- sequence [encodeProp field15,encodeProp field16] + pure(X.Tuple[X.Text "Iff",X.Tuple values]) + +encodeImplicant :: (S.Implicant) -> IO X.Value +encodeImplicant value=pure(opaqueEq "HMath.Discrete.Implicant" (-1) value force view) + where + force=forceFields [pure(X.Scalar SInteger (S.implicantValue value)),pure(X.Scalar SInteger (S.implicantMask value))] + view=case value of + S.Implicant field17 field18 -> do + values <- sequence [pure(X.Scalar SInteger field17),pure(X.Scalar SInteger field18)] + pure(X.Tuple[X.Text "Implicant",X.Tuple values]) + +encodeStopReason :: (V.StopReason) -> IO X.Value +encodeStopReason value=pure(opaqueEq "HMath.API.Convergence.StopReason" (-1) value force view) + where + force=evaluate value >> pure() + view=case value of + V.ResidualSatisfied -> do + values <- sequence [] + pure(X.Tuple[X.Text "ResidualSatisfied",X.Tuple values]) + V.IterationLimit -> do + values <- sequence [] + pure(X.Tuple[X.Text "IterationLimit",X.Tuple values]) + V.Stagnation -> do + values <- sequence [] + pure(X.Tuple[X.Text "Stagnation",X.Tuple values]) + +encodeConvergence :: (V.Convergence EqualityValue) -> IO X.Value +encodeConvergence value=pure(opaqueEq "HMath.API.Convergence.Convergence" (-1) value force view) + where + force=forceFields [writeEquality (V.estimate value),pure(X.Index (V.iterationCount value)),pure(X.Scalar SDouble (V.finalResidual value)),encodeStopReason (V.stopReason value)] + view=case value of + V.Convergence field19 field20 field21 field22 -> do + values <- sequence [writeEquality field19,pure(X.Index field20),pure(X.Scalar SDouble field21),encodeStopReason field22] + pure(X.Tuple[X.Text "Convergence",X.Tuple values]) + +encodeIterationOptions :: (V.IterationOptions) -> IO X.Value +encodeIterationOptions value=pure(opaqueEq "HMath.API.Convergence.IterationOptions" (-1) value force view) + where + force=forceFields [pure(X.Index (V.maximumIterations value)),pure(X.Scalar SDouble (V.absoluteTolerance value)),pure(X.Scalar SDouble (V.relativeTolerance value))] + view=case value of + V.IterationOptions field23 field24 field25 -> do + values <- sequence [pure(X.Index field23),pure(X.Scalar SDouble field24),pure(X.Scalar SDouble field25)] + pure(X.Tuple[X.Text "IterationOptions",X.Tuple values]) + +apply :: Int -> [X.Value] -> IO X.Value +apply operation args=case(operation,args) of + (0,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item26 -> X.asScalar item26) :: IO [(Integer)]) + source ((D.fenwick a0Value) :: (Either (E.MathError) (D.Fenwick))) >>= \_result27 -> encodeFenwick _result27 + (1,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + a2Value <- (unbox "HMath.DataStructure.Fenwick" a2 :: IO (D.Fenwick)) + source ((D.fenwickAdd a0Value a1Value a2Value) :: (Either (E.MathError) (D.Fenwick))) >>= \_result28 -> encodeFenwick _result28 + (2,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.DataStructure.Fenwick" a1 :: IO (D.Fenwick)) + source ((D.fenwickPrefix a0Value a1Value) :: (Either (E.MathError) (Integer))) >>= \_result29 -> pure(X.Scalar SInteger _result29) + (3,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.Fenwick" a2 :: IO (D.Fenwick)) + source ((D.fenwickRange a0Value a1Value a2Value) :: (Either (E.MathError) (Integer))) >>= \_result30 -> pure(X.Scalar SInteger _result30) + (4,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item31 -> X.asScalar item31) :: IO [(Integer)]) + source ((D.segmentTree a0Value) :: (Either (E.MathError) (D.SegmentTree))) >>= \_result32 -> encodeSegmentTree _result32 + (5,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + a2Value <- (unbox "HMath.DataStructure.SegmentTree" a2 :: IO (D.SegmentTree)) + source ((D.segmentSet a0Value a1Value a2Value) :: (Either (E.MathError) (D.SegmentTree))) >>= \_result33 -> encodeSegmentTree _result33 + (6,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.SegmentTree" a2 :: IO (D.SegmentTree)) + source ((D.segmentRange a0Value a1Value a2Value) :: (Either (E.MathError) (Integer))) >>= \_result34 -> pure(X.Scalar SInteger _result34) + (7,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item35 -> X.asScalar item35) :: IO [(Integer)]) + source ((D.sparseTable a0Value) :: (Either (E.MathError) (D.SparseTable))) >>= \_result36 -> encodeSparseTable _result36 + (8,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.SparseTable" a2 :: IO (D.SparseTable)) + source ((D.sparseMinimum a0Value a1Value a2Value) :: (Either (E.MathError) (Integer))) >>= \_result37 -> pure(X.Scalar SInteger _result37) + (9,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item38 -> X.asScalar item38) :: IO [(Integer)]) + source ((D.disjointSparseTable a0Value) :: (Either (E.MathError) (D.DisjointSparseTable))) >>= \_result39 -> encodeDisjointSparseTable _result39 + (10,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.DisjointSparseTable" a2 :: IO (D.DisjointSparseTable)) + source ((D.disjointRange a0Value a1Value a2Value) :: (Either (E.MathError) (Integer))) >>= \_result40 -> pure(X.Scalar SInteger _result40) + (11,[a0]) -> do + examples <- concat <$> sequence [X.asList a0] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (X.asList a0 >>= mapM(\item41 -> readOrdered witness item41) :: IO [OrderedValue]) + X.List <$>mapM(\item42 -> (case item42 of {Nothing -> pure X.None;Just item43 -> pure(X.Index item43) >>= maybeValue . Just})) ((D.nextGreater a0Value) :: [(Maybe (Int))]) + (12,[]) -> do + (pure heapEmpty) >>= \result -> encodeHeap result + (13,[a0,a1]) -> do + a0Value <- (pure a0 :: IO X.Value) + a1Value <- (unbox "HMath.DataStructure.Heap" a1 :: IO HeapState) + (heapInsert a0Value a1Value) >>= \result -> encodeHeap result + (14,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.Heap" a0 :: IO HeapState) + (heapPop a0Value) >>= \result -> (case result of {Nothing -> pure X.None;Just item44 -> (\(part45,part46) -> X.Tuple <$> sequence [pure part45,encodeHeap part46]) item44 >>= maybeValue . Just}) + (15,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item47 -> pure item47) :: IO [X.Value]) + (heapFromList a0Value) >>= \result -> encodeHeap result + (16,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item48 -> X.asScalar item48) :: IO [(Integer)]) + source ((D.binaryHeap a0Value) :: (Either (E.MathError) (D.BinaryHeap))) >>= \_result49 -> encodeBinaryHeap _result49 + (17,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (unbox "HMath.DataStructure.BinaryHeap" a1 :: IO (D.BinaryHeap)) + encodeBinaryHeap ((D.binaryInsert a0Value a1Value) :: (D.BinaryHeap)) + (18,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.BinaryHeap" a0 :: IO (D.BinaryHeap)) + (case ((D.binaryPop a0Value) :: (Maybe ((Integer),(D.BinaryHeap)))) of {Nothing -> pure X.None;Just item50 -> (\(part51,part52) -> X.Tuple <$> sequence [pure(X.Scalar SInteger part51),encodeBinaryHeap part52]) item50 >>= maybeValue . Just}) + (19,[]) -> do + encodeIndexedHeap ((D.indexedHeap ) :: (D.IndexedHeap)) + (20,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + a2Value <- (unbox "HMath.DataStructure.IndexedHeap" a2 :: IO (D.IndexedHeap)) + encodeIndexedHeap ((D.indexedSet a0Value a1Value a2Value) :: (D.IndexedHeap)) + (21,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.IndexedHeap" a0 :: IO (D.IndexedHeap)) + (case ((D.indexedPop a0Value) :: (Maybe (((Int),(Integer)),(D.IndexedHeap)))) of {Nothing -> pure X.None;Just item53 -> (\(part54,part55) -> X.Tuple <$> sequence [(\(part56,part57) -> X.Tuple <$> sequence [pure(X.Index part56),pure(X.Scalar SInteger part57)]) part54,encodeIndexedHeap part55]) item53 >>= maybeValue . Just}) + (22,[a0]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + source ((D.unionFind a0Value) :: (Either (E.MathError) (D.UnionFind))) >>= \_result58 -> encodeUnionFind _result58 + (23,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.DataStructure.UnionFind" a1 :: IO (D.UnionFind)) + source ((D.findRoot a0Value a1Value) :: (Either (E.MathError) (Int))) >>= \_result59 -> pure(X.Index _result59) + (24,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.UnionFind" a2 :: IO (D.UnionFind)) + source ((D.union a0Value a1Value a2Value) :: (Either (E.MathError) (D.UnionFind))) >>= \_result60 -> encodeUnionFind _result60 + (25,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.DataStructure.UnionFind" a2 :: IO (D.UnionFind)) + source ((D.connected a0Value a1Value a2Value) :: (Either (E.MathError) (Bool))) >>= \_result61 -> pure(X.Boolean _result61) + (26,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.UnionFind" a0 :: IO (D.UnionFind)) + X.List <$>mapM(\item62 -> X.List <$>mapM(\item63 -> pure(X.Index item63)) item62) ((D.components a0Value) :: [[(Int)]]) + (27,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((D.bloom a0Value a1Value) :: (Either (E.MathError) (D.Bloom))) >>= \_result64 -> encodeBloom _result64 + (28,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Word64)) + a1Value <- (unbox "HMath.DataStructure.Bloom" a1 :: IO (D.Bloom)) + encodeBloom ((D.bloomInsert a0Value a1Value) :: (D.Bloom)) + (29,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Word64)) + a1Value <- (unbox "HMath.DataStructure.Bloom" a1 :: IO (D.Bloom)) + pure(X.Boolean ((D.bloomMember a0Value a1Value) :: (Bool))) + (30,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.Bloom" a0 :: IO (D.Bloom)) + pure(X.Scalar SDouble ((D.bloomFalsePositiveBound a0Value) :: (Double))) + (31,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((D.countMin a0Value a1Value) :: (Either (E.MathError) (D.CountMin))) >>= \_result65 -> encodeCountMin _result65 + (32,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Word64)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + a2Value <- (unbox "HMath.DataStructure.CountMin" a2 :: IO (D.CountMin)) + source ((D.countMinAdd a0Value a1Value a2Value) :: (Either (E.MathError) (D.CountMin))) >>= \_result66 -> encodeCountMin _result66 + (33,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Word64)) + a1Value <- (unbox "HMath.DataStructure.CountMin" a1 :: IO (D.CountMin)) + pure(X.Scalar SInteger ((D.countMinEstimate a0Value a1Value) :: (Integer))) + (34,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.CountMin" a0 :: IO (D.CountMin)) + (\(part67,part68) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part67),pure(X.Scalar SDouble part68)]) ((D.countMinErrorBound a0Value) :: ((Double),(Double))) + (35,[a0]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + source ((D.hyperLogLog a0Value) :: (Either (E.MathError) (D.HyperLogLog))) >>= \_result69 -> encodeHyperLogLog _result69 + (36,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Word64)) + a1Value <- (unbox "HMath.DataStructure.HyperLogLog" a1 :: IO (D.HyperLogLog)) + encodeHyperLogLog ((D.hllAdd a0Value a1Value) :: (D.HyperLogLog)) + (37,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.HyperLogLog" a0 :: IO (D.HyperLogLog)) + pure(X.Scalar SDouble ((D.hllEstimate a0Value) :: (Double))) + (38,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Word64)) + source ((D.reservoir a0Value a1Value) :: (Either (E.MathError) (D.Reservoir EqualityValue))) >>= \_result70 -> encodeReservoir _result70 + (39,[a0,a1]) -> do + a0Value <- (readEquality a0 :: IO EqualityValue) + a1Value <- (unbox "HMath.DataStructure.Reservoir" a1 :: IO (D.Reservoir EqualityValue)) + source ((D.reservoirAdd a0Value a1Value) :: (Either (E.MathError) (D.Reservoir EqualityValue))) >>= \_result71 -> encodeReservoir _result71 + (40,[a0]) -> do + a0Value <- (unbox "HMath.DataStructure.Reservoir" a0 :: IO (D.Reservoir EqualityValue)) + X.List <$>mapM(\item72 -> writeEquality item72) ((D.reservoirValues a0Value) :: [EqualityValue]) + (41,[a0]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + source ((D.onlineQuantiles a0Value) :: (Either (E.MathError) (D.OnlineQuantiles))) >>= \_result73 -> encodeOnlineQuantiles _result73 + (42,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (unbox "HMath.DataStructure.OnlineQuantiles" a1 :: IO (D.OnlineQuantiles)) + source ((D.quantileAdd a0Value a1Value) :: (Either (E.MathError) (D.OnlineQuantiles))) >>= \_result74 -> encodeOnlineQuantiles _result74 + (43,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (unbox "HMath.DataStructure.OnlineQuantiles" a1 :: IO (D.OnlineQuantiles)) + source ((D.onlineQuantile a0Value a1Value) :: (Either (E.MathError) (Double))) >>= \_result75 -> pure(X.Scalar SDouble _result75) + (44,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item76 -> pure item76) :: IO [X.Value]) + (multiset a0Value) >>= \result -> encodeMultiSet result + (45,[a0,a1]) -> do + a0Value <- (pure a0 :: IO X.Value) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multiplicity a0Value a1Value) >>= \result -> pure(X.Scalar SInteger result) + (46,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.MultiSet" a0 :: IO MultiState) + (multisetEntries a0Value) >>= \result -> X.List <$>mapM(\item77 -> (\(part78,part79) -> X.Tuple <$> sequence [pure part78,pure(X.Scalar SInteger part79)]) item77) result + (47,[a0,a1]) -> do + a0Value <- (pure a0 :: IO X.Value) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multisetInsert a0Value a1Value) >>= \result -> encodeMultiSet result + (48,[a0,a1]) -> do + a0Value <- (pure a0 :: IO X.Value) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multisetDelete a0Value a1Value) >>= \result -> encodeMultiSet result + (49,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.MultiSet" a0 :: IO MultiState) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multisetBinary S.multisetUnion a0Value a1Value) >>= \result -> encodeMultiSet result + (50,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.MultiSet" a0 :: IO MultiState) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multisetBinary S.multisetIntersection a0Value a1Value) >>= \result -> encodeMultiSet result + (51,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.MultiSet" a0 :: IO MultiState) + a1Value <- (unbox "HMath.Discrete.MultiSet" a1 :: IO MultiState) + (multisetBinary S.multisetDifference a0Value a1Value) >>= \result -> encodeMultiSet result + (52,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + source ((S.bitSet a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result80 -> encodeBitSet _result80 + (53,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + pure(X.Index ((S.bitWidth a0Value) :: (Int))) + (54,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + pure(X.Scalar SInteger ((S.bitValue a0Value) :: (Integer))) + (55,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((S.bitMember a0Value a1Value) :: (Either (E.MathError) (Bool))) >>= \_result81 -> pure(X.Boolean _result81) + (56,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((S.bitInsert a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result82 -> encodeBitSet _result82 + (57,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((S.bitDelete a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result83 -> encodeBitSet _result83 + (58,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + source ((S.bitUnion a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result84 -> encodeBitSet _result84 + (59,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + source ((S.bitIntersection a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result85 -> encodeBitSet _result85 + (60,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + source ((S.bitDifference a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result86 -> encodeBitSet _result86 + (61,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + source ((S.resizeBitSet a0Value a1Value) :: (Either (E.MathError) (S.BitSet))) >>= \_result87 -> encodeBitSet _result87 + (62,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + pure(X.Index ((S.populationCount a0Value) :: (Int))) + (63,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + pure(X.Index ((S.leadingZeros a0Value) :: (Int))) + (64,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + pure(X.Index ((S.trailingZeros a0Value) :: (Int))) + (65,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + encodeBitSet ((S.rotateBits a0Value a1Value) :: (S.BitSet)) + (66,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + encodeBitSet ((S.reverseBits a0Value) :: (S.BitSet)) + (67,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + encodeBitSet ((S.grayEncode a0Value) :: (S.BitSet)) + (68,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + encodeBitSet ((S.grayDecode a0Value) :: (S.BitSet)) + (69,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.BitSet" a0 :: IO (S.BitSet)) + a1Value <- (unbox "HMath.Discrete.BitSet" a1 :: IO (S.BitSet)) + source ((S.hammingDistance a0Value a1Value) :: (Either (E.MathError) (Int))) >>= \_result88 -> pure(X.Index _result88) + (70,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item89 -> X.asList item89 >>= mapM(\item90 -> X.asBoolean item90)) :: IO [[(Bool)]]) + source ((S.transitiveClosure a0Value) :: (Either (E.MathError) [[(Bool)]])) >>= \_result91 -> X.List <$>mapM(\item92 -> X.List <$>mapM(\item93 -> pure(X.Boolean item93)) item92) _result91 + (71,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item94 -> X.asList item94 >>= mapM(\item95 -> X.asBoolean item95)) :: IO [[(Bool)]]) + source ((S.equivalenceClosure a0Value) :: (Either (E.MathError) [[(Bool)]])) >>= \_result96 -> X.List <$>mapM(\item97 -> X.List <$>mapM(\item98 -> pure(X.Boolean item98)) item97) _result96 + (72,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item99 -> X.asList item99 >>= mapM(\item100 -> X.asBoolean item100)) :: IO [[(Bool)]]) + source ((S.isEquivalence a0Value) :: (Either (E.MathError) (Bool))) >>= \_result101 -> pure(X.Boolean _result101) + (73,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM(\item102 -> X.asList item102 >>= mapM(\item103 -> X.asBoolean item103)) :: IO [[(Bool)]]) + a1Value <- (X.asList a1 >>= mapM(\item104 -> X.asList item104 >>= mapM(\item105 -> X.asBoolean item105)) :: IO [[(Bool)]]) + source ((S.booleanMultiply a0Value a1Value) :: (Either (E.MathError) [[(Bool)]])) >>= \_result106 -> X.List <$>mapM(\item107 -> X.List <$>mapM(\item108 -> pure(X.Boolean item108)) item107) _result106 + (74,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM(\item109 -> X.asBoolean item109) :: IO [(Bool)]) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + source ((S.evaluateProp a0Value a1Value) :: (Either (E.MathError) (Bool))) >>= \_result110 -> pure(X.Boolean _result110) + (75,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + source ((S.truthTable a0Value a1Value) :: (Either (E.MathError) [([(Bool)],(Bool))])) >>= \_result111 -> X.List <$>mapM(\item112 -> (\(part113,part114) -> X.Tuple <$> sequence [X.List <$>mapM(\item115 -> pure(X.Boolean item115)) part113,pure(X.Boolean part114)]) item112) _result111 + (76,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Implicant" a0 :: IO (S.Implicant)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + pure(X.Boolean ((S.implicantCovers a0Value a1Value) :: (Bool))) + (77,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM(\item116 -> X.asScalar item116) :: IO [(Integer)]) + a3Value <- (X.asList a3 >>= mapM(\item117 -> X.asScalar item117) :: IO [(Integer)]) + source ((S.quineMcCluskey a0Value a1Value a2Value a3Value) :: (Either (E.MathError) [(S.Implicant)])) >>= \_result118 -> X.List <$>mapM(\item119 -> encodeImplicant item119) _result118 + (78,[a0]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + encodeProp ((S.Literal a0Value) :: (S.Prop)) + (79,[a0]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + encodeProp ((S.Variable a0Value) :: (S.Prop)) + (80,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + encodeProp ((S.Not a0Value) :: (S.Prop)) + (81,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + encodeProp ((S.And a0Value a1Value) :: (S.Prop)) + (82,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + encodeProp ((S.Or a0Value a1Value) :: (S.Prop)) + (83,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + encodeProp ((S.Xor a0Value a1Value) :: (S.Prop)) + (84,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + encodeProp ((S.Implies a0Value a1Value) :: (S.Prop)) + (85,[a0,a1]) -> do + a0Value <- (unbox "HMath.Discrete.Prop" a0 :: IO (S.Prop)) + a1Value <- (unbox "HMath.Discrete.Prop" a1 :: IO (S.Prop)) + encodeProp ((S.Iff a0Value a1Value) :: (S.Prop)) + (86,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.Implicant" a0 :: IO (S.Implicant)) + pure(X.Scalar SInteger ((S.implicantValue a0Value) :: (Integer))) + (87,[a0]) -> do + a0Value <- (unbox "HMath.Discrete.Implicant" a0 :: IO (S.Implicant)) + pure(X.Scalar SInteger ((S.implicantMask a0Value) :: (Integer))) + (88,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (X.asScalar a1 :: IO (Integer)) + encodeImplicant ((S.Implicant a0Value a1Value) :: (S.Implicant)) + (89,[a0,a1]) -> do + examples <- concat <$> sequence [pure [a0],X.asList a1] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (readOrdered witness a0 :: IO OrderedValue) + a1Value <- (X.asList a1 >>= mapM(\item120 -> readOrdered witness item120) :: IO [OrderedValue]) + source ((A.binarySearch a0Value a1Value) :: (Either (E.MathError) (Maybe (Int)))) >>= \_result121 -> (case _result121 of {Nothing -> pure X.None;Just item122 -> pure(X.Index item122) >>= maybeValue . Just}) + (90,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (X.asList a1 >>= mapM(\item123 -> X.asScalar item123) :: IO [(Integer)]) + source ((A.interpolationSearch a0Value a1Value) :: (Either (E.MathError) (Maybe (Int)))) >>= \_result124 -> (case _result124 of {Nothing -> pure X.None;Just item125 -> pure(X.Index item125) >>= maybeValue . Just}) + (91,[a0,a1]) -> do + examples <- concat <$> sequence [pure [a0],X.asList a1] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (readOrdered witness a0 :: IO OrderedValue) + a1Value <- (X.asList a1 >>= mapM(\item126 -> readOrdered witness item126) :: IO [OrderedValue]) + source ((A.exponentialSearch a0Value a1Value) :: (Either (E.MathError) (Maybe (Int)))) >>= \_result127 -> (case _result127 of {Nothing -> pure X.None;Just item128 -> pure(X.Index item128) >>= maybeValue . Just}) + (92,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure(\callbackArg129 -> unsafePerformIO $ do {inputs <- sequence [pure(X.Scalar SDouble callbackArg129)];let { input=X.Tuple inputs };LC.callbackValue a1 input >>= \reply -> X.asScalar reply}) :: IO ((Double) -> (Double))) + a2Value <- (X.asScalar a2 :: IO (Double)) + a3Value <- (X.asScalar a3 :: IO (Double)) + source ((A.ternarySearch a0Value a1Value a2Value a3Value) :: (Either (E.MathError) ((Double),(Double)))) >>= \_result130 -> (\(part131,part132) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part131),pure(X.Scalar SDouble part132)]) _result130 + (93,[a0]) -> do + examples <- concat <$> sequence [X.asList a0] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (X.asList a0 >>= mapM(\item133 -> readOrdered witness item133) :: IO [OrderedValue]) + X.List <$>mapM(\item134 -> (\(part135,part136) -> X.Tuple <$> sequence [writeOrdered part135,pure(X.Index part136)]) item134) ((A.numericGroups a0Value) :: [(OrderedValue,(Int))]) + (94,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item137 -> readEquality item137) :: IO [EqualityValue]) + X.List <$>mapM(\item138 -> (\(part139,part140) -> X.Tuple <$> sequence [writeEquality part139,pure(X.Index part140)]) item138) ((A.runLengthEncode a0Value) :: [(EqualityValue,(Int))]) + (95,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item141 -> (X.asTuple 2 item141 >>= \parts144 -> case parts144 of { [part142,part143] -> (,) <$> (pure part142) <*> (X.asIndex part143);_ -> X.invalid "tuple arity differs"})) :: IO [(X.Value,(Int))]) + source ((A.runLengthDecode a0Value a1Value) :: (Either (E.MathError) [X.Value])) >>= \_result145 -> X.List <$>mapM(\item146 -> pure item146) _result145 + (96,[a0]) -> do + examples <- concat <$> sequence [X.asList a0] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (X.asList a0 >>= mapM(\item147 -> readOrdered witness item147) :: IO [OrderedValue]) + (\(part148,part149) -> X.Tuple <$> sequence [X.List <$>mapM(\item150 -> writeOrdered item150) part148,X.List <$>mapM(\item151 -> pure(X.Index item151)) part149]) ((A.coordinateCompression a0Value) :: ([OrderedValue],[(Int)])) + (97,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM(\item152 -> (X.asTuple 2 item152 >>= \parts155 -> case parts155 of { [part153,part154] -> (,) <$> (X.asScalar part153) <*> (X.asScalar part154);_ -> X.invalid "tuple arity differs"})) :: IO [((Integer),(Integer))]) + source ((A.intervalSweep a0Value) :: (Either (E.MathError) ((Integer),(Int)))) >>= \_result156 -> (\(part157,part158) -> X.Tuple <$> sequence [pure(X.Scalar SInteger part157),pure(X.Index part158)]) _result156 + (98,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM(\item159 -> X.asScalar item159) :: IO [(Double)]) + a1Value <- (pure(\callbackArg160 callbackArg161 -> unsafePerformIO $ do {inputs <- sequence [pure(X.Index callbackArg160),pure(X.Index callbackArg161)];let { input=X.Tuple inputs };LC.callbackValue a1 input >>= \reply -> X.asScalar reply}) :: IO ((Int) -> (Int) -> (Double))) + source ((A.divideConquerDP a0Value a1Value) :: (Either (E.MathError) [(Double)])) >>= \_result162 -> X.List <$>mapM(\item163 -> pure(X.Scalar SDouble item163)) _result162 + (99,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure(\callbackArg164 -> unsafePerformIO $ do {inputs <- sequence [pure(X.Index callbackArg164)];let { input=X.Tuple inputs };LC.callbackValue a1 input >>= \reply -> X.asList reply >>= mapM(\item165 -> (X.asTuple 2 item165 >>= \parts168 -> case parts168 of { [part166,part167] -> (,) <$> (X.asIndex part166) <*> (X.asScalar part167);_ -> X.invalid "tuple arity differs"}))}) :: IO ((Int) -> [((Int),(Integer))])) + source ((A.tabulateDP a0Value a1Value) :: (Either (E.MathError) [(Integer)])) >>= \_result169 -> X.List <$>mapM(\item170 -> pure(X.Scalar SInteger item170)) _result169 + (100,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure(\callbackArg171 -> unsafePerformIO $ do {inputs <- sequence [pure(X.Index callbackArg171)];let { input=X.Tuple inputs };LC.callbackValue a1 input >>= \reply -> (X.asTuple 2 reply >>= \parts174 -> case parts174 of { [part172,part173] -> (,) <$> (X.asScalar part172) <*> (X.asList part173 >>= mapM(\item175 -> (X.asTuple 2 item175 >>= \parts178 -> case parts178 of { [part176,part177] -> (,) <$> (X.asIndex part176) <*> (X.asScalar part177);_ -> X.invalid "tuple arity differs"})));_ -> X.invalid "tuple arity differs"})}) :: IO ((Int) -> ((Integer),[((Int),(Integer))]))) + a2Value <- (X.asIndex a2 :: IO (Int)) + source ((A.memoizedDP a0Value a1Value a2Value) :: (Either (E.MathError) (Integer))) >>= \_result179 -> pure(X.Scalar SInteger _result179) + (101,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM(\item180 -> X.asList item180 >>= mapM(\item181 -> X.asScalar item181)) :: IO [[(Integer)]]) + a1Value <- (X.asScalar a1 :: IO (Integer)) + source ((A.integerMatrixPower a0Value a1Value) :: (Either (E.MathError) [[(Integer)]])) >>= \_result182 -> X.List <$>mapM(\item183 -> X.List <$>mapM(\item184 -> pure(X.Scalar SInteger item184)) item183) _result182 + (102,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM(\item185 -> pure item185) :: IO [X.Value]) + source ((C.permutationsOf a0Value a1Value a2Value) :: (Either (E.MathError) [[X.Value]])) >>= \_result186 -> X.List <$>mapM(\item187 -> X.List <$>mapM(\item188 -> pure item188) item187) _result186 + (103,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM(\item189 -> pure item189) :: IO [X.Value]) + source ((C.combinationsOf a0Value a1Value a2Value) :: (Either (E.MathError) [[X.Value]])) >>= \_result190 -> X.List <$>mapM(\item191 -> X.List <$>mapM(\item192 -> pure item192) item191) _result190 + (104,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((C.derangements a0Value a1Value) :: (Either (E.MathError) [[(Int)]])) >>= \_result193 -> X.List <$>mapM(\item194 -> X.List <$>mapM(\item195 -> pure(X.Index item195)) item194) _result193 + (105,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((C.integerPartitions a0Value a1Value) :: (Either (E.MathError) [[(Int)]])) >>= \_result196 -> X.List <$>mapM(\item197 -> X.List <$>mapM(\item198 -> pure(X.Index item198)) item197) _result196 + (106,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((C.setPartitions a0Value a1Value) :: (Either (E.MathError) [[[(Int)]]])) >>= \_result199 -> X.List <$>mapM(\item200 -> X.List <$>mapM(\item201 -> X.List <$>mapM(\item202 -> pure(X.Index item202)) item201) item200) _result199 + (107,[a0]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + source ((C.pascalTriangle a0Value) :: (Either (E.MathError) [[(Integer)]])) >>= \_result203 -> X.List <$>mapM(\item204 -> X.List <$>mapM(\item205 -> pure(X.Scalar SInteger item205)) item204) _result203 + (108,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item206 -> pure item206) :: IO [X.Value]) + source ((C.subsets a0Value a1Value) :: (Either (E.MathError) [[X.Value]])) >>= \_result207 -> X.List <$>mapM(\item208 -> X.List <$>mapM(\item209 -> pure item209) item208) _result207 + (109,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item210 -> X.asList item210 >>= mapM(\item211 -> pure item211)) :: IO [[X.Value]]) + source ((C.cartesianProduct a0Value a1Value) :: (Either (E.MathError) [[X.Value]])) >>= \_result212 -> X.List <$>mapM(\item213 -> X.List <$>mapM(\item214 -> pure item214) item213) _result212 + (110,[a0,a1]) -> do + examples <- concat <$> sequence [X.asList a1] + witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item215 -> readOrdered witness item215) :: IO [OrderedValue]) + source ((C.multisetPermutations a0Value a1Value) :: (Either (E.MathError) [[OrderedValue]])) >>= \_result216 -> X.List <$>mapM(\item217 -> X.List <$>mapM(\item218 -> writeOrdered item218) item217) _result216 + (111,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item219 -> X.asScalar item219) :: IO [(Rational)]) + a2Value <- (X.asList a2 >>= mapM(\item220 -> X.asScalar item220) :: IO [(Rational)]) + source ((C.generatingCoefficients a0Value a1Value a2Value) :: (Either (E.MathError) [(Rational)])) >>= \_result221 -> X.List <$>mapM(\item222 -> pure(X.Scalar SRational item222)) _result221 + (112,[prototype,a0]) -> LC.withWitness prototype $ \(w::ScalarType a) -> do + a0Value <- (X.asList a0 >>= mapM(\item223 -> X.asScalar item223) :: IO [a]) + X.List <$>mapM(\item224 -> X.List <$>mapM(\item225 -> pure(X.Scalar w item225)) item224) ((C.finiteDifferences a0Value) :: [[a]]) + (113,[]) -> do + encodeIterationOptions ((V.defaultIterationOptions ) :: (V.IterationOptions)) + (114,[a0,a1,a2,a3,a4]) -> do + a0Value <- (unbox "HMath.API.Convergence.IterationOptions" a0 :: IO (V.IterationOptions)) + a1Value <- (pure(\callbackArg226 -> unsafePerformIO $ do {inputs <- sequence [writeEquality callbackArg226];let { input=X.Tuple inputs };checkedCallback a1 input (\reply -> readEquality reply)}) :: IO (EqualityValue -> (Either (E.MathError) EqualityValue))) + a2Value <- (pure(\callbackArg227 -> unsafePerformIO $ do {inputs <- sequence [writeEquality callbackArg227];let { input=X.Tuple inputs };checkedCallback a2 input (\reply -> X.asScalar reply)}) :: IO (EqualityValue -> (Either (E.MathError) (Double)))) + a3Value <- (pure(\callbackArg228 callbackArg229 -> unsafePerformIO $ do {inputs <- sequence [writeEquality callbackArg228,writeEquality callbackArg229];let { input=X.Tuple inputs };LC.callbackValue a3 input >>= \reply -> X.asBoolean reply}) :: IO (EqualityValue -> EqualityValue -> (Bool))) + a4Value <- (readEquality a4 :: IO EqualityValue) + source ((V.iterateUntil a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (V.Convergence EqualityValue))) >>= \_result230 -> encodeConvergence _result230 + (115,[a0,a1]) -> do + a0Value <- (X.asText a0 :: IO (String)) + a1Value <- (unbox "HMath.API.Convergence.Convergence" a1 :: IO (V.Convergence EqualityValue)) + source ((V.requireConvergence a0Value a1Value) :: (Either (E.MathError) EqualityValue)) >>= \_result231 -> writeEquality _result231 + (116,[a0]) -> do + a0Value <- (asEitherValue a0 :: IO (Either X.Value X.Value)) + (case ((V.resultMaybe a0Value) :: (Maybe X.Value)) of {Nothing -> pure X.None;Just item232 -> pure item232 >>= maybeValue . Just}) + (117,[a0,a1]) -> do + a0Value <- (pure a0 :: IO X.Value) + a1Value <- ((asMaybeValue a1 >>= \optional233 -> case optional233 of {Nothing -> pure Nothing;Just item -> Just <$> (pure item)}) :: IO (Maybe X.Value)) + eitherValue ((V.fromMaybeError a0Value a1Value) :: (Either X.Value X.Value)) + (118,[]) -> do + encodeStopReason ((V.ResidualSatisfied ) :: (V.StopReason)) + (119,[]) -> do + encodeStopReason ((V.IterationLimit ) :: (V.StopReason)) + (120,[]) -> do + encodeStopReason ((V.Stagnation ) :: (V.StopReason)) + (121,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.Convergence" a0 :: IO (V.Convergence EqualityValue)) + writeEquality ((V.estimate a0Value) :: EqualityValue) + (122,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.Convergence" a0 :: IO (V.Convergence EqualityValue)) + pure(X.Index ((V.iterationCount a0Value) :: (Int))) + (123,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.Convergence" a0 :: IO (V.Convergence EqualityValue)) + pure(X.Scalar SDouble ((V.finalResidual a0Value) :: (Double))) + (124,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.Convergence" a0 :: IO (V.Convergence EqualityValue)) + encodeStopReason ((V.stopReason a0Value) :: (V.StopReason)) + (125,[a0,a1,a2,a3]) -> do + a0Value <- (readEquality a0 :: IO EqualityValue) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asScalar a2 :: IO (Double)) + a3Value <- (unbox "HMath.API.Convergence.StopReason" a3 :: IO (V.StopReason)) + encodeConvergence ((V.Convergence a0Value a1Value a2Value a3Value) :: (V.Convergence EqualityValue)) + (126,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.IterationOptions" a0 :: IO (V.IterationOptions)) + pure(X.Index ((V.maximumIterations a0Value) :: (Int))) + (127,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.IterationOptions" a0 :: IO (V.IterationOptions)) + pure(X.Scalar SDouble ((V.absoluteTolerance a0Value) :: (Double))) + (128,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.IterationOptions" a0 :: IO (V.IterationOptions)) + pure(X.Scalar SDouble ((V.relativeTolerance a0Value) :: (Double))) + (129,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asScalar a2 :: IO (Double)) + encodeIterationOptions ((V.IterationOptions a0Value a1Value a2Value) :: (V.IterationOptions)) + (130,[a0]) -> do + a0Value <- (unbox "HMath.API.Convergence.Convergence" a0 :: IO (V.Convergence EqualityValue)) + (case ((case a0Value of V.Converged x -> Just x;_ -> Nothing) :: (Maybe EqualityValue)) of {Nothing -> pure X.None;Just item234 -> writeEquality item234 >>= maybeValue . Just}) + (131,[prototype,a0]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (X.asList a0 >>= mapM(\item235 -> readOrdered witness item235) :: IO [OrderedValue]) + X.List <$>mapM(\item236 -> (case item236 of {Nothing -> pure X.None;Just item237 -> pure(X.Index item237) >>= maybeValue . Just})) ((D.nextGreater a0Value) :: [(Maybe (Int))]) + (132,[prototype,a0,a1]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (readOrdered witness a0 :: IO OrderedValue) + a1Value <- (X.asList a1 >>= mapM(\item238 -> readOrdered witness item238) :: IO [OrderedValue]) + source ((A.binarySearch a0Value a1Value) :: (Either (E.MathError) (Maybe (Int)))) >>= \_result239 -> (case _result239 of {Nothing -> pure X.None;Just item240 -> pure(X.Index item240) >>= maybeValue . Just}) + (133,[prototype,a0,a1]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (readOrdered witness a0 :: IO OrderedValue) + a1Value <- (X.asList a1 >>= mapM(\item241 -> readOrdered witness item241) :: IO [OrderedValue]) + source ((A.exponentialSearch a0Value a1Value) :: (Either (E.MathError) (Maybe (Int)))) >>= \_result242 -> (case _result242 of {Nothing -> pure X.None;Just item243 -> pure(X.Index item243) >>= maybeValue . Just}) + (134,[prototype,a0]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (X.asList a0 >>= mapM(\item244 -> readOrdered witness item244) :: IO [OrderedValue]) + X.List <$>mapM(\item245 -> (\(part246,part247) -> X.Tuple <$> sequence [writeOrdered part246,pure(X.Index part247)]) item245) ((A.numericGroups a0Value) :: [(OrderedValue,(Int))]) + (135,[prototype,a0]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (X.asList a0 >>= mapM(\item248 -> readOrdered witness item248) :: IO [OrderedValue]) + (\(part249,part250) -> X.Tuple <$> sequence [X.List <$>mapM(\item251 -> writeOrdered item251) part249,X.List <$>mapM(\item252 -> pure(X.Index item252)) part250]) ((A.coordinateCompression a0Value) :: ([OrderedValue],[(Int)])) + (136,[prototype,a0,a1]) -> do + witness <- orderedWith [foundationOrdering][prototype] + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM(\item253 -> readOrdered witness item253) :: IO [OrderedValue]) + source ((C.multisetPermutations a0Value a1Value) :: (Either (E.MathError) [[OrderedValue]])) >>= \_result254 -> X.List <$>mapM(\item255 -> X.List <$>mapM(\item256 -> writeOrdered item256) item255) _result254 + (-1,[value]) -> X.Text <$> objectName value + (-2,[value]) -> objectParts value + (-3,[value]) -> eitherValue(Left value) + (-4,[value]) -> eitherValue(Right value) + (-5,[value]) -> maybeValue(Just value) + (-6,[value]) -> orderedType value + (-7,[value]) -> optionalType value + (-8,[prototype,values]) -> X.asList values >>= heapFromListTyped prototype >>= encodeHeap + (-9,[prototype,values]) -> X.asList values >>= multisetTyped prototype >>= encodeMultiSet + _ -> X.invalid "invalid foundation operation/arity" +foreign export ccall "hm_foundation_apply" ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(X.publish value out)) diff --git a/src/HMath/FFI/FoundationCodec.hs b/src/HMath/FFI/FoundationCodec.hs new file mode 100644 index 0000000..5312e79 --- /dev/null +++ b/src/HMath/FFI/FoundationCodec.hs @@ -0,0 +1,239 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Foreign representation, original dictionaries and persistent owners only. +module HMath.FFI.FoundationCodec where +import Control.Exception (catch,evaluate,throw,throwIO) +import Data.Dynamic (Dynamic,toDyn,fromDynamic) +import Data.Typeable (Typeable,cast,typeRep) +import Data.Proxy (Proxy(..)) +import Foreign.C (CInt) +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.DataStructure as D +import qualified HMath.Discrete as S +import qualified HMath.API.Algebra as AlgebraAPI +import qualified HMath.API.Shape as ShapeAPI +import HMath.Matrix (Matrix) +import qualified HMath.Error as E +import qualified HMath.FFI.Autodiff as AD +import qualified HMath.FFI.AutodiffValue as ADValue +import qualified HMath.FFI.NumericTypes.Core as NumericCore +import qualified HMath.FFI.Polynomial as Polynomial +import qualified HMath.FFI.TensorCodec as Tensor +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.Coefficient +import HMath.FFI.MathError +import HMath.FFI.Ordering + +data Envelope=Envelope String Dynamic (IO X.Value) (Maybe(Dynamic -> IO Bool)) +opaque :: Typeable a => String -> Int -> a -> IO () -> IO X.Value -> X.Value +opaque name dtype value force view=X.Opaque 400 dtype 0 force(Envelope name(toDyn value)view Nothing) +opaqueEq :: (Typeable a,Eq a) => String -> Int -> a -> IO () -> IO X.Value -> X.Value +opaqueEq name dtype value force view=X.Opaque 400 dtype 0 force(Envelope name(toDyn value)view(Just compareValue)) + where + compareValue other=maybe(X.invalid "equality source types differ")(pure . (value==))(fromDynamic other) + +unbox :: forall a. Typeable a => String -> X.Value -> IO a +unbox name(X.Opaque 400 _ _ _ payload)=case cast payload of + Just(Envelope actual value _ _) | name==actual -> maybe(X.invalid "foundation object type differs") pure(fromDynamic value) + _ -> X.invalid "foundation object subtype differs" +unbox _ _=X.invalid "expected foundation object" +objectName :: X.Value -> IO String +objectName(X.Opaque 400 _ _ _ payload)=case cast payload of + Just(Envelope name _ _ _) -> pure name + _ -> X.invalid "invalid foundation envelope" +objectName _=X.invalid "expected foundation object" +objectParts :: X.Value -> IO X.Value +objectParts(X.Opaque 400 _ _ _ payload)=case cast payload of + Just(Envelope _ _ view _) -> view + _ -> X.invalid "invalid foundation envelope" +objectParts _=X.invalid "expected foundation object" +source :: Either E.MathError a -> IO a +source=either(throwIO . CallbackMathError)pure +foundationBoundary :: IO CInt -> IO CInt +foundationBoundary action=Boundary.boundary $ callbackBoundary (\e -> Boundary.checked(Left e)(const(pure()))) action +forceFields :: [IO X.Value] -> IO () +forceFields actions=sequence actions >>= mapM_ X.forceValue + +-- Only a successful Just containing None needs an explicit wrapper. Ordinary +-- optional non-None values retain the common language representation. +data Present=Present X.Value +maybeValue :: Maybe X.Value -> IO X.Value +maybeValue Nothing=pure X.None +maybeValue(Just value)=case value of + X.None -> pure(opaque "HMath.Internal.Just" (-1) (Present value) (X.forceValue value) (pure(X.Tuple[X.Text "Just",value]))) + _ -> pure value +asMaybeValue :: X.Value -> IO(Maybe X.Value) +asMaybeValue X.None=pure Nothing +asMaybeValue value@(X.Opaque 400 _ _ _ _)=do + name <- objectName value + if name=="HMath.Internal.Just" then do Present x <- unbox name value;pure(Just x) else pure(Just value) +asMaybeValue value=pure(Just value) +newtype Choice=Choice(Either X.Value X.Value) +eitherValue :: Either X.Value X.Value -> IO X.Value +eitherValue result=pure(opaque "HMath.Internal.Either" (-1)(Choice result) force view) + where + force=either X.forceValue X.forceValue result + view=pure(case result of Left e -> X.Tuple[X.Text "Left",e];Right x -> X.Tuple[X.Text "Right",x]) +asEitherValue :: X.Value -> IO(Either X.Value X.Value) +asEitherValue value=do Choice result <- unbox "HMath.Internal.Either" value;pure result + +-- These wrappers delegate to the actual original Ord/Eq dictionaries. No +-- alternate numeric ordering, hashing or sorting algorithm is implemented. +data OrderedValue where + OrderedValue :: (Typeable a,Ord a) => (a -> IO X.Value) -> a -> OrderedValue +instance Eq OrderedValue where + OrderedValue _ a == OrderedValue _ b=case cast b of Just y -> a==y;Nothing -> throw(CallbackFailure 1 "incompatible foreign ordered types") +instance Ord OrderedValue where + compare(OrderedValue _ a)(OrderedValue _ b)=case cast b of Just y -> compare a y;Nothing -> throw(CallbackFailure 1 "incompatible foreign ordered types") +writeOrdered :: OrderedValue -> IO X.Value +writeOrdered(OrderedValue write value)=write value +readOrdered :: SomeOrdered -> X.Value -> IO OrderedValue +readOrdered(SomeOrdered write readValue) value=OrderedValue write <$> readValue value +sameDomain :: SomeOrdered -> SomeOrdered -> Bool +sameDomain(SomeOrdered(_::a->IO X.Value)_)(SomeOrdered(_::b->IO X.Value)_)=typeRep(Proxy::Proxy a)==typeRep(Proxy::Proxy b) +chooseDomain :: Maybe SomeOrdered -> [X.Value] -> IO SomeOrdered +chooseDomain(Just domain) _=pure domain +chooseDomain Nothing examples=orderedWith [foundationOrdering] examples +mergeDomain :: Maybe SomeOrdered -> Maybe SomeOrdered -> IO(Maybe SomeOrdered) +mergeDomain Nothing b=pure b +mergeDomain a Nothing=pure a +mergeDomain a@(Just left)(Just right) + | sameDomain left right=pure a + | otherwise=X.invalid "ordered container element types differ" + +data HeapState=HeapState (Maybe SomeOrdered) (D.Heap OrderedValue) +instance Eq HeapState where + HeapState a x == HeapState b y=case(a,b) of + (Just left,Just right) | not(sameDomain left right) -> throw(CallbackFailure 1 "heap element types differ") + _ -> x==y +heapEmpty :: HeapState +heapEmpty=HeapState Nothing D.emptyHeap +heapFromList :: [X.Value] -> IO HeapState +heapFromList []=pure heapEmpty +heapFromList values=do domain <- chooseDomain Nothing values;xs <- mapM(readOrdered domain) values;pure(HeapState(Just domain)(D.heapFromList xs)) +heapFromListTyped :: X.Value -> [X.Value] -> IO HeapState +heapFromListTyped prototype values=do domain <- orderedWith [foundationOrdering][prototype];xs <- mapM(readOrdered domain)values;pure(HeapState(Just domain)(D.heapFromList xs)) +heapInsert :: X.Value -> HeapState -> IO HeapState +heapInsert value(HeapState existing heap)=do + domain <- chooseDomain existing [value];x <- readOrdered domain value + pure(HeapState(Just domain)(D.heapInsert x heap)) +heapPop :: HeapState -> IO(Maybe(X.Value,HeapState)) +heapPop(HeapState domain heap)=case D.heapPop heap of + Nothing -> pure Nothing + Just(value,next) -> do x <- writeOrdered value;pure(Just(x,HeapState domain next)) + +data MultiState=MultiState (Maybe SomeOrdered) (S.MultiSet OrderedValue) +instance Eq MultiState where + MultiState a x == MultiState b y=case(a,b) of + (Just left,Just right) | not(sameDomain left right) -> throw(CallbackFailure 1 "multiset element types differ") + _ -> x==y +multiset :: [X.Value] -> IO MultiState +multiset []=pure(MultiState Nothing(S.multiset [])) +multiset values=do domain <- chooseDomain Nothing values;xs <- mapM(readOrdered domain) values;pure(MultiState(Just domain)(S.multiset xs)) +multisetTyped :: X.Value -> [X.Value] -> IO MultiState +multisetTyped prototype values=do domain <- orderedWith [foundationOrdering][prototype];xs <- mapM(readOrdered domain)values;pure(MultiState(Just domain)(S.multiset xs)) +multiplicity :: X.Value -> MultiState -> IO Integer +multiplicity value(MultiState domain set)=do witness <- chooseDomain domain [value];x <- readOrdered witness value;pure(S.multiplicity x set) +multisetEntries :: MultiState -> IO[(X.Value,Integer)] +multisetEntries(MultiState _ set)=mapM(\(x,n) -> do v <- writeOrdered x;pure(v,n))(S.multisetEntries set) +multisetInsert :: X.Value -> MultiState -> IO MultiState +multisetInsert value(MultiState existing set)=do + domain <- chooseDomain existing [value];x <- readOrdered domain value + pure(MultiState(Just domain)(S.multisetInsert x set)) +multisetDelete :: X.Value -> MultiState -> IO MultiState +multisetDelete value(MultiState existing set)=do + domain <- chooseDomain existing [value];x <- readOrdered domain value + pure(MultiState(Just domain)(S.multisetDelete x set)) +multisetBinary :: (S.MultiSet OrderedValue -> S.MultiSet OrderedValue -> S.MultiSet OrderedValue) -> MultiState -> MultiState -> IO MultiState +multisetBinary operation(MultiState a left)(MultiState b right)=do domain <- mergeDomain a b;pure(MultiState domain(operation left right)) + +foundationOrdering :: Resolver +foundationOrdering value=case value of + X.Opaque 400 _ _ _ _ -> do + name <- objectName value + case name of + "HMath.Internal.OrderedType" -> do OrderedType domain <- unbox name value;pure(Just domain) + "HMath.API.Shape.Shape" -> pure(Just(SomeOrdered (\x -> pure(opaqueEq name (-1)(x::ShapeAPI.Shape)(evaluate(ShapeAPI.shapeElements x)>>pure())(X.unsupported "original Shape is abstract")))(unbox name))) + "HMath.API.Algebra.Exact" -> pure(Just(SomeOrdered (\x -> pure(opaqueEq name 18 (x::AlgebraAPI.Exact)(evaluate(AlgebraAPI.getExact x)>>pure())(pure(X.Tuple[X.Text "Exact",X.Tuple[X.Scalar SRational(AlgebraAPI.getExact x)]]))))(unbox name))) + "HMath.Discrete.Implicant" -> pure(Just(SomeOrdered (\x -> pure(opaque name (-1)(x::S.Implicant)(evaluate x>>pure())(pure(X.Tuple[X.Text "Implicant",X.Tuple[X.Scalar SInteger(S.implicantValue x),X.Scalar SInteger(S.implicantMask x)]]))))(unbox name))) + _ -> pure Nothing + _ -> pure Nothing + +newtype OrderedType=OrderedType SomeOrdered +orderedType :: X.Value -> IO X.Value +orderedType prototype=do domain <- orderedWith [foundationOrdering][prototype];pure(boxOrderedType domain) +optionalType :: X.Value -> IO X.Value +optionalType prototype=do + SomeOrdered write readValue <- orderedWith [foundationOrdering][prototype] + let writeMaybe Nothing=pure X.None + writeMaybe(Just x)=write x >>= maybeValue . Just + readMaybe value=asMaybeValue value >>= traverse readValue + pure(boxOrderedType(SomeOrdered writeMaybe readMaybe)) +boxOrderedType :: SomeOrdered -> X.Value +boxOrderedType domain=opaque "HMath.Internal.OrderedType" (-1)(OrderedType domain)(pure())(X.unsupported "an original Ord dictionary prototype has no value fields") + +checkedCallback :: X.Value -> X.Value -> (X.Value -> IO a) -> IO(Either E.MathError a) +checkedCallback function argument decodeResult=(LC.callbackValue function argument >>= decodeResult >>= pure . Right) `catch` relay + where + relay(CallbackMathError e)=pure(Left e) + relay other=throwIO(other::CallbackFailure) + +newtype EqualityValue=EqualityValue X.Value +instance Eq EqualityValue where + EqualityValue a == EqualityValue b=unsafePerformIO(eqValue a b) +writeEquality :: EqualityValue -> IO X.Value +writeEquality(EqualityValue value)=pure value +readEquality :: X.Value -> IO EqualityValue +readEquality=pure . EqualityValue +eqValue :: X.Value -> X.Value -> IO Bool +eqValue (X.Scalar (_::ScalarType a) a)(X.Scalar _ b)= + maybe(X.invalid "equality coefficient types differ")(pure . (a==))(cast b) +eqValue (X.Index a)(X.Index b)=pure(a==b) +eqValue (X.Boolean a)(X.Boolean b)=pure(a==b) +eqValue (X.Text a)(X.Text b)=pure(a==b) +eqValue X.None X.None=pure True +eqValue (X.List a)(X.List b)=pure(map EqualityValue a==map EqualityValue b) +eqValue (X.Tuple a)(X.Tuple b) + | length a==length b=pure(map EqualityValue a==map EqualityValue b) + | otherwise=X.invalid "equality tuple types differ" +-- Recover the original Eq dictionaries of standard mathematical owners. +-- Equality is performed by each source instance, including tensor views and NaN. +eqValue (X.Dense(X.SomeMatrix _ left)) right = (left==) <$> X.asMatrix right +eqValue left@(X.Dense(X.StructuralMatrix code _ _ _ _)) right = case code of + 16 -> do a <- X.asMatrix left :: IO(Matrix Bool); b <- X.asMatrix right; pure(a==b) + 17 -> do a <- X.asMatrix left :: IO(Matrix String); b <- X.asMatrix right; pure(a==b) + 18 -> do a <- X.asMatrix left :: IO(Matrix AlgebraAPI.Exact); b <- X.asMatrix right; pure(a==b) + _ -> X.unsupported "structural Matrix has no exposed original Eq dictionary" +eqValue (X.Opaque 6 _ _ _ payload) right = case cast payload of + Just(Polynomial.SomePolynomial _ left) -> (left==) <$> Polynomial.asPolynomial right + Nothing -> X.invalid "invalid Polynomial equality payload" +eqValue (X.Opaque 7 _ _ _ payload) right = case cast payload of + Just(Polynomial.SomeSeries _ left) -> (left==) <$> Polynomial.asSeries right + Nothing -> X.invalid "invalid PowerSeries equality payload" +eqValue left@(X.Opaque 8 _ _ _ _) right = (==) <$> Polynomial.asRationalFunction left <*> Polynomial.asRationalFunction right +eqValue left@(X.Opaque kind _ _ _ _) right | kind>=40 && kind<=53 = + NumericCore.equalValueWith eqValue left right +eqValue left@(X.Opaque 289 _ _ _ _) right = do + AD.Tower a <- ADValue.asADTower left + AD.Tower b <- ADValue.asADTower right + maybe(X.invalid "original AD equality component types differ")(pure . (a==))(cast b) +eqValue left@(X.Opaque kind _ _ _ _) right | kind==161 || kind==270 = do + Tensor.SomeTensor _ original <- Tensor.asTensor left + (original==) <$> Tensor.asTensorType right +eqValue a@(X.Opaque 400 _ _ _ left) b@(X.Opaque 400 _ _ _ right)=case(cast left,cast right) of + (Just(Envelope name _ _ (Just compareValue)),Just(Envelope other payload _ _)) + | name==other -> compareValue payload + _ -> do + SomeOrdered _ readValue <- orderedWith [foundationOrdering] [a,b] + (==) <$> readValue a <*> readValue b +eqValue a b=do + SomeOrdered _ readValue <- orderedWith [foundationOrdering] [a,b] + (==) <$> readValue a <*> readValue b + +orderedValues :: [X.Value] -> IO[OrderedValue] +orderedValues []=pure[] +orderedValues values=do domain <- orderedWith [foundationOrdering] values;mapM(readOrdered domain) values diff --git a/src/HMath/FFI/Geometry.hs b/src/HMath/FFI/Geometry.hs new file mode 100644 index 0000000..b94c7ec --- /dev/null +++ b/src/HMath/FFI/Geometry.hs @@ -0,0 +1,807 @@ +{-# OPTIONS_GHC -Wno-orphans #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_geometry_bindings.py. +module HMath.FFI.Geometry where +import Foreign +import Foreign.C +import Data.Typeable (cast) +import HMath.FFI.Boundary +import HMath.FFI.Coefficient (ScalarType (SDouble)) +import HMath.FFI.GraphCodec (Wire(..),boxed,unboxed) +import HMath.FFI.Value +import qualified HMath.Geometry as G +import qualified HMath.Matrix as M + +matrixValue :: M.Matrix Double -> Value +matrixValue = Dense . SomeMatrix SDouble +matrixInput :: Value -> IO (M.Matrix Double) +matrixInput (Dense (SomeMatrix _ value)) = maybe (invalid "Matrix Double required") pure (cast value) +matrixInput _ = invalid "dense Matrix Double required" +orderingValue :: Ordering -> Value +orderingValue value = Index (case value of LT -> -1;EQ -> 0;GT -> 1) +-- Outer presence must remain explicit: Nothing and Just Nothing are distinct. +nestedMaybeValue :: Wire a => Maybe (Maybe a) -> Value +nestedMaybeValue Nothing = Tuple [Boolean False,None] +nestedMaybeValue (Just value) = Tuple [Boolean True,wire value] +instance Wire G.Point2 where + wire = boxed 169 + unwire = unboxed 169 +instance Wire G.Point3 where + wire = boxed 170 + unwire = unboxed 170 +instance Wire G.PointND where + wire = boxed 171 + unwire = unboxed 171 +instance Wire G.Line where + wire = boxed 172 + unwire = unboxed 172 +instance Wire G.Ray where + wire = boxed 173 + unwire = unboxed 173 +instance Wire G.Segment where + wire = boxed 174 + unwire = unboxed 174 +instance Wire G.Plane where + wire = boxed 175 + unwire = unboxed 175 +instance Wire G.Triangle where + wire = boxed 176 + unwire = unboxed 176 +instance Wire G.Rectangle where + wire = boxed 177 + unwire = unboxed 177 +instance Wire G.Circle where + wire = boxed 178 + unwire = unboxed 178 +instance Wire G.Ellipse where + wire = boxed 179 + unwire = unboxed 179 +instance Wire G.Polygon where + wire = boxed 180 + unwire = unboxed 180 +instance Wire G.Sphere where + wire = boxed 181 + unwire = unboxed 181 +instance Wire G.AABB where + wire = boxed 182 + unwire = unboxed 182 +instance Wire G.OBB where + wire = boxed 183 + unwire = unboxed 183 +instance Wire G.Capsule where + wire = boxed 184 + unwire = unboxed 184 +instance Wire G.Cylinder where + wire = boxed 185 + unwire = unboxed 185 +instance Wire G.Cone where + wire = boxed 186 + unwire = unboxed 186 +instance Wire G.Frustum where + wire = boxed 187 + unwire = unboxed 187 +instance Wire G.Orientation where + wire = boxed 188 + unwire = unboxed 188 +instance Wire G.Location where + wire = boxed 189 + unwire = unboxed 189 +instance Wire G.Penetration where + wire = boxed 190 + unwire = unboxed 190 +instance Wire G.HullAlgorithm where + wire = boxed 191 + unwire = unboxed 191 +instance Wire G.BooleanOperation where + wire = boxed 192 + unwire = unboxed 192 +instance Wire G.Metric where + wire = boxed 193 + unwire = unboxed 193 +instance Wire G.Intersection2 where + wire = boxed 194 + unwire = unboxed 194 +instance Wire G.CircleIntersection where + wire = boxed 195 + unwire = unboxed 195 +instance Wire G.SpatialKind where + wire = boxed 196 + unwire = unboxed 196 +instance Wire G.PointCloud where + wire = boxed 197 + unwire = unboxed 197 +instance Wire G.SpatialIndex where + wire = boxed 198 + unwire = unboxed 198 +instance Wire G.NeighborQuery where + wire = boxed 199 + unwire = unboxed 199 +foreign export ccall "hm_geometry_describe" describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +describe input out = boundary $ do + value <- deRefStablePtr input + text <- case valueInfo value of + (169,_,_) -> show <$> (unwire value :: IO G.Point2) + (170,_,_) -> show <$> (unwire value :: IO G.Point3) + (171,_,_) -> show <$> (unwire value :: IO G.PointND) + (172,_,_) -> show <$> (unwire value :: IO G.Line) + (173,_,_) -> show <$> (unwire value :: IO G.Ray) + (174,_,_) -> show <$> (unwire value :: IO G.Segment) + (175,_,_) -> show <$> (unwire value :: IO G.Plane) + (176,_,_) -> show <$> (unwire value :: IO G.Triangle) + (177,_,_) -> show <$> (unwire value :: IO G.Rectangle) + (178,_,_) -> show <$> (unwire value :: IO G.Circle) + (179,_,_) -> show <$> (unwire value :: IO G.Ellipse) + (180,_,_) -> show <$> (unwire value :: IO G.Polygon) + (181,_,_) -> show <$> (unwire value :: IO G.Sphere) + (182,_,_) -> show <$> (unwire value :: IO G.AABB) + (183,_,_) -> show <$> (unwire value :: IO G.OBB) + (184,_,_) -> show <$> (unwire value :: IO G.Capsule) + (185,_,_) -> show <$> (unwire value :: IO G.Cylinder) + (186,_,_) -> show <$> (unwire value :: IO G.Cone) + (187,_,_) -> show <$> (unwire value :: IO G.Frustum) + (188,_,_) -> show <$> (unwire value :: IO G.Orientation) + (189,_,_) -> show <$> (unwire value :: IO G.Location) + (190,_,_) -> show <$> (unwire value :: IO G.Penetration) + (191,_,_) -> show <$> (unwire value :: IO G.HullAlgorithm) + (192,_,_) -> show <$> (unwire value :: IO G.BooleanOperation) + (193,_,_) -> show <$> (unwire value :: IO G.Metric) + (194,_,_) -> show <$> (unwire value :: IO G.Intersection2) + (195,_,_) -> show <$> (unwire value :: IO G.CircleIntersection) + (196,_,_) -> show <$> (unwire value :: IO G.SpatialKind) + (197,_,_) -> show <$> (unwire value :: IO G.PointCloud) + (198,_,_) -> show <$> (unwire value :: IO G.SpatialIndex) + (199,_,_) -> show <$> (unwire value :: IO G.NeighborQuery) + _ -> invalid "expected Geometry object" + checked (Right (Text text)) (`publish` out) +foreign export ccall "hm_geometry_equal" equal :: StablePtr Value -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +equal :: StablePtr Value -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +equal first second out = boundary $ do + a <- deRefStablePtr first + b <- deRefStablePtr second + result <- case (valueInfo a,valueInfo b) of + ((169,_,_),(169,_,_)) -> (==) <$> (unwire a :: IO G.Point2) <*> unwire b + ((170,_,_),(170,_,_)) -> (==) <$> (unwire a :: IO G.Point3) <*> unwire b + ((171,_,_),(171,_,_)) -> (==) <$> (unwire a :: IO G.PointND) <*> unwire b + ((172,_,_),(172,_,_)) -> (==) <$> (unwire a :: IO G.Line) <*> unwire b + ((173,_,_),(173,_,_)) -> (==) <$> (unwire a :: IO G.Ray) <*> unwire b + ((174,_,_),(174,_,_)) -> (==) <$> (unwire a :: IO G.Segment) <*> unwire b + ((175,_,_),(175,_,_)) -> (==) <$> (unwire a :: IO G.Plane) <*> unwire b + ((176,_,_),(176,_,_)) -> (==) <$> (unwire a :: IO G.Triangle) <*> unwire b + ((177,_,_),(177,_,_)) -> (==) <$> (unwire a :: IO G.Rectangle) <*> unwire b + ((178,_,_),(178,_,_)) -> (==) <$> (unwire a :: IO G.Circle) <*> unwire b + ((179,_,_),(179,_,_)) -> (==) <$> (unwire a :: IO G.Ellipse) <*> unwire b + ((180,_,_),(180,_,_)) -> (==) <$> (unwire a :: IO G.Polygon) <*> unwire b + ((181,_,_),(181,_,_)) -> (==) <$> (unwire a :: IO G.Sphere) <*> unwire b + ((182,_,_),(182,_,_)) -> (==) <$> (unwire a :: IO G.AABB) <*> unwire b + ((183,_,_),(183,_,_)) -> (==) <$> (unwire a :: IO G.OBB) <*> unwire b + ((184,_,_),(184,_,_)) -> (==) <$> (unwire a :: IO G.Capsule) <*> unwire b + ((185,_,_),(185,_,_)) -> (==) <$> (unwire a :: IO G.Cylinder) <*> unwire b + ((186,_,_),(186,_,_)) -> (==) <$> (unwire a :: IO G.Cone) <*> unwire b + ((187,_,_),(187,_,_)) -> (==) <$> (unwire a :: IO G.Frustum) <*> unwire b + ((188,_,_),(188,_,_)) -> (==) <$> (unwire a :: IO G.Orientation) <*> unwire b + ((189,_,_),(189,_,_)) -> (==) <$> (unwire a :: IO G.Location) <*> unwire b + ((190,_,_),(190,_,_)) -> (==) <$> (unwire a :: IO G.Penetration) <*> unwire b + ((191,_,_),(191,_,_)) -> (==) <$> (unwire a :: IO G.HullAlgorithm) <*> unwire b + ((192,_,_),(192,_,_)) -> (==) <$> (unwire a :: IO G.BooleanOperation) <*> unwire b + ((193,_,_),(193,_,_)) -> (==) <$> (unwire a :: IO G.Metric) <*> unwire b + ((194,_,_),(194,_,_)) -> (==) <$> (unwire a :: IO G.Intersection2) <*> unwire b + ((195,_,_),(195,_,_)) -> (==) <$> (unwire a :: IO G.CircleIntersection) <*> unwire b + ((196,_,_),(196,_,_)) -> (==) <$> (unwire a :: IO G.SpatialKind) <*> unwire b + ((197,_,_),(197,_,_)) -> (==) <$> (unwire a :: IO G.PointCloud) <*> unwire b + ((198,_,_),(198,_,_)) -> (==) <$> (unwire a :: IO G.SpatialIndex) <*> unwire b + ((199,_,_),(199,_,_)) -> (==) <$> (unwire a :: IO G.NeighborQuery) <*> unwire b + _ -> pure False + checked (Right (Boolean result)) (`publish` out) +foreign export ccall "hm_geometry_parts" parts :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +parts :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +parts input out = boundary $ do + value <- deRefStablePtr input + result <- case valueInfo value of + (169,_,_) -> do + object <- unwire value :: IO G.Point2 + pure $ case object of + G.P2 field0 field1 -> Tuple [Text "P2",Tuple [wire field0,wire field1]] + (170,_,_) -> do + object <- unwire value :: IO G.Point3 + pure $ case object of + G.P3 field0 field1 field2 -> Tuple [Text "P3",Tuple [wire field0,wire field1,wire field2]] + (171,_,_) -> do + object <- unwire value :: IO G.PointND + pure $ case object of + G.PointND field0 -> Tuple [Text "PointND",Tuple [wire field0]] + (172,_,_) -> do + object <- unwire value :: IO G.Line + pure $ case object of + G.Line field0 field1 -> Tuple [Text "Line",Tuple [wire field0,wire field1]] + (173,_,_) -> do + object <- unwire value :: IO G.Ray + pure $ case object of + G.Ray field0 field1 -> Tuple [Text "Ray",Tuple [wire field0,wire field1]] + (174,_,_) -> do + object <- unwire value :: IO G.Segment + pure $ case object of + G.Segment field0 field1 -> Tuple [Text "Segment",Tuple [wire field0,wire field1]] + (175,_,_) -> do + object <- unwire value :: IO G.Plane + pure $ case object of + G.Plane field0 field1 -> Tuple [Text "Plane",Tuple [wire field0,wire field1]] + (176,_,_) -> do + object <- unwire value :: IO G.Triangle + pure $ case object of + G.Triangle field0 field1 field2 -> Tuple [Text "Triangle",Tuple [wire field0,wire field1,wire field2]] + (177,_,_) -> do + object <- unwire value :: IO G.Rectangle + pure $ case object of + G.Rectangle field0 field1 -> Tuple [Text "Rectangle",Tuple [wire field0,wire field1]] + (178,_,_) -> do + object <- unwire value :: IO G.Circle + pure $ case object of + G.Circle field0 field1 -> Tuple [Text "Circle",Tuple [wire field0,wire field1]] + (179,_,_) -> do + object <- unwire value :: IO G.Ellipse + pure $ case object of + G.Ellipse field0 field1 field2 field3 -> Tuple [Text "Ellipse",Tuple [wire field0,wire field1,wire field2,wire field3]] + (180,_,_) -> do + object <- unwire value :: IO G.Polygon + pure $ case object of + G.Polygon field0 -> Tuple [Text "Polygon",Tuple [wire field0]] + (181,_,_) -> do + object <- unwire value :: IO G.Sphere + pure $ case object of + G.Sphere field0 field1 -> Tuple [Text "Sphere",Tuple [wire field0,wire field1]] + (182,_,_) -> do + object <- unwire value :: IO G.AABB + pure $ case object of + G.AABB field0 field1 -> Tuple [Text "AABB",Tuple [wire field0,wire field1]] + (183,_,_) -> do + object <- unwire value :: IO G.OBB + pure $ case object of + G.OBB field0 field1 field2 -> Tuple [Text "OBB",Tuple [wire field0,wire field1,wire field2]] + (184,_,_) -> do + object <- unwire value :: IO G.Capsule + pure $ case object of + G.Capsule field0 field1 field2 -> Tuple [Text "Capsule",Tuple [wire field0,wire field1,wire field2]] + (185,_,_) -> do + object <- unwire value :: IO G.Cylinder + pure $ case object of + G.Cylinder field0 field1 field2 -> Tuple [Text "Cylinder",Tuple [wire field0,wire field1,wire field2]] + (186,_,_) -> do + object <- unwire value :: IO G.Cone + pure $ case object of + G.Cone field0 field1 field2 -> Tuple [Text "Cone",Tuple [wire field0,wire field1,wire field2]] + (187,_,_) -> do + object <- unwire value :: IO G.Frustum + pure $ case object of + G.Frustum field0 -> Tuple [Text "Frustum",Tuple [wire field0]] + (188,_,_) -> do + object <- unwire value :: IO G.Orientation + pure $ case object of + G.Clockwise -> Tuple [Text "Clockwise",Tuple []] + G.Collinear -> Tuple [Text "Collinear",Tuple []] + G.Counterclockwise -> Tuple [Text "Counterclockwise",Tuple []] + (189,_,_) -> do + object <- unwire value :: IO G.Location + pure $ case object of + G.Boundary -> Tuple [Text "Boundary",Tuple []] + G.Inside -> Tuple [Text "Inside",Tuple []] + G.Outside -> Tuple [Text "Outside",Tuple []] + (190,_,_) -> do + object <- unwire value :: IO G.Penetration + pure $ case object of + G.Penetration field0 field1 field2 field3 -> Tuple [Text "Penetration",Tuple [wire field0,wire field1,wire field2,wire field3]] + (191,_,_) -> do + object <- unwire value :: IO G.HullAlgorithm + pure $ case object of + G.GiftWrapping -> Tuple [Text "GiftWrapping",Tuple []] + G.GrahamScan -> Tuple [Text "GrahamScan",Tuple []] + G.MonotoneChain -> Tuple [Text "MonotoneChain",Tuple []] + G.Quickhull -> Tuple [Text "Quickhull",Tuple []] + (192,_,_) -> do + object <- unwire value :: IO G.BooleanOperation + pure $ case object of + G.Difference -> Tuple [Text "Difference",Tuple []] + G.Intersection -> Tuple [Text "Intersection",Tuple []] + G.Union -> Tuple [Text "Union",Tuple []] + (193,_,_) -> do + object <- unwire value :: IO G.Metric + pure $ case object of + G.Chebyshev -> Tuple [Text "Chebyshev",Tuple []] + G.Euclidean -> Tuple [Text "Euclidean",Tuple []] + G.Manhattan -> Tuple [Text "Manhattan",Tuple []] + G.Minkowski field0 -> Tuple [Text "Minkowski",Tuple [wire field0]] + (194,_,_) -> do + object <- unwire value :: IO G.Intersection2 + pure $ case object of + G.CoincidentLine -> Tuple [Text "CoincidentLine",Tuple []] + G.IntersectionPoint field0 -> Tuple [Text "IntersectionPoint",Tuple [wire field0]] + G.NoIntersection -> Tuple [Text "NoIntersection",Tuple []] + G.OverlapSegment field0 field1 -> Tuple [Text "OverlapSegment",Tuple [wire field0,wire field1]] + (195,_,_) -> do + object <- unwire value :: IO G.CircleIntersection + pure $ case object of + G.CirclePoints field0 -> Tuple [Text "CirclePoints",Tuple [wire field0]] + G.CoincidentCircles -> Tuple [Text "CoincidentCircles",Tuple []] + G.DisjointCircles -> Tuple [Text "DisjointCircles",Tuple []] + (196,_,_) -> do + object <- unwire value :: IO G.SpatialKind + pure $ case object of + G.BVH -> Tuple [Text "BVH",Tuple []] + G.BallTree -> Tuple [Text "BallTree",Tuple []] + G.KDTree -> Tuple [Text "KDTree",Tuple []] + G.Octree -> Tuple [Text "Octree",Tuple []] + G.Quadtree -> Tuple [Text "Quadtree",Tuple []] + G.RTree -> Tuple [Text "RTree",Tuple []] + G.SpatialHash field0 -> Tuple [Text "SpatialHash",Tuple [wire field0]] + (199,_,_) -> do + object <- unwire value :: IO G.NeighborQuery + pure $ case object of + G.NeighborQuery field0 field1 field2 -> Tuple [Text "NeighborQuery",Tuple [wire field0,wire field1,wire field2]] + _ -> unsupported "public constructor fields unavailable for this abstract Geometry type" + checked (Right result) (`publish` out) +foreign export ccall "hm_geometry_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +apply operation inputs arity out = boundary $ do + values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr + case (operation,values) of + (0,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (Double)) + arg3 <- (unwire v3 :: IO (Int)) + checked (Right (G.Penetration arg0 arg1 arg2 arg3)) (\result -> publish (wire result) out) + (1,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (Int)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO ([G.Point2])) + arg3 <- (unwire v3 :: IO ([G.Point2])) + checked (G.epa arg0 arg1 arg2 arg3) (\result -> publish (wire result) out) + (2,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (Int)) + arg1 <- (unwire v1 :: IO ([G.Point2])) + arg2 <- (unwire v2 :: IO ([G.Point2])) + checked (G.gjk arg0 arg1 arg2) (\result -> publish (wire result) out) + (3,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Penetration)) + checked (Right (G.penetrationDepth arg0)) (\result -> publish (wire result) out) + (4,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Penetration)) + checked (Right (G.penetrationError arg0)) (\result -> publish (wire result) out) + (5,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Penetration)) + checked (Right (G.penetrationIterations arg0)) (\result -> publish (wire result) out) + (6,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Penetration)) + checked (Right (G.penetrationNormal arg0)) (\result -> publish (wire result) out) + (7,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + arg1 <- (unwire v1 :: IO ([G.Point2])) + checked (G.separatingAxis arg0 arg1) (\result -> publish (wire result) out) + (8,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (Right (G.AABB arg0 arg1)) (\result -> publish (wire result) out) + (9,[]) -> do + checked (Right (G.Boundary)) (\result -> publish (wire result) out) + (10,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Point3)) + arg2 <- (unwire v2 :: IO (Double)) + checked (Right (G.Capsule arg0 arg1 arg2)) (\result -> publish (wire result) out) + (11,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (Double)) + checked (Right (G.Circle arg0 arg1)) (\result -> publish (wire result) out) + (12,[]) -> do + checked (Right (G.Clockwise)) (\result -> publish (wire result) out) + (13,[]) -> do + checked (Right (G.Collinear)) (\result -> publish (wire result) out) + (14,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Point3)) + arg2 <- (unwire v2 :: IO (Double)) + checked (Right (G.Cone arg0 arg1 arg2)) (\result -> publish (wire result) out) + (15,[]) -> do + checked (Right (G.Counterclockwise)) (\result -> publish (wire result) out) + (16,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Point3)) + arg2 <- (unwire v2 :: IO (Double)) + checked (Right (G.Cylinder arg0 arg1 arg2)) (\result -> publish (wire result) out) + (17,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO (Double)) + arg3 <- (unwire v3 :: IO (Double)) + checked (Right (G.Ellipse arg0 arg1 arg2 arg3)) (\result -> publish (wire result) out) + (18,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Plane])) + checked (Right (G.Frustum arg0)) (\result -> publish (wire result) out) + (19,[]) -> do + checked (Right (G.Inside)) (\result -> publish (wire result) out) + (20,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (Right (G.Line arg0 arg1)) (\result -> publish (wire result) out) + (21,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO ([G.Point3])) + arg2 <- (unwire v2 :: IO (G.Point3)) + checked (Right (G.OBB arg0 arg1 arg2)) (\result -> publish (wire result) out) + (22,[]) -> do + checked (Right (G.Outside)) (\result -> publish (wire result) out) + (23,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + checked (Right (G.P2 arg0 arg1)) (\result -> publish (wire result) out) + (24,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO (Double)) + checked (Right (G.P3 arg0 arg1 arg2)) (\result -> publish (wire result) out) + (25,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (Double)) + checked (Right (G.Plane arg0 arg1)) (\result -> publish (wire result) out) + (26,[v0]) -> do + arg0 <- (unwire v0 :: IO ([Double])) + checked (Right (G.PointND arg0)) (\result -> publish (wire result) out) + (27,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + checked (Right (G.Polygon arg0)) (\result -> publish (wire result) out) + (28,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (Right (G.Ray arg0 arg1)) (\result -> publish (wire result) out) + (29,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (Right (G.Rectangle arg0 arg1)) (\result -> publish (wire result) out) + (30,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (Right (G.Segment arg0 arg1)) (\result -> publish (wire result) out) + (31,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (Double)) + checked (Right (G.Sphere arg0 arg1)) (\result -> publish (wire result) out) + (32,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (G.Point2)) + checked (Right (G.Triangle arg0 arg1 arg2)) (\result -> publish (wire result) out) + (33,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + checked (G.point2 arg0 arg1) (\result -> publish (wire result) out) + (34,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO (Double)) + checked (G.point3 arg0 arg1 arg2) (\result -> publish (wire result) out) + (35,[v0]) -> do + arg0 <- (unwire v0 :: IO ([Double])) + checked (G.pointND arg0) (\result -> publish (wire result) out) + (36,[]) -> do + checked (Right (G.Difference)) (\result -> publish (wire result) out) + (37,[]) -> do + checked (Right (G.GiftWrapping)) (\result -> publish (wire result) out) + (38,[]) -> do + checked (Right (G.GrahamScan)) (\result -> publish (wire result) out) + (39,[]) -> do + checked (Right (G.Intersection)) (\result -> publish (wire result) out) + (40,[]) -> do + checked (Right (G.MonotoneChain)) (\result -> publish (wire result) out) + (41,[]) -> do + checked (Right (G.Quickhull)) (\result -> publish (wire result) out) + (42,[]) -> do + checked (Right (G.Union)) (\result -> publish (wire result) out) + (43,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + arg1 <- (unwire v1 :: IO (G.Polygon)) + checked (G.clipPolygon arg0 arg1) (\result -> publish (wire result) out) + (44,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.HullAlgorithm)) + arg1 <- (unwire v1 :: IO ([G.Point2])) + checked (G.convexHull arg0 arg1) (\result -> publish (wire result) out) + (45,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + checked (G.minimumBoundingCircle arg0) (\result -> publish (wire result) out) + (46,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + checked (G.minimumBoundingRectangle arg0) (\result -> publish (wire result) out) + (47,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + arg1 <- (unwire v1 :: IO ([G.Point2])) + checked (G.minkowskiSum arg0 arg1) (\result -> publish (wire result) out) + (48,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + checked (G.polygonArea arg0) (\result -> publish (wire result) out) + (49,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.BooleanOperation)) + arg1 <- (unwire v1 :: IO (G.Polygon)) + arg2 <- (unwire v2 :: IO (G.Polygon)) + checked (G.polygonBoolean arg0 arg1 arg2) (\result -> publish (wire result) out) + (50,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + checked (G.polygonCentroid arg0) (\result -> publish (wire result) out) + (51,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + checked (G.shoelace arg0) (\result -> publish (wire result) out) + (52,[]) -> do + checked (Right (G.Chebyshev)) (\result -> publish (wire result) out) + (53,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + checked (Right (G.CirclePoints arg0)) (\result -> publish (wire result) out) + (54,[]) -> do + checked (Right (G.CoincidentCircles)) (\result -> publish (wire result) out) + (55,[]) -> do + checked (Right (G.CoincidentLine)) (\result -> publish (wire result) out) + (56,[]) -> do + checked (Right (G.DisjointCircles)) (\result -> publish (wire result) out) + (57,[]) -> do + checked (Right (G.Euclidean)) (\result -> publish (wire result) out) + (58,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + checked (Right (G.IntersectionPoint arg0)) (\result -> publish (wire result) out) + (59,[]) -> do + checked (Right (G.Manhattan)) (\result -> publish (wire result) out) + (60,[v0]) -> do + arg0 <- (unwire v0 :: IO (Double)) + checked (Right (G.Minkowski arg0)) (\result -> publish (wire result) out) + (61,[]) -> do + checked (Right (G.NoIntersection)) (\result -> publish (wire result) out) + (62,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (Right (G.OverlapSegment arg0 arg1)) (\result -> publish (wire result) out) + (63,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.AABB)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (G.boxContains arg0 arg1) (\result -> publish (wire result) out) + (64,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.AABB)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (G.boxSDF arg0 arg1) (\result -> publish (wire result) out) + (65,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Capsule)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.capsuleSDF arg0 arg1) (\result -> publish (wire result) out) + (66,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Circle)) + arg1 <- (unwire v1 :: IO (G.Circle)) + checked (G.circleIntersection arg0 arg1) (\result -> publish (wire result) out) + (67,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Triangle)) + checked (G.circumcenter arg0) (\result -> publish (wire result) out) + (68,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Cone)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.coneSDF arg0 arg1) (\result -> publish (wire result) out) + (69,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (G.cosineDistance arg0 arg1) (\result -> publish (wire result) out) + (70,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Cylinder)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.cylinderSDF arg0 arg1) (\result -> publish (wire result) out) + (71,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Metric)) + arg1 <- (unwire v1 :: IO (G.PointND)) + arg2 <- (unwire v2 :: IO (G.PointND)) + checked (G.distance arg0 arg1 arg2) (\result -> publish (wire result) out) + (72,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Ellipse)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (G.ellipseContains arg0 arg1) (\result -> publish (wire result) out) + (73,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO ([G.PointND])) + arg1 <- (unwire v1 :: IO ([G.PointND])) + checked (G.hausdorffDistance arg0 arg1) (\result -> publish (wire result) out) + (74,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Triangle)) + checked (G.incenter arg0) (\result -> publish (wire result) out) + (75,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (G.Point2)) + arg3 <- (unwire v3 :: IO (G.Point2)) + checked (G.incircle arg0 arg1 arg2 arg3) (\result -> publish (orderingValue result) out) + (76,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (G.Point2)) + arg3 <- (unwire v3 :: IO (G.Point2)) + checked (G.lineIntersection arg0 arg1 arg2 arg3) (\result -> publish (wire result) out) + (77,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Line)) + arg1 <- (unwire v1 :: IO (G.Plane)) + checked (G.linePlaneIntersection arg0 arg1) (\result -> publish (nestedMaybeValue result) out) + (78,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO ([[Double]])) + arg1 <- (unwire v1 :: IO (G.PointND)) + arg2 <- (unwire v2 :: IO (G.PointND)) + checked (G.mahalanobisDistance arg0 arg1 arg2) (\result -> publish (wire result) out) + (79,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.OBB)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.obbSDF arg0 arg1) (\result -> publish (wire result) out) + (80,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (G.Point2)) + checked (G.orientation arg0 arg1 arg2) (\result -> publish (wire result) out) + (81,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Plane)) + arg1 <- (unwire v1 :: IO (G.Plane)) + checked (G.planeIntersection arg0 arg1) (\result -> publish (nestedMaybeValue result) out) + (82,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.Line)) + checked (G.pointLineDistance arg0 arg1) (\result -> publish (wire result) out) + (83,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Plane)) + checked (G.pointPlaneDistance arg0 arg1) (\result -> publish (wire result) out) + (84,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.PointND)) + arg1 <- (unwire v1 :: IO (G.Segment)) + checked (G.pointSegmentDistance arg0 arg1) (\result -> publish (wire result) out) + (85,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (G.polygonLocation arg0 arg1) (\result -> publish (wire result) out) + (86,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Ray)) + arg1 <- (unwire v1 :: IO (G.AABB)) + checked (G.rayBox arg0 arg1) (\result -> publish (wire result) out) + (87,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Ray)) + arg1 <- (unwire v1 :: IO (G.Sphere)) + checked (G.raySphere arg0 arg1) (\result -> publish (wire result) out) + (88,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Ray)) + arg1 <- (unwire v1 :: IO ((G.Point3,G.Point3,G.Point3))) + checked (G.rayTriangle arg0 arg1) (\result -> publish (wire result) out) + (89,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (G.Point2)) + arg1 <- (unwire v1 :: IO (G.Point2)) + arg2 <- (unwire v2 :: IO (G.Point2)) + arg3 <- (unwire v3 :: IO (G.Point2)) + checked (G.segmentIntersection arg0 arg1 arg2 arg3) (\result -> publish (wire result) out) + (90,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Sphere)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.sphereContains arg0 arg1) (\result -> publish (wire result) out) + (91,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Sphere)) + arg1 <- (unwire v1 :: IO (G.Point3)) + checked (G.sphereSDF arg0 arg1) (\result -> publish (wire result) out) + (92,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Triangle)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (G.triangleBarycentric arg0 arg1) (\result -> publish (wire result) out) + (93,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Triangle)) + arg1 <- (unwire v1 :: IO (G.Triangle)) + checked (G.triangleIntersection arg0 arg1) (\result -> publish (wire result) out) + (94,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Triangle)) + arg1 <- (unwire v1 :: IO (G.Point2)) + checked (G.triangleLocation arg0 arg1) (\result -> publish (wire result) out) + (95,[]) -> do + checked (Right (G.BVH)) (\result -> publish (wire result) out) + (96,[]) -> do + checked (Right (G.BallTree)) (\result -> publish (wire result) out) + (97,[]) -> do + checked (Right (G.KDTree)) (\result -> publish (wire result) out) + (98,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO ([(Int,Double)])) + arg1 <- (unwire v1 :: IO (Int)) + arg2 <- (unwire v2 :: IO (Bool)) + checked (Right (G.NeighborQuery arg0 arg1 arg2)) (\result -> publish (wire result) out) + (99,[]) -> do + checked (Right (G.Octree)) (\result -> publish (wire result) out) + (100,[]) -> do + checked (Right (G.Quadtree)) (\result -> publish (wire result) out) + (101,[]) -> do + checked (Right (G.RTree)) (\result -> publish (wire result) out) + (102,[v0]) -> do + arg0 <- (unwire v0 :: IO (Double)) + checked (Right (G.SpatialHash arg0)) (\result -> publish (wire result) out) + (103,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.SpatialKind)) + arg1 <- (unwire v1 :: IO (G.PointCloud)) + checked (G.buildSpatialIndex arg0 arg1) (\result -> publish (wire result) out) + (104,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.PointCloud)) + checked (Right (G.cloudPoints arg0)) (\result -> publish (wire result) out) + (105,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (Int)) + arg1 <- (unwire v1 :: IO (Int)) + arg2 <- (unwire v2 :: IO (G.SpatialIndex)) + arg3 <- (unwire v3 :: IO (G.PointND)) + checked (G.nearestQuery arg0 arg1 arg2 arg3) (\result -> publish (wire result) out) + (106,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.PointND])) + checked (G.pointCloud arg0) (\result -> publish (wire result) out) + (107,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.NeighborQuery)) + checked (Right (G.queryExhaustive arg0)) (\result -> publish (wire result) out) + (108,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.NeighborQuery)) + checked (Right (G.queryLeaves arg0)) (\result -> publish (wire result) out) + (109,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.NeighborQuery)) + checked (Right (G.queryNeighbors arg0)) (\result -> publish (wire result) out) + (110,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.SpatialIndex)) + arg1 <- (unwire v1 :: IO (G.PointND)) + arg2 <- (unwire v2 :: IO (Double)) + checked (G.radiusQuery arg0 arg1 arg2) (\result -> publish (wire result) out) + (111,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.SpatialIndex)) + arg1 <- (unwire v1 :: IO (G.AABB)) + checked (G.rangeQuery arg0 arg1) (\result -> publish (wire result) out) + (112,[v0,v1]) -> do + arg0 <- matrixInput v0 + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (G.affineTransform arg0 arg1) (\result -> publish (matrixValue result) out) + (113,[v0,v1]) -> do + arg0 <- matrixInput v0 + arg1 <- (unwire v1 :: IO (G.PointND)) + checked (G.applyTransform arg0 arg1) (\result -> publish (wire result) out) + (114,[v0,v1]) -> do + arg0 <- matrixInput v0 + arg1 <- matrixInput v1 + checked (G.composeTransforms arg0 arg1) (\result -> publish (matrixValue result) out) + (115,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Frustum)) + arg1 <- (unwire v1 :: IO (G.AABB)) + checked (G.cullBox arg0 arg1) (\result -> publish (wire result) out) + (116,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Frustum)) + arg1 <- (unwire v1 :: IO (G.Sphere)) + checked (G.cullSphere arg0 arg1) (\result -> publish (wire result) out) + (117,[v0]) -> do + arg0 <- matrixInput v0 + checked (G.extractFrustum arg0) (\result -> publish (wire result) out) + (118,[v0]) -> do + arg0 <- matrixInput v0 + checked (G.inverseTransform arg0) (\result -> publish (matrixValue result) out) + (119,[v0,v1,v2]) -> do + arg0 <- (unwire v0 :: IO (G.Point3)) + arg1 <- (unwire v1 :: IO (G.Point3)) + arg2 <- (unwire v2 :: IO (G.Point3)) + checked (G.lookAt arg0 arg1 arg2) (\result -> publish (matrixValue result) out) + (120,[v0,v1,v2,v3,v4,v5]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO (Double)) + arg3 <- (unwire v3 :: IO (Double)) + arg4 <- (unwire v4 :: IO (Double)) + arg5 <- (unwire v5 :: IO (Double)) + checked (G.orthographic arg0 arg1 arg2 arg3 arg4 arg5) (\result -> publish (matrixValue result) out) + (121,[v0,v1,v2,v3]) -> do + arg0 <- (unwire v0 :: IO (Double)) + arg1 <- (unwire v1 :: IO (Double)) + arg2 <- (unwire v2 :: IO (Double)) + arg3 <- (unwire v3 :: IO (Double)) + checked (G.perspective arg0 arg1 arg2 arg3) (\result -> publish (matrixValue result) out) + (122,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + arg1 <- (unwire v1 :: IO ([(Int,Int)])) + checked (G.constrainedDelaunay arg0 arg1) (\result -> publish (wire result) out) + (123,[v0]) -> do + arg0 <- (unwire v0 :: IO ([G.Point2])) + checked (G.delaunay arg0) (\result -> publish (wire result) out) + (124,[v0]) -> do + arg0 <- (unwire v0 :: IO (G.Polygon)) + checked (G.earClip arg0) (\result -> publish (wire result) out) + (125,[v0,v1]) -> do + arg0 <- (unwire v0 :: IO (G.Rectangle)) + arg1 <- (unwire v1 :: IO ([G.Point2])) + checked (G.voronoi arg0 arg1) (\result -> publish (wire result) out) + _ -> invalid "Geometry operation identifier or arity differs" diff --git a/src/HMath/FFI/Graph.hs b/src/HMath/FFI/Graph.hs new file mode 100644 index 0000000..7b11151 --- /dev/null +++ b/src/HMath/FFI/Graph.hs @@ -0,0 +1,428 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; do not edit. +module HMath.FFI.Graph where +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.FFI.Value +import HMath.FFI.GraphCodec +import qualified HMath.Graph as G +foreign export ccall "hm_graph_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr Heuristic -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr Heuristic -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +apply operation input arity callback userdata out = boundary $ do + values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr + case (operation, values) of + (0, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.betweennessCentrality graph)) (\result_value -> publish (wire result_value) out) + (1, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.bipartiteColors graph)) (\result_value -> publish (wire result_value) out) + (2, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.closenessCentrality graph)) (\result_value -> publish (wire result_value) out) + (3, [vgraph]) -> do + graph <- unwire vgraph + checked (G.clusteringCoefficients graph) (\result_value -> publish (wire result_value) out) + (4, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.degreeCentrality graph)) (\result_value -> publish (wire result_value) out) + (5, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.density graph)) (\result_value -> publish (wire result_value) out) + (6, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.diameterRadius graph)) (\result_value -> publish (wire result_value) out) + (7, [viterations, vtolerance, vgraph]) -> do + iterations <- unwire viterations + tolerance <- unwire vtolerance + graph <- unwire vgraph + checked (G.eigenvectorCentrality iterations tolerance graph) (\result_value -> publish (wire result_value) out) + (8, [vgraph]) -> do + graph <- unwire vgraph + checked (G.eulerianPath graph) (\result_value -> publish (wire result_value) out) + (9, [vfuel, vgraph]) -> do + fuel <- unwire vfuel + graph <- unwire vgraph + checked (G.exactColoring fuel graph) (\result_value -> publish (wire result_value) out) + (10, [vbudget, vleft, vright]) -> do + budget <- unwire vbudget + left <- unwire vleft + right <- unwire vright + checked (G.graphEditDistance budget left right) (\result_value -> publish (wire result_value) out) + (11, [vnormalized, vgraph]) -> do + normalized <- unwire vnormalized + graph <- unwire vgraph + checked (G.graphLaplacian normalized graph) (\result_value -> publish (wire result_value) out) + (12, [vleft, vright]) -> do + left <- unwire vleft + right <- unwire vright + checked (G.graphSimilarity left right) (\result_value -> publish (wire result_value) out) + (13, [vgraph]) -> do + graph <- unwire vgraph + checked (G.greedyColoring graph) (\result_value -> publish (wire result_value) out) + (14, [vfuel, vgraph]) -> do + fuel <- unwire vfuel + graph <- unwire vgraph + checked (G.hamiltonianPath fuel graph) (\result_value -> publish (wire result_value) out) + (15, [viterations, vtolerance, valpha, vbeta, vgraph]) -> do + iterations <- unwire viterations + tolerance <- unwire vtolerance + alpha <- unwire valpha + beta <- unwire vbeta + graph <- unwire vgraph + checked (G.katzCentrality iterations tolerance alpha beta graph) (\result_value -> publish (wire result_value) out) + (16, [viterations, vgraph]) -> do + iterations <- unwire viterations + graph <- unwire vgraph + checked (G.labelPropagation iterations graph) (\result_value -> publish (wire result_value) out) + (17, [viterations, vtolerance, vnormalized, vgraph]) -> do + iterations <- unwire viterations + tolerance <- unwire vtolerance + normalized <- unwire vnormalized + graph <- unwire vgraph + checked (G.laplacianSpectrum iterations tolerance normalized graph) (\result_value -> publish (wire result_value) out) + (18, [vbudget, vgraph]) -> do + budget <- unwire vbudget + graph <- unwire vgraph + checked (G.louvain budget graph) (\result_value -> publish (wire result_value) out) + (19, [vgraph, vlabels]) -> do + graph <- unwire vgraph + labels <- unwire vlabels + checked (G.modularity graph labels) (\result_value -> publish (wire result_value) out) + (20, [vgraph, vstart]) -> do + graph <- unwire vgraph + start <- unwire vstart + checked (G.nearestNeighborTour graph start) (\result_value -> publish (wire result_value) out) + (21, [viterations, vtolerance, vdamping, vgraph]) -> do + iterations <- unwire viterations + tolerance <- unwire vtolerance + damping <- unwire vdamping + graph <- unwire vgraph + checked (G.pageRank iterations tolerance damping graph) (\result_value -> publish (wire result_value) out) + (22, [vcount, vseed, vgraph, vstart]) -> do + count <- unwire vcount + seed <- unwire vseed + graph <- unwire vgraph + start <- unwire vstart + checked (G.randomWalk count seed graph start) (\result_value -> publish (wire result_value) out) + (23, [viterations, vgraph, vtour]) -> do + iterations <- unwire viterations + graph <- unwire vgraph + tour <- unwire vtour + checked (G.twoOptTour iterations graph tour) (\result_value -> publish (wire result_value) out) + (24, [vdirected, vvertex_count, voffsets, vtargets, vweights, vedge_ids, vorientations]) -> do + directed <- unwire vdirected + vertex_count <- unwire vvertex_count + offsets <- unwire voffsets + targets <- unwire vtargets + weights <- unwire vweights + edge_ids <- unwire vedge_ids + orientations <- unwire vorientations + checked (Right (G.CSR directed vertex_count offsets targets weights edge_ids orientations)) (\result_value -> publish (wire result_value) out) + (25, [vedge_id, vsource, vtarget, vweight]) -> do + edge_id <- unwire vedge_id + source <- unwire vsource + target <- unwire vtarget + weight <- unwire vweight + checked (Right (G.Edge edge_id source target weight)) (\result_value -> publish (wire result_value) out) + (26, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.adjacencyList graph)) (\result_value -> publish (wire result_value) out) + (27, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.adjacencyMatrix graph)) (\result_value -> publish (wire result_value) out) + (28, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.arcs graph)) (\result_value -> publish (wire result_value) out) + (29, [vgraph]) -> do + graph <- unwire vgraph + checked (G.articulationPoints graph) (\result_value -> publish (wire result_value) out) + (30, [vgraph, vstart]) -> do + graph <- unwire vgraph + start <- unwire vstart + checked (G.bfs graph start) (\result_value -> publish (wire result_value) out) + (31, [vbipartite_graph]) -> do + bipartite_graph <- unwire vbipartite_graph + checked (Right (G.bipartiteBase bipartite_graph)) (\result_value -> publish (wire result_value) out) + (32, [vleft_vertices, vright_vertices, vedges]) -> do + left_vertices <- unwire vleft_vertices + right_vertices <- unwire vright_vertices + edges <- unwire vedges + checked (G.bipartiteGraph left_vertices right_vertices edges) (\result_value -> publish (wire result_value) out) + (33, [vbipartite_graph]) -> do + bipartite_graph <- unwire vbipartite_graph + checked (Right (G.bipartiteParts bipartite_graph)) (\result_value -> publish (wire result_value) out) + (34, [vgraph]) -> do + graph <- unwire vgraph + checked (G.boruvka graph) (\result_value -> publish (wire result_value) out) + (35, [vgraph]) -> do + graph <- unwire vgraph + checked (G.bridges graph) (\result_value -> publish (wire result_value) out) + (36, [vgraph, vvertex]) -> do + graph <- unwire vgraph + vertex <- unwire vvertex + checked (G.checkVertex graph vertex) (\result_value -> publish (wire result_value) out) + (37, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.connectedComponents graph)) (\result_value -> publish (wire result_value) out) + (38, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrDirected csr)) (\result_value -> publish (wire result_value) out) + (39, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrIds csr)) (\result_value -> publish (wire result_value) out) + (40, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrOffsets csr)) (\result_value -> publish (wire result_value) out) + (41, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrOrientations csr)) (\result_value -> publish (wire result_value) out) + (42, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrTargets csr)) (\result_value -> publish (wire result_value) out) + (43, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrVertices csr)) (\result_value -> publish (wire result_value) out) + (44, [vcsr]) -> do + csr <- unwire vcsr + checked (Right (G.csrWeights csr)) (\result_value -> publish (wire result_value) out) + (45, [vtext]) -> do + text <- unwire vtext + checked (G.deserializeBipartiteGraph text) (\result_value -> publish (wire result_value) out) + (46, [vtext]) -> do + text <- unwire vtext + checked (G.deserializeGraph text) (\result_value -> publish (wire result_value) out) + (47, [vtext]) -> do + text <- unwire vtext + checked (G.deserializeHypergraph text) (\result_value -> publish (wire result_value) out) + (48, [vgraph, vstart]) -> do + graph <- unwire vgraph + start <- unwire vstart + checked (G.dfs graph start) (\result_value -> publish (wire result_value) out) + (49, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.directed graph)) (\result_value -> publish (wire result_value) out) + (50, [vedge]) -> do + edge <- unwire vedge + checked (Right (G.edgeFrom edge)) (\result_value -> publish (wire result_value) out) + (51, [vedge]) -> do + edge <- unwire vedge + checked (Right (G.edgeId edge)) (\result_value -> publish (wire result_value) out) + (52, [vedge]) -> do + edge <- unwire vedge + checked (Right (G.edgeTo edge)) (\result_value -> publish (wire result_value) out) + (53, [vedge]) -> do + edge <- unwire vedge + checked (Right (G.edgeWeight edge)) (\result_value -> publish (wire result_value) out) + (54, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.edges graph)) (\result_value -> publish (wire result_value) out) + (55, [vx]) -> do + x <- unwire vx + checked (Right (G.finite x)) (\result_value -> publish (wire result_value) out) + (56, [vdirected, vrows, vorientations]) -> do + directed <- unwire vdirected + rows <- unwire vrows + orientations <- unwire vorientations + checked (G.fromAdjacencyList directed rows orientations) (\result_value -> publish (wire result_value) out) + (57, [vdirected, vcells]) -> do + directed <- unwire vdirected + cells <- unwire vcells + checked (G.fromAdjacencyMatrix directed cells) (\result_value -> publish (wire result_value) out) + (58, [vcsr]) -> do + csr <- unwire vcsr + checked (G.fromCSR csr) (\result_value -> publish (wire result_value) out) + (59, [vdirected, vcells, vorientations]) -> do + directed <- unwire vdirected + cells <- unwire vcells + orientations <- unwire vorientations + checked (G.fromLabeledAdjacencyMatrix directed cells orientations) (\result_value -> publish (wire result_value) out) + (60, [vdirected, vvertex_count, vedges]) -> do + directed <- unwire vdirected + vertex_count <- unwire vvertex_count + edges <- unwire vedges + checked (G.graph directed vertex_count edges) (\result_value -> publish (wire result_value) out) + (61, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.hasCycle graph)) (\result_value -> publish (wire result_value) out) + (62, [vhypergraph]) -> do + hypergraph <- unwire vhypergraph + checked (Right (G.hyperVertices hypergraph)) (\result_value -> publish (wire result_value) out) + (63, [vhypergraph]) -> do + hypergraph <- unwire vhypergraph + checked (Right (G.hyperedges hypergraph)) (\result_value -> publish (wire result_value) out) + (64, [vvertex_count, vhyperedges]) -> do + vertex_count <- unwire vvertex_count + hyperedges <- unwire vhyperedges + checked (G.hypergraph vertex_count hyperedges) (\result_value -> publish (wire result_value) out) + (65, [vbudget, vgraph, vsource, vtarget]) -> do + budget <- unwire vbudget + graph <- unwire vgraph + source <- unwire vsource + target <- unwire vtarget + checked (G.iterativeDeepening budget graph source target) (\result_value -> publish (wire result_value) out) + (66, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.kosarajuSCC graph)) (\result_value -> publish (wire result_value) out) + (67, [vgraph]) -> do + graph <- unwire vgraph + checked (G.kruskal graph) (\result_value -> publish (wire result_value) out) + (68, [vgraph, vvertex]) -> do + graph <- unwire vgraph + vertex <- unwire vvertex + checked (Right (G.neighbors graph vertex)) (\result_value -> publish (wire result_value) out) + (69, [vgraph]) -> do + graph <- unwire vgraph + checked (G.prim graph) (\result_value -> publish (wire result_value) out) + (70, [vgraph]) -> do + graph <- unwire vgraph + checked (G.requireUndirected graph) (\result_value -> publish (wire result_value) out) + (71, [vbipartite]) -> do + bipartite <- unwire vbipartite + checked (Right (G.serializeBipartiteGraph bipartite)) (\result_value -> publish (wire result_value) out) + (72, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.serializeGraph graph)) (\result_value -> publish (wire result_value) out) + (73, [vhypergraph]) -> do + hypergraph <- unwire vhypergraph + checked (Right (G.serializeHypergraph hypergraph)) (\result_value -> publish (wire result_value) out) + (74, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.tarjanSCC graph)) (\result_value -> publish (wire result_value) out) + (75, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.toCSR graph)) (\result_value -> publish (wire result_value) out) + (76, [vgraph]) -> do + graph <- unwire vgraph + checked (G.topologicalSort graph) (\result_value -> publish (wire result_value) out) + (77, [vgraph]) -> do + graph <- unwire vgraph + checked (Right (G.vertexCount graph)) (\result_value -> publish (wire result_value) out) + (78, [vvalue, vedge_flows, vcost]) -> do + value <- unwire vvalue + edge_flows <- unwire vedge_flows + cost <- unwire vcost + checked (Right (G.FlowResult value edge_flows cost)) (\result_value -> publish (wire result_value) out) + (79, [vedge_id, vsource, vtarget, vcapacity, vcost]) -> do + edge_id <- unwire vedge_id + source <- unwire vsource + target <- unwire vtarget + capacity <- unwire vcapacity + cost <- unwire vcost + checked (Right (G.NetworkEdge edge_id source target capacity cost)) (\result_value -> publish (wire result_value) out) + (80, [vbudget, vnetwork, vsource, vtarget]) -> do + budget <- unwire vbudget + network <- unwire vnetwork + source <- unwire vsource + target <- unwire vtarget + checked (G.dinic budget network source target) (\result_value -> publish (wire result_value) out) + (81, [vflow_result]) -> do + flow_result <- unwire vflow_result + checked (Right (G.edgeFlows flow_result)) (\result_value -> publish (wire result_value) out) + (82, [vvalue, vnetwork, vvalue3, vvalue4]) -> do + value <- unwire vvalue + network <- unwire vnetwork + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (G.edmondsKarp value network value3 value4) (\result_value -> publish (wire result_value) out) + (83, [vflow_result]) -> do + flow_result <- unwire vflow_result + checked (Right (G.flowCost flow_result)) (\result_value -> publish (wire result_value) out) + (84, [vflow_result]) -> do + flow_result <- unwire vflow_result + checked (Right (G.flowValue flow_result)) (\result_value -> publish (wire result_value) out) + (85, [vvalue, vnetwork, vvalue3, vvalue4]) -> do + value <- unwire vvalue + network <- unwire vnetwork + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (G.fordFulkerson value network value3 value4) (\result_value -> publish (wire result_value) out) + (86, [vbipartite]) -> do + bipartite <- unwire vbipartite + checked (Right (G.hopcroftKarp bipartite)) (\result_value -> publish (wire result_value) out) + (87, [vcosts]) -> do + costs <- unwire vcosts + checked (G.hungarian costs) (\result_value -> publish (wire result_value) out) + (88, [vvalue, vnetwork, vvalue3, vvalue4]) -> do + value <- unwire vvalue + network <- unwire vnetwork + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (G.minimumCostMaximumFlow value network value3 value4) (\result_value -> publish (wire result_value) out) + (89, [vvalue, vnetwork, vvalue3, vvalue4]) -> do + value <- unwire vvalue + network <- unwire vnetwork + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (G.minimumCut value network value3 value4) (\result_value -> publish (wire result_value) out) + (90, [vvertex_count, vedges]) -> do + vertex_count <- unwire vvertex_count + edges <- unwire vedges + checked (G.network vertex_count edges) (\result_value -> publish (wire result_value) out) + (91, [vnetwork_edge]) -> do + network_edge <- unwire vnetwork_edge + checked (Right (G.networkCapacity network_edge)) (\result_value -> publish (wire result_value) out) + (92, [vnetwork_edge]) -> do + network_edge <- unwire vnetwork_edge + checked (Right (G.networkCost network_edge)) (\result_value -> publish (wire result_value) out) + (93, [vnetwork_edge]) -> do + network_edge <- unwire vnetwork_edge + checked (Right (G.networkEdgeId network_edge)) (\result_value -> publish (wire result_value) out) + (94, [vnetwork]) -> do + network <- unwire vnetwork + checked (Right (G.networkEdges network)) (\result_value -> publish (wire result_value) out) + (95, [vnetwork_edge]) -> do + network_edge <- unwire vnetwork_edge + checked (Right (G.networkFrom network_edge)) (\result_value -> publish (wire result_value) out) + (96, [vnetwork_edge]) -> do + network_edge <- unwire vnetwork_edge + checked (Right (G.networkTo network_edge)) (\result_value -> publish (wire result_value) out) + (97, [vvalue, vnetwork, vvalue3, vvalue4]) -> do + value <- unwire vvalue + network <- unwire vnetwork + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (G.pushRelabel value network value3 value4) (\result_value -> publish (wire result_value) out) + (98, [vgraph, vsource, vtarget]) -> do + graph <- unwire vgraph + let heuristic = heuristicFunction callback userdata + source <- unwire vsource + target <- unwire vtarget + checked (G.aStar graph heuristic source target) (\result_value -> publish (wire result_value) out) + (99, [vgraph, vsource]) -> do + graph <- unwire vgraph + source <- unwire vsource + checked (G.bellmanFord graph source) (\result_value -> publish (wire result_value) out) + (100, [vgraph, vsource, vtarget]) -> do + graph <- unwire vgraph + source <- unwire vsource + target <- unwire vtarget + checked (G.bidirectionalDijkstra graph source target) (\result_value -> publish (wire result_value) out) + (101, [vgraph, vsource]) -> do + graph <- unwire vgraph + source <- unwire vsource + checked (G.dijkstra graph source) (\result_value -> publish (wire result_value) out) + (102, [vgraph]) -> do + graph <- unwire vgraph + checked (G.floydWarshall graph) (\result_value -> publish (wire result_value) out) + (103, [vgraph]) -> do + graph <- unwire vgraph + checked (G.johnson graph) (\result_value -> publish (wire result_value) out) + (104, [vbudget, vcount, vgraph, vsource, vtarget]) -> do + budget <- unwire vbudget + count <- unwire vcount + graph <- unwire vgraph + source <- unwire vsource + target <- unwire vtarget + checked (G.kShortestPaths budget count graph source target) (\result_value -> publish (wire result_value) out) + (105, [vgraph, vsource]) -> do + graph <- unwire vgraph + source <- unwire vsource + checked (G.longestDAGPaths graph source) (\result_value -> publish (wire result_value) out) + (106, [vgraph, vsources]) -> do + graph <- unwire vgraph + sources <- unwire vsources + checked (G.multiSourceDijkstra graph sources) (\result_value -> publish (wire result_value) out) + _ -> invalid "Graph operation arity or identifier differs" diff --git a/src/HMath/FFI/GraphCodec.hs b/src/HMath/FFI/GraphCodec.hs new file mode 100644 index 0000000..07b8d21 --- /dev/null +++ b/src/HMath/FFI/GraphCodec.hs @@ -0,0 +1,126 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE ForeignFunctionInterface #-} + +-- SPDX-License-Identifier: MPL-2.0 +-- | Representation only. Graph algorithms remain in the original modules. +module HMath.FFI.GraphCodec where + +import Control.Exception (evaluate, throwIO) +import Data.Typeable (Typeable, cast) +import Foreign +import Foreign.C +import HMath.FFI.Coefficient +import HMath.FFI.MathError (CallbackFailure (..)) +import HMath.FFI.Value +import qualified HMath.Graph as G +import System.IO.Unsafe (unsafePerformIO) + +class Wire a where + wire :: a -> Value + unwire :: Value -> IO a + +instance Wire Int where + wire = Index + unwire = asIndex +instance Wire Integer where + wire = Scalar SInteger + unwire (Index value) = pure (toInteger value) + unwire value = asScalar @Integer value +instance Wire Word64 where + wire = Scalar SWord64 + unwire (Scalar SWord64 value) = pure value + unwire value = do + integer <- unwire value :: IO Integer + if integer < 0 || integer > toInteger (maxBound :: Word64) + then throwIO (CallbackFailure 3 "Word64 input is outside its representation") + else pure (fromInteger integer) +instance Wire Double where + wire = Scalar SDouble + unwire = asScalar @Double +instance Wire Bool where + wire = Boolean + unwire = asBoolean +instance Wire () where + wire () = Tuple [] + unwire value = asTuple 0 value >> pure () +instance {-# OVERLAPPING #-} Wire String where + wire = Text + unwire = asText +instance {-# OVERLAPPABLE #-} Wire a => Wire [a] where + wire = List . map wire + unwire value = asList value >>= mapM unwire +instance Wire a => Wire (Maybe a) where + wire Nothing = None + wire (Just value) = wire value + unwire None = pure Nothing + unwire value = Just <$> unwire value +instance (Wire a, Wire b) => Wire (a,b) where + wire (a,b) = Tuple [wire a,wire b] + unwire value = do + items <- asTuple 2 value + case items of + [a,b] -> (,) <$> unwire a <*> unwire b + _ -> invalid "pair arity differs" +instance (Wire a, Wire b, Wire c) => Wire (a,b,c) where + wire (a,b,c) = Tuple [wire a,wire b,wire c] + unwire value = do + items <- asTuple 3 value + case items of + [a,b,c] -> (,,) <$> unwire a <*> unwire b <*> unwire c + _ -> invalid "triple arity differs" +instance (Wire a, Wire b, Wire c, Wire d) => Wire (a,b,c,d) where + wire (a,b,c,d) = Tuple [wire a,wire b,wire c,wire d] + unwire value = do + items <- asTuple 4 value + case items of + [a,b,c,d] -> (,,,) <$> unwire a <*> unwire b <*> unwire c <*> unwire d + _ -> invalid "quadruple arity differs" + +boxed :: Typeable a => Int -> a -> Value +boxed kind value = Opaque kind (-1) 0 (evaluate value >> pure ()) value +unboxed :: Typeable a => Int -> Value -> IO a +unboxed expected (Opaque kind _ _ _ value) + | kind == expected = maybe (invalid "Graph payload type differs") pure (cast value) +unboxed _ _ = invalid "Graph object kind differs" +instance Wire G.Graph where + wire = boxed 60 + unwire = unboxed 60 +instance Wire G.Edge where + wire = boxed 61 + unwire = unboxed 61 +instance Wire G.CSR where + wire = boxed 62 + unwire = unboxed 62 +instance Wire G.BipartiteGraph where + wire = boxed 63 + unwire = unboxed 63 +instance Wire G.Hypergraph where + wire = boxed 64 + unwire = unboxed 64 +instance Wire G.Network where + wire = boxed 65 + unwire = unboxed 65 +instance Wire G.NetworkEdge where + wire = boxed 66 + unwire = unboxed 66 +instance Wire G.FlowResult where + wire = boxed 67 + unwire = unboxed 67 + +type Heuristic = CPtrdiff -> Ptr () -> Ptr CDouble -> IO CInt +foreign import ccall "dynamic" callHeuristic :: FunPtr Heuristic -> Heuristic + +-- The original heuristic is pure/deterministic; callbacks are borrowed only +-- during the operation. The entire returned path/value is forced before exit. +{-# NOINLINE heuristicFunction #-} +heuristicFunction :: FunPtr Heuristic -> Ptr () -> Int -> Double +heuristicFunction callback userdata vertex = unsafePerformIO $ + alloca $ \out -> do + status <- callHeuristic callback (fromIntegral vertex) userdata out + if status == 0 + then realToFrac <$> peek out + else throwIO (CallbackFailure status "Graph heuristic callback failed") diff --git a/src/HMath/FFI/Image.hs b/src/HMath/FFI/Image.hs new file mode 100644 index 0000000..ecbc7d5 --- /dev/null +++ b/src/HMath/FFI/Image.hs @@ -0,0 +1,393 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_image_bindings.py. +module HMath.FFI.Image where +import Control.Exception (Exception,bracket,catch,evaluate,throwIO) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.FFI.GraphCodec (Wire(..),boxed,unboxed) +import HMath.FFI.Value +import qualified HMath.Image.Core as C +import qualified HMath.Image.Filter as F +import qualified HMath.Image.Histogram as H +import qualified HMath.Image.Measure as M +import qualified HMath.Image.Spatial as S +import qualified HMath.Image.Color as K +import qualified HMath.Tensor as T +import System.IO.Unsafe (unsafePerformIO) + +instance Wire C.Image where + wire image = Opaque 160 0 (length (C.imageValues image)) (mapM_ evaluate (C.imageValues image)) image + unwire = unboxed 160 +instance Wire (T.Tensor Double) where + wire tensor = Opaque 161 0 (length (T.tensorValues tensor)) (mapM_ evaluate (T.tensorValues tensor)) tensor + unwire = unboxed 161 + +data CallbackStatus = CallbackStatus CInt deriving Show +instance Exception CallbackStatus +imageBoundary :: IO CInt -> IO CInt +imageBoundary action = boundary (action `catch` (\(CallbackStatus status) -> pure status)) +type ImageCallback = Ptr () -> Ptr () -> Ptr (Ptr ()) -> IO CInt +foreign import ccall safe "hm_image_invoke" invokeCallback :: FunPtr ImageCallback -> Ptr () -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +{-# NOINLINE callbackFunction #-} +callbackFunction :: FunPtr ImageCallback -> Ptr () -> [Double] -> Double +callbackFunction callback userdata arguments = unsafePerformIO $ do + let input=Tuple (map wire arguments) + forceValue input + pointer <- newStablePtr input + alloca $ \out -> do + status <- invokeCallback callback userdata pointer out + if status /= 0 then throwIO (CallbackStatus status) else pure () + result <- peek out + bracket (pure result) freeStablePtr (\value -> deRefStablePtr value >>= unwire) +foreign export ccall "hm_image_clone" clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone input out = imageBoundary $ do + value <- deRefStablePtr input + checked (Right value) (`publish` out) +instance Wire C.Boundary where + wire = boxed 162 + unwire = unboxed 162 +instance Wire F.GradientOperator where + wire = boxed 163 + unwire = unboxed 163 +instance Wire F.Morphology where + wire = boxed 164 + unwire = unboxed 164 +instance Wire M.TemplateMetric where + wire = boxed 165 + unwire = unboxed 165 +instance Wire S.Interpolation where + wire = boxed 166 + unwire = unboxed 166 +instance Wire S.Connectivity where + wire = boxed 167 + unwire = unboxed 167 +instance Wire K.ColorSpace where + wire = boxed 168 + unwire = unboxed 168 +foreign export ccall "hm_image_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr ImageCallback -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr ImageCallback -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +apply operation inputs arity callback userdata out = imageBoundary $ do + values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr + case (operation,values) of + (0,[vshape,vchannels,vvalues]) -> do + argShape <- (unwire vshape :: IO ([Int])) + argChannels <- (unwire vchannels :: IO (Int)) + argValues <- (unwire vvalues :: IO ([Double])) + checked (C.image argShape argChannels argValues) (\result -> publish (wire result) out) + (1,[vtensor]) -> do + argTensor <- (unwire vtensor :: IO (T.Tensor Double)) + checked (C.fromTensor argTensor) (\result -> publish (wire result) out) + (2,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.toTensor argImage) (\result -> publish (wire result) out) + (3,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (Right (C.imageShape argImage)) (\result -> publish (wire result) out) + (4,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (Right (C.imageChannels argImage)) (\result -> publish (wire result) out) + (5,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (Right (C.imageValues argImage)) (\result -> publish (wire result) out) + (6,[vimage,vcoordinates]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + argCoordinates <- (unwire vcoordinates :: IO ([Int])) + checked (C.pixel argImage argCoordinates) (\result -> publish (wire result) out) + (7,[vindex,vimage]) -> do + argIndex <- (unwire vindex :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.channel argIndex argImage) (\result -> publish (wire result) out) + (8,[vimages]) -> do + argImages <- (unwire vimages :: IO ([C.Image])) + checked (C.combineChannels argImages) (\result -> publish (wire result) out) + (9,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + let argFunction x = callbackFunction callback userdata [x] + checked (C.mapImage argFunction argImage) (\result -> publish (wire result) out) + (10,[va,vb]) -> do + argA <- (unwire va :: IO (C.Image)) + argB <- (unwire vb :: IO (C.Image)) + let argFunction x y = callbackFunction callback userdata [x,y] + checked (C.zipImage argFunction argA argB) (\result -> publish (wire result) out) + (11,[vlow,vhigh,vimage]) -> do + argLow <- (unwire vlow :: IO (Double)) + argHigh <- (unwire vhigh :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.normalize argLow argHigh argImage) (\result -> publish (wire result) out) + (12,[voffset,vimage]) -> do + argOffset <- (unwire voffset :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.brightness argOffset argImage) (\result -> publish (wire result) out) + (13,[vfactor,vpivot,vimage]) -> do + argFactor <- (unwire vfactor :: IO (Double)) + argPivot <- (unwire vpivot :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.contrast argFactor argPivot argImage) (\result -> publish (wire result) out) + (14,[vpower,vimage]) -> do + argPower <- (unwire vpower :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (C.gamma argPower argImage) (\result -> publish (wire result) out) + (15,[vfill]) -> do + argFill <- (unwire vfill :: IO (Double)) + checked (Right (C.Constant argFill)) (\result -> publish (wire result) out) + (16,[]) -> do + checked (Right (C.Clamp)) (\result -> publish (wire result) out) + (17,[]) -> do + checked (Right (C.Reflect)) (\result -> publish (wire result) out) + (18,[]) -> do + checked (Right (C.Wrap)) (\result -> publish (wire result) out) + (19,[vboundary,vshape,vweights,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ([Int])) + argWeights <- (unwire vweights :: IO ([Double])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.convolve argBoundary argShape argWeights argImage) (\result -> publish (wire result) out) + (20,[vboundary,vshape,vweights,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ([Int])) + argWeights <- (unwire vweights :: IO ([Double])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.correlate argBoundary argShape argWeights argImage) (\result -> publish (wire result) out) + (21,[vboundary,vsigma,vradius,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argSigma <- (unwire vsigma :: IO (Double)) + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.gaussianBlur argBoundary argSigma argRadius argImage) (\result -> publish (wire result) out) + (22,[vboundary,vradius,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.boxBlur argBoundary argRadius argImage) (\result -> publish (wire result) out) + (23,[vboundary,vradius,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.medianBlur argBoundary argRadius argImage) (\result -> publish (wire result) out) + (24,[vboundary,vsigma_space,vsigma_range,vradius,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argSigma_space <- (unwire vsigma_space :: IO (Double)) + argSigma_range <- (unwire vsigma_range :: IO (Double)) + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.bilateralBlur argBoundary argSigma_space argSigma_range argRadius argImage) (\result -> publish (wire result) out) + (25,[vboundary,vamount,vsigma,vradius,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argAmount <- (unwire vamount :: IO (Double)) + argSigma <- (unwire vsigma :: IO (Double)) + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.sharpen argBoundary argAmount argSigma argRadius argImage) (\result -> publish (wire result) out) + (26,[vmethod,vboundary,vimage]) -> do + argMethod <- (unwire vmethod :: IO (F.GradientOperator)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.gradient argMethod argBoundary argImage) (\result -> publish (wire result) out) + (27,[vboundary,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.laplacian argBoundary argImage) (\result -> publish (wire result) out) + (28,[vboundary,vsigma,vradius,vlow,vhigh,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argSigma <- (unwire vsigma :: IO (Double)) + argRadius <- (unwire vradius :: IO (Int)) + argLow <- (unwire vlow :: IO (Double)) + argHigh <- (unwire vhigh :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.canny argBoundary argSigma argRadius argLow argHigh argImage) (\result -> publish (wire result) out) + (29,[voperation,vboundary,vshape,vmask,vimage]) -> do + argOperation <- (unwire voperation :: IO (F.Morphology)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ([Int])) + argMask <- (unwire vmask :: IO ([Bool])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.morphology argOperation argBoundary argShape argMask argImage) (\result -> publish (wire result) out) + (30,[vboundary,vshape,vmask,vimage]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ([Int])) + argMask <- (unwire vmask :: IO ([Bool])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.morphologicalGradient argBoundary argShape argMask argImage) (\result -> publish (wire result) out) + (31,[vboundary]) -> do + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + checked (F.validateBoundary argBoundary) (\result -> publish (wire result) out) + (32,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.scalar2D argImage) (\result -> publish (wire result) out) + (33,[vradius,vimage]) -> do + argRadius <- (unwire vradius :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (F.windowOffsets argRadius argImage) (\result -> publish (wire result) out) + (34,[]) -> do + checked (Right (F.Sobel)) (\result -> publish (wire result) out) + (35,[]) -> do + checked (Right (F.Prewitt)) (\result -> publish (wire result) out) + (36,[]) -> do + checked (Right (F.Scharr)) (\result -> publish (wire result) out) + (37,[]) -> do + checked (Right (F.Erosion)) (\result -> publish (wire result) out) + (38,[]) -> do + checked (Right (F.Dilation)) (\result -> publish (wire result) out) + (39,[]) -> do + checked (Right (F.Opening)) (\result -> publish (wire result) out) + (40,[]) -> do + checked (Right (F.Closing)) (\result -> publish (wire result) out) + (41,[vbins,vimage]) -> do + argBins <- (unwire vbins :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.histogram argBins argImage) (\result -> publish (wire result) out) + (42,[vbins,vimage]) -> do + argBins <- (unwire vbins :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.equalizeHistogram argBins argImage) (\result -> publish (wire result) out) + (43,[vbins,vtiles,vclip_limit,vimage]) -> do + argBins <- (unwire vbins :: IO (Int)) + argTiles <- (unwire vtiles :: IO ((Int, Int))) + argClip_limit <- (unwire vclip_limit :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.clahe argBins argTiles argClip_limit argImage) (\result -> publish (wire result) out) + (44,[vlevel,vimage]) -> do + argLevel <- (unwire vlevel :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.threshold argLevel argImage) (\result -> publish (wire result) out) + (45,[vbins,vimage]) -> do + argBins <- (unwire vbins :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.otsu argBins argImage) (\result -> publish (wire result) out) + (46,[vgaussian,vboundary,vradius,voffset,vimage]) -> do + argGaussian <- (unwire vgaussian :: IO (Bool)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argRadius <- (unwire vradius :: IO (Int)) + argOffset <- (unwire voffset :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (H.adaptiveThreshold argGaussian argBoundary argRadius argOffset argImage) (\result -> publish (wire result) out) + (47,[vmetric,vneedle,vhaystack]) -> do + argMetric <- (unwire vmetric :: IO (M.TemplateMetric)) + argNeedle <- (unwire vneedle :: IO (C.Image)) + argHaystack <- (unwire vhaystack :: IO (C.Image)) + checked (M.templateMatch argMetric argNeedle argHaystack) (\result -> publish (wire result) out) + (48,[vrow_order,vcolumn_order,vimage]) -> do + argRow_order <- (unwire vrow_order :: IO (Int)) + argColumn_order <- (unwire vcolumn_order :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (M.rawMoment argRow_order argColumn_order argImage) (\result -> publish (wire result) out) + (49,[vrow_order,vcolumn_order,vimage]) -> do + argRow_order <- (unwire vrow_order :: IO (Int)) + argColumn_order <- (unwire vcolumn_order :: IO (Int)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (M.centralMoment argRow_order argColumn_order argImage) (\result -> publish (wire result) out) + (50,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (M.imageCentroid argImage) (\result -> publish (wire result) out) + (51,[vimage]) -> do + argImage <- (unwire vimage :: IO (C.Image)) + checked (M.integralImage argImage) (\result -> publish (wire result) out) + (52,[vorigin,vextent,vimage]) -> do + argOrigin <- (unwire vorigin :: IO ((Int, Int))) + argExtent <- (unwire vextent :: IO ((Int, Int))) + argImage <- (unwire vimage :: IO (C.Image)) + checked (M.rectangleSum argOrigin argExtent argImage) (\result -> publish (wire result) out) + (53,[va,vb]) -> do + argA <- (unwire va :: IO (C.Image)) + argB <- (unwire vb :: IO (C.Image)) + checked (M.meanSquaredError argA argB) (\result -> publish (wire result) out) + (54,[vdata_range,va,vb]) -> do + argData_range <- (unwire vdata_range :: IO (Double)) + argA <- (unwire va :: IO (C.Image)) + argB <- (unwire vb :: IO (C.Image)) + checked (M.peakSignalToNoise argData_range argA argB) (\result -> publish (wire result) out) + (55,[vdata_range,vwindow,va,vb]) -> do + argData_range <- (unwire vdata_range :: IO (Double)) + argWindow <- (unwire vwindow :: IO (Int)) + argA <- (unwire va :: IO (C.Image)) + argB <- (unwire vb :: IO (C.Image)) + checked (M.structuralSimilarity argData_range argWindow argA argB) (\result -> publish (wire result) out) + (56,[]) -> do + checked (Right (M.SquaredDifference)) (\result -> publish (wire result) out) + (57,[]) -> do + checked (Right (M.NormalizedCorrelation)) (\result -> publish (wire result) out) + (58,[vinterpolation,vboundary,vshape,vimage]) -> do + argInterpolation <- (unwire vinterpolation :: IO (S.Interpolation)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ((Int, Int))) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.resize argInterpolation argBoundary argShape argImage) (\result -> publish (wire result) out) + (59,[vinterpolation,vboundary,vshape,vmatrix,vimage]) -> do + argInterpolation <- (unwire vinterpolation :: IO (S.Interpolation)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argShape <- (unwire vshape :: IO ((Int, Int))) + argMatrix <- (unwire vmatrix :: IO ([[Double]])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.warp argInterpolation argBoundary argShape argMatrix argImage) (\result -> publish (wire result) out) + (60,[vinterpolation,vboundary,vrow_shift,vcolumn_shift,vimage]) -> do + argInterpolation <- (unwire vinterpolation :: IO (S.Interpolation)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argRow_shift <- (unwire vrow_shift :: IO (Double)) + argColumn_shift <- (unwire vcolumn_shift :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.translate argInterpolation argBoundary argRow_shift argColumn_shift argImage) (\result -> publish (wire result) out) + (61,[vinterpolation,vboundary,vangle,vimage]) -> do + argInterpolation <- (unwire vinterpolation :: IO (S.Interpolation)) + argBoundary <- (unwire vboundary :: IO (C.Boundary)) + argAngle <- (unwire vangle :: IO (Double)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.rotate argInterpolation argBoundary argAngle argImage) (\result -> publish (wire result) out) + (62,[vconnectivity,vimage]) -> do + argConnectivity <- (unwire vconnectivity :: IO (S.Connectivity)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.connectedComponents argConnectivity argImage) (\result -> publish (wire result) out) + (63,[vspacing,vimage]) -> do + argSpacing <- (unwire vspacing :: IO ([Double])) + argImage <- (unwire vimage :: IO (C.Image)) + checked (S.distanceTransform argSpacing argImage) (\result -> publish (wire result) out) + (64,[]) -> do + checked (Right (S.Nearest)) (\result -> publish (wire result) out) + (65,[]) -> do + checked (Right (S.Bilinear)) (\result -> publish (wire result) out) + (66,[]) -> do + checked (Right (S.Bicubic)) (\result -> publish (wire result) out) + (67,[]) -> do + checked (Right (S.Lanczos)) (\result -> publish (wire result) out) + (68,[]) -> do + checked (Right (S.AxisConnected)) (\result -> publish (wire result) out) + (69,[]) -> do + checked (Right (S.FullyConnected)) (\result -> publish (wire result) out) + (70,[vsource,vdestination,vimage]) -> do + argSource <- (unwire vsource :: IO (K.ColorSpace)) + argDestination <- (unwire vdestination :: IO (K.ColorSpace)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (K.convertColor argSource argDestination argImage) (\result -> publish (wire result) out) + (71,[vsource,vimage]) -> do + argSource <- (unwire vsource :: IO (K.ColorSpace)) + argImage <- (unwire vimage :: IO (C.Image)) + checked (K.grayscale argSource argImage) (\result -> publish (wire result) out) + (72,[]) -> do + checked (Right (K.SRGB)) (\result -> publish (wire result) out) + (73,[]) -> do + checked (Right (K.LinearRGB)) (\result -> publish (wire result) out) + (74,[]) -> do + checked (Right (K.HSV)) (\result -> publish (wire result) out) + (75,[]) -> do + checked (Right (K.HSL)) (\result -> publish (wire result) out) + (76,[]) -> do + checked (Right (K.XYZ)) (\result -> publish (wire result) out) + (77,[]) -> do + checked (Right (K.Lab)) (\result -> publish (wire result) out) + (78,[]) -> do + checked (Right (K.YCbCr)) (\result -> publish (wire result) out) + (79,[vshape,vvalues]) -> do + argShape <- (unwire vshape :: IO ([Int])) + argValues <- (unwire vvalues :: IO ([Double])) + checked (T.tensor argShape argValues) (\result -> publish (wire result) out) + (80,[vtensor]) -> do + argTensor <- (unwire vtensor :: IO (T.Tensor Double)) + checked (Right (T.tensorShape argTensor)) (\result -> publish (wire result) out) + (81,[vtensor]) -> do + argTensor <- (unwire vtensor :: IO (T.Tensor Double)) + checked (Right (T.tensorValues argTensor)) (\result -> publish (wire result) out) + _ -> invalid "Image operation identifier or arity differs" diff --git a/src/HMath/FFI/InterchangeAll.hs b/src/HMath/FFI/InterchangeAll.hs new file mode 100644 index 0000000..cf4a02e --- /dev/null +++ b/src/HMath/FFI/InterchangeAll.hs @@ -0,0 +1,229 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Direct original serialization, typed elements, streaming and mapped scopes. +module HMath.FFI.InterchangeAll where + +import Control.Exception (IOException,catch,throwIO) +import Data.Binary.Get (Get) +import Data.Binary.Put (runPut) +import qualified Data.ByteString as BS +import qualified Data.ByteString.Lazy as Lazy +import Foreign +import Foreign.C +import qualified System.IO as File +import HMath.FFI.InterchangeCodec +import qualified HMath.FFI.InterchangeElement as E +import qualified HMath.FFI.InterchangeError as Error +import qualified HMath.FFI.Boundary as Boundary +import qualified HMath.FFI.Value as V +import qualified HMath.Interchange.Array as A +import qualified HMath.Interchange.Binary as B +import qualified HMath.Interchange.Compression as C +import qualified HMath.Interchange.IO as I +import qualified HMath.Interchange.Numpy as N +import qualified HMath.Interchange.Text as T + +instance From A.Array where from=unbox 451 +instance To A.Array where to value=pure(box 451 value [to(A.arrayShape value),to(A.arrayBytes value)]) +instance From A.InterchangeError where from=unbox 453 +instance To A.InterchangeError where + to value=pure(box 453 value [to(snd(Error.fields value))]) +instance From A.Limits where from=unbox 457 +instance To A.Limits where + to value=pure(box 457 value [to(A.maxBytes value),to(A.maxElements value),to(A.maxRank value),to(A.maxMetadata value),to(A.maxArchiveEntries value)]) +instance From A.DType where from=unbox 458 +instance To A.DType where to value=pure(box 458 value []) +instance From A.Endian where from=unbox 459 +instance To A.Endian where to value=pure(box 459 value []) +instance From A.Order where from=unbox 460 +instance To A.Order where to value=pure(box 460 value []) +instance From C.Compression where from=unbox 461 +instance To C.Compression where to value=pure(box 461 value []) +instance From I.RawSpec where from=unbox 462 +instance To I.RawSpec where to value=pure(box 462 value []) + +toValues :: forall a. A.Element a=>E.Element a->A.Array->IO V.Value +toValues witness array=do + values<-Error.source(A.toValues array :: Either A.InterchangeError[a]) + pure(V.List(map(E.scalar witness) values)) +toMatrix :: forall a. A.Element a=>E.Element a->A.Array->IO V.Value +toMatrix witness array=E.matrix witness <$>Error.source(A.toMatrix array) +toTensor :: forall a. A.Element a=>E.Element a->A.Array->IO V.Value +toTensor witness array=E.tensor witness <$>Error.source(A.toTensor array) +mappedValue :: forall a. A.Element a=>E.Element a->Mapping->[Int]->IO V.Value +mappedValue witness(Mapping mapped) index=I.mappedValue mapped index >>=Error.source >>=pure . E.scalar witness + +ioErrors :: IO a->IO a +ioErrors action=action `catch` (\(errorValue::IOException)->throwIO(Error.Failure(A.InterchangeIOError(show errorValue)))) +openHandle :: String->String->IO File.Handle +openHandle path mode=case mode of + "rb"->ioErrors(File.openBinaryFile path File.ReadMode) + "wb"->ioErrors(File.openBinaryFile path File.WriteMode) + "ab"->ioErrors(File.openBinaryFile path File.AppendMode) + "r+b"->ioErrors(File.openBinaryFile path File.ReadWriteMode) + _->V.invalid "binary handle mode must be rb,wb,ab or r+b" +seekHandle :: File.Handle->Int->Integer->IO () +seekHandle handle whence offset=case whence of + 0->ioErrors(File.hSeek handle File.AbsoluteSeek offset) + 1->ioErrors(File.hSeek handle File.RelativeSeek offset) + 2->ioErrors(File.hSeek handle File.SeekFromEnd offset) + _->V.invalid "seek origin must be0,1 or2" + +foreign export ccall "hm_interchange_apply" dispatch :: CString->Ptr(StablePtr V.Value)->CSize->Ptr(StablePtr V.Value)->IO CInt +dispatch :: CString->Ptr(StablePtr V.Value)->CSize->Ptr(StablePtr V.Value)->IO CInt +dispatch name input count out=Error.boundary $ do + operation<-peekCString name + arguments<-peekArray(fromIntegral count) input >>=mapM deRefStablePtr + result<-case operation of + "HMath.Interchange.Array.elementType"->do + [prototype]<-pure arguments + E.SomeElement witness<-E.element prototype + to(E.code witness) + "HMath.Interchange.Array.getElement"->do + [prototype,endian]<-pure arguments + E.SomeElement witness<-E.element prototype + order<-from endian + to(E.get witness order) + "HMath.Interchange.Array.putElement"->do + [prototype,endian,value]<-pure arguments + E.SomeElement witness<-E.element prototype + order<-from endian + E.put witness order value >>=to + "HMath.Interchange.Array.fromValues"->do + [prototype,limits,endian,shape,items]<-pure arguments + E.SomeElement witness<-E.element prototype + policy<-from limits;order<-from endian;dims<-from shape + values<-E.values witness items + to(A.fromValues policy order dims values) + "HMath.Interchange.Array.toValues"->do + [prototype,value]<-pure arguments + E.SomeElement witness<-E.element prototype + from value >>=toValues witness + "HMath.Interchange.Array.fromMatrix"->do + [limits,endian,value]<-pure arguments + policy<-from limits;order<-from endian + E.fromMatrix policy order value >>=to + "HMath.Interchange.Array.fromTensor"->do + [limits,endian,value]<-pure arguments + policy<-from limits;order<-from endian + E.fromTensor policy order value >>=to + "HMath.Interchange.Array.toMatrix"->do + [prototype,value]<-pure arguments + E.SomeElement witness<-E.element prototype + from value >>=toMatrix witness + "HMath.Interchange.Array.toTensor"->do + [prototype,value]<-pure arguments + E.SomeElement witness<-E.element prototype + from value >>=toTensor witness + "HMath.Interchange.Binary.runDecoder"->apply(B.runDecoder :: Get V.Value->BS.ByteString->Either A.InterchangeError V.Value) arguments + "HMath.Interchange.IO.mappedValue"->do + [prototype,value,index]<-pure arguments + E.SomeElement witness<-E.element prototype + mapping<-from value;coordinates<-from index + mappedValue witness mapping coordinates + "HMath.Interchange.IO.mappedShape"->do + [value]<-pure arguments + Mapping mapped<-from value + to(I.mappedShape mapped) + "HMath.Interchange.IO.mappedReadBytes"->do + [value,offset,size]<-pure arguments + Mapping mapped<-from value + start<-from offset;lengthValue<-from size + to(I.mappedReadBytes mapped start lengthValue) + "HMath.Interchange.IO.withMappedArray"->do + [limits,specification,path,callback]<-pure arguments + policy<-from limits;layout<-from specification;filename<-from path + action<-from callback :: IO(Mapping->IO V.Value) + I.withMappedArray policy layout filename (action . Mapping) >>=to +-- BEGIN GENERATED + "HMath.Interchange.Array.BigEndian"->apply A.BigEndian arguments + "HMath.Interchange.Array.Bool8"->apply A.Bool8 arguments + "HMath.Interchange.Array.C128"->apply A.C128 arguments + "HMath.Interchange.Array.C64"->apply A.C64 arguments + "HMath.Interchange.Array.COrder"->apply A.COrder arguments + "HMath.Interchange.Array.F32"->apply A.F32 arguments + "HMath.Interchange.Array.F64"->apply A.F64 arguments + "HMath.Interchange.Array.FOrder"->apply A.FOrder arguments + "HMath.Interchange.Array.I16"->apply A.I16 arguments + "HMath.Interchange.Array.I32"->apply A.I32 arguments + "HMath.Interchange.Array.I64"->apply A.I64 arguments + "HMath.Interchange.Array.I8"->apply A.I8 arguments + "HMath.Interchange.Array.InterchangeIOError"->apply A.InterchangeIOError arguments + "HMath.Interchange.Array.InvalidData"->apply A.InvalidData arguments + "HMath.Interchange.Array.LimitExceeded"->apply A.LimitExceeded arguments + "HMath.Interchange.Array.Limits"->apply A.Limits arguments + "HMath.Interchange.Array.LittleEndian"->apply A.LittleEndian arguments + "HMath.Interchange.Array.U16"->apply A.U16 arguments + "HMath.Interchange.Array.U32"->apply A.U32 arguments + "HMath.Interchange.Array.U64"->apply A.U64 arguments + "HMath.Interchange.Array.U8"->apply A.U8 arguments + "HMath.Interchange.Array.Unsupported"->apply A.Unsupported arguments + "HMath.Interchange.Array.array"->apply A.array arguments + "HMath.Interchange.Array.arrayBytes"->apply A.arrayBytes arguments + "HMath.Interchange.Array.arrayDType"->apply A.arrayDType arguments + "HMath.Interchange.Array.arrayEndian"->apply A.arrayEndian arguments + "HMath.Interchange.Array.arrayMetadata"->apply A.arrayMetadata arguments + "HMath.Interchange.Array.arrayOffset"->apply A.arrayOffset arguments + "HMath.Interchange.Array.arrayShape"->apply A.arrayShape arguments + "HMath.Interchange.Array.arrayStrides"->apply A.arrayStrides arguments + "HMath.Interchange.Array.contiguousArray"->apply A.contiguousArray arguments + "HMath.Interchange.Array.defaultLimits"->apply A.defaultLimits arguments + "HMath.Interchange.Array.denseStrides"->apply A.denseStrides arguments + "HMath.Interchange.Array.elementBytes"->apply A.elementBytes arguments + "HMath.Interchange.Array.elementCount"->apply A.elementCount arguments + "HMath.Interchange.Array.maxArchiveEntries"->apply A.maxArchiveEntries arguments + "HMath.Interchange.Array.maxBytes"->apply A.maxBytes arguments + "HMath.Interchange.Array.maxElements"->apply A.maxElements arguments + "HMath.Interchange.Array.maxMetadata"->apply A.maxMetadata arguments + "HMath.Interchange.Array.maxRank"->apply A.maxRank arguments + "HMath.Interchange.Array.rawDecode"->apply A.rawDecode arguments + "HMath.Interchange.Array.rawEncode"->apply A.rawEncode arguments + "HMath.Interchange.Array.repack"->apply A.repack arguments + "HMath.Interchange.Array.validateShape"->apply A.validateShape arguments + "HMath.Interchange.Array.withMetadata"->apply A.withMetadata arguments + "HMath.Interchange.Binary.crc32"->apply B.crc32 arguments + "HMath.Interchange.Binary.decodeBinary"->apply B.decodeBinary arguments + "HMath.Interchange.Binary.encodeBinary"->apply B.encodeBinary arguments + "HMath.Interchange.Compression.Gzip"->apply C.Gzip arguments + "HMath.Interchange.Compression.RawDeflate"->apply C.RawDeflate arguments + "HMath.Interchange.Compression.Zlib"->apply C.Zlib arguments + "HMath.Interchange.Compression.compress"->apply C.compress arguments + "HMath.Interchange.Compression.compressionAvailable"->apply C.compressionAvailable arguments + "HMath.Interchange.Compression.decompress"->apply C.decompress arguments + "HMath.Interchange.IO.RawSpec"->apply I.RawSpec arguments + "HMath.Interchange.IO.readArrayFile"->apply I.readArrayFile arguments + "HMath.Interchange.IO.readRawChunks"->apply I.readRawChunks arguments + "HMath.Interchange.IO.writeArrayFile"->apply I.writeArrayFile arguments + "HMath.Interchange.IO.writeRawChunks"->apply I.writeRawChunks arguments + "HMath.Interchange.Numpy.decodeNpy"->apply N.decodeNpy arguments + "HMath.Interchange.Numpy.decodeNpz"->apply N.decodeNpz arguments + "HMath.Interchange.Numpy.encodeNpy"->apply N.encodeNpy arguments + "HMath.Interchange.Numpy.encodeNpz"->apply N.encodeNpz arguments + "HMath.Interchange.Text.decodeDelimited"->apply T.decodeDelimited arguments + "HMath.Interchange.Text.decodeMatrixMarket"->apply T.decodeMatrixMarket arguments + "HMath.Interchange.Text.decodeText"->apply T.decodeText arguments + "HMath.Interchange.Text.encodeDelimited"->apply T.encodeDelimited arguments + "HMath.Interchange.Text.encodeMatrixMarket"->apply T.encodeMatrixMarket arguments + "HMath.Interchange.Text.encodeText"->apply T.encodeText arguments + "HMath.Interchange.Array.boundedInt"->apply A.boundedInt arguments + "HMath.Interchange.Array.byteOffsets"->apply A.byteOffsets arguments + "HMath.Interchange.Array.checkLimits"->apply A.checkLimits arguments + "HMath.Interchange.Array.guardI"->apply A.guardI arguments +-- END GENERATED + "__dtype_code"->apply(fromEnum :: A.DType->Int) arguments + "__error_fields"->apply(\value->let(kind,message)=Error.fields value in(fromIntegral kind::Int,message)) arguments + "__put_bytes"->apply(Lazy.toStrict . runPut) arguments + "__open_handle"->apply openHandle arguments + "__close_handle"->apply(\handle->ioErrors(File.hClose handle)) arguments + "__seek_handle"->apply seekHandle arguments + "__tell_handle"->apply(\handle->ioErrors(File.hTell handle)) arguments + "__flush_handle"->apply(\handle->ioErrors(File.hFlush handle)) arguments + "__equal_array"->apply((==)::A.Array->A.Array->Bool) arguments + _->V.invalid "unknown interchange operation" + V.forceValue result + Boundary.checked(Right())(const(V.publish result out)) diff --git a/src/HMath/FFI/InterchangeCodec.hs b/src/HMath/FFI/InterchangeCodec.hs new file mode 100644 index 0000000..3775b8a --- /dev/null +++ b/src/HMath/FFI/InterchangeCodec.hs @@ -0,0 +1,125 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE UndecidableInstances #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Typed transport for the original interchange APIs and scoped IO callbacks. +module HMath.FFI.InterchangeCodec where + +import Control.Exception (bracket,catch,evaluate,throwIO) +import Data.Binary.Get (Get) +import Data.Binary.Put (Put) +import qualified Data.ByteString as BS +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import System.IO (Handle) +import System.IO.Unsafe (unsafePerformIO) +import HMath.FFI.Coefficient (ScalarType(SWord32)) +import HMath.FFI.MathError (withMathErrorWire,readCallbackFailure) +import qualified HMath.FFI.Bytes as Bytes +import qualified HMath.FFI.InterchangeError as Error +import qualified HMath.FFI.LinearCodec as L +import qualified HMath.FFI.NumericalCodec as N +import qualified HMath.FFI.Value as V +import qualified HMath.Interchange.Array as A +import qualified HMath.Interchange.IO as I + +class From a where from :: V.Value -> IO a +class To a where to :: a -> IO V.Value +instance {-# OVERLAPPABLE #-} N.From a => From a where from=N.from +instance {-# OVERLAPPABLE #-} N.To a => To a where to=N.to +instance {-# OVERLAPPING #-} From String where from=V.asText +instance {-# OVERLAPPING #-} To String where to=pure . V.Text +instance {-# OVERLAPPING #-} From Char where + from value=do + text<-V.asText value + case text of + [character]->pure character + _->V.invalid "delimiter must be exactly one Haskell Char" +instance {-# OVERLAPPING #-} To Char where to=pure . V.Text . (:[]) +instance {-# OVERLAPPING #-} From Word32 where from=V.asScalar +instance {-# OVERLAPPING #-} To Word32 where to=pure . V.Scalar SWord32 +instance {-# OVERLAPPING #-} From BS.ByteString where from=Bytes.asBytes +instance {-# OVERLAPPING #-} To BS.ByteString where to=pure . Bytes.bytes +instance {-# OVERLAPPING #-} From a=>From [a] where from value=V.asList value >>=mapM from +instance {-# OVERLAPPING #-} To a=>To [a] where to values=V.List <$>mapM to values +instance {-# OVERLAPPING #-} From a=>From(Maybe a) where + from V.None=pure Nothing + from value=Just <$>from value +instance {-# OVERLAPPING #-} To a=>To(Maybe a) where to=maybe(pure V.None) to +instance {-# OVERLAPPING #-} (From a,From b)=>From(a,b) where + from value=do + fields<-V.asTuple 2 value + case fields of + [a,b]->(,) <$>from a <*>from b + _->V.invalid "interchange pair arity differs" +instance {-# OVERLAPPING #-} (To a,To b)=>To(a,b) where to(a,b)=V.Tuple <$>sequence[to a,to b] +instance {-# OVERLAPPING #-} To a=>To(Either A.InterchangeError a) where to result=Error.source result >>=to +instance {-# OVERLAPPING #-} To a=>To(IO a) where to action=action >>=to +instance {-# OVERLAPPING #-} From (Get V.Value) where from=unbox 463 +instance {-# OVERLAPPING #-} To (Get V.Value) where to value=pure(box 463 value []) +instance {-# OVERLAPPING #-} From Put where from=unbox 464 +instance {-# OVERLAPPING #-} To Put where to value=pure(box 464 value []) +instance {-# OVERLAPPING #-} From Handle where from=unbox 452 +instance {-# OVERLAPPING #-} To Handle where to value=pure(box 452 value []) + +data Mapping where Mapping :: I.MappedArray s -> Mapping +instance {-# OVERLAPPING #-} From Mapping where from=unbox 465 +instance {-# OVERLAPPING #-} To Mapping where + to value@(Mapping mapped)=pure(box 465 value [to(I.mappedShape mapped)]) + +box :: Typeable a=>Int->a->[IO V.Value]->V.Value +box kind value fields=V.Opaque kind (-1) 0 (evaluate value >>sequence fields >>=mapM_ V.forceValue) value +unbox :: Typeable a=>Int->V.Value->IO a +unbox kind(V.Opaque actual _ _ _ value) + |kind==actual=maybe(V.invalid "interchange payload type differs") pure(cast value) +unbox _ _=V.invalid "interchange object kind differs" + +class Apply a where apply :: a->[V.Value]->IO V.Value +instance {-# OVERLAPPABLE #-} To a=>Apply a where + apply value []=to value + apply _ _=V.invalid "too many interchange arguments" +instance {-# OVERLAPPING #-} (From a,Apply b)=>Apply(a->b) where + apply operation(value:rest)=from value >>= \argument->apply(operation argument) rest + apply _ []=V.invalid "missing interchange argument" + +foreign import ccall safe "hm_linear_invoke_callback" + invokeCallback :: FunPtr ()->Ptr ()->StablePtr V.Value->Ptr(StablePtr V.Value)->Ptr ()->IO CInt +callbackResult :: V.Value->[IO V.Value]->IO V.Value +callbackResult (V.Opaque 101 _ _ _ payload) arguments=case cast payload of + Just(L.Callback pointer userdata)->do + encoded<-V.Tuple <$>sequence arguments + V.forceValue encoded + bracket(newStablePtr encoded) freeStablePtr $ \input-> + alloca $ \out->withMathErrorWire $ \errorWire->do + status<-invokeCallback pointer userdata input out errorWire + if status==13 then Error.readCallbackError errorWire >>=throwIO . Error.Failure + else if status/=0 then readCallbackFailure status errorWire >>=throwIO + else do + result<-peek out + bracket(pure result) freeStablePtr deRefStablePtr + Nothing->V.invalid "interchange callback payload differs" +callbackResult _ _=V.invalid "expected a callback Value" + +class Function a where function :: V.Value->[IO V.Value]->a +instance {-# OVERLAPPABLE #-} From a=>Function a where function=pureResult +instance {-# OVERLAPPING #-} (To a,Function b)=>Function(a->b) where + function callback arguments argument=function callback(arguments++[to argument]) +instance {-# OVERLAPPING #-} From a=>Function(IO a) where + function callback arguments=callbackResult callback arguments >>=from +instance {-# OVERLAPPING #-} From a=>Function(Either A.InterchangeError a) where + function callback arguments=unsafePerformIO(checkedResult callback arguments) +instance {-# OVERLAPPING #-} From a=>Function(IO(Either A.InterchangeError a)) where + function=checkedResult +instance {-# OVERLAPPING #-} (To a,Function b)=>From(a->b) where from callback=pure(function callback []) + +{-# NOINLINE pureResult #-} +pureResult :: From a=>V.Value->[IO V.Value]->a +pureResult callback arguments=unsafePerformIO(callbackResult callback arguments >>=from) +checkedResult :: From a=>V.Value->[IO V.Value]->IO(Either A.InterchangeError a) +checkedResult callback arguments=(Right <$> (callbackResult callback arguments >>=from)) `catch` recover + where recover(Error.Failure errorValue)=pure(Left errorValue) diff --git a/src/HMath/FFI/InterchangeElement.hs b/src/HMath/FFI/InterchangeElement.hs new file mode 100644 index 0000000..517679a --- /dev/null +++ b/src/HMath/FFI/InterchangeElement.hs @@ -0,0 +1,92 @@ +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Exactly the fixed-width Element instances defined by Interchange.Array. +module HMath.FFI.InterchangeElement where + +import Control.Exception (evaluate) +import Data.Binary.Get (Get) +import Data.Binary.Put (Put) +import Data.Proxy (Proxy(..)) +import Data.Typeable (Typeable) +import qualified HMath.Interchange.Array as A +import HMath.FFI.Coefficient +import qualified HMath.FFI.TensorCodec as T +import qualified HMath.FFI.Value as V +import qualified HMath.Matrix as M +import qualified HMath.Tensor as Tensor + +data Element a where + Numeric :: (Coefficient a,A.Element a) => ScalarType a -> Element a + Logical :: Element Bool +data SomeElement where + SomeElement :: (A.Element a,Typeable a) => Element a -> SomeElement + +dictionary :: Coefficient a => ScalarType a -> Maybe (Dict (A.Element a)) +dictionary witness = case witness of + SDouble -> Just Dict + SFloat -> Just Dict + SComplexDouble -> Just Dict + SComplexFloat -> Just Dict + SInt8 -> Just Dict + SInt16 -> Just Dict + SInt32 -> Just Dict + SInt64 -> Just Dict + SWord8 -> Just Dict + SWord16 -> Just Dict + SWord32 -> Just Dict + SWord64 -> Just Dict + _ -> Nothing +element :: V.Value -> IO SomeElement +element (V.Boolean _) = pure (SomeElement Logical) +element (V.Scalar witness _) = case dictionary witness of + Just Dict -> pure (SomeElement (Numeric witness)) + Nothing -> V.unsupported "source Element instance does not exist for this coefficient" +element _ = V.invalid "expected a fixed-width Element prototype" + +scalar :: Element a -> a -> V.Value +scalar (Numeric witness) = V.Scalar witness +scalar Logical = V.Boolean +readScalar :: Element a -> V.Value -> IO a +readScalar (Numeric _) = V.asScalar +readScalar Logical = V.asBoolean +values :: Element a -> V.Value -> IO [a] +values witness value = V.asList value >>= mapM (readScalar witness) +matrix :: Element a -> M.Matrix a -> V.Value +matrix (Numeric witness) = V.Dense . V.SomeMatrix witness +matrix Logical = V.booleanMatrix +tensor :: Element a -> Tensor.Tensor a -> V.Value +tensor (Numeric witness) = T.fromTensor (T.Numeric witness) +tensor Logical = T.fromTensor T.Logical +code :: forall a. A.Element a => Element a -> A.DType +code _ = A.elementType (Proxy :: Proxy a) + +get :: forall a. A.Element a => Element a -> A.Endian -> Get V.Value +get witness endian = scalar witness <$> (A.getElement endian :: Get a) +put :: A.Element a => Element a -> A.Endian -> V.Value -> IO Put +put witness endian value = A.putElement endian <$> readScalar witness value + +fromMatrix :: A.Limits -> A.Endian -> V.Value -> IO (Either A.InterchangeError A.Array) +fromMatrix limits endian value = case value of + V.Dense (V.SomeMatrix witness original) -> case dictionary witness of + Just Dict -> pure (A.fromMatrix limits endian original) + Nothing -> V.unsupported "Matrix element has no source Element instance" + V.Dense (V.StructuralMatrix 16 _ _ _ _) -> do + original <- V.asMatrix value :: IO (M.Matrix Bool) + pure (A.fromMatrix limits endian original) + _ -> V.unsupported "Matrix element has no source Element instance" +fromTensor :: A.Limits -> A.Endian -> V.Value -> IO (Either A.InterchangeError A.Array) +fromTensor limits endian value = do + T.SomeTensor witness original <- T.asTensor value + case witness of + T.Numeric numeric -> case dictionary numeric of + Just Dict -> pure (A.fromTensor limits endian original) + Nothing -> V.unsupported "Tensor element has no source Element instance" + T.Logical -> pure (A.fromTensor limits endian original) + T.Characters -> V.unsupported "String has no source Element instance" + T.Structural _ -> V.unsupported "structural Tensor element has no source fixed-width Element instance" + +forceProgram :: Put -> IO () +forceProgram program = evaluate program >> pure () diff --git a/src/HMath/FFI/InterchangeError.hs b/src/HMath/FFI/InterchangeError.hs new file mode 100644 index 0000000..352e40e --- /dev/null +++ b/src/HMath/FFI/InterchangeError.hs @@ -0,0 +1,48 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Lossless original InterchangeError transport, distinct from MathError. +module HMath.FFI.InterchangeError where + +import Control.Exception (Exception, catch, throwIO) +import Foreign +import Foreign.C +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError (withEncodedMessage, readWireMessage) +import qualified HMath.Interchange.Array as A + +newtype Failure = Failure A.InterchangeError deriving (Show) +instance Exception Failure +foreign import ccall unsafe "hm_error" report :: CInt -> CString -> IO CInt +foreign import ccall unsafe "hm_record_interchange_error" + record :: CInt -> CString -> CSize -> IO CInt +foreign import ccall unsafe "hm_math_error_kind" callbackKind :: Ptr () -> IO CInt + +fields :: A.InterchangeError -> (CInt, String) +fields value = case value of + A.InvalidData message -> (0,message) + A.Unsupported message -> (1,message) + A.LimitExceeded message -> (2,message) + A.InterchangeIOError message -> (3,message) +fromFields :: CInt -> String -> IO A.InterchangeError +fromFields kind message = case kind of + 0 -> pure (A.InvalidData message) + 1 -> pure (A.Unsupported message) + 2 -> pure (A.LimitExceeded message) + 3 -> pure (A.InterchangeIOError message) + _ -> ioError (userError "unknown InterchangeError constructor") +source :: Either A.InterchangeError a -> IO a +source = either (throwIO . Failure) pure +boundary :: IO CInt -> IO CInt +boundary action = B.boundary (action `catch` failure) + where + failure (Failure value) = do + _ <- withCString (show value) (report 13) + let (kind,message)=fields value + status <- withEncodedMessage message (record kind) + if status == 0 then pure 13 + else withCString "unable to record InterchangeError" (report status) +readCallbackError :: Ptr () -> IO A.InterchangeError +readCallbackError pointer = do + kind <- callbackKind pointer + message <- readWireMessage pointer + fromFields kind message diff --git a/src/HMath/FFI/LinearAll.hs b/src/HMath/FFI/LinearAll.hs new file mode 100644 index 0000000..eafdb08 --- /dev/null +++ b/src/HMath/FFI/LinearAll.hs @@ -0,0 +1,1126 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; every operation calls the original Haskell public function. +module HMath.FFI.LinearAll where +import Foreign +import Foreign.C +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as LU +import qualified HMath.Matrix.QR as QR +import Data.Complex (Complex) +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import HMath.FFI.Coefficient +import HMath.FFI.LinearCodec +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import qualified HMath.Vector as V +import qualified HMath.Matrix.Advanced as A +import qualified HMath.Matrix.Decomposition as D +import qualified HMath.Matrix.Iterative as I +import qualified HMath.Matrix.LAPACK as L +import qualified HMath.Sparse as S +import qualified HMath.Sparse.Spectral as P +import qualified HMath.Backend as B + +generic :: forall a. Coefficient a => ScalarType a -> Int -> [X.Value] -> IO X.Value +generic w operation args=case(operation,args) of + (0,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item209 -> X.asScalar item209) :: IO [(a)]) + encodeVector w ((V.vector a0Value) :: (V.Vector (a))) + (1,[a0]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + X.List <$> mapM (\item210 -> pure (X.Scalar w item210)) ((V.vectorValues a0Value) :: [(a)]) + (2,[a0]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + pure (X.Index ((V.vectorDimension a0Value) :: (Int))) + (5,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item211 -> (X.asTuple 2 item211 >>= \items212 -> case items212 of { [part213,part214] -> (,) <$> (X.asIndex part213) <*> (X.asScalar part214); _ -> X.invalid "tuple arity differs" })) :: IO [((Int),(a))]) + source ((V.sparseVector a0Value a1Value) :: (Either (E.MathError) (V.SparseVector (a)))) >>= \_result215 -> encodeSparseVector w _result215 + (6,[a0]) -> do + a0Value <- (unbox "HMath.Vector.SparseVector" a0 :: IO (V.SparseVector (a))) + X.List <$> mapM (\item216 -> pure (X.Scalar w item216)) ((V.sparseVectorValues a0Value) :: [(a)]) + (7,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.Vector.Vector" a2 :: IO (V.Vector (a))) + source ((V.vectorSlice a0Value a1Value a2Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result217 -> encodeVector w _result217 + (8,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item218 -> unbox "HMath.Vector.Vector" item218) :: IO [(V.Vector (a))]) + source ((V.vectorConcat a0Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result219 -> encodeVector w _result219 + (9,[a0,a1]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.vectorAdd a0Value a1Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result220 -> encodeVector w _result220 + (10,[a0,a1]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.vectorSubtract a0Value a1Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result221 -> encodeVector w _result221 + (11,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + encodeVector w ((V.vectorScale a0Value a1Value) :: (V.Vector (a))) + (12,[a0,a1]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.vectorDot a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result222 -> pure (X.Scalar w _result222) + (13,[a0,a1]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.cross a0Value a1Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result223 -> encodeVector w _result223 + (14,[a0,a1]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.outer a0Value a1Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result224 -> pure (X.Dense (X.SomeMatrix w _result224)) + (15,[a0,a1,a2]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + a2Value <- (unbox "HMath.Vector.Vector" a2 :: IO (V.Vector (a))) + source ((V.triple a0Value a1Value a2Value) :: (Either (E.MathError) (a))) >>= \_result225 -> pure (X.Scalar w _result225) + (16,[a0]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + pure (X.Index ((V.norm0 a0Value) :: (Int))) + (17,[a0]) -> do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + pure (X.Scalar w ((V.norm1 a0Value) :: (a))) + (18,[a0]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + pure (X.Scalar w ((V.norm2 a0Value) :: (a))) + (19,[a0]) -> ordered w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + pure (X.Scalar w ((V.normInfinity a0Value) :: (a))) + (20,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.normP a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result226 -> pure (X.Scalar w _result226) + (21,[a0]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + source ((V.normalizeVector a0Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result227 -> encodeVector w _result227 + (22,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.project a0Value a1Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result228 -> encodeVector w _result228 + (23,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.reflect a0Value a1Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result229 -> encodeVector w _result229 + (24,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + a2Value <- (unbox "HMath.Vector.Vector" a2 :: IO (V.Vector (a))) + source ((V.refract a0Value a1Value a2Value) :: (Either (E.MathError) (V.Vector (a)))) >>= \_result230 -> encodeVector w _result230 + (25,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.distance a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result231 -> pure (X.Scalar w _result231) + (26,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.cosineSimilarity a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result232 -> pure (X.Scalar w _result232) + (27,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Vector.Vector" a0 :: IO (V.Vector (a))) + a1Value <- (unbox "HMath.Vector.Vector" a1 :: IO (V.Vector (a))) + source ((V.angle a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result233 -> pure (X.Scalar w _result233) + (28,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asList a1 >>= mapM (\item234 -> unbox "HMath.Vector.Vector" item234) :: IO [(V.Vector (a))]) + source ((V.gramSchmidt a0Value a1Value) :: (Either (E.MathError) [(V.Vector (a))])) >>= \_result235 -> X.List <$> mapM (\item236 -> encodeVector w item236) _result235 + (30,[a0,a1]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((A.triangularMatrix a0Value a1Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result237 -> pure (X.Dense (X.SomeMatrix w _result237)) + (31,[a0]) -> fractional w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((A.symmetricMatrix a0Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result238 -> pure (X.Dense (X.SomeMatrix w _result238)) + (32,[a0]) -> realFloat w $ withComplex w $ \cw -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Complex (a)))) + source ((A.hermitianMatrix a0Value) :: (Either (E.MathError) (M.Matrix (Complex (a))))) >>= \_result239 -> pure (X.Dense (X.SomeMatrix cw _result239)) + (33,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item240 -> X.asIndex item240) :: IO [(Int)]) + source ((A.permutationMatrix a0Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result241 -> pure (X.Dense (X.SomeMatrix w _result241)) + (34,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item242 -> X.asList item242 >>= mapM (\item243 -> asMatrix item243)) :: IO [[(M.Matrix (a))]]) + source ((A.blockMatrix a0Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result244 -> pure (X.Dense (X.SomeMatrix w _result244)) + (35,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item245 -> (X.asTuple 2 item245 >>= \items246 -> case items246 of { [part247,part248] -> (,) <$> (X.asIndex part247) <*> (X.asList part248 >>= mapM (\item249 -> X.asScalar item249)); _ -> X.invalid "tuple arity differs" })) :: IO [((Int),[(a)])]) + source ((A.bandedMatrix a0Value a1Value a2Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result250 -> pure (X.Dense (X.SomeMatrix w _result250)) + (36,[a0]) -> realFloat w $ withComplex w $ \cw -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Complex (a)))) + pure (X.Dense (X.SomeMatrix cw ((A.conjugateTranspose a0Value) :: (M.Matrix (Complex (a)))))) + (38,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item251 -> asMatrix item251) :: IO [(M.Matrix (a))]) + a1Value <- (X.asList a1 >>= mapM (\item252 -> asMatrix item252) :: IO [(M.Matrix (a))]) + source ((A.batchedMultiply a0Value a1Value) :: (Either (E.MathError) [(M.Matrix (a))])) >>= \_result253 -> X.List <$> mapM (\item254 -> pure (X.Dense (X.SomeMatrix w item254))) _result253 + (39,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((A.kronecker a0Value a1Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result255 -> pure (X.Dense (X.SomeMatrix w _result255)) + (40,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((A.khatriRao a0Value a1Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result256 -> pure (X.Dense (X.SomeMatrix w _result256)) + (41,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((A.matrixPower a0Value a1Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result257 -> pure (X.Dense (X.SomeMatrix w _result257)) + (42,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((A.trace a0Value) :: (Either (E.MathError) (a))) >>= \_result258 -> pure (X.Scalar w _result258) + (43,[a0]) -> ordered w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + pure (X.Scalar w ((A.matrixNorm1 a0Value) :: (a))) + (44,[a0]) -> ordered w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + pure (X.Scalar w ((A.matrixNormInfinity a0Value) :: (a))) + (45,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + pure (X.Scalar w ((A.frobeniusNorm a0Value) :: (a))) + (53,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item259 -> X.asScalar item259) :: IO [(a)]) + source ((A.changeCoordinates a0Value a1Value a2Value) :: (Either (E.MathError) [(a)])) >>= \_result260 -> X.List <$> mapM (\item261 -> pure (X.Scalar w item261)) _result260 + (54,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + source ((A.matrixExp a0Value a1Value a2Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result262 -> pure (X.Dense (X.SomeMatrix w _result262)) + (61,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((D.gaussianElimination a0Value a1Value) :: (Either (E.MathError) ((M.Matrix (a)),[(Int)]))) >>= \_result263 -> (\(part264,part265) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part264)),X.List <$> mapM (\item266 -> pure (X.Index item266)) part265]) _result263 + (62,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((D.gaussJordan a0Value a1Value) :: (Either (E.MathError) ((M.Matrix (a)),[(Int)]))) >>= \_result267 -> (\(part268,part269) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part268)),X.List <$> mapM (\item270 -> pure (X.Index item270)) part269]) _result267 + (63,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((D.cholesky a0Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result271 -> pure (X.Dense (X.SomeMatrix w _result271)) + (64,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((D.ldlt a0Value) :: (Either (E.MathError) ((M.Matrix (a)),[(a)]))) >>= \_result272 -> (\(part273,part274) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part273)),X.List <$> mapM (\item275 -> pure (X.Scalar w item275)) part274]) _result272 + (65,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((D.givensQR a0Value) :: (Either (E.MathError) ((M.Matrix (a)),(M.Matrix (a))))) >>= \_result276 -> (\(part277,part278) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part277)),pure (X.Dense (X.SomeMatrix w part278))]) _result276 + (66,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((D.bidiagonalize a0Value) :: (Either (E.MathError) (D.Bidiagonal (a)))) >>= \_result279 -> encodeBidiagonal w _result279 + (68,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item280 -> X.asScalar item280) :: IO [(a)]) + source ((D.powerIteration a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (D.Iteration (a)))) >>= \_result281 -> encodeIteration w _result281 + (69,[a0,a1,a2,a3,a4]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asScalar a2 :: IO (a)) + a3Value <- (asMatrix a3 :: IO (M.Matrix (a))) + a4Value <- (X.asList a4 >>= mapM (\item282 -> X.asScalar item282) :: IO [(a)]) + source ((D.inverseIteration a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (D.Iteration (a)))) >>= \_result283 -> encodeIteration w _result283 + (70,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item284 -> X.asScalar item284) :: IO [(a)]) + source ((D.rayleighIteration a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (D.Iteration (a)))) >>= \_result285 -> encodeIteration w _result285 + (71,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item286 -> X.asScalar item286) :: IO [(a)]) + source ((D.arnoldi a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (D.Arnoldi (a)))) >>= \_result287 -> encodeArnoldi w _result287 + (72,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item288 -> X.asScalar item288) :: IO [(a)]) + source ((D.lanczos a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (D.Arnoldi (a)))) >>= \_result289 -> encodeArnoldi w _result289 + (73,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + source ((D.qrIteration a0Value a1Value a2Value) :: (Either (E.MathError) ((M.Matrix (a)),(M.Matrix (a))))) >>= \_result290 -> (\(part291,part292) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part291)),pure (X.Dense (X.SomeMatrix w part292))]) _result290 + (74,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item293 -> (X.asTuple 2 item293 >>= \items294 -> case items294 of { [part295,part296] -> (,) <$> (X.asScalar part295) <*> (X.asList part296 >>= mapM (\item297 -> X.asList item297 >>= mapM (\item298 -> X.asScalar item298))); _ -> X.invalid "tuple arity differs" })) :: IO [((a),[[(a)]])]) + source ((D.jordanChains a0Value a1Value a2Value) :: (Either (E.MathError) ((M.Matrix (a)),(M.Matrix (a))))) >>= \_result299 -> (\(part300,part301) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix w part300)),pure (X.Dense (X.SomeMatrix w part301))]) _result299 + (76,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Bidiagonal" a0 :: IO (D.Bidiagonal (a))) + pure (X.Dense (X.SomeMatrix w ((D.bidiagonalU a0Value) :: (M.Matrix (a))))) + (77,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Bidiagonal" a0 :: IO (D.Bidiagonal (a))) + pure (X.Dense (X.SomeMatrix w ((D.bidiagonalB a0Value) :: (M.Matrix (a))))) + (78,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Bidiagonal" a0 :: IO (D.Bidiagonal (a))) + pure (X.Dense (X.SomeMatrix w ((D.bidiagonalV a0Value) :: (M.Matrix (a))))) + (79,[a0,a1,a2]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + encodeBidiagonal w ((D.Bidiagonal a0Value a1Value a2Value) :: (D.Bidiagonal (a))) + (80,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Iteration" a0 :: IO (D.Iteration (a))) + pure (X.Scalar w ((D.iterationValue a0Value) :: (a))) + (81,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Iteration" a0 :: IO (D.Iteration (a))) + X.List <$> mapM (\item302 -> pure (X.Scalar w item302)) ((D.iterationVector a0Value) :: [(a)]) + (82,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Iteration" a0 :: IO (D.Iteration (a))) + pure (X.Scalar w ((D.iterationResidual a0Value) :: (a))) + (83,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Iteration" a0 :: IO (D.Iteration (a))) + pure (X.Index ((D.iterationCount a0Value) :: (Int))) + (84,[a0,a1,a2,a3]) -> do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asList a1 >>= mapM (\item303 -> X.asScalar item303) :: IO [(a)]) + a2Value <- (X.asScalar a2 :: IO (a)) + a3Value <- (X.asIndex a3 :: IO (Int)) + encodeIteration w ((D.Iteration a0Value a1Value a2Value a3Value) :: (D.Iteration (a))) + (85,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Arnoldi" a0 :: IO (D.Arnoldi (a))) + pure (X.Dense (X.SomeMatrix w ((D.arnoldiBasis a0Value) :: (M.Matrix (a))))) + (86,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Decomposition.Arnoldi" a0 :: IO (D.Arnoldi (a))) + pure (X.Dense (X.SomeMatrix w ((D.arnoldiHessenberg a0Value) :: (M.Matrix (a))))) + (87,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + encodeArnoldi w ((D.Arnoldi a0Value a1Value) :: (D.Arnoldi (a))) + (88,[]) -> fractional w $ do + encodeIterativeOptions w ((I.defaultIterativeOptions ) :: (I.IterativeOptions (a))) + (89,[a0,a1]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.Preconditioner" a0 :: IO (I.Preconditioner (a))) + a1Value <- (X.asList a1 >>= mapM (\item304 -> X.asScalar item304) :: IO [(a)]) + source ((I.applyPreconditioner a0Value a1Value) :: (Either (E.MathError) [(a)])) >>= \_result305 -> X.List <$> mapM (\item306 -> pure (X.Scalar w item306)) _result305 + (90,[a0]) -> realFloat w $ do + a0Value <- (X.asIndex a0 :: IO (Int)) + source ((I.identityPreconditioner a0Value) :: (Either (E.MathError) (I.Preconditioner (a)))) >>= \_result307 -> encodePreconditioner w _result307 + (91,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((I.jacobiPreconditioner a0Value) :: (Either (E.MathError) (I.Preconditioner (a)))) >>= \_result308 -> encodePreconditioner w _result308 + (92,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asList a0 >>= mapM (\item309 -> X.asIndex item309) :: IO [(Int)]) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + source ((I.blockJacobiPreconditioner a0Value a1Value) :: (Either (E.MathError) (I.Preconditioner (a)))) >>= \_result310 -> encodePreconditioner w _result310 + (93,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((I.ilu0Preconditioner a0Value) :: (Either (E.MathError) (I.Preconditioner (a)))) >>= \_result311 -> encodePreconditioner w _result311 + (94,[a0]) -> realFloat w $ do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + source ((I.ic0Preconditioner a0Value) :: (Either (E.MathError) (I.Preconditioner (a)))) >>= \_result312 -> encodePreconditioner w _result312 + (95,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item313 -> X.asScalar item313) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item314 -> X.asScalar item314) :: IO [(a)]) + source ((I.conjugateGradient a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result315 -> encodeIterativeResult w _result315 + (96,[a0,a1,a2,a3,a4]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (unbox "HMath.Matrix.Iterative.Preconditioner" a1 :: IO (I.Preconditioner (a))) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item316 -> X.asScalar item316) :: IO [(a)]) + a4Value <- (X.asList a4 >>= mapM (\item317 -> X.asScalar item317) :: IO [(a)]) + source ((I.preconditionedCG a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result318 -> encodeIterativeResult w _result318 + (97,[a0,a1,a2,a3,a4]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item319 -> X.asScalar item319) :: IO [(a)]) + a4Value <- (X.asList a4 >>= mapM (\item320 -> X.asScalar item320) :: IO [(a)]) + source ((I.gmres a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result321 -> encodeIterativeResult w _result321 + (98,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item322 -> X.asScalar item322) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item323 -> X.asScalar item323) :: IO [(a)]) + source ((I.minres a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result324 -> encodeIterativeResult w _result324 + (99,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item325 -> X.asScalar item325) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item326 -> X.asScalar item326) :: IO [(a)]) + source ((I.bicg a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result327 -> encodeIterativeResult w _result327 + (100,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item328 -> X.asScalar item328) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item329 -> X.asScalar item329) :: IO [(a)]) + source ((I.bicgstab a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result330 -> encodeIterativeResult w _result330 + (101,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item331 -> X.asScalar item331) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item332 -> X.asScalar item332) :: IO [(a)]) + source ((I.lsqr a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result333 -> encodeIterativeResult w _result333 + (102,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item334 -> X.asScalar item334) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item335 -> X.asScalar item335) :: IO [(a)]) + source ((I.lsmr a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result336 -> encodeIterativeResult w _result336 + (103,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item337 -> X.asScalar item337) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item338 -> X.asScalar item338) :: IO [(a)]) + source ((I.jacobiSolve a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result339 -> encodeIterativeResult w _result339 + (104,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item340 -> X.asScalar item340) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item341 -> X.asScalar item341) :: IO [(a)]) + source ((I.gaussSeidelSolve a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result342 -> encodeIterativeResult w _result342 + (105,[a0,a1,a2,a3,a4]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (X.asScalar a1 :: IO (a)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (a))) + a3Value <- (X.asList a3 >>= mapM (\item343 -> X.asScalar item343) :: IO [(a)]) + a4Value <- (X.asList a4 >>= mapM (\item344 -> X.asScalar item344) :: IO [(a)]) + source ((I.sorSolve a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result345 -> encodeIterativeResult w _result345 + (106,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + a2Value <- (X.asList a2 >>= mapM (\item346 -> X.asScalar item346) :: IO [(a)]) + a3Value <- (X.asList a3 >>= mapM (\item347 -> X.asScalar item347) :: IO [(a)]) + source ((I.iterativeRefinement a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (I.IterativeResult (a)))) >>= \_result348 -> encodeIterativeResult w _result348 + (107,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + pure (X.Scalar w ((I.absoluteTolerance a0Value) :: (a))) + (108,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + pure (X.Scalar w ((I.relativeTolerance a0Value) :: (a))) + (109,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeOptions" a0 :: IO (I.IterativeOptions (a))) + pure (X.Index ((I.maximumIterations a0Value) :: (Int))) + (110,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asScalar a1 :: IO (a)) + a2Value <- (X.asIndex a2 :: IO (Int)) + encodeIterativeOptions w ((I.IterativeOptions a0Value a1Value a2Value) :: (I.IterativeOptions (a))) + (111,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeResult" a0 :: IO (I.IterativeResult (a))) + X.List <$> mapM (\item349 -> pure (X.Scalar w item349)) ((I.iterativeSolution a0Value) :: [(a)]) + (112,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeResult" a0 :: IO (I.IterativeResult (a))) + pure (X.Index ((I.iterativeIterations a0Value) :: (Int))) + (113,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeResult" a0 :: IO (I.IterativeResult (a))) + pure (X.Scalar w ((I.iterativeResidualNorm a0Value) :: (a))) + (114,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.Iterative.IterativeResult" a0 :: IO (I.IterativeResult (a))) + pure (X.Scalar w ((I.iterativeNormalResidualNorm a0Value) :: (a))) + (115,[a0,a1,a2,a3]) -> do + a0Value <- (X.asList a0 >>= mapM (\item350 -> X.asScalar item350) :: IO [(a)]) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asScalar a2 :: IO (a)) + a3Value <- (X.asScalar a3 :: IO (a)) + encodeIterativeResult w ((I.IterativeResult a0Value a1Value a2Value a3Value) :: (I.IterativeResult (a))) + (161,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item351 -> (X.asTuple 3 item351 >>= \items352 -> case items352 of { [part353,part354,part355] -> (,,) <$> (X.asIndex part353) <*> (X.asIndex part354) <*> (X.asScalar part355); _ -> X.invalid "tuple arity differs" })) :: IO [((Int),(Int),(a))]) + source ((S.sparse a0Value a1Value a2Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result356 -> encodeSparse w _result356 + (162,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + (\(part357,part358) -> X.Tuple <$> sequence [pure (X.Index part357),pure (X.Index part358)]) ((S.sparseShape a0Value) :: ((Int),(Int))) + (163,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + X.List <$> mapM (\item359 -> (\(part360,part361,part362) -> X.Tuple <$> sequence [pure (X.Index part360),pure (X.Index part361),pure (X.Scalar w part362)]) item359) ((S.sparseEntries a0Value) :: [((Int),(Int),(a))]) + (164,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + pure (X.Index ((S.nonzeros a0Value) :: (Int))) + (165,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseFormat" a0 :: IO (S.SparseFormat (a))) + source ((S.fromFormat a0Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result363 -> encodeSparse w _result363 + (166,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + encodeSparseFormat w ((S.toCOO a0Value) :: (S.SparseFormat (a))) + (167,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + encodeSparseFormat w ((S.toCSR a0Value) :: (S.SparseFormat (a))) + (168,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + encodeSparseFormat w ((S.toCSC a0Value) :: (S.SparseFormat (a))) + (169,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + encodeSparseFormat w ((S.toDIA a0Value) :: (S.SparseFormat (a))) + (170,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (unbox "HMath.Sparse.Sparse" a2 :: IO (S.Sparse (a))) + source ((S.toBSR a0Value a1Value a2Value) :: (Either (E.MathError) (S.SparseFormat (a)))) >>= \_result364 -> encodeSparseFormat w _result364 + (171,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + source ((S.toELLPACK a0Value) :: (Either (E.MathError) (S.SparseFormat (a)))) >>= \_result365 -> encodeSparseFormat w _result365 + (172,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + source ((S.sparseToDense a0Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result366 -> pure (X.Dense (X.SomeMatrix w _result366)) + (173,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (a))) + encodeSparse w ((S.denseToSparse a0Value) :: (S.Sparse (a))) + (174,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + encodeSparse w ((S.sparseTranspose a0Value) :: (S.Sparse (a))) + (175,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.sparseAdd a0Value a1Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result367 -> encodeSparse w _result367 + (176,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.sparseSubtract a0Value a1Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result368 -> encodeSparse w _result368 + (177,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (X.asList a1 >>= mapM (\item369 -> X.asScalar item369) :: IO [(a)]) + source ((S.spmv a0Value a1Value) :: (Either (E.MathError) [(a)])) >>= \_result370 -> X.List <$> mapM (\item371 -> pure (X.Scalar w item371)) _result370 + (178,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.spmm a0Value a1Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result372 -> encodeSparse w _result372 + (179,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.sparseKronecker a0Value a1Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result373 -> encodeSparse w _result373 + (180,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + a2Value <- (X.asList a2 >>= mapM (\item374 -> X.asScalar item374) :: IO [(a)]) + source ((S.sparseTriangularSolve a0Value a1Value a2Value) :: (Either (E.MathError) [(a)])) >>= \_result375 -> X.List <$> mapM (\item376 -> pure (X.Scalar w item376)) _result375 + (181,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + a1Value <- (X.asList a1 >>= mapM (\item377 -> X.asScalar item377) :: IO [(a)]) + source ((S.sparseDiagonalSolve a0Value a1Value) :: (Either (E.MathError) [(a)])) >>= \_result378 -> X.List <$> mapM (\item379 -> pure (X.Scalar w item379)) _result378 + (182,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseLU" a0 :: IO (S.SparseLU (a))) + encodeSparse w ((S.sparseLULower a0Value) :: (S.Sparse (a))) + (183,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseLU" a0 :: IO (S.SparseLU (a))) + encodeSparse w ((S.sparseLUUpper a0Value) :: (S.Sparse (a))) + (184,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseLU" a0 :: IO (S.SparseLU (a))) + X.List <$> mapM (\item380 -> pure (X.Index item380)) ((S.sparseLUPermutation a0Value) :: [(Int)]) + (185,[a0,a1]) -> realFloat w $ do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.sparseLU a0Value a1Value) :: (Either (E.MathError) (S.SparseLU (a)))) >>= \_result381 -> encodeSparseLU w _result381 + (186,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.SparseLU" a0 :: IO (S.SparseLU (a))) + a1Value <- (X.asList a1 >>= mapM (\item382 -> X.asScalar item382) :: IO [(a)]) + source ((S.sparseSolveLU a0Value a1Value) :: (Either (E.MathError) [(a)])) >>= \_result383 -> X.List <$> mapM (\item384 -> pure (X.Scalar w item384)) _result383 + (187,[a0]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + source ((S.sparseCholesky a0Value) :: (Either (E.MathError) (S.Sparse (a)))) >>= \_result385 -> encodeSparse w _result385 + (188,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseQR" a0 :: IO (S.SparseQR (a))) + encodeSparse w ((S.sparseQRUpper a0Value) :: (S.Sparse (a))) + (189,[a0]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + source ((S.sparseQR a0Value) :: (Either (E.MathError) (S.SparseQR (a)))) >>= \_result386 -> encodeSparseQR w _result386 + (190,[a0,a1]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.SparseQR" a0 :: IO (S.SparseQR (a))) + a1Value <- (X.asList a1 >>= mapM (\item387 -> X.asScalar item387) :: IO [(a)]) + source ((S.sparseQRApplyQT a0Value a1Value) :: (Either (E.MathError) [(a)])) >>= \_result388 -> X.List <$> mapM (\item389 -> pure (X.Scalar w item389)) _result388 + (191,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Sparse" a0 :: IO (S.Sparse (a))) + source ((S.sparseGraph a0Value) :: (Either (E.MathError) [((Int),[((Int),(a))])])) >>= \_result390 -> X.List <$> mapM (\item391 -> (\(part392,part393) -> X.Tuple <$> sequence [pure (X.Index part392),X.List <$> mapM (\item394 -> (\(part395,part396) -> X.Tuple <$> sequence [pure (X.Index part395),pure (X.Scalar w part396)]) item394) part393]) item391) _result390 + (192,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + source ((S.sparseStorageBytes a0Value a1Value) :: (Either (E.MathError) (Integer))) >>= \_result397 -> pure (X.Scalar SInteger _result397) + (193,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item398 -> X.asIndex item398) :: IO [(Int)]) + a1Value <- (X.asList a1 >>= mapM (\item399 -> (X.asTuple 2 item399 >>= \items400 -> case items400 of { [part401,part402] -> (,) <$> (X.asList part401 >>= mapM (\item403 -> X.asIndex item403)) <*> (X.asScalar part402); _ -> X.invalid "tuple arity differs" })) :: IO [([(Int)],(a))]) + source ((S.sparseTensor a0Value a1Value) :: (Either (E.MathError) (S.SparseTensor (a)))) >>= \_result404 -> encodeSparseTensor w _result404 + (194,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseTensor" a0 :: IO (S.SparseTensor (a))) + X.List <$> mapM (\item405 -> pure (X.Index item405)) ((S.sparseTensorShape a0Value) :: [(Int)]) + (195,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.SparseTensor" a0 :: IO (S.SparseTensor (a))) + X.List <$> mapM (\item406 -> (\(part407,part408) -> X.Tuple <$> sequence [X.List <$> mapM (\item409 -> pure (X.Index item409)) part407,pure (X.Scalar w part408)]) item406) ((S.sparseTensorEntries a0Value) :: [([(Int)],(a))]) + (196,[a0,a1]) -> do + a0Value <- (unbox "HMath.Sparse.SparseTensor" a0 :: IO (S.SparseTensor (a))) + a1Value <- (X.asList a1 >>= mapM (\item410 -> X.asIndex item410) :: IO [(Int)]) + source ((S.sparseTensorLookup a0Value a1Value) :: (Either (E.MathError) (a))) >>= \_result411 -> pure (X.Scalar w _result411) + (199,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item412 -> (X.asTuple 3 item412 >>= \items413 -> case items413 of { [part414,part415,part416] -> (,,) <$> (X.asIndex part414) <*> (X.asIndex part415) <*> (X.asScalar part416); _ -> X.invalid "tuple arity differs" })) :: IO [((Int),(Int),(a))]) + encodeSparseFormat w ((S.COO a0Value a1Value a2Value) :: (S.SparseFormat (a))) + (200,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item417 -> X.asIndex item417) :: IO [(Int)]) + a3Value <- (X.asList a3 >>= mapM (\item418 -> X.asIndex item418) :: IO [(Int)]) + a4Value <- (X.asList a4 >>= mapM (\item419 -> X.asScalar item419) :: IO [(a)]) + encodeSparseFormat w ((S.CSR a0Value a1Value a2Value a3Value a4Value) :: (S.SparseFormat (a))) + (201,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item420 -> X.asIndex item420) :: IO [(Int)]) + a3Value <- (X.asList a3 >>= mapM (\item421 -> X.asIndex item421) :: IO [(Int)]) + a4Value <- (X.asList a4 >>= mapM (\item422 -> X.asScalar item422) :: IO [(a)]) + encodeSparseFormat w ((S.CSC a0Value a1Value a2Value a3Value a4Value) :: (S.SparseFormat (a))) + (202,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asList a2 >>= mapM (\item423 -> (X.asTuple 2 item423 >>= \items424 -> case items424 of { [part425,part426] -> (,) <$> (X.asIndex part425) <*> (X.asList part426 >>= mapM (\item427 -> X.asScalar item427)); _ -> X.invalid "tuple arity differs" })) :: IO [((Int),[(a)])]) + encodeSparseFormat w ((S.DIA a0Value a1Value a2Value) :: (S.SparseFormat (a))) + (203,[a0,a1,a2,a3,a4,a5,a6]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asIndex a3 :: IO (Int)) + a4Value <- (X.asList a4 >>= mapM (\item428 -> X.asIndex item428) :: IO [(Int)]) + a5Value <- (X.asList a5 >>= mapM (\item429 -> X.asIndex item429) :: IO [(Int)]) + a6Value <- (X.asList a6 >>= mapM (\item430 -> X.asList item430 >>= mapM (\item431 -> X.asScalar item431)) :: IO [[(a)]]) + encodeSparseFormat w ((S.BSR a0Value a1Value a2Value a3Value a4Value a5Value a6Value) :: (S.SparseFormat (a))) + (204,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asList a3 >>= mapM (\item432 -> X.asIndex item432) :: IO [(Int)]) + a4Value <- (X.asList a4 >>= mapM (\item433 -> X.asScalar item433) :: IO [(a)]) + encodeSparseFormat w ((S.ELLPACK a0Value a1Value a2Value a3Value a4Value) :: (S.SparseFormat (a))) + (205,[]) -> fractional w $ do + encodeSparseSpectralOptions w ((P.defaultSparseSpectralOptions ) :: (P.SparseSpectralOptions (a))) + (206,[a0,a1,a2]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (a))) + a2Value <- (X.asList a2 >>= mapM (\item434 -> X.asScalar item434) :: IO [(a)]) + source ((P.sparseDominantEigen a0Value a1Value a2Value) :: (Either (E.MathError) (P.SparseEigenResult (a)))) >>= \_result435 -> encodeSparseEigenResult w _result435 + (207,[a0,a1,a2,a3]) -> realFloat w $ do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asScalar a2 :: IO (Integer)) + a3Value <- (unbox "HMath.Sparse.Sparse" a3 :: IO (S.Sparse (a))) + source ((P.sparseTruncatedSVD a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (P.SparseSVD (a)))) >>= \_result436 -> encodeSparseSVD w _result436 + (208,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + pure (X.Scalar w ((P.sparseAbsoluteTolerance a0Value) :: (a))) + (209,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + pure (X.Scalar w ((P.sparseRelativeTolerance a0Value) :: (a))) + (210,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + pure (X.Index ((P.sparseIterationLimit a0Value) :: (Int))) + (211,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSpectralOptions" a0 :: IO (P.SparseSpectralOptions (a))) + pure (X.Scalar SInteger ((P.sparseWorkspaceLimit a0Value) :: (Integer))) + (212,[a0,a1,a2,a3]) -> do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asScalar a1 :: IO (a)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asScalar a3 :: IO (Integer)) + encodeSparseSpectralOptions w ((P.SparseSpectralOptions a0Value a1Value a2Value a3Value) :: (P.SparseSpectralOptions (a))) + (213,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseEigenResult" a0 :: IO (P.SparseEigenResult (a))) + pure (X.Scalar w ((P.sparseEigenvalue a0Value) :: (a))) + (214,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseEigenResult" a0 :: IO (P.SparseEigenResult (a))) + X.List <$> mapM (\item437 -> pure (X.Scalar w item437)) ((P.sparseEigenvector a0Value) :: [(a)]) + (215,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseEigenResult" a0 :: IO (P.SparseEigenResult (a))) + pure (X.Scalar w ((P.sparseEigenResidual a0Value) :: (a))) + (216,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseEigenResult" a0 :: IO (P.SparseEigenResult (a))) + pure (X.Index ((P.sparseEigenIterations a0Value) :: (Int))) + (217,[a0,a1,a2,a3]) -> do + a0Value <- (X.asScalar a0 :: IO (a)) + a1Value <- (X.asList a1 >>= mapM (\item438 -> X.asScalar item438) :: IO [(a)]) + a2Value <- (X.asScalar a2 :: IO (a)) + a3Value <- (X.asIndex a3 :: IO (Int)) + encodeSparseEigenResult w ((P.SparseEigenResult a0Value a1Value a2Value a3Value) :: (P.SparseEigenResult (a))) + (218,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSVD" a0 :: IO (P.SparseSVD (a))) + X.List <$> mapM (\item439 -> pure (X.Scalar w item439)) ((P.sparseSingularValues a0Value) :: [(a)]) + (219,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSVD" a0 :: IO (P.SparseSVD (a))) + X.List <$> mapM (\item440 -> X.List <$> mapM (\item441 -> pure (X.Scalar w item441)) item440) ((P.sparseLeftVectors a0Value) :: [[(a)]]) + (220,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSVD" a0 :: IO (P.SparseSVD (a))) + X.List <$> mapM (\item442 -> X.List <$> mapM (\item443 -> pure (X.Scalar w item443)) item442) ((P.sparseRightVectors a0Value) :: [[(a)]]) + (221,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSVD" a0 :: IO (P.SparseSVD (a))) + X.List <$> mapM (\item444 -> (\(part445,part446) -> X.Tuple <$> sequence [pure (X.Scalar w part445),pure (X.Scalar w part446)]) item444) ((P.sparseSingularResiduals a0Value) :: [((a),(a))]) + (222,[a0]) -> do + a0Value <- (unbox "HMath.Sparse.Spectral.SparseSVD" a0 :: IO (P.SparseSVD (a))) + X.List <$> mapM (\item447 -> pure (X.Index item447)) ((P.sparseSingularIterations a0Value) :: [(Int)]) + (223,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asList a0 >>= mapM (\item448 -> X.asScalar item448) :: IO [(a)]) + a1Value <- (X.asList a1 >>= mapM (\item449 -> X.asList item449 >>= mapM (\item450 -> X.asScalar item450)) :: IO [[(a)]]) + a2Value <- (X.asList a2 >>= mapM (\item451 -> X.asList item451 >>= mapM (\item452 -> X.asScalar item452)) :: IO [[(a)]]) + a3Value <- (X.asList a3 >>= mapM (\item453 -> (X.asTuple 2 item453 >>= \items454 -> case items454 of { [part455,part456] -> (,) <$> (X.asScalar part455) <*> (X.asScalar part456); _ -> X.invalid "tuple arity differs" })) :: IO [((a),(a))]) + a4Value <- (X.asList a4 >>= mapM (\item457 -> X.asIndex item457) :: IO [(Int)]) + encodeSparseSVD w ((P.SparseSVD a0Value a1Value a2Value a3Value a4Value) :: (P.SparseSVD (a))) + (230,[a0,a1,a2,a3]) -> do + a0Value <- (unbox "HMath.Backend.BackendLayout" a0 :: IO (B.BackendLayout)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asList a3 >>= mapM (\item458 -> X.asScalar item458) :: IO [(a)]) + source ((B.matrixFromLayout a0Value a1Value a2Value a3Value) :: (Either (E.MathError) (M.Matrix (a)))) >>= \_result459 -> pure (X.Dense (X.SomeMatrix w _result459)) + (231,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.BackendLayout" a0 :: IO (B.BackendLayout)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (a))) + X.List <$> mapM (\item460 -> pure (X.Scalar w item460)) ((B.matrixToLayout a0Value a1Value) :: [(a)]) + _ -> X.invalid "unsupported generic linear operation/arity" + +concrete :: Int -> [X.Value] -> IO X.Value +concrete operation args=case(operation,args) of + (46,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((A.spectralNorm a0Value) :: (Either (E.MathError) (Double))) >>= \_result461 -> pure (X.Scalar SDouble _result461) + (47,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((A.matrixRank a0Value a1Value) :: (Either (E.MathError) (Int))) >>= \_result462 -> pure (X.Index _result462) + (48,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((A.pseudoinverse a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result463 -> pure (X.Dense (X.SomeMatrix SDouble _result463)) + (49,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((A.conditionNumber a0Value) :: (Either (E.MathError) (Double))) >>= \_result464 -> pure (X.Scalar SDouble _result464) + (50,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((A.columnSpace a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result465 -> pure (X.Dense (X.SomeMatrix SDouble _result465)) + (51,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((A.rowSpace a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result466 -> pure (X.Dense (X.SomeMatrix SDouble _result466)) + (52,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((A.nullSpace a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result467 -> pure (X.Dense (X.SomeMatrix SDouble _result467)) + (55,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((A.matrixLog a0Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result468 -> pure (X.Dense (X.SomeMatrix SDouble _result468)) + (56,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((A.matrixSqrt a0Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result469 -> pure (X.Dense (X.SomeMatrix SDouble _result469)) + (57,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((A.polar a0Value) :: (Either (E.MathError) ((M.Matrix (Double)),(M.Matrix (Double))))) >>= \_result470 -> (\(part471,part472) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix SDouble part471)),pure (X.Dense (X.SomeMatrix SDouble part472))]) _result470 + (58,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Complex (Double)))) + source ((A.complexPseudoinverse a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Complex (Double))))) >>= \_result473 -> pure (X.Dense (X.SomeMatrix SComplexDouble _result473)) + (59,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Double))) + source ((A.matrixSqrtGeneral a0Value a1Value a2Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result474 -> pure (X.Dense (X.SomeMatrix SDouble _result474)) + (60,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Double))) + source ((A.matrixLogGeneral a0Value a1Value a2Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result475 -> pure (X.Dense (X.SomeMatrix SDouble _result475)) + (67,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((D.tridiagonalize a0Value) :: (Either (E.MathError) ((M.Matrix (Double)),(M.Matrix (Double))))) >>= \_result476 -> (\(part477,part478) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix SDouble part477)),pure (X.Dense (X.SomeMatrix SDouble part478))]) _result476 + (75,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Rational))) + a1Value <- (X.asList a1 >>= mapM (\item479 -> X.asScalar item479) :: IO [(Rational)]) + source ((D.jordanForm a0Value a1Value) :: (Either (E.MathError) ((M.Matrix (Rational)),(M.Matrix (Rational))))) >>= \_result480 -> (\(part481,part482) -> X.Tuple <$> sequence [pure (X.Dense (X.SomeMatrix SRational part481)),pure (X.Dense (X.SomeMatrix SRational part482))]) _result480 + (116,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.svd a0Value) :: (Either (E.MathError) (L.SVD))) >>= \_result483 -> encodeSVD _result483 + (117,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.fullSVD a0Value) :: (Either (E.MathError) (L.SVD))) >>= \_result484 -> encodeSVD _result484 + (118,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((L.truncatedSVD a0Value a1Value) :: (Either (E.MathError) (L.SVD))) >>= \_result485 -> encodeSVD _result485 + (119,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asScalar a3 :: IO (Integer)) + a4Value <- (asMatrix a4 :: IO (M.Matrix (Double))) + source ((L.randomizedSVD a0Value a1Value a2Value a3Value a4Value) :: (Either (E.MathError) (L.SVD))) >>= \_result486 -> encodeSVD _result486 + (120,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.eigen a0Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result487 -> encodeEigen _result487 + (121,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.symmetricEigen a0Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result488 -> encodeEigen _result488 + (122,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((L.generalizedEigen a0Value a1Value) :: (Either (E.MathError) (L.GeneralizedEigen))) >>= \_result489 -> encodeGeneralizedEigen _result489 + (123,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.schur a0Value) :: (Either (E.MathError) (L.Schur))) >>= \_result490 -> encodeSchur _result490 + (124,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((L.qz a0Value a1Value) :: (Either (E.MathError) (L.QZ))) >>= \_result491 -> encodeQZ _result491 + (125,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.hessenberg a0Value) :: (Either (E.MathError) (L.Hessenberg))) >>= \_result492 -> encodeHessenberg _result492 + (126,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((L.balance a0Value) :: (Either (E.MathError) (L.Balance))) >>= \_result493 -> encodeBalance _result493 + (127,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Complex (Double)))) + source ((L.complexSVD a0Value) :: (Either (E.MathError) (L.ComplexSVD))) >>= \_result494 -> encodeComplexSVD _result494 + (128,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Complex (Double)))) + source ((L.complexEigen a0Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result495 -> encodeEigen _result495 + (129,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.SVD" a0 :: IO (L.SVD)) + pure (X.Dense (X.SomeMatrix SDouble ((L.svdU a0Value) :: (M.Matrix (Double))))) + (130,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.SVD" a0 :: IO (L.SVD)) + X.List <$> mapM (\item496 -> pure (X.Scalar SDouble item496)) ((L.singularValues a0Value) :: [(Double)]) + (131,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.SVD" a0 :: IO (L.SVD)) + pure (X.Dense (X.SomeMatrix SDouble ((L.svdVT a0Value) :: (M.Matrix (Double))))) + (132,[a0,a1,a2]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (X.asList a1 >>= mapM (\item497 -> X.asScalar item497) :: IO [(Double)]) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Double))) + encodeSVD ((L.SVD a0Value a1Value a2Value) :: (L.SVD)) + (133,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Eigen" a0 :: IO (L.Eigen)) + X.List <$> mapM (\item498 -> pure (X.Scalar SComplexDouble item498)) ((L.eigenvalues a0Value) :: [(Complex (Double))]) + (134,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Eigen" a0 :: IO (L.Eigen)) + pure (X.Dense (X.SomeMatrix SComplexDouble ((L.eigenvectors a0Value) :: (M.Matrix (Complex (Double)))))) + (135,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item499 -> X.asScalar item499) :: IO [(Complex (Double))]) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Complex (Double)))) + encodeEigen ((L.Eigen a0Value a1Value) :: (L.Eigen)) + (136,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.GeneralizedEigen" a0 :: IO (L.GeneralizedEigen)) + X.List <$> mapM (\item500 -> pure (X.Scalar SComplexDouble item500)) ((L.eigenAlpha a0Value) :: [(Complex (Double))]) + (137,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.GeneralizedEigen" a0 :: IO (L.GeneralizedEigen)) + X.List <$> mapM (\item501 -> pure (X.Scalar SDouble item501)) ((L.eigenBeta a0Value) :: [(Double)]) + (138,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.GeneralizedEigen" a0 :: IO (L.GeneralizedEigen)) + pure (X.Dense (X.SomeMatrix SComplexDouble ((L.generalizedEigenvectors a0Value) :: (M.Matrix (Complex (Double)))))) + (139,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item502 -> X.asScalar item502) :: IO [(Complex (Double))]) + a1Value <- (X.asList a1 >>= mapM (\item503 -> X.asScalar item503) :: IO [(Double)]) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Complex (Double)))) + encodeGeneralizedEigen ((L.GeneralizedEigen a0Value a1Value a2Value) :: (L.GeneralizedEigen)) + (140,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Schur" a0 :: IO (L.Schur)) + pure (X.Dense (X.SomeMatrix SDouble ((L.schurQ a0Value) :: (M.Matrix (Double))))) + (141,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Schur" a0 :: IO (L.Schur)) + pure (X.Dense (X.SomeMatrix SDouble ((L.schurT a0Value) :: (M.Matrix (Double))))) + (142,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Schur" a0 :: IO (L.Schur)) + X.List <$> mapM (\item504 -> pure (X.Scalar SComplexDouble item504)) ((L.schurEigenvalues a0Value) :: [(Complex (Double))]) + (143,[a0,a1,a2]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (X.asList a2 >>= mapM (\item505 -> X.asScalar item505) :: IO [(Complex (Double))]) + encodeSchur ((L.Schur a0Value a1Value a2Value) :: (L.Schur)) + (144,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + pure (X.Dense (X.SomeMatrix SDouble ((L.qzQ a0Value) :: (M.Matrix (Double))))) + (145,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + pure (X.Dense (X.SomeMatrix SDouble ((L.qzZ a0Value) :: (M.Matrix (Double))))) + (146,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + pure (X.Dense (X.SomeMatrix SDouble ((L.qzS a0Value) :: (M.Matrix (Double))))) + (147,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + pure (X.Dense (X.SomeMatrix SDouble ((L.qzT a0Value) :: (M.Matrix (Double))))) + (148,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + X.List <$> mapM (\item506 -> pure (X.Scalar SComplexDouble item506)) ((L.qzAlpha a0Value) :: [(Complex (Double))]) + (149,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.QZ" a0 :: IO (L.QZ)) + X.List <$> mapM (\item507 -> pure (X.Scalar SDouble item507)) ((L.qzBeta a0Value) :: [(Double)]) + (150,[a0,a1,a2,a3,a4,a5]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Double))) + a3Value <- (asMatrix a3 :: IO (M.Matrix (Double))) + a4Value <- (X.asList a4 >>= mapM (\item508 -> X.asScalar item508) :: IO [(Complex (Double))]) + a5Value <- (X.asList a5 >>= mapM (\item509 -> X.asScalar item509) :: IO [(Double)]) + encodeQZ ((L.QZ a0Value a1Value a2Value a3Value a4Value a5Value) :: (L.QZ)) + (151,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Hessenberg" a0 :: IO (L.Hessenberg)) + pure (X.Dense (X.SomeMatrix SDouble ((L.hessenbergQ a0Value) :: (M.Matrix (Double))))) + (152,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Hessenberg" a0 :: IO (L.Hessenberg)) + pure (X.Dense (X.SomeMatrix SDouble ((L.hessenbergH a0Value) :: (M.Matrix (Double))))) + (153,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + encodeHessenberg ((L.Hessenberg a0Value a1Value) :: (L.Hessenberg)) + (154,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Balance" a0 :: IO (L.Balance)) + pure (X.Dense (X.SomeMatrix SDouble ((L.balancedMatrix a0Value) :: (M.Matrix (Double))))) + (155,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.Balance" a0 :: IO (L.Balance)) + X.List <$> mapM (\item510 -> pure (X.Scalar SDouble item510)) ((L.balanceScales a0Value) :: [(Double)]) + (156,[a0,a1]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + a1Value <- (X.asList a1 >>= mapM (\item511 -> X.asScalar item511) :: IO [(Double)]) + encodeBalance ((L.Balance a0Value a1Value) :: (L.Balance)) + (157,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.ComplexSVD" a0 :: IO (L.ComplexSVD)) + pure (X.Dense (X.SomeMatrix SComplexDouble ((L.complexU a0Value) :: (M.Matrix (Complex (Double)))))) + (158,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.ComplexSVD" a0 :: IO (L.ComplexSVD)) + X.List <$> mapM (\item512 -> pure (X.Scalar SDouble item512)) ((L.complexSingularValues a0Value) :: [(Double)]) + (159,[a0]) -> do + a0Value <- (unbox "HMath.Matrix.LAPACK.ComplexSVD" a0 :: IO (L.ComplexSVD)) + pure (X.Dense (X.SomeMatrix SComplexDouble ((L.complexVT a0Value) :: (M.Matrix (Complex (Double)))))) + (160,[a0,a1,a2]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Complex (Double)))) + a1Value <- (X.asList a1 >>= mapM (\item513 -> X.asScalar item513) :: IO [(Double)]) + a2Value <- (asMatrix a2 :: IO (M.Matrix (Complex (Double)))) + encodeComplexSVD ((L.ComplexSVD a0Value a1Value a2Value) :: (L.ComplexSVD)) + (197,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (Double))) + source ((S.sparseEigenReference a0Value a1Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result514 -> encodeEigen _result514 + (198,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Integer)) + a1Value <- (unbox "HMath.Sparse.Sparse" a1 :: IO (S.Sparse (Double))) + source ((S.sparseSVDReference a0Value a1Value) :: (Either (E.MathError) (L.SVD))) >>= \_result515 -> encodeSVD _result515 + (224,[a0]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + encodeBackendInfo ((B.backendInfo a0Value) :: (B.BackendInfo)) + (225,[]) -> do + encodeBackend ((B.pureBackend ) :: (B.Backend)) + (226,[]) -> do + ((B.lapackAvailable ) :: (IO (Bool))) >>= \_result516 -> pure (X.Boolean _result516) + (227,[a0]) -> do + a0Value <- (unbox "HMath.Backend.BackendRequest" a0 :: IO (B.BackendRequest)) + ((B.selectBackend a0Value) :: (IO (Either (E.MathError) (B.Backend)))) >>= \_result517 -> source _result517 >>= \_result518 -> encodeBackend _result518 + (228,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asIndex a1 :: IO (Int)) + ((B.setBackendThreads a0Value a1Value) :: (IO (Either (E.MathError) ()))) >>= \_result519 -> source _result519 >>= \_result520 -> pure X.None + (229,[a0,a1]) -> do + a0Value <- (X.asText a0 :: IO (String)) + a1Value <- (X.asIndex a1 :: IO (Int)) + source ((B.lapackStatus a0Value a1Value) :: (Either (E.MathError) ())) >>= \_result521 -> pure X.None + (232,[a0,a1,a2,a3]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asList a2 >>= mapM (\item522 -> X.asScalar item522) :: IO [(Double)]) + a3Value <- (X.asList a3 >>= mapM (\item523 -> X.asScalar item523) :: IO [(Double)]) + ((B.axpy a0Value a1Value a2Value a3Value) :: (IO (Either (E.MathError) [(Double)]))) >>= \_result524 -> source _result524 >>= \_result525 -> X.List <$> mapM (\item526 -> pure (X.Scalar SDouble item526)) _result525 + (233,[a0,a1,a2]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asList a1 >>= mapM (\item527 -> X.asScalar item527) :: IO [(Double)]) + a2Value <- (X.asList a2 >>= mapM (\item528 -> X.asScalar item528) :: IO [(Double)]) + ((B.dot a0Value a1Value a2Value) :: (IO (Either (E.MathError) (Double)))) >>= \_result529 -> source _result529 >>= \_result530 -> pure (X.Scalar SDouble _result530) + (234,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asList a1 >>= mapM (\item531 -> X.asScalar item531) :: IO [(Double)]) + ((B.nrm2 a0Value a1Value) :: (IO (Either (E.MathError) (Double)))) >>= \_result532 -> source _result532 >>= \_result533 -> pure (X.Scalar SDouble _result533) + (235,[a0,a1,a2,a3,a4,a5,a6]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (unbox "HMath.Backend.Transpose" a1 :: IO (B.Transpose)) + a2Value <- (X.asScalar a2 :: IO (Double)) + a3Value <- (asMatrix a3 :: IO (M.Matrix (Double))) + a4Value <- (X.asList a4 >>= mapM (\item534 -> X.asScalar item534) :: IO [(Double)]) + a5Value <- (X.asScalar a5 :: IO (Double)) + a6Value <- (X.asList a6 >>= mapM (\item535 -> X.asScalar item535) :: IO [(Double)]) + ((B.gemv a0Value a1Value a2Value a3Value a4Value a5Value a6Value) :: (IO (Either (E.MathError) [(Double)]))) >>= \_result536 -> source _result536 >>= \_result537 -> X.List <$> mapM (\item538 -> pure (X.Scalar SDouble item538)) _result537 + (236,[a0,a1,a2,a3,a4,a5,a6,a7]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (unbox "HMath.Backend.Transpose" a1 :: IO (B.Transpose)) + a2Value <- (unbox "HMath.Backend.Transpose" a2 :: IO (B.Transpose)) + a3Value <- (X.asScalar a3 :: IO (Double)) + a4Value <- (asMatrix a4 :: IO (M.Matrix (Double))) + a5Value <- (asMatrix a5 :: IO (M.Matrix (Double))) + a6Value <- (X.asScalar a6 :: IO (Double)) + a7Value <- (asMatrix a7 :: IO (M.Matrix (Double))) + ((B.gemm a0Value a1Value a2Value a3Value a4Value a5Value a6Value a7Value) :: (IO (Either (E.MathError) (M.Matrix (Double))))) >>= \_result539 -> source _result539 >>= \_result540 -> pure (X.Dense (X.SomeMatrix SDouble _result540)) + (237,[a0,a1,a2,a3,a4,a5,a6,a7]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (unbox "HMath.Backend.Transpose" a1 :: IO (B.Transpose)) + a2Value <- (unbox "HMath.Backend.Transpose" a2 :: IO (B.Transpose)) + a3Value <- (X.asScalar a3 :: IO (Complex (Double))) + a4Value <- (asMatrix a4 :: IO (M.Matrix (Complex (Double)))) + a5Value <- (asMatrix a5 :: IO (M.Matrix (Complex (Double)))) + a6Value <- (X.asScalar a6 :: IO (Complex (Double))) + a7Value <- (asMatrix a7 :: IO (M.Matrix (Complex (Double)))) + ((B.complexGemm a0Value a1Value a2Value a3Value a4Value a5Value a6Value a7Value) :: (IO (Either (E.MathError) (M.Matrix (Complex (Double)))))) >>= \_result541 -> source _result541 >>= \_result542 -> pure (X.Dense (X.SomeMatrix SComplexDouble _result542)) + (238,[a0,a1,a2,a3]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asScalar a1 :: IO (Complex (Double))) + a2Value <- (X.asList a2 >>= mapM (\item543 -> X.asScalar item543) :: IO [(Complex (Double))]) + a3Value <- (X.asList a3 >>= mapM (\item544 -> X.asScalar item544) :: IO [(Complex (Double))]) + ((B.complexAxpy a0Value a1Value a2Value a3Value) :: (IO (Either (E.MathError) [(Complex (Double))]))) >>= \_result545 -> source _result545 >>= \_result546 -> X.List <$> mapM (\item547 -> pure (X.Scalar SComplexDouble item547)) _result546 + (239,[a0,a1,a2,a3]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asBoolean a1 :: IO (Bool)) + a2Value <- (X.asList a2 >>= mapM (\item548 -> X.asScalar item548) :: IO [(Complex (Double))]) + a3Value <- (X.asList a3 >>= mapM (\item549 -> X.asScalar item549) :: IO [(Complex (Double))]) + ((B.complexDot a0Value a1Value a2Value a3Value) :: (IO (Either (E.MathError) (Complex (Double))))) >>= \_result550 -> source _result550 >>= \_result551 -> pure (X.Scalar SComplexDouble _result551) + (240,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asList a1 >>= mapM (\item552 -> X.asScalar item552) :: IO [(Complex (Double))]) + ((B.complexNrm2 a0Value a1Value) :: (IO (Either (E.MathError) (Double)))) >>= \_result553 -> source _result553 >>= \_result554 -> pure (X.Scalar SDouble _result554) + (241,[a0,a1,a2,a3,a4,a5,a6]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (unbox "HMath.Backend.Transpose" a1 :: IO (B.Transpose)) + a2Value <- (X.asScalar a2 :: IO (Complex (Double))) + a3Value <- (asMatrix a3 :: IO (M.Matrix (Complex (Double)))) + a4Value <- (X.asList a4 >>= mapM (\item555 -> X.asScalar item555) :: IO [(Complex (Double))]) + a5Value <- (X.asScalar a5 :: IO (Complex (Double))) + a6Value <- (X.asList a6 >>= mapM (\item556 -> X.asScalar item556) :: IO [(Complex (Double))]) + ((B.complexGemv a0Value a1Value a2Value a3Value a4Value a5Value a6Value) :: (IO (Either (E.MathError) [(Complex (Double))]))) >>= \_result557 -> source _result557 >>= \_result558 -> X.List <$> mapM (\item559 -> pure (X.Scalar SComplexDouble item559)) _result558 + (242,[a0,a1,a2,a3,a4,a5]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (unbox "HMath.Backend.Transpose" a1 :: IO (B.Transpose)) + a2Value <- (unbox "HMath.Backend.Transpose" a2 :: IO (B.Transpose)) + a3Value <- (X.asScalar a3 :: IO (Double)) + a4Value <- (X.asScalar a4 :: IO (Double)) + a5Value <- (X.asList a5 >>= mapM (\item560 -> (X.asTuple 3 item560 >>= \items561 -> case items561 of { [part562,part563,part564] -> (,,) <$> (asMatrix part562) <*> (asMatrix part563) <*> (asMatrix part564); _ -> X.invalid "tuple arity differs" })) :: IO [((M.Matrix (Double)),(M.Matrix (Double)),(M.Matrix (Double)))]) + ((B.batchedGemm a0Value a1Value a2Value a3Value a4Value a5Value) :: (IO (Either (E.MathError) [(M.Matrix (Double))]))) >>= \_result565 -> source _result565 >>= \_result566 -> X.List <$> mapM (\item567 -> pure (X.Dense (X.SomeMatrix SDouble item567))) _result566 + (243,[a0,a1,a2,a3,a4,a5,a6,a7,a8]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asIndex a3 :: IO (Int)) + a4Value <- (X.asIndex a4 :: IO (Int)) + a5Value <- (X.asIndex a5 :: IO (Int)) + a6Value <- (X.asList a6 >>= mapM (\item568 -> X.asScalar item568) :: IO [(Double)]) + a7Value <- (X.asIndex a7 :: IO (Int)) + a8Value <- (X.asList a8 >>= mapM (\item569 -> X.asScalar item569) :: IO [(Double)]) + ((B.stridedBatchedGemm a0Value a1Value a2Value a3Value a4Value a5Value a6Value a7Value a8Value) :: (IO (Either (E.MathError) [(M.Matrix (Double))]))) >>= \_result570 -> source _result570 >>= \_result571 -> X.List <$> mapM (\item572 -> pure (X.Dense (X.SomeMatrix SDouble item572))) _result571 + (244,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((B.backendLU a0Value a1Value) :: (Either (E.MathError) (LU.LU (Double)))) >>= \_result573 -> encodeLegacyLU _result573 + (245,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((B.backendQR a0Value a1Value) :: (Either (E.MathError) (QR.QR (Double)))) >>= \_result574 -> encodeLegacyQR _result574 + (246,[a0,a1,a2]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (X.asList a2 >>= mapM (\item575 -> X.asScalar item575) :: IO [(Double)]) + source ((B.backendSolve a0Value a1Value a2Value) :: (Either (E.MathError) [(Double)])) >>= \_result576 -> X.List <$> mapM (\item577 -> pure (X.Scalar SDouble item577)) _result576 + (247,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((B.backendCholesky a0Value a1Value) :: (Either (E.MathError) (M.Matrix (Double)))) >>= \_result578 -> pure (X.Dense (X.SomeMatrix SDouble _result578)) + (248,[a0,a1,a2]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (X.asList a2 >>= mapM (\item579 -> X.asScalar item579) :: IO [(Double)]) + source ((B.backendLeastSquares a0Value a1Value a2Value) :: (Either (E.MathError) [(Double)])) >>= \_result580 -> X.List <$> mapM (\item581 -> pure (X.Scalar SDouble item581)) _result580 + (249,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((B.backendSVD a0Value a1Value) :: (Either (E.MathError) (L.SVD))) >>= \_result582 -> encodeSVD _result582 + (250,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Backend" a0 :: IO (B.Backend)) + a1Value <- (asMatrix a1 :: IO (M.Matrix (Double))) + source ((B.backendSymmetricEigen a0Value a1Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result583 -> encodeEigen _result583 + (251,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((B.pureSymmetricEigen a0Value) :: (Either (E.MathError) (L.Eigen))) >>= \_result584 -> encodeEigen _result584 + (252,[a0]) -> do + a0Value <- (asMatrix a0 :: IO (M.Matrix (Double))) + source ((B.pureSVD a0Value) :: (Either (E.MathError) (L.SVD))) >>= \_result585 -> encodeSVD _result585 + (253,[]) -> do + encodeProvider ((B.Pure ) :: (B.Provider)) + (254,[]) -> do + encodeProvider ((B.OpenBLAS ) :: (B.Provider)) + (255,[]) -> do + encodeProvider ((B.BLIS ) :: (B.Provider)) + (256,[]) -> do + encodeProvider ((B.OneMKL ) :: (B.Provider)) + (257,[]) -> do + encodeProvider ((B.Accelerate ) :: (B.Provider)) + (258,[]) -> do + encodeIntegerABI ((B.LP64 ) :: (B.IntegerABI)) + (259,[]) -> do + encodeIntegerABI ((B.ILP64 ) :: (B.IntegerABI)) + (260,[]) -> do + encodeBackendRequest ((B.AutoBackend ) :: (B.BackendRequest)) + (261,[a0,a1,a2]) -> do + a0Value <- (unbox "HMath.Backend.Provider" a0 :: IO (B.Provider)) + a1Value <- (unbox "HMath.Backend.IntegerABI" a1 :: IO (B.IntegerABI)) + a2Value <- ((case a2 of { X.None -> pure Nothing; _ -> Just <$> (X.asText a2) }) :: IO (Maybe (String))) + encodeBackendRequest ((B.RequireBackend a0Value a1Value a2Value) :: (B.BackendRequest)) + (262,[a0]) -> do + a0Value <- (unbox "HMath.Backend.BackendInfo" a0 :: IO (B.BackendInfo)) + encodeProvider ((B.selectedProvider a0Value) :: (B.Provider)) + (263,[a0]) -> do + a0Value <- (unbox "HMath.Backend.BackendInfo" a0 :: IO (B.BackendInfo)) + encodeIntegerABI ((B.selectedIntegerABI a0Value) :: (B.IntegerABI)) + (264,[a0,a1]) -> do + a0Value <- (unbox "HMath.Backend.Provider" a0 :: IO (B.Provider)) + a1Value <- (unbox "HMath.Backend.IntegerABI" a1 :: IO (B.IntegerABI)) + encodeBackendInfo ((B.BackendInfo a0Value a1Value) :: (B.BackendInfo)) + (265,[]) -> do + encodeBackendLayout ((B.RowMajor ) :: (B.BackendLayout)) + (266,[]) -> do + encodeBackendLayout ((B.ColumnMajor ) :: (B.BackendLayout)) + (267,[]) -> do + encodeTranspose ((B.NoTranspose ) :: (B.Transpose)) + (268,[]) -> do + encodeTranspose ((B.Transpose ) :: (B.Transpose)) + (269,[]) -> do + encodeTranspose ((B.ConjugateTranspose ) :: (B.Transpose)) + (-1,[value]) -> X.Text <$> objectName value + (-2,[value]) -> objectParts value + _ -> X.invalid "unsupported concrete linear operation/arity" + +{-# NOINLINE generateCallback #-} +generateCallback :: Coefficient a => X.Value -> Int -> Int -> a +generateCallback callback row column=unsafePerformIO $ callbackValue callback (X.Tuple[X.Index row,X.Index column]) >>= X.asScalar +{-# NOINLINE zipCallback #-} +zipCallback :: (Coefficient a,Coefficient b,Coefficient c) => ScalarType a -> ScalarType b -> X.Value -> a -> b -> c +zipCallback wa wb callback left right=unsafePerformIO $ callbackValue callback (X.Tuple[X.Scalar wa left,X.Scalar wb right]) >>= X.asScalar +special :: Int -> X.Value -> [X.Value] -> IO X.Value +special operation prototype args=case(operation,args) of + (3,[dimension,values]) -> withWitness prototype $ \(w::ScalarType a) -> do + count <- X.asIndex dimension + xs <- X.asList values >>= mapM X.asScalar + fixedFrom w count xs + (4,[value]) -> withWitness prototype $ \(w::ScalarType a) -> do + fixed <- (unbox "HMath.Vector.FixedVector" value :: IO(SomeFixed a)) + case fixed of SomeFixed f -> X.List . map (X.Scalar w) <$> pure(V.fixedValues f) + (29,[rows,columns,callback]) -> withWitness prototype $ \(w::ScalarType a) -> do + r <- X.asIndex rows; c <- X.asIndex columns + matrix <- source(A.generateMatrix r c (generateCallback callback) :: Either E.MathError(M.Matrix a)) + pure(X.Dense(X.SomeMatrix w matrix)) + (37,[callback,left,right]) -> do + prototypes <- X.asTuple 3 prototype + case prototypes of + [pa,pb,pc] -> withWitness pa $ \(wa::ScalarType a) -> withWitness pb $ \(wb::ScalarType b) -> withWitness pc $ \(wc::ScalarType c) -> do + a <- (asMatrix left :: IO(M.Matrix a)); b <- (asMatrix right :: IO(M.Matrix b)) + matrix <- source(A.zipMatrixWith (zipCallback wa wb callback) a b :: Either E.MathError(M.Matrix c)) + pure(X.Dense(X.SomeMatrix wc matrix)) + _ -> X.invalid "zipMatrixWith requires three coefficient prototypes" + _ -> X.invalid "invalid special linear operation/arity" +foreign export ccall "hm_linear_apply" ffiApply :: CInt -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation prototype pointers count out=linearBoundary $ do + values <- peekArray(fromIntegral count) pointers >>= mapM deRefStablePtr + let op=fromIntegral operation + value <- if op `elem` [3, 4, 29, 37] then do + p <- deRefStablePtr prototype + if structuralVectorInput p values then structuralVectors op p values else special op p values + else if op `elem` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 53, 54, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 230, 231] then do + p <- deRefStablePtr prototype + if structuralVectorInput p values then structuralVectors op p values else withWitness p (\w -> generic w op values) + else concrete op values + Boundary.checked(Right())(const(X.publish value out)) diff --git a/src/HMath/FFI/LinearCodec.hs b/src/HMath/FFI/LinearCodec.hs new file mode 100644 index 0000000..b5bafec --- /dev/null +++ b/src/HMath/FFI/LinearCodec.hs @@ -0,0 +1,516 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_linear_bindings.py. Representation/lifetime only. +module HMath.FFI.LinearCodec where +import Control.Exception (bracket,evaluate,throwIO) +import Data.Dynamic (Dynamic,toDyn,fromDynamic) +import Data.Typeable (Typeable,cast) +import Data.Proxy (Proxy(..)) +import Data.Complex (Complex) +import Foreign +import Foreign.C +import GHC.TypeLits (KnownNat,SomeNat(..),someNatVal) +import qualified HMath.Error as E +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as LU +import qualified HMath.Matrix.QR as QR +import qualified HMath.FFI.Matrix as Legacy +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.Coefficient +import HMath.FFI.MathError +import qualified HMath.FFI.TensorCodec as TensorCodec +import qualified HMath.Vector as V +import qualified HMath.Matrix.Decomposition as D +import qualified HMath.Matrix.Iterative as I +import qualified HMath.Matrix.LAPACK as L +import qualified HMath.Sparse as S +import qualified HMath.Sparse.Spectral as P +import qualified HMath.Backend as B + +data Envelope=Envelope String Dynamic (IO X.Value) +opaque :: Typeable a => String -> Int -> a -> IO () -> IO X.Value -> X.Value +opaque name dtype payload force view=X.Opaque 100 dtype 0 force (Envelope name (toDyn payload) view) +unbox :: forall a. Typeable a => String -> X.Value -> IO a +unbox expected (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope actual value _) | actual==expected -> maybe (X.invalid "linear object coefficient/type differs") pure (fromDynamic value) + _ -> X.invalid "linear object subtype differs" +unbox _ _=X.invalid "expected linear object" +objectName :: X.Value -> IO String +objectName (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope name _ _) -> pure name + _ -> X.invalid "invalid linear envelope" +objectName _=X.invalid "expected linear object" +objectParts :: X.Value -> IO X.Value +objectParts (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope _ _ view) -> view + _ -> X.invalid "invalid linear envelope" +objectParts _=X.invalid "expected linear object" +asMatrix :: forall a. Coefficient a => X.Value -> IO(M.Matrix a) +asMatrix (X.Dense(X.SomeMatrix _ matrix))=maybe (X.invalid "matrix coefficient types differ") pure (cast matrix) +asMatrix _=X.invalid "expected Matrix" +withWitness :: X.Value -> (forall a. Coefficient a => ScalarType a -> IO X.Value) -> IO X.Value +withWitness (X.Scalar witness _) action=action witness +withWitness _ _=X.invalid "expected scalar coefficient prototype" +source :: Either E.MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +forceFields :: [IO X.Value] -> IO () +forceFields fields=sequence fields >>= mapM_ X.forceValue +fractional :: forall a. Coefficient a => ScalarType a -> (Fractional a => IO X.Value) -> IO X.Value +fractional _ action=case fractionalDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires Fractional coefficients" +realFloat :: forall a. Coefficient a => ScalarType a -> (RealFloat a => IO X.Value) -> IO X.Value +realFloat _ action=case realFloatDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires RealFloat coefficients" +ordered :: forall a. Coefficient a => ScalarType a -> (Ord a => IO X.Value) -> IO X.Value +ordered _ action=case orderingDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires ordered coefficients" +withComplex :: forall a. Coefficient a => ScalarType a -> (Coefficient(Complex a) => ScalarType(Complex a) -> IO X.Value) -> IO X.Value +withComplex SFloat action=action SComplexFloat +withComplex SDouble action=action SComplexDouble +withComplex _ _=X.unsupported "complex component must retain original Float/Double RealFloat type" +linearBoundary :: IO CInt -> IO CInt +linearBoundary action=Boundary.boundary $ callbackBoundary (\e -> Boundary.checked(Left e)(const(pure ()))) action + +data SomeFixed a where + SomeFixed :: KnownNat n => V.FixedVector n a -> SomeFixed a +fixedFrom :: forall a. Coefficient a => ScalarType a -> Int -> [a] -> IO X.Value +fixedFrom w count values=case someNatVal(toInteger count) of + Nothing -> X.invalid "fixed dimension cannot be a negative type-level natural" + Just(SomeNat(_::Proxy n)) -> do + result <- source(V.fixedVector values :: Either E.MathError(V.FixedVector n a)) + encodeFixedVector w (SomeFixed result) + +encodeVector :: Coefficient a => ScalarType a -> (V.Vector a) -> IO X.Value +encodeVector w value=pure(opaque "HMath.Vector.Vector" (scalarTypeCode w) value force view) + where + force=forceFields [X.List <$> mapM (\item1 -> pure (X.Scalar w item1)) (V.vectorValues value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeFixedVector :: Coefficient a => ScalarType a -> (SomeFixed a) -> IO X.Value +encodeFixedVector w value=pure(opaque "HMath.Vector.FixedVector" (scalarTypeCode w) value force view) + where + force=case value of SomeFixed fixed -> forceFields [X.List <$> mapM (\item2 -> pure (X.Scalar w item2)) (V.fixedValues fixed)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseVector :: Coefficient a => ScalarType a -> (V.SparseVector a) -> IO X.Value +encodeSparseVector w value=pure(opaque "HMath.Vector.SparseVector" (scalarTypeCode w) value force view) + where + force=evaluate value >> pure () + view=X.unsupported "original abstract type has no public constructor fields" + +encodeBidiagonal :: Coefficient a => ScalarType a -> (D.Bidiagonal a) -> IO X.Value +encodeBidiagonal w value=pure(opaque "HMath.Matrix.Decomposition.Bidiagonal" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix w (D.bidiagonalU value))),pure (X.Dense (X.SomeMatrix w (D.bidiagonalB value))),pure (X.Dense (X.SomeMatrix w (D.bidiagonalV value)))] + view=case value of + D.Bidiagonal field3 field4 field5 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix w field3)),pure (X.Dense (X.SomeMatrix w field4)),pure (X.Dense (X.SomeMatrix w field5))] + pure(X.Tuple[X.Text "Bidiagonal",X.Tuple values]) + +encodeIteration :: Coefficient a => ScalarType a -> (D.Iteration a) -> IO X.Value +encodeIteration w value=pure(opaque "HMath.Matrix.Decomposition.Iteration" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Scalar w (D.iterationValue value)),X.List <$> mapM (\item6 -> pure (X.Scalar w item6)) (D.iterationVector value),pure (X.Scalar w (D.iterationResidual value)),pure (X.Index (D.iterationCount value))] + view=case value of + D.Iteration field7 field8 field9 field10 -> do + values <- sequence [pure (X.Scalar w field7),X.List <$> mapM (\item11 -> pure (X.Scalar w item11)) field8,pure (X.Scalar w field9),pure (X.Index field10)] + pure(X.Tuple[X.Text "Iteration",X.Tuple values]) + +encodeArnoldi :: Coefficient a => ScalarType a -> (D.Arnoldi a) -> IO X.Value +encodeArnoldi w value=pure(opaque "HMath.Matrix.Decomposition.Arnoldi" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix w (D.arnoldiBasis value))),pure (X.Dense (X.SomeMatrix w (D.arnoldiHessenberg value)))] + view=case value of + D.Arnoldi field12 field13 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix w field12)),pure (X.Dense (X.SomeMatrix w field13))] + pure(X.Tuple[X.Text "Arnoldi",X.Tuple values]) + +encodeIterativeOptions :: Coefficient a => ScalarType a -> (I.IterativeOptions a) -> IO X.Value +encodeIterativeOptions w value=pure(opaque "HMath.Matrix.Iterative.IterativeOptions" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Scalar w (I.absoluteTolerance value)),pure (X.Scalar w (I.relativeTolerance value)),pure (X.Index (I.maximumIterations value))] + view=case value of + I.IterativeOptions field14 field15 field16 -> do + values <- sequence [pure (X.Scalar w field14),pure (X.Scalar w field15),pure (X.Index field16)] + pure(X.Tuple[X.Text "IterativeOptions",X.Tuple values]) + +encodeIterativeResult :: Coefficient a => ScalarType a -> (I.IterativeResult a) -> IO X.Value +encodeIterativeResult w value=pure(opaque "HMath.Matrix.Iterative.IterativeResult" (scalarTypeCode w) value force view) + where + force=forceFields [X.List <$> mapM (\item17 -> pure (X.Scalar w item17)) (I.iterativeSolution value),pure (X.Index (I.iterativeIterations value)),pure (X.Scalar w (I.iterativeResidualNorm value)),pure (X.Scalar w (I.iterativeNormalResidualNorm value))] + view=case value of + I.IterativeResult field18 field19 field20 field21 -> do + values <- sequence [X.List <$> mapM (\item22 -> pure (X.Scalar w item22)) field18,pure (X.Index field19),pure (X.Scalar w field20),pure (X.Scalar w field21)] + pure(X.Tuple[X.Text "IterativeResult",X.Tuple values]) + +encodePreconditioner :: Coefficient a => ScalarType a -> (I.Preconditioner a) -> IO X.Value +encodePreconditioner w value=pure(opaque "HMath.Matrix.Iterative.Preconditioner" (scalarTypeCode w) value force view) + where + force=evaluate value >> pure () + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSVD :: (L.SVD) -> IO X.Value +encodeSVD value=pure(opaque "HMath.Matrix.LAPACK.SVD" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SDouble (L.svdU value))),X.List <$> mapM (\item23 -> pure (X.Scalar SDouble item23)) (L.singularValues value),pure (X.Dense (X.SomeMatrix SDouble (L.svdVT value)))] + view=case value of + L.SVD field24 field25 field26 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SDouble field24)),X.List <$> mapM (\item27 -> pure (X.Scalar SDouble item27)) field25,pure (X.Dense (X.SomeMatrix SDouble field26))] + pure(X.Tuple[X.Text "SVD",X.Tuple values]) + +encodeEigen :: (L.Eigen) -> IO X.Value +encodeEigen value=pure(opaque "HMath.Matrix.LAPACK.Eigen" (-1) value force view) + where + force=forceFields [X.List <$> mapM (\item28 -> pure (X.Scalar SComplexDouble item28)) (L.eigenvalues value),pure (X.Dense (X.SomeMatrix SComplexDouble (L.eigenvectors value)))] + view=case value of + L.Eigen field29 field30 -> do + values <- sequence [X.List <$> mapM (\item31 -> pure (X.Scalar SComplexDouble item31)) field29,pure (X.Dense (X.SomeMatrix SComplexDouble field30))] + pure(X.Tuple[X.Text "Eigen",X.Tuple values]) + +encodeGeneralizedEigen :: (L.GeneralizedEigen) -> IO X.Value +encodeGeneralizedEigen value=pure(opaque "HMath.Matrix.LAPACK.GeneralizedEigen" (-1) value force view) + where + force=forceFields [X.List <$> mapM (\item32 -> pure (X.Scalar SComplexDouble item32)) (L.eigenAlpha value),X.List <$> mapM (\item33 -> pure (X.Scalar SDouble item33)) (L.eigenBeta value),pure (X.Dense (X.SomeMatrix SComplexDouble (L.generalizedEigenvectors value)))] + view=case value of + L.GeneralizedEigen field34 field35 field36 -> do + values <- sequence [X.List <$> mapM (\item37 -> pure (X.Scalar SComplexDouble item37)) field34,X.List <$> mapM (\item38 -> pure (X.Scalar SDouble item38)) field35,pure (X.Dense (X.SomeMatrix SComplexDouble field36))] + pure(X.Tuple[X.Text "GeneralizedEigen",X.Tuple values]) + +encodeSchur :: (L.Schur) -> IO X.Value +encodeSchur value=pure(opaque "HMath.Matrix.LAPACK.Schur" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SDouble (L.schurQ value))),pure (X.Dense (X.SomeMatrix SDouble (L.schurT value))),X.List <$> mapM (\item39 -> pure (X.Scalar SComplexDouble item39)) (L.schurEigenvalues value)] + view=case value of + L.Schur field40 field41 field42 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SDouble field40)),pure (X.Dense (X.SomeMatrix SDouble field41)),X.List <$> mapM (\item43 -> pure (X.Scalar SComplexDouble item43)) field42] + pure(X.Tuple[X.Text "Schur",X.Tuple values]) + +encodeQZ :: (L.QZ) -> IO X.Value +encodeQZ value=pure(opaque "HMath.Matrix.LAPACK.QZ" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SDouble (L.qzQ value))),pure (X.Dense (X.SomeMatrix SDouble (L.qzZ value))),pure (X.Dense (X.SomeMatrix SDouble (L.qzS value))),pure (X.Dense (X.SomeMatrix SDouble (L.qzT value))),X.List <$> mapM (\item44 -> pure (X.Scalar SComplexDouble item44)) (L.qzAlpha value),X.List <$> mapM (\item45 -> pure (X.Scalar SDouble item45)) (L.qzBeta value)] + view=case value of + L.QZ field46 field47 field48 field49 field50 field51 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SDouble field46)),pure (X.Dense (X.SomeMatrix SDouble field47)),pure (X.Dense (X.SomeMatrix SDouble field48)),pure (X.Dense (X.SomeMatrix SDouble field49)),X.List <$> mapM (\item52 -> pure (X.Scalar SComplexDouble item52)) field50,X.List <$> mapM (\item53 -> pure (X.Scalar SDouble item53)) field51] + pure(X.Tuple[X.Text "QZ",X.Tuple values]) + +encodeHessenberg :: (L.Hessenberg) -> IO X.Value +encodeHessenberg value=pure(opaque "HMath.Matrix.LAPACK.Hessenberg" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SDouble (L.hessenbergQ value))),pure (X.Dense (X.SomeMatrix SDouble (L.hessenbergH value)))] + view=case value of + L.Hessenberg field54 field55 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SDouble field54)),pure (X.Dense (X.SomeMatrix SDouble field55))] + pure(X.Tuple[X.Text "Hessenberg",X.Tuple values]) + +encodeBalance :: (L.Balance) -> IO X.Value +encodeBalance value=pure(opaque "HMath.Matrix.LAPACK.Balance" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SDouble (L.balancedMatrix value))),X.List <$> mapM (\item56 -> pure (X.Scalar SDouble item56)) (L.balanceScales value)] + view=case value of + L.Balance field57 field58 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SDouble field57)),X.List <$> mapM (\item59 -> pure (X.Scalar SDouble item59)) field58] + pure(X.Tuple[X.Text "Balance",X.Tuple values]) + +encodeComplexSVD :: (L.ComplexSVD) -> IO X.Value +encodeComplexSVD value=pure(opaque "HMath.Matrix.LAPACK.ComplexSVD" (-1) value force view) + where + force=forceFields [pure (X.Dense (X.SomeMatrix SComplexDouble (L.complexU value))),X.List <$> mapM (\item60 -> pure (X.Scalar SDouble item60)) (L.complexSingularValues value),pure (X.Dense (X.SomeMatrix SComplexDouble (L.complexVT value)))] + view=case value of + L.ComplexSVD field61 field62 field63 -> do + values <- sequence [pure (X.Dense (X.SomeMatrix SComplexDouble field61)),X.List <$> mapM (\item64 -> pure (X.Scalar SDouble item64)) field62,pure (X.Dense (X.SomeMatrix SComplexDouble field63))] + pure(X.Tuple[X.Text "ComplexSVD",X.Tuple values]) + +encodeSparse :: Coefficient a => ScalarType a -> (S.Sparse a) -> IO X.Value +encodeSparse w value=pure(opaque "HMath.Sparse.Sparse" (scalarTypeCode w) value force view) + where + force=forceFields [X.List <$> mapM (\item65 -> (\(part66,part67,part68) -> X.Tuple <$> sequence [pure (X.Index part66),pure (X.Index part67),pure (X.Scalar w part68)]) item65) (S.sparseEntries value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseFormat :: Coefficient a => ScalarType a -> (S.SparseFormat a) -> IO X.Value +encodeSparseFormat w value=pure(opaque "HMath.Sparse.SparseFormat" (scalarTypeCode w) value force view) + where + force=case value of + S.COO field69 field70 field71 -> forceFields [pure (X.Index field69),pure (X.Index field70),X.List <$> mapM (\item72 -> (\(part73,part74,part75) -> X.Tuple <$> sequence [pure (X.Index part73),pure (X.Index part74),pure (X.Scalar w part75)]) item72) field71] + S.CSR field76 field77 field78 field79 field80 -> forceFields [pure (X.Index field76),pure (X.Index field77),X.List <$> mapM (\item81 -> pure (X.Index item81)) field78,X.List <$> mapM (\item82 -> pure (X.Index item82)) field79,X.List <$> mapM (\item83 -> pure (X.Scalar w item83)) field80] + S.CSC field84 field85 field86 field87 field88 -> forceFields [pure (X.Index field84),pure (X.Index field85),X.List <$> mapM (\item89 -> pure (X.Index item89)) field86,X.List <$> mapM (\item90 -> pure (X.Index item90)) field87,X.List <$> mapM (\item91 -> pure (X.Scalar w item91)) field88] + S.DIA field92 field93 field94 -> forceFields [pure (X.Index field92),pure (X.Index field93),X.List <$> mapM (\item95 -> (\(part96,part97) -> X.Tuple <$> sequence [pure (X.Index part96),X.List <$> mapM (\item98 -> pure (X.Scalar w item98)) part97]) item95) field94] + S.BSR field99 field100 field101 field102 field103 field104 field105 -> forceFields [pure (X.Index field99),pure (X.Index field100),pure (X.Index field101),pure (X.Index field102),X.List <$> mapM (\item106 -> pure (X.Index item106)) field103,X.List <$> mapM (\item107 -> pure (X.Index item107)) field104,X.List <$> mapM (\item108 -> X.List <$> mapM (\item109 -> pure (X.Scalar w item109)) item108) field105] + S.ELLPACK field110 field111 field112 field113 field114 -> forceFields [pure (X.Index field110),pure (X.Index field111),pure (X.Index field112),X.List <$> mapM (\item115 -> pure (X.Index item115)) field113,X.List <$> mapM (\item116 -> pure (X.Scalar w item116)) field114] + view=case value of + S.COO field117 field118 field119 -> do + values <- sequence [pure (X.Index field117),pure (X.Index field118),X.List <$> mapM (\item120 -> (\(part121,part122,part123) -> X.Tuple <$> sequence [pure (X.Index part121),pure (X.Index part122),pure (X.Scalar w part123)]) item120) field119] + pure(X.Tuple[X.Text "COO",X.Tuple values]) + S.CSR field124 field125 field126 field127 field128 -> do + values <- sequence [pure (X.Index field124),pure (X.Index field125),X.List <$> mapM (\item129 -> pure (X.Index item129)) field126,X.List <$> mapM (\item130 -> pure (X.Index item130)) field127,X.List <$> mapM (\item131 -> pure (X.Scalar w item131)) field128] + pure(X.Tuple[X.Text "CSR",X.Tuple values]) + S.CSC field132 field133 field134 field135 field136 -> do + values <- sequence [pure (X.Index field132),pure (X.Index field133),X.List <$> mapM (\item137 -> pure (X.Index item137)) field134,X.List <$> mapM (\item138 -> pure (X.Index item138)) field135,X.List <$> mapM (\item139 -> pure (X.Scalar w item139)) field136] + pure(X.Tuple[X.Text "CSC",X.Tuple values]) + S.DIA field140 field141 field142 -> do + values <- sequence [pure (X.Index field140),pure (X.Index field141),X.List <$> mapM (\item143 -> (\(part144,part145) -> X.Tuple <$> sequence [pure (X.Index part144),X.List <$> mapM (\item146 -> pure (X.Scalar w item146)) part145]) item143) field142] + pure(X.Tuple[X.Text "DIA",X.Tuple values]) + S.BSR field147 field148 field149 field150 field151 field152 field153 -> do + values <- sequence [pure (X.Index field147),pure (X.Index field148),pure (X.Index field149),pure (X.Index field150),X.List <$> mapM (\item154 -> pure (X.Index item154)) field151,X.List <$> mapM (\item155 -> pure (X.Index item155)) field152,X.List <$> mapM (\item156 -> X.List <$> mapM (\item157 -> pure (X.Scalar w item157)) item156) field153] + pure(X.Tuple[X.Text "BSR",X.Tuple values]) + S.ELLPACK field158 field159 field160 field161 field162 -> do + values <- sequence [pure (X.Index field158),pure (X.Index field159),pure (X.Index field160),X.List <$> mapM (\item163 -> pure (X.Index item163)) field161,X.List <$> mapM (\item164 -> pure (X.Scalar w item164)) field162] + pure(X.Tuple[X.Text "ELLPACK",X.Tuple values]) + +encodeSparseLU :: Coefficient a => ScalarType a -> (S.SparseLU a) -> IO X.Value +encodeSparseLU w value=pure(opaque "HMath.Sparse.SparseLU" (scalarTypeCode w) value force view) + where + force=forceFields [encodeSparse w (S.sparseLULower value),encodeSparse w (S.sparseLUUpper value),X.List <$> mapM (\item165 -> pure (X.Index item165)) (S.sparseLUPermutation value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseQR :: Coefficient a => ScalarType a -> (S.SparseQR a) -> IO X.Value +encodeSparseQR w value=pure(opaque "HMath.Sparse.SparseQR" (scalarTypeCode w) value force view) + where + force=forceFields [encodeSparse w (S.sparseQRUpper value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseTensor :: Coefficient a => ScalarType a -> (S.SparseTensor a) -> IO X.Value +encodeSparseTensor w value=pure(opaque "HMath.Sparse.SparseTensor" (scalarTypeCode w) value force view) + where + force=forceFields [X.List <$> mapM (\item166 -> (\(part167,part168) -> X.Tuple <$> sequence [X.List <$> mapM (\item169 -> pure (X.Index item169)) part167,pure (X.Scalar w part168)]) item166) (S.sparseTensorEntries value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeSparseSpectralOptions :: Coefficient a => ScalarType a -> (P.SparseSpectralOptions a) -> IO X.Value +encodeSparseSpectralOptions w value=pure(opaque "HMath.Sparse.Spectral.SparseSpectralOptions" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Scalar w (P.sparseAbsoluteTolerance value)),pure (X.Scalar w (P.sparseRelativeTolerance value)),pure (X.Index (P.sparseIterationLimit value)),pure (X.Scalar SInteger (P.sparseWorkspaceLimit value))] + view=case value of + P.SparseSpectralOptions field170 field171 field172 field173 -> do + values <- sequence [pure (X.Scalar w field170),pure (X.Scalar w field171),pure (X.Index field172),pure (X.Scalar SInteger field173)] + pure(X.Tuple[X.Text "SparseSpectralOptions",X.Tuple values]) + +encodeSparseEigenResult :: Coefficient a => ScalarType a -> (P.SparseEigenResult a) -> IO X.Value +encodeSparseEigenResult w value=pure(opaque "HMath.Sparse.Spectral.SparseEigenResult" (scalarTypeCode w) value force view) + where + force=forceFields [pure (X.Scalar w (P.sparseEigenvalue value)),X.List <$> mapM (\item174 -> pure (X.Scalar w item174)) (P.sparseEigenvector value),pure (X.Scalar w (P.sparseEigenResidual value)),pure (X.Index (P.sparseEigenIterations value))] + view=case value of + P.SparseEigenResult field175 field176 field177 field178 -> do + values <- sequence [pure (X.Scalar w field175),X.List <$> mapM (\item179 -> pure (X.Scalar w item179)) field176,pure (X.Scalar w field177),pure (X.Index field178)] + pure(X.Tuple[X.Text "SparseEigenResult",X.Tuple values]) + +encodeSparseSVD :: Coefficient a => ScalarType a -> (P.SparseSVD a) -> IO X.Value +encodeSparseSVD w value=pure(opaque "HMath.Sparse.Spectral.SparseSVD" (scalarTypeCode w) value force view) + where + force=forceFields [X.List <$> mapM (\item180 -> pure (X.Scalar w item180)) (P.sparseSingularValues value),X.List <$> mapM (\item181 -> X.List <$> mapM (\item182 -> pure (X.Scalar w item182)) item181) (P.sparseLeftVectors value),X.List <$> mapM (\item183 -> X.List <$> mapM (\item184 -> pure (X.Scalar w item184)) item183) (P.sparseRightVectors value),X.List <$> mapM (\item185 -> (\(part186,part187) -> X.Tuple <$> sequence [pure (X.Scalar w part186),pure (X.Scalar w part187)]) item185) (P.sparseSingularResiduals value),X.List <$> mapM (\item188 -> pure (X.Index item188)) (P.sparseSingularIterations value)] + view=case value of + P.SparseSVD field189 field190 field191 field192 field193 -> do + values <- sequence [X.List <$> mapM (\item194 -> pure (X.Scalar w item194)) field189,X.List <$> mapM (\item195 -> X.List <$> mapM (\item196 -> pure (X.Scalar w item196)) item195) field190,X.List <$> mapM (\item197 -> X.List <$> mapM (\item198 -> pure (X.Scalar w item198)) item197) field191,X.List <$> mapM (\item199 -> (\(part200,part201) -> X.Tuple <$> sequence [pure (X.Scalar w part200),pure (X.Scalar w part201)]) item199) field192,X.List <$> mapM (\item202 -> pure (X.Index item202)) field193] + pure(X.Tuple[X.Text "SparseSVD",X.Tuple values]) + +encodeProvider :: (B.Provider) -> IO X.Value +encodeProvider value=pure(opaque "HMath.Backend.Provider" (-1) value force view) + where + force=evaluate value >> pure () + view=case value of + B.Pure -> do + values <- sequence [] + pure(X.Tuple[X.Text "Pure",X.Tuple values]) + B.OpenBLAS -> do + values <- sequence [] + pure(X.Tuple[X.Text "OpenBLAS",X.Tuple values]) + B.BLIS -> do + values <- sequence [] + pure(X.Tuple[X.Text "BLIS",X.Tuple values]) + B.OneMKL -> do + values <- sequence [] + pure(X.Tuple[X.Text "OneMKL",X.Tuple values]) + B.Accelerate -> do + values <- sequence [] + pure(X.Tuple[X.Text "Accelerate",X.Tuple values]) + +encodeIntegerABI :: (B.IntegerABI) -> IO X.Value +encodeIntegerABI value=pure(opaque "HMath.Backend.IntegerABI" (-1) value force view) + where + force=evaluate value >> pure () + view=case value of + B.LP64 -> do + values <- sequence [] + pure(X.Tuple[X.Text "LP64",X.Tuple values]) + B.ILP64 -> do + values <- sequence [] + pure(X.Tuple[X.Text "ILP64",X.Tuple values]) + +encodeBackendRequest :: (B.BackendRequest) -> IO X.Value +encodeBackendRequest value=pure(opaque "HMath.Backend.BackendRequest" (-1) value force view) + where + force=evaluate value >> pure () + view=case value of + B.AutoBackend -> do + values <- sequence [] + pure(X.Tuple[X.Text "AutoBackend",X.Tuple values]) + B.RequireBackend field203 field204 field205 -> do + values <- sequence [encodeProvider field203,encodeIntegerABI field204,(case field205 of {Nothing -> pure X.None;Just item206 -> pure (X.Text item206)})] + pure(X.Tuple[X.Text "RequireBackend",X.Tuple values]) + +encodeBackendInfo :: (B.BackendInfo) -> IO X.Value +encodeBackendInfo value=pure(opaque "HMath.Backend.BackendInfo" (-1) value force view) + where + force=forceFields [encodeProvider (B.selectedProvider value),encodeIntegerABI (B.selectedIntegerABI value)] + view=case value of + B.BackendInfo field207 field208 -> do + values <- sequence [encodeProvider field207,encodeIntegerABI field208] + pure(X.Tuple[X.Text "BackendInfo",X.Tuple values]) + +encodeBackend :: (B.Backend) -> IO X.Value +encodeBackend value=pure(opaque "HMath.Backend.Backend" (-1) value force view) + where + force=forceFields [encodeBackendInfo (B.backendInfo value)] + view=X.unsupported "original abstract type has no public constructor fields" + +encodeBackendLayout :: (B.BackendLayout) -> IO X.Value +encodeBackendLayout value=pure(opaque "HMath.Backend.BackendLayout" (-1) value force view) + where + force=evaluate value >> pure () + view=case value of + B.RowMajor -> do + values <- sequence [] + pure(X.Tuple[X.Text "RowMajor",X.Tuple values]) + B.ColumnMajor -> do + values <- sequence [] + pure(X.Tuple[X.Text "ColumnMajor",X.Tuple values]) + +encodeTranspose :: (B.Transpose) -> IO X.Value +encodeTranspose value=pure(opaque "HMath.Backend.Transpose" (-1) value force view) + where + force=evaluate value >> pure () + view=case value of + B.NoTranspose -> do + values <- sequence [] + pure(X.Tuple[X.Text "NoTranspose",X.Tuple values]) + B.Transpose -> do + values <- sequence [] + pure(X.Tuple[X.Text "Transpose",X.Tuple values]) + B.ConjugateTranspose -> do + values <- sequence [] + pure(X.Tuple[X.Text "ConjugateTranspose",X.Tuple values]) + +encodeLegacyLU :: LU.LU Double -> IO X.Value +encodeLegacyLU value=pure(opaque "HMath.Matrix.LU.LU" 0 value (forceFields [pure(X.Dense(X.SomeMatrix SDouble(LU.luLower value))),pure(X.Dense(X.SomeMatrix SDouble(LU.luUpper value)))]) (X.unsupported "abstract LU constructor")) +encodeLegacyQR :: QR.QR Double -> IO X.Value +encodeLegacyQR value=pure(opaque "HMath.Matrix.QR.QR" 0 value (forceFields [pure(X.Dense(X.SomeMatrix SDouble(QR.qrR value)))]) (X.unsupported "abstract QR constructor")) +foreign export ccall "hm_linear_legacy" legacy :: StablePtr X.Value -> Ptr CInt -> Ptr(StablePtr Legacy.Object) -> IO CInt +legacy :: StablePtr X.Value -> Ptr CInt -> Ptr(StablePtr Legacy.Object) -> IO CInt +legacy pointer kind out=linearBoundary $ do + value <- deRefStablePtr pointer + name <- objectName value + case name of + "HMath.Matrix.LU.LU" -> do + result <- unbox name value + Boundary.checked(Right())(const(Legacy.publish(Legacy.L64 result) out >> poke kind 2)) + "HMath.Matrix.QR.QR" -> do + result <- unbox name value + Boundary.checked(Right())(const(Legacy.publish(Legacy.Q64 result) out >> poke kind 3)) + _ -> X.invalid "expected original LU/QR result" +foreign export ccall "hm_linear_clone" clone :: StablePtr X.Value -> Ptr(StablePtr X.Value) -> IO CInt +clone :: StablePtr X.Value -> Ptr(StablePtr X.Value) -> IO CInt +clone pointer out=linearBoundary $ do + value <- deRefStablePtr pointer + Boundary.checked(Right())(const(X.publish value out)) + +data Callback=Callback (FunPtr ()) (Ptr ()) +foreign import ccall safe "hm_linear_invoke_callback" + invokeCallback :: FunPtr () -> Ptr () -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> Ptr () -> IO CInt +callbackValue :: X.Value -> X.Value -> IO X.Value +callbackValue (X.Opaque 101 _ _ _ payload) argument=case cast payload of + Just(Callback function userdata) -> do + X.forceValue argument + bracket (newStablePtr argument) freeStablePtr $ \input -> alloca $ \out -> withMathErrorWire $ \wire -> do + status <- invokeCallback function userdata input out wire + if status/=0 then readCallbackFailure status wire >>= throwIO + else peek out >>= \pointer -> bracket(pure pointer) freeStablePtr deRefStablePtr + Nothing -> X.invalid "invalid linear callback payload" +callbackValue _ _=X.invalid "expected linear callback" +foreign export ccall "hm_linear_callback" createCallback :: FunPtr () -> Ptr () -> Ptr(StablePtr X.Value) -> IO CInt +createCallback :: FunPtr () -> Ptr () -> Ptr(StablePtr X.Value) -> IO CInt +createCallback pointer userdata out=linearBoundary $ Boundary.checked(Right()) $ const $ X.publish (X.Opaque 101 (-1) 0 (pure()) (Callback pointer userdata)) out + +-- Non-Num vectors retain actual original structural values and their codec. +data StructuralVector where + StructuralVector :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> V.Vector a -> StructuralVector +data StructuralFixed where + StructuralFixed :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> SomeFixed a -> StructuralFixed +encodeStructuralVector :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> V.Vector a -> X.Value +encodeStructuralVector code write readValue force value=opaque "HMath.Vector.Vector" code (StructuralVector code write readValue force value)(mapM_ force(V.vectorValues value))(X.unsupported "original Vector is abstract") +encodeStructuralFixed :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> SomeFixed a -> X.Value +encodeStructuralFixed code write readValue force value=opaque "HMath.Vector.FixedVector" code (StructuralFixed code write readValue force value)(case value of SomeFixed fixed -> mapM_ force(V.fixedValues fixed))(X.unsupported "original FixedVector is abstract") +asStructuralVector :: X.Value -> IO StructuralVector +asStructuralVector=unbox "HMath.Vector.Vector" +asStructuralFixed :: X.Value -> IO StructuralFixed +asStructuralFixed=unbox "HMath.Vector.FixedVector" +structuralVectorValue :: X.Value -> Bool +structuralVectorValue(X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope _ dynamic _) -> case(fromDynamic dynamic::Maybe StructuralVector,fromDynamic dynamic::Maybe StructuralFixed)of + (Just _,_) -> True + (_,Just _) -> True + _ -> False + _ -> False +structuralVectorValue(X.List values)=any structuralVectorValue values +structuralVectorValue _=False +structuralVectorInput :: X.Value -> [X.Value] -> Bool +structuralVectorInput prototype args=structuralVectorValue prototype || any structuralVectorValue args || case prototype of + X.Boolean _ -> True + X.Text _ -> True + X.Opaque 294 _ _ _ _ -> True + _ -> False +withStructuralVector :: X.Value -> [X.Value] -> (forall a. Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> IO X.Value) -> IO X.Value +withStructuralVector prototype args action=case filter structuralVectorValue(prototype:concatMap flatten args) of + first:_ -> do + name <- objectName first + if name=="HMath.Vector.Vector" then do + StructuralVector code write readValue force _ <- asStructuralVector first + action code write readValue force + else do + StructuralFixed code write readValue force _ <- asStructuralFixed first + action code write readValue force + [] -> do + TensorCodec.SomeElement kind <- TensorCodec.element prototype + action(TensorCodec.elementCode kind)(pure . TensorCodec.scalar kind)(TensorCodec.asElement kind)(TensorCodec.forceElement kind) + where + flatten(X.List xs)=concatMap flatten xs + flatten value=[value] +structuralVectors :: Int -> X.Value -> [X.Value] -> IO X.Value +structuralVectors operation prototype args=withStructuralVector prototype args $ \code write readValue force -> case(operation,args)of + (0,[values]) -> X.asList values >>= mapM readValue >>= pure . encodeStructuralVector code write readValue force . V.vector + (1,[value]) -> do + StructuralVector _ _ _ _ raw <- asStructuralVector value + case cast raw of + Just vector -> X.List <$> mapM write(V.vectorValues vector) + Nothing -> X.invalid "structural Vector element types differ" + (2,[value]) -> do StructuralVector _ _ _ _ raw <- asStructuralVector value;pure(X.Index(V.vectorDimension raw)) + (7,[start,count,value]) -> do + s <- X.asIndex start;n <- X.asIndex count + StructuralVector _ _ _ _ raw <- asStructuralVector value + case cast raw of + Just vector -> encodeStructuralVector code write readValue force <$> source(V.vectorSlice s n vector) + Nothing -> X.invalid "structural Vector element types differ" + (8,[values]) -> do + xs <- X.asList values >>= mapM(\value -> do StructuralVector _ _ _ _ raw <- asStructuralVector value;maybe(X.invalid "structural Vector element types differ")pure(cast raw)) + encodeStructuralVector code write readValue force <$> source(V.vectorConcat xs) + (3,[count,values]) -> do + n <- X.asIndex count;xs <- X.asList values >>= mapM readValue + structuralFixedFrom code write readValue force n xs + (4,[value]) -> do + StructuralFixed _ _ _ _ raw <- asStructuralFixed value + case cast raw of + Just(SomeFixed fixed) -> X.List <$>mapM write(V.fixedValues fixed) + Nothing -> X.invalid "structural FixedVector element types differ" + _ -> X.unsupported "original vector operation requires a numeric instance" +structuralFixedFrom :: forall a. Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> Int -> [a] -> IO X.Value +structuralFixedFrom code write readValue force n xs=case someNatVal(toInteger n)of + Nothing -> X.invalid "fixed dimension must be nonnegative" + Just(SomeNat(_::Proxy k)) -> do + result <- source(V.fixedVector xs::Either E.MathError(V.FixedVector k a)) + pure(encodeStructuralFixed code write readValue force(SomeFixed result)) diff --git a/src/HMath/FFI/MachineLearning.hs b/src/HMath/FFI/MachineLearning.hs new file mode 100644 index 0000000..4181a95 --- /dev/null +++ b/src/HMath/FFI/MachineLearning.hs @@ -0,0 +1,385 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_machinelearning_bindings.py. +module HMath.FFI.MachineLearning where +import Foreign +import Foreign.C +import qualified HMath.Error as E +import qualified HMath.FFI.Boundary as B +import qualified HMath.FFI.NumericalCodec as N +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.MachineLearning.Codec as C +import HMath.FFI.MachineLearning.Types () +import qualified HMath.MachineLearning as M +foreign export ccall "hm_ml_describe" describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +describe input out = B.boundary $ do + value <- deRefStablePtr input + text <- case V.valueInfo value of + (310,_,_) -> show <$> (N.from value :: IO M.ClusterModel) + (311,_,_) -> show <$> (N.from value :: IO M.GaussianMixture) + (312,_,_) -> show <$> (N.from value :: IO M.Linkage) + (313,_,_) -> show <$> (N.from value :: IO M.Merge) + (314,_,_) -> show <$> (N.from value :: IO M.CCA) + (315,_,_) -> show <$> (N.from value :: IO M.FactorAnalysis) + (316,_,_) -> show <$> (N.from value :: IO M.ICA) + (317,_,_) -> show <$> (N.from value :: IO M.IncrementalPCA) + (318,_,_) -> show <$> (N.from value :: IO M.KernelPCA) + (319,_,_) -> show <$> (N.from value :: IO M.PCA) + (320,_,_) -> show <$> (N.from value :: IO M.PLS) + (322,_,_) -> show <$> (N.from value :: IO M.MLConfig) + (323,_,_) -> show <$> (N.from value :: IO M.IndexKind) + (324,_,_) -> show <$> (N.from value :: IO M.IsolationForest) + (325,_,_) -> show <$> (N.from value :: IO M.LSH) + (326,_,_) -> show <$> (N.from value :: IO M.NeighborResult) + (327,_,_) -> show <$> (N.from value :: IO M.OneClassSVM) + (328,_,_) -> show <$> (N.from value :: IO M.SpatialIndex) + (330,_,_) -> show <$> (N.from value :: IO M.Fold) + (331,_,_) -> show <$> (N.from value :: IO M.Imputation) + (332,_,_) -> show <$> (N.from value :: IO M.Imputer) + (333,_,_) -> show <$> (N.from value :: IO M.PowerTransform) + (334,_,_) -> show <$> (N.from value :: IO M.QuantileTransformer) + (335,_,_) -> show <$> (N.from value :: IO M.Scaler) + (336,_,_) -> show <$> (N.from value :: IO M.Scaling) + (337,_,_) -> show <$> (N.from value :: IO M.UnknownCategory) + (338,_,_) -> show <$> (N.from value :: IO M.BayesFamily) + (339,_,_) -> show <$> (N.from value :: IO M.BayesianLinear) + (340,_,_) -> show <$> (N.from value :: IO M.Discriminant) + (341,_,_) -> show <$> (N.from value :: IO M.GLM) + (342,_,_) -> show <$> (N.from value :: IO M.GLMFamily) + (343,_,_) -> show <$> (N.from value :: IO M.GPClassifier) + (344,_,_) -> show <$> (N.from value :: IO M.GaussianProcess) + (345,_,_) -> show <$> (N.from value :: IO M.Kernel) + (346,_,_) -> show <$> (N.from value :: IO M.LinearModel) + (347,_,_) -> show <$> (N.from value :: IO M.MultinomialModel) + (348,_,_) -> show <$> (N.from value :: IO M.NaiveBayes) + (349,_,_) -> show <$> (N.from value :: IO M.Penalty) + (350,_,_) -> show <$> (N.from value :: IO M.RecursiveLS) + (351,_,_) -> show <$> (N.from value :: IO M.SVM) + _ -> V.unsupported "use original Fit/Encoder getters for generic payloads" + B.checked (Right (V.Text text)) (`V.publish` out) +foreign export ccall "hm_ml_parts" parts :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +parts :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +parts input out = B.boundary $ do + value <- deRefStablePtr input + result <- case V.valueInfo value of + (312,_,_) -> do + original <- N.from value :: IO M.Linkage + case original of + M.Average -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Average",V.Tuple fields]) + M.Complete -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Complete",V.Tuple fields]) + M.Single -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Single",V.Tuple fields]) + M.Ward -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Ward",V.Tuple fields]) + (313,_,_) -> do + original <- N.from value :: IO M.Merge + case original of + M.Merge field0 field1 field2 field3 -> do + fields <- sequence [N.to field0,N.to field1,N.to field2,N.to field3] + pure (V.Tuple [V.Text "Merge",V.Tuple fields]) + (321,_,_) -> do + original <- N.from value :: IO (M.Fit V.Value) + case original of + M.Fit field0 field1 field2 field3 -> do + fields <- sequence [N.to field0,N.to field1,N.to field2,N.to field3] + pure (V.Tuple [V.Text "Fit",V.Tuple fields]) + (322,_,_) -> do + original <- N.from value :: IO M.MLConfig + case original of + M.MLConfig field0 field1 field2 field3 -> do + fields <- sequence [N.to field0,N.to field1,N.to field2,N.to field3] + pure (V.Tuple [V.Text "MLConfig",V.Tuple fields]) + (323,_,_) -> do + original <- N.from value :: IO M.IndexKind + case original of + M.BallTree -> do + fields <- sequence [] + pure (V.Tuple [V.Text "BallTree",V.Tuple fields]) + M.KDTree -> do + fields <- sequence [] + pure (V.Tuple [V.Text "KDTree",V.Tuple fields]) + (326,_,_) -> do + original <- N.from value :: IO M.NeighborResult + case original of + M.NeighborResult field0 field1 field2 -> do + fields <- sequence [N.to field0,N.to field1,N.to field2] + pure (V.Tuple [V.Text "NeighborResult",V.Tuple fields]) + (330,_,_) -> do + original <- N.from value :: IO M.Fold + case original of + M.Fold field0 field1 -> do + fields <- sequence [N.to field0,N.to field1] + pure (V.Tuple [V.Text "Fold",V.Tuple fields]) + (331,_,_) -> do + original <- N.from value :: IO M.Imputation + case original of + M.ConstantImpute field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "ConstantImpute",V.Tuple fields]) + M.MeanImpute -> do + fields <- sequence [] + pure (V.Tuple [V.Text "MeanImpute",V.Tuple fields]) + M.MedianImpute -> do + fields <- sequence [] + pure (V.Tuple [V.Text "MedianImpute",V.Tuple fields]) + (333,_,_) -> do + original <- N.from value :: IO M.PowerTransform + case original of + M.BoxCox field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "BoxCox",V.Tuple fields]) + M.YeoJohnson field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "YeoJohnson",V.Tuple fields]) + (336,_,_) -> do + original <- N.from value :: IO M.Scaling + case original of + M.MinMax -> do + fields <- sequence [] + pure (V.Tuple [V.Text "MinMax",V.Tuple fields]) + M.RobustScale -> do + fields <- sequence [] + pure (V.Tuple [V.Text "RobustScale",V.Tuple fields]) + M.Standardize -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Standardize",V.Tuple fields]) + (337,_,_) -> do + original <- N.from value :: IO M.UnknownCategory + case original of + M.RejectUnknown -> do + fields <- sequence [] + pure (V.Tuple [V.Text "RejectUnknown",V.Tuple fields]) + M.ZeroUnknown -> do + fields <- sequence [] + pure (V.Tuple [V.Text "ZeroUnknown",V.Tuple fields]) + (338,_,_) -> do + original <- N.from value :: IO M.BayesFamily + case original of + M.BernoulliBayes -> do + fields <- sequence [] + pure (V.Tuple [V.Text "BernoulliBayes",V.Tuple fields]) + M.GaussianBayes -> do + fields <- sequence [] + pure (V.Tuple [V.Text "GaussianBayes",V.Tuple fields]) + M.MultinomialBayes -> do + fields <- sequence [] + pure (V.Tuple [V.Text "MultinomialBayes",V.Tuple fields]) + (342,_,_) -> do + original <- N.from value :: IO M.GLMFamily + case original of + M.BinomialLogit -> do + fields <- sequence [] + pure (V.Tuple [V.Text "BinomialLogit",V.Tuple fields]) + M.PoissonLog -> do + fields <- sequence [] + pure (V.Tuple [V.Text "PoissonLog",V.Tuple fields]) + (345,_,_) -> do + original <- N.from value :: IO M.Kernel + case original of + M.LinearKernel -> do + fields <- sequence [] + pure (V.Tuple [V.Text "LinearKernel",V.Tuple fields]) + M.PolynomialKernel field0 field1 field2 -> do + fields <- sequence [N.to field0,N.to field1,N.to field2] + pure (V.Tuple [V.Text "PolynomialKernel",V.Tuple fields]) + M.RBFKernel field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "RBFKernel",V.Tuple fields]) + (349,_,_) -> do + original <- N.from value :: IO M.Penalty + case original of + M.ElasticNet field0 field1 -> do + fields <- sequence [N.to field0,N.to field1] + pure (V.Tuple [V.Text "ElasticNet",V.Tuple fields]) + M.Lasso field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "Lasso",V.Tuple fields]) + M.Ordinary -> do + fields <- sequence [] + pure (V.Tuple [V.Text "Ordinary",V.Tuple fields]) + M.Ridge field0 -> do + fields <- sequence [N.to field0] + pure (V.Tuple [V.Text "Ridge",V.Tuple fields]) + _ -> V.unsupported "original model type has no public constructor" + B.checked (Right result) (`V.publish` out) +foreign export ccall "hm_ml_apply" apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +apply operation inputs arity prototypePointer out = B.boundary $ do + values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr + prototype <- if castStablePtrToPtr prototypePointer == nullPtr then pure V.None else deRefStablePtr prototypePointer + result <- case operation of + 0 -> N.apply (M.Average :: M.Linkage) values + 1 -> N.apply (M.Complete :: M.Linkage) values + 2 -> N.apply (M.Merge :: Int -> Int -> Double -> Int -> M.Merge) values + 3 -> N.apply (M.Single :: M.Linkage) values + 4 -> N.apply (M.Ward :: M.Linkage) values + 5 -> N.apply (M.affinityPropagation :: M.MLConfig -> Double -> Double -> M.Dataset -> (Either E.MathError ((M.Fit [Int])))) values + 6 -> N.apply (M.clusterCenters :: M.ClusterModel -> M.Dataset) values + 7 -> N.apply (M.cutHierarchy :: Int -> Int -> [M.Merge] -> (Either E.MathError [Int])) values + 8 -> N.apply (M.dbscan :: Double -> Int -> M.Dataset -> (Either E.MathError [Int])) values + 9 -> N.apply (M.extractOPTICS :: Double -> [(Int,(Maybe Double),(Maybe Double))] -> (Either E.MathError [Int])) values + 10 -> N.apply (M.fitGaussianMixture :: M.MLConfig -> Int -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.GaussianMixture)))) values + 11 -> N.apply (M.hierarchical :: M.Linkage -> M.Dataset -> (Either E.MathError [M.Merge])) values + 12 -> N.apply (M.kMeans :: M.MLConfig -> Int -> M.Dataset -> (Either E.MathError ((M.Fit M.ClusterModel)))) values + 13 -> N.apply (M.kMeansPlusPlus :: M.MLConfig -> Int -> M.Dataset -> (Either E.MathError ((M.Fit M.ClusterModel)))) values + 14 -> N.apply (M.kMedoids :: M.MLConfig -> Int -> M.Dataset -> (Either E.MathError ((M.Fit [Int])))) values + 15 -> N.apply (M.leftCluster :: M.Merge -> Int) values + 16 -> N.apply (M.meanShift :: M.MLConfig -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.ClusterModel)))) values + 17 -> N.apply (M.mergeDistance :: M.Merge -> Double) values + 18 -> N.apply (M.mergedSize :: M.Merge -> Int) values + 19 -> N.apply (M.miniBatchKMeans :: M.MLConfig -> Int -> Int -> M.Dataset -> (Either E.MathError ((M.Fit M.ClusterModel)))) values + 20 -> N.apply (M.mixtureCovariances :: M.GaussianMixture -> [M.Dataset]) values + 21 -> N.apply (M.mixtureMeans :: M.GaussianMixture -> M.Dataset) values + 22 -> N.apply (M.mixtureResponsibilities :: M.GaussianMixture -> M.Dataset -> (Either E.MathError M.Dataset)) values + 23 -> N.apply (M.mixtureWeights :: M.GaussianMixture -> [Double]) values + 24 -> N.apply (M.optics :: Double -> Int -> M.Dataset -> (Either E.MathError [(Int,(Maybe Double),(Maybe Double))])) values + 25 -> N.apply (M.predictClusters :: M.ClusterModel -> M.Dataset -> (Either E.MathError [Int])) values + 26 -> N.apply (M.rightCluster :: M.Merge -> Int) values + 27 -> N.apply (M.spectralClustering :: M.MLConfig -> Int -> Double -> M.Dataset -> (Either E.MathError ((M.Fit [Int])))) values + 28 -> N.apply (M.canonicalCorrelations :: M.CCA -> [Double]) values + 29 -> N.apply (M.classicalMDS :: Int -> M.Dataset -> (Either E.MathError M.Dataset)) values + 30 -> N.apply (M.factorLoadings :: M.FactorAnalysis -> M.Dataset) values + 31 -> N.apply (M.factorNoise :: M.FactorAnalysis -> [Double]) values + 32 -> N.apply (M.finishPCA :: Int -> M.IncrementalPCA -> (Either E.MathError M.PCA)) values + 33 -> N.apply (M.fitCCA :: Int -> Double -> M.Dataset -> M.Dataset -> (Either E.MathError M.CCA)) values + 34 -> N.apply (M.fitFactorAnalysis :: M.MLConfig -> Int -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.FactorAnalysis)))) values + 35 -> N.apply (M.fitICA :: M.MLConfig -> Int -> M.Dataset -> (Either E.MathError ((M.Fit M.ICA)))) values + 36 -> N.apply (M.fitKernelPCA :: Int -> M.Kernel -> M.Dataset -> (Either E.MathError M.KernelPCA)) values + 37 -> N.apply (M.fitPCA :: Int -> M.Dataset -> (Either E.MathError M.PCA)) values + 38 -> N.apply (M.fitPLS :: M.MLConfig -> Int -> M.Dataset -> M.Dataset -> (Either E.MathError ((M.Fit M.PLS)))) values + 39 -> N.apply (M.incrementalPCA :: Int -> (Either E.MathError M.IncrementalPCA)) values + 40 -> N.apply (M.inversePCA :: M.PCA -> M.Dataset -> (Either E.MathError M.Dataset)) values + 41 -> N.apply (M.isomap :: Int -> Int -> M.Dataset -> (Either E.MathError M.Dataset)) values + 42 -> N.apply (M.mergePCA :: M.IncrementalPCA -> M.IncrementalPCA -> (Either E.MathError M.IncrementalPCA)) values + 43 -> N.apply (M.pcaComponents :: M.PCA -> M.Dataset) values + 44 -> N.apply (M.pcaMean :: M.PCA -> [Double]) values + 45 -> N.apply (M.pcaVariances :: M.PCA -> [Double]) values + 46 -> N.apply (M.predictPLS :: M.PLS -> M.Dataset -> (Either E.MathError M.Dataset)) values + 47 -> N.apply (M.randomProjection :: M.MLConfig -> Int -> M.Dataset -> (Either E.MathError M.Dataset)) values + 48 -> N.apply (M.transformCCA :: M.CCA -> M.Dataset -> M.Dataset -> (Either E.MathError (M.Dataset,M.Dataset))) values + 49 -> N.apply (M.transformICA :: M.ICA -> M.Dataset -> (Either E.MathError M.Dataset)) values + 50 -> N.apply (M.transformKernelPCA :: M.KernelPCA -> M.Dataset -> (Either E.MathError M.Dataset)) values + 51 -> N.apply (M.transformPCA :: M.PCA -> M.Dataset -> (Either E.MathError M.Dataset)) values + 52 -> N.apply (M.truncatedSVD :: Int -> M.Dataset -> (Either E.MathError (M.Dataset,[Double],M.Dataset))) values + 53 -> N.apply (M.tsne :: M.MLConfig -> Int -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.Dataset)))) values + 54 -> N.apply (M.umap :: M.MLConfig -> Int -> Int -> Double -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.Dataset)))) values + 55 -> N.apply (M.updatePCA :: M.IncrementalPCA -> M.Dataset -> (Either E.MathError M.IncrementalPCA)) values + 56 -> N.apply (M.Fit :: V.Value -> Int -> Double -> Bool -> (M.Fit V.Value)) values + 57 -> N.apply (M.MLConfig :: Int -> Double -> Double -> Word64 -> M.MLConfig) values + 58 -> N.apply (M.defaultMLConfig :: M.MLConfig) values + 59 -> N.apply (M.fitConverged :: (M.Fit V.Value) -> Bool) values + 60 -> N.apply (M.fitIterations :: (M.Fit V.Value) -> Int) values + 61 -> N.apply (M.fitResidual :: (M.Fit V.Value) -> Double) values + 62 -> N.apply (M.fitted :: (M.Fit V.Value) -> V.Value) values + 63 -> N.apply (M.mlIterations :: M.MLConfig -> Int) values + 64 -> N.apply (M.mlRate :: M.MLConfig -> Double) values + 65 -> N.apply (M.mlSeed :: M.MLConfig -> Word64) values + 66 -> N.apply (M.mlTolerance :: M.MLConfig -> Double) values + 67 -> N.apply (M.BallTree :: M.IndexKind) values + 68 -> N.apply (M.KDTree :: M.IndexKind) values + 69 -> N.apply (M.NeighborResult :: [(Int,Double)] -> Int -> Bool -> M.NeighborResult) values + 70 -> N.apply (M.buildIndex :: M.IndexKind -> Int -> M.Dataset -> (Either E.MathError M.SpatialIndex)) values + 71 -> N.apply (M.buildLSH :: Word64 -> Int -> Int -> Double -> M.Dataset -> (Either E.MathError M.LSH)) values + 72 -> N.apply (M.decisionOneClassSVM :: M.OneClassSVM -> M.Dataset -> (Either E.MathError [Double])) values + 73 -> N.apply (M.exhaustive :: M.NeighborResult -> Bool) values + 74 -> N.apply (M.fitIsolationForest :: Word64 -> Int -> Int -> M.Dataset -> (Either E.MathError M.IsolationForest)) values + 75 -> N.apply (M.fitOneClassSVM :: M.MLConfig -> M.Kernel -> Double -> M.Dataset -> (Either E.MathError ((M.Fit M.OneClassSVM)))) values + 76 -> N.apply (M.knnClassify :: Int -> M.SpatialIndex -> [Int] -> M.Dataset -> (Either E.MathError [Int])) values + 77 -> N.apply (M.knnRegress :: Int -> M.SpatialIndex -> [Double] -> M.Dataset -> (Either E.MathError [Double])) values + 78 -> N.apply (M.localOutlierFactor :: Int -> M.Dataset -> (Either E.MathError [Double])) values + 79 -> N.apply (M.nearestNeighbors :: Int -> Int -> M.SpatialIndex -> [Double] -> (Either E.MathError M.NeighborResult)) values + 80 -> N.apply (M.neighbors :: M.NeighborResult -> [(Int,Double)]) values + 81 -> N.apply (M.queryLSH :: Int -> M.LSH -> [Double] -> (Either E.MathError [(Int,Double)])) values + 82 -> N.apply (M.scoreIsolationForest :: M.IsolationForest -> M.Dataset -> (Either E.MathError [Double])) values + 83 -> N.apply (M.visitedLeaves :: M.NeighborResult -> Int) values + 84 -> N.apply (M.BoxCox :: Double -> M.PowerTransform) values + 85 -> N.apply (M.ConstantImpute :: Double -> M.Imputation) values + 86 -> N.apply (M.Fold :: [Int] -> [Int] -> M.Fold) values + 87 -> N.apply (M.MeanImpute :: M.Imputation) values + 88 -> N.apply (M.MedianImpute :: M.Imputation) values + 89 -> N.apply (M.MinMax :: M.Scaling) values + 90 -> N.apply (M.RejectUnknown :: M.UnknownCategory) values + 91 -> N.apply (M.RobustScale :: M.Scaling) values + 92 -> N.apply (M.Standardize :: M.Scaling) values + 93 -> N.apply (M.YeoJohnson :: Double -> M.PowerTransform) values + 94 -> N.apply (M.ZeroUnknown :: M.UnknownCategory) values + 95 -> case values of + [v0] -> C.fitEncoder v0 prototype + _ -> V.invalid "category operation arity differs" + 96 -> N.apply (M.fitImputer :: M.Imputation -> M.Dataset -> (Either E.MathError M.Imputer)) values + 97 -> N.apply (M.fitQuantileTransformer :: M.Dataset -> (Either E.MathError M.QuantileTransformer)) values + 98 -> N.apply (M.fitScaler :: M.Scaling -> M.Dataset -> (Either E.MathError M.Scaler)) values + 99 -> N.apply (M.gridSearch :: [V.Value] -> [M.Fold] -> (V.Value -> M.Fold -> (Either E.MathError Double)) -> (Either E.MathError (V.Value,Double))) values + 100 -> N.apply (M.impute :: M.Imputer -> M.Dataset -> (Either E.MathError M.Dataset)) values + 101 -> N.apply (M.inversePowerTransform :: M.PowerTransform -> M.Dataset -> (Either E.MathError M.Dataset)) values + 102 -> N.apply (M.inverseQuantileTransform :: M.QuantileTransformer -> M.Dataset -> (Either E.MathError M.Dataset)) values + 103 -> N.apply (M.inverseTransform :: M.Scaler -> M.Dataset -> (Either E.MathError M.Dataset)) values + 104 -> N.apply (M.kFold :: Word64 -> Int -> Int -> (Either E.MathError [M.Fold])) values + 105 -> case values of + [v0,v1] -> C.labelDecode v0 v1 + _ -> V.invalid "category operation arity differs" + 106 -> case values of + [v0,v1] -> C.labelEncode v0 v1 + _ -> V.invalid "category operation arity differs" + 107 -> case values of + [v0,v1,v2] -> C.oneHotEncode v0 v1 v2 + _ -> V.invalid "category operation arity differs" + 108 -> N.apply (M.powerTransform :: M.PowerTransform -> M.Dataset -> (Either E.MathError M.Dataset)) values + 109 -> N.apply (M.quantileTransform :: M.QuantileTransformer -> M.Dataset -> (Either E.MathError M.Dataset)) values + 110 -> N.apply (M.randomSearch :: Word64 -> Int -> [V.Value] -> [M.Fold] -> (V.Value -> M.Fold -> (Either E.MathError Double)) -> (Either E.MathError (V.Value,Double))) values + 111 -> case values of + [v0,v1,v2] -> C.stratifiedKFold v0 v1 v2 prototype + _ -> V.invalid "category operation arity differs" + 112 -> N.apply (M.trainTestSplit :: Word64 -> Double -> Int -> (Either E.MathError M.Fold)) values + 113 -> N.apply (M.trainingIndices :: M.Fold -> [Int]) values + 114 -> N.apply (M.transform :: M.Scaler -> M.Dataset -> (Either E.MathError M.Dataset)) values + 115 -> N.apply (M.validationIndices :: M.Fold -> [Int]) values + 116 -> N.apply (M.BernoulliBayes :: M.BayesFamily) values + 117 -> N.apply (M.BinomialLogit :: M.GLMFamily) values + 118 -> N.apply (M.ElasticNet :: Double -> Double -> M.Penalty) values + 119 -> N.apply (M.GaussianBayes :: M.BayesFamily) values + 120 -> N.apply (M.Lasso :: Double -> M.Penalty) values + 121 -> N.apply (M.LinearKernel :: M.Kernel) values + 122 -> N.apply (M.MultinomialBayes :: M.BayesFamily) values + 123 -> N.apply (M.Ordinary :: M.Penalty) values + 124 -> N.apply (M.PoissonLog :: M.GLMFamily) values + 125 -> N.apply (M.PolynomialKernel :: Int -> Double -> Double -> M.Kernel) values + 126 -> N.apply (M.RBFKernel :: Double -> M.Kernel) values + 127 -> N.apply (M.Ridge :: Double -> M.Penalty) values + 128 -> N.apply (M.bayesianCovariance :: M.BayesianLinear -> M.Dataset) values + 129 -> N.apply (M.bayesianMean :: M.BayesianLinear -> M.LinearModel) values + 130 -> N.apply (M.coefficients :: M.LinearModel -> [Double]) values + 131 -> N.apply (M.decisionSVM :: M.SVM -> M.Dataset -> (Either E.MathError [Double])) values + 132 -> N.apply (M.fitBayesian :: Double -> Double -> M.Dataset -> [Double] -> (Either E.MathError M.BayesianLinear)) values + 133 -> N.apply (M.fitDiscriminant :: Bool -> Double -> M.Dataset -> [Int] -> (Either E.MathError M.Discriminant)) values + 134 -> N.apply (M.fitGLM :: M.MLConfig -> M.GLMFamily -> Double -> M.Dataset -> [Double] -> (Either E.MathError ((M.Fit M.GLM)))) values + 135 -> N.apply (M.fitGPClassifier :: M.MLConfig -> M.Kernel -> M.Dataset -> [Double] -> (Either E.MathError ((M.Fit M.GPClassifier)))) values + 136 -> N.apply (M.fitGaussianProcess :: M.Kernel -> Double -> M.Dataset -> [Double] -> (Either E.MathError M.GaussianProcess)) values + 137 -> N.apply (M.fitLinear :: M.MLConfig -> M.Penalty -> M.Dataset -> [Double] -> (Either E.MathError ((M.Fit M.LinearModel)))) values + 138 -> N.apply (M.fitMultinomial :: M.MLConfig -> Double -> M.Dataset -> [Int] -> (Either E.MathError ((M.Fit M.MultinomialModel)))) values + 139 -> N.apply (M.fitNaiveBayes :: M.BayesFamily -> Double -> M.Dataset -> [Int] -> (Either E.MathError M.NaiveBayes)) values + 140 -> N.apply (M.fitRobust :: M.MLConfig -> Double -> M.Dataset -> [Double] -> (Either E.MathError ((M.Fit M.LinearModel)))) values + 141 -> N.apply (M.fitSVM :: M.MLConfig -> M.Kernel -> Double -> M.Dataset -> [Double] -> (Either E.MathError ((M.Fit M.SVM)))) values + 142 -> N.apply (M.fitWeighted :: M.Dataset -> [Double] -> [Double] -> (Either E.MathError M.LinearModel)) values + 143 -> N.apply (M.kernel :: M.Kernel -> [Double] -> [Double] -> (Either E.MathError Double)) values + 144 -> N.apply (M.polynomialFeatures :: Int -> [Double] -> (Either E.MathError M.Dataset)) values + 145 -> N.apply (M.predictDiscriminant :: M.Discriminant -> M.Dataset -> (Either E.MathError [Int])) values + 146 -> N.apply (M.predictGLM :: M.GLM -> M.Dataset -> (Either E.MathError [Double])) values + 147 -> N.apply (M.predictGPClassifier :: M.GPClassifier -> M.Dataset -> (Either E.MathError [Double])) values + 148 -> N.apply (M.predictGaussianProcess :: M.GaussianProcess -> M.Dataset -> (Either E.MathError [(Double,Double)])) values + 149 -> N.apply (M.predictLinear :: M.LinearModel -> M.Dataset -> (Either E.MathError [Double])) values + 150 -> N.apply (M.predictMultinomial :: M.MultinomialModel -> M.Dataset -> (Either E.MathError [[(Int,Double)]])) values + 151 -> N.apply (M.predictNaiveBayes :: M.NaiveBayes -> M.Dataset -> (Either E.MathError [Int])) values + 152 -> N.apply (M.predictSVM :: M.SVM -> M.Dataset -> (Either E.MathError [Double])) values + 153 -> N.apply (M.recursiveCoefficients :: M.RecursiveLS -> [Double]) values + 154 -> N.apply (M.recursiveLS :: Int -> Double -> Double -> (Either E.MathError M.RecursiveLS)) values + 155 -> N.apply (M.updateRecursiveLS :: M.RecursiveLS -> [Double] -> Double -> (Either E.MathError M.RecursiveLS)) values + _ -> V.invalid "ML operation identifier differs" + B.checked (Right result) (`V.publish` out) diff --git a/src/HMath/FFI/MachineLearning/Codec.hs b/src/HMath/FFI/MachineLearning/Codec.hs new file mode 100644 index 0000000..13ada97 --- /dev/null +++ b/src/HMath/FFI/MachineLearning/Codec.hs @@ -0,0 +1,98 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE UndecidableInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Typed records/labels. Every fitting, encoding and split operation is original. +module HMath.FFI.MachineLearning.Codec where + +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import HMath.Error (MathError) +import HMath.FFI.MathError (CallbackFailure(..)) +import HMath.FFI.NumericalCodec (From(..),To(..)) +import qualified HMath.FFI.NumericalCodec as N +import HMath.FFI.Ordering (SomeOrdered(..),orderedWith) +import HMath.FFI.MachineLearning.Types () +import qualified HMath.FFI.FoundationCodec as F +import qualified HMath.FFI.Value as V +import qualified HMath.MachineLearning as M + + +-- Generic record fields stay lossless Value payloads, as with Estimate/Rounded. +-- This transports the original Fit constructor and all diagnostics without +-- converting its model/label payload through a numerical approximation. +instance From a => From (M.Fit a) where + from value = do + original <- N.unbox 321 value :: IO (M.Fit V.Value) + payload <- from (M.fitted original) + pure (M.Fit payload (M.fitIterations original) (M.fitResidual original) (M.fitConverged original)) +instance To a => To (M.Fit a) where + to original = do + payload <- to (M.fitted original) + let value=M.Fit payload (M.fitIterations original) (M.fitResidual original) (M.fitConverged original) + pure (N.box 321 value [pure payload,to (M.fitIterations original),to (M.fitResidual original),to (M.fitConverged original)]) + +-- Encoder is abstract in Haskell. Retain its actual homogeneous type and Ord +-- dictionary, rather than converting labels to Double/text or comparing fields. +data EncoderBox where + EncoderBox :: (Typeable a,Ord a) => (a -> IO V.Value) -> (V.Value -> IO a) -> M.Encoder a -> EncoderBox + +encoderValue :: EncoderBox -> V.Value +encoderValue value = V.Opaque 329 (-1) 0 (evaluate value >> pure ()) value +getEncoder :: V.Value -> IO EncoderBox +getEncoder (V.Opaque 329 _ _ _ value) = maybe (V.invalid "Encoder payload differs") pure (cast value) +getEncoder _ = V.invalid "expected MachineLearning.Encoder" +source :: Either MathError a -> IO a +source = either (throwIO . CallbackMathError) pure + +categoryOrdering :: [V.Value] -> V.Value -> IO SomeOrdered +categoryOrdering values prototype = do + result@(SomeOrdered _ readValue) <- orderedWith [F.foundationOrdering] (values ++ case prototype of V.None -> [];_ -> [prototype]) + case prototype of V.None -> pure ();_ -> readValue prototype >> pure () + pure result + +fitEncoder :: V.Value -> V.Value -> IO V.Value +fitEncoder input prototype = do + values <- V.asList input + if null values then do + _ <- source (M.fitEncoder ([] :: [Integer])) + V.invalid "an empty Encoder needs a prototype" + else fit values + where + fit values = do + SomeOrdered write readValue <- categoryOrdering values prototype + labels <- mapM readValue values + encoder <- source (M.fitEncoder labels) + pure (encoderValue (EncoderBox write readValue encoder)) + +labelEncode :: V.Value -> V.Value -> IO V.Value +labelEncode encoded input = do + EncoderBox _ readValue encoder <- getEncoder encoded + values <- V.asList input >>= mapM readValue + source (M.labelEncode encoder values) >>= to + +labelDecode :: V.Value -> V.Value -> IO V.Value +labelDecode encoded input = do + EncoderBox write _ encoder <- getEncoder encoded + indices <- from input + labels <- source (M.labelDecode encoder indices) + V.List <$> mapM write labels + +oneHotEncode :: V.Value -> V.Value -> V.Value -> IO V.Value +oneHotEncode policyValue encoded input = do + policy <- from policyValue + EncoderBox _ readValue encoder <- getEncoder encoded + labels <- V.asList input >>= mapM readValue + source (M.oneHotEncode policy encoder labels) >>= to + +stratifiedKFold :: V.Value -> V.Value -> V.Value -> V.Value -> IO V.Value +stratifiedKFold seedValue countValue input prototype = do + seed <- from seedValue + count <- from countValue + values <- V.asList input + if null values then source (M.stratifiedKFold seed count ([] :: [Integer])) >>= to else do + SomeOrdered _ readValue <- categoryOrdering values prototype + labels <- mapM readValue values + source (M.stratifiedKFold seed count labels) >>= to diff --git a/src/HMath/FFI/MachineLearning/Types.hs b/src/HMath/FFI/MachineLearning/Types.hs new file mode 100644 index 0000000..f0c69d5 --- /dev/null +++ b/src/HMath/FFI/MachineLearning/Types.hs @@ -0,0 +1,87 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_machinelearning_bindings.py. +module HMath.FFI.MachineLearning.Types where +import HMath.FFI.NumericalCodec (From(..),To(..),box,unbox) +import qualified HMath.MachineLearning as M +instance From M.ClusterModel where from = unbox 310 +instance To M.ClusterModel where to value = pure (box 310 value [to (M.clusterCenters value)]) +instance From M.GaussianMixture where from = unbox 311 +instance To M.GaussianMixture where to value = pure (box 311 value [to (M.mixtureCovariances value),to (M.mixtureMeans value),to (M.mixtureWeights value)]) +instance From M.Linkage where from = unbox 312 +instance To M.Linkage where to value = pure (box 312 value []) +instance From M.Merge where from = unbox 313 +instance To M.Merge where to value = pure (box 313 value [to (M.leftCluster value),to (M.mergeDistance value),to (M.mergedSize value),to (M.rightCluster value)]) +instance From M.CCA where from = unbox 314 +instance To M.CCA where to value = pure (box 314 value [to (M.canonicalCorrelations value)]) +instance From M.FactorAnalysis where from = unbox 315 +instance To M.FactorAnalysis where to value = pure (box 315 value [to (M.factorLoadings value),to (M.factorNoise value)]) +instance From M.ICA where from = unbox 316 +instance To M.ICA where to value = pure (box 316 value []) +instance From M.IncrementalPCA where from = unbox 317 +instance To M.IncrementalPCA where to value = pure (box 317 value []) +instance From M.KernelPCA where from = unbox 318 +instance To M.KernelPCA where to value = pure (box 318 value []) +instance From M.PCA where from = unbox 319 +instance To M.PCA where to value = pure (box 319 value [to (M.pcaComponents value),to (M.pcaMean value),to (M.pcaVariances value)]) +instance From M.PLS where from = unbox 320 +instance To M.PLS where to value = pure (box 320 value []) +instance From M.MLConfig where from = unbox 322 +instance To M.MLConfig where to value = pure (box 322 value [to (M.mlIterations value),to (M.mlRate value),to (M.mlSeed value),to (M.mlTolerance value)]) +instance From M.IndexKind where from = unbox 323 +instance To M.IndexKind where to value = pure (box 323 value []) +instance From M.IsolationForest where from = unbox 324 +instance To M.IsolationForest where to value = pure (box 324 value []) +instance From M.LSH where from = unbox 325 +instance To M.LSH where to value = pure (box 325 value []) +instance From M.NeighborResult where from = unbox 326 +instance To M.NeighborResult where to value = pure (box 326 value [to (M.exhaustive value),to (M.neighbors value),to (M.visitedLeaves value)]) +instance From M.OneClassSVM where from = unbox 327 +instance To M.OneClassSVM where to value = pure (box 327 value []) +instance From M.SpatialIndex where from = unbox 328 +instance To M.SpatialIndex where to value = pure (box 328 value []) +instance From M.Fold where from = unbox 330 +instance To M.Fold where to value = pure (box 330 value [to (M.trainingIndices value),to (M.validationIndices value)]) +instance From M.Imputation where from = unbox 331 +instance To M.Imputation where to value = pure (box 331 value []) +instance From M.Imputer where from = unbox 332 +instance To M.Imputer where to value = pure (box 332 value []) +instance From M.PowerTransform where from = unbox 333 +instance To M.PowerTransform where to value = pure (box 333 value []) +instance From M.QuantileTransformer where from = unbox 334 +instance To M.QuantileTransformer where to value = pure (box 334 value []) +instance From M.Scaler where from = unbox 335 +instance To M.Scaler where to value = pure (box 335 value []) +instance From M.Scaling where from = unbox 336 +instance To M.Scaling where to value = pure (box 336 value []) +instance From M.UnknownCategory where from = unbox 337 +instance To M.UnknownCategory where to value = pure (box 337 value []) +instance From M.BayesFamily where from = unbox 338 +instance To M.BayesFamily where to value = pure (box 338 value []) +instance From M.BayesianLinear where from = unbox 339 +instance To M.BayesianLinear where to value = pure (box 339 value [to (M.bayesianCovariance value),to (M.bayesianMean value)]) +instance From M.Discriminant where from = unbox 340 +instance To M.Discriminant where to value = pure (box 340 value []) +instance From M.GLM where from = unbox 341 +instance To M.GLM where to value = pure (box 341 value []) +instance From M.GLMFamily where from = unbox 342 +instance To M.GLMFamily where to value = pure (box 342 value []) +instance From M.GPClassifier where from = unbox 343 +instance To M.GPClassifier where to value = pure (box 343 value []) +instance From M.GaussianProcess where from = unbox 344 +instance To M.GaussianProcess where to value = pure (box 344 value []) +instance From M.Kernel where from = unbox 345 +instance To M.Kernel where to value = pure (box 345 value []) +instance From M.LinearModel where from = unbox 346 +instance To M.LinearModel where to value = pure (box 346 value [to (M.coefficients value)]) +instance From M.MultinomialModel where from = unbox 347 +instance To M.MultinomialModel where to value = pure (box 347 value []) +instance From M.NaiveBayes where from = unbox 348 +instance To M.NaiveBayes where to value = pure (box 348 value []) +instance From M.Penalty where from = unbox 349 +instance To M.Penalty where to value = pure (box 349 value []) +instance From M.RecursiveLS where from = unbox 350 +instance To M.RecursiveLS where to value = pure (box 350 value [to (M.recursiveCoefficients value)]) +instance From M.SVM where from = unbox 351 +instance To M.SVM where to value = pure (box 351 value []) diff --git a/src/HMath/FFI/MathError.hs b/src/HMath/FFI/MathError.hs new file mode 100644 index 0000000..fbe2dc7 --- /dev/null +++ b/src/HMath/FFI/MathError.hs @@ -0,0 +1,163 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Lossless MathError callback transport, independent of error pretty-printing. +module HMath.FFI.MathError + ( CallbackFailure (..), callbackBoundary, recordMathError, readMathError, readWireMessage, withMathErrorWire, withEncodedMessage, readCallbackFailure ) where +import Control.Exception (Exception, catch, throwIO) +import Data.Char (chr, ord) +import Foreign +import Foreign.C +import HMath.Error (MathError (..)) + +data CallbackFailure + = CallbackFailure CInt String + | CallbackMathError MathError + | CallbackDomainError CInt CInt [Int] String + deriving (Show) +instance Exception CallbackFailure +foreign import ccall unsafe "hm_error" reportCallbackError :: CInt -> CString -> IO CInt +foreign import ccall unsafe "hm_record_math_error" record :: CInt -> Ptr CPtrdiff -> CString -> CSize -> IO CInt +foreign import ccall unsafe "hm_record_expression_error" recordExpression :: CInt -> Ptr CPtrdiff -> CString -> CSize -> IO CInt +foreign import ccall unsafe "hm_record_interchange_error" recordInterchange :: CInt -> CString -> CSize -> IO CInt +foreign import ccall unsafe "hm_math_error_size" wireSize :: IO CSize +foreign import ccall unsafe "hm_math_error_reset" resetWire :: Ptr () -> IO () +foreign import ccall unsafe "hm_math_error_kind" kindOf :: Ptr () -> IO CInt +foreign import ccall unsafe "hm_math_error_detail" detailOf :: Ptr () -> CInt -> IO CPtrdiff +foreign import ccall unsafe "hm_math_error_message" messageOf :: Ptr () -> IO CString +foreign import ccall unsafe "hm_math_error_message_length" lengthOf :: Ptr () -> IO CSize + +-- Install this inside the ordinary SomeException boundary. Source Either +-- callbacks return Left directly; pure callbacks may throw CallbackMathError. +callbackBoundary :: (MathError -> IO CInt) -> IO CInt -> IO CInt +callbackBoundary onMath action = action `catch` relay + where + relay (CallbackMathError value) = onMath value + relay (CallbackFailure code message) = withEncodedMessage message (\pointer _ -> reportCallbackError code pointer) + relay (CallbackDomainError status kind details message) = do + _ <- withCString ("Haskell domain error " ++ show status ++ ": " ++ show message) (reportCallbackError status) + recorded <- withEncodedMessage message $ \pointer count -> case status of + 12 -> withArray (map fromIntegral (take 3 (details ++ repeat 0))) $ \position -> recordExpression kind position pointer count + 13 -> recordInterchange kind pointer count + _ -> pure 1 + if recorded == 0 then pure status + else withCString "unable to record callback domain error" (reportCallbackError recorded) + +-- The existing callback wire is ABI-compatible across error domains. Return +-- status selects MathError, ExprError(position in details0..2), or interchange. +readCallbackFailure :: CInt -> Ptr () -> IO CallbackFailure +readCallbackFailure status pointer + | status == 11 = CallbackMathError <$> readMathError pointer + | status == 12 = do + kind <- kindOf pointer + details <- mapM (fmap fromIntegral . detailOf pointer) [0,1,2] + CallbackDomainError status kind details <$> readWireMessage pointer + | status == 13 = do + kind <- kindOf pointer + CallbackDomainError status kind [] <$> readWireMessage pointer + | otherwise = CallbackFailure status <$> readWireMessage pointer + +-- UTF8 for scalar values, with surrogatepass/WTF8 for the additional Char +-- codepoints permitted by Haskell String. This also preserves embedded NUL. +encodeChar :: Char -> [Word8] +encodeChar character = map fromIntegral $ let n=ord character in + if n < 0x80 then [n] + else if n < 0x800 then [0xc0 .|. (n `shiftR` 6),0x80 .|. (n .&. 0x3f)] + else if n < 0x10000 then [0xe0 .|. (n `shiftR` 12),0x80 .|. ((n `shiftR` 6) .&. 0x3f),0x80 .|. (n .&. 0x3f)] + else [0xf0 .|. (n `shiftR` 18),0x80 .|. ((n `shiftR` 12) .&. 0x3f),0x80 .|. ((n `shiftR` 6) .&. 0x3f),0x80 .|. (n .&. 0x3f)] +decodeBytes :: [Word8] -> IO String +decodeBytes [] = pure [] +decodeBytes (a:rest) + | a < 0x80 = (chr (fromIntegral a):) <$> decodeBytes rest + | a >= 0xc2 && a <= 0xdf = more 1 (fromIntegral a .&. 0x1f) rest + | a >= 0xe0 && a <= 0xef = more 2 (fromIntegral a .&. 0x0f) rest + | a >= 0xf0 && a <= 0xf4 = more 3 (fromIntegral a .&. 0x07) rest + | otherwise = invalidText + where + more count initial bytes = do + let (chunk,remaining)=splitAt count bytes + n=foldl (\value byte -> (value `shiftL` 6) .|. (fromIntegral byte .&. 0x3f)) initial chunk + minimumValue=case count of {1 -> 0x80; 2 -> 0x800; _ -> 0x10000} + if length chunk /= count || any (\byte -> byte < 0x80 || byte > 0xbf) chunk || n < minimumValue || n > 0x10ffff + then invalidText + else (chr n:) <$> decodeBytes remaining + invalidText = throwIO (CallbackFailure 1 "invalid MathError UTF8 message") +readWireMessage :: Ptr () -> IO String +readWireMessage pointer = do + messagePointer <- messageOf pointer + size <- lengthOf pointer + if toInteger size > toInteger (maxBound :: Int) || (size /= 0 && messagePointer == nullPtr) + then throwIO (CallbackFailure 1 "invalid MathError message span") + else if size == 0 then pure "" else peekArray (fromIntegral size) (castPtr messagePointer) >>= decodeBytes + +recordMathError :: MathError -> IO CInt +recordMathError value = + let (kind,details,message)=fields value + in withArray (map fromIntegral (take 6 (details ++ repeat 0))) $ \numbers -> + withEncodedMessage message (record kind numbers) + where + fields e = case e of + NegativeDimensions (a,b) -> (1,[a,b],"") + ElementCountOverflow (a,b) -> (2,[a,b],"") + ElementCountMismatch a b -> (3,[a,b],"") + ShapeMismatch (a,b) (c,d) -> (4,[a,b,c,d],"") + InnerDimensionMismatch a b -> (5,[a,b],"") + IndexOutOfBounds (a,b) (c,d) -> (6,[a,b,c,d],"") + SliceOutOfBounds (a,b) (c,d) (f,g) -> (7,[a,b,c,d,f,g],"") + VectorLengthMismatch a b -> (8,[a,b],"") + NonSquareMatrix (a,b) -> (9,[a,b],"") + InvalidTolerance -> (10,[],"") + SingularMatrix a -> (11,[a],"") + NearSingularMatrix a -> (12,[a],"") + NonFiniteMatrixEntry (a,b) -> (13,[a,b],"") + NonFiniteVectorEntry a -> (14,[a],"") + NonFiniteResult -> (15,[],"") + RightHandSideMismatch a b -> (16,[a,b],"") + DomainError s -> (17,[],s) + InvalidArgument s -> (18,[],s) + NonConvergence s a -> (19,[a],s) + RankDeficient a -> (20,[a],"") + NotPositiveDefinite a -> (21,[a],"") + +-- Shared domain-error text transport preserves every Haskell Char, including +-- embedded NUL and isolated surrogates, without locale-dependent conversion. +withEncodedMessage :: String -> (CString -> CSize -> IO a) -> IO a +withEncodedMessage message action = + let bytes = concatMap encodeChar message + in withArray bytes $ \pointer -> action (castPtr pointer) (fromIntegral (length bytes)) + +withMathErrorWire :: (Ptr () -> IO a) -> IO a +withMathErrorWire action = do + size <- wireSize + allocaBytes (fromIntegral size) $ \pointer -> resetWire pointer >> action pointer + +readMathError :: Ptr () -> IO MathError +readMathError pointer = do + kind <- kindOf pointer + numbers <- mapM (fmap fromIntegral . detailOf pointer) [0..5] + message <- if kind `elem` [17,18,19] then readWireMessage pointer else pure "" + let decoded = do + let a=numbers!!0; b=numbers!!1; c=numbers!!2; d=numbers!!3; f=numbers!!4; g=numbers!!5 + case kind of + 1 -> pure (NegativeDimensions (a,b)) + 2 -> pure (ElementCountOverflow (a,b)) + 3 -> pure (ElementCountMismatch a b) + 4 -> pure (ShapeMismatch (a,b) (c,d)) + 5 -> pure (InnerDimensionMismatch a b) + 6 -> pure (IndexOutOfBounds (a,b) (c,d)) + 7 -> pure (SliceOutOfBounds (a,b) (c,d) (f,g)) + 8 -> pure (VectorLengthMismatch a b) + 9 -> pure (NonSquareMatrix (a,b)) + 10 -> pure InvalidTolerance + 11 -> pure (SingularMatrix a) + 12 -> pure (NearSingularMatrix a) + 13 -> pure (NonFiniteMatrixEntry (a,b)) + 14 -> pure (NonFiniteVectorEntry a) + 15 -> pure NonFiniteResult + 16 -> pure (RightHandSideMismatch a b) + 17 -> pure (DomainError message) + 18 -> pure (InvalidArgument message) + 19 -> pure (NonConvergence message a) + 20 -> pure (RankDeficient a) + 21 -> pure (NotPositiveDefinite a) + _ -> throwIO (CallbackFailure 1 "invalid MathError constructor kind") + decoded diff --git a/src/HMath/FFI/Matrix.hs b/src/HMath/FFI/Matrix.hs new file mode 100644 index 0000000..6f500c8 --- /dev/null +++ b/src/HMath/FFI/Matrix.hs @@ -0,0 +1,848 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_matrix_bindings.py. +module HMath.FFI.Matrix where +import Control.Exception (bracketOnError, evaluate) +import Data.Coerce (coerce) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.Error (MathError) +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as L +import qualified HMath.Matrix.QR as Q + +data Object = M32 (M.Matrix Float) | M64 (M.Matrix Double) + | L32 (L.LU Float) | L64 (L.LU Double) + | Q32 (Q.QR Float) | Q64 (Q.QR Double) + | V32 [Float] | V64 [Double] | Indices [Int] + +forceList :: [a] -> IO () +forceList = mapM_ evaluate +forceObject :: Object -> IO () +forceObject object = case object of + M32 m -> forceList (M.toList m) + M64 m -> forceList (M.toList m) + L32 f -> forceList (M.toList (L.luLower f)) >> forceList (M.toList (L.luUpper f)) >> forceList (L.luPermutation f) + L64 f -> forceList (M.toList (L.luLower f)) >> forceList (M.toList (L.luUpper f)) >> forceList (L.luPermutation f) + Q32 f -> forceList (M.toList (Q.qrQ f)) >> forceList (M.toList (Q.qrR f)) >> forceList (Q.qrPermutation f) >> evaluate (Q.qrRank f) >> pure () + Q64 f -> forceList (M.toList (Q.qrQ f)) >> forceList (M.toList (Q.qrR f)) >> forceList (Q.qrPermutation f) >> evaluate (Q.qrRank f) >> pure () + V32 xs -> forceList xs + V64 xs -> forceList xs + Indices xs -> forceList xs +publish :: Object -> Ptr (StablePtr Object) -> IO () +publish value out = forceObject value >> bracketOnError (newStablePtr value) freeStablePtr (poke out) +publishMaybe :: (a -> Object) -> Maybe a -> Ptr (StablePtr Object) -> IO () +publishMaybe wrap value out = case value of + Nothing -> poke (castPtr out :: Ptr (Ptr ())) nullPtr + Just result -> publish (wrap result) out + +foreign export ccall "hm_dense_free" release :: StablePtr Object -> IO () +release :: StablePtr Object -> IO () +release = freeStablePtr + +foreign export ccall "hm_dense_metadata" metadata :: StablePtr Object -> Ptr CPtrdiff -> Ptr CPtrdiff -> Ptr CSize -> IO CInt +metadata :: StablePtr Object -> Ptr CPtrdiff -> Ptr CPtrdiff -> Ptr CSize -> IO CInt +metadata pointer rows columns count = boundary $ do + value <- deRefStablePtr pointer + let (r,c,n) = case value of + M32 m -> let (a,b)=M.shape m in (a,b,length (M.toList m)) + M64 m -> let (a,b)=M.shape m in (a,b,length (M.toList m)) + V32 xs -> (0,0,length xs) + V64 xs -> (0,0,length xs) + Indices xs -> (0,0,length xs) + _ -> error "dense metadata kind mismatch" + _ <- evaluate r >> evaluate c >> evaluate n + poke rows (fromIntegral r) >> poke columns (fromIntegral c) >> poke count (fromIntegral n) + checked (Right ()) (const (pure ())) +foreign export ccall "hm_dense_indices_copy" indicesCopy :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +indicesCopy :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +indicesCopy pointer out = boundary $ do + value <- deRefStablePtr pointer + case value of + Indices xs -> checked (Right ()) (const (pokeArray out (map fromIntegral xs))) + _ -> error "dense indices kind mismatch" + +getM32 :: StablePtr Object -> IO (M.Matrix Float) +getM32 pointer = do + value <- deRefStablePtr pointer + case value of + M32 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +getL32 :: StablePtr Object -> IO (L.LU Float) +getL32 pointer = do + value <- deRefStablePtr pointer + case value of + L32 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +getQ32 :: StablePtr Object -> IO (Q.QR Float) +getQ32 pointer = do + value <- deRefStablePtr pointer + case value of + Q32 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +foreign export ccall "hm_dense_values_f32" values32 :: StablePtr Object -> Ptr CFloat -> IO CInt +values32 :: StablePtr Object -> Ptr CFloat -> IO CInt +values32 pointer out = boundary $ do + object <- deRefStablePtr pointer + let values = case object of + M32 m -> M.toList m + V32 xs -> xs + _ -> error "dense values kind/precision mismatch" + strict <- mapM evaluate values + checked (Right ()) (const (pokeArray (castPtr out :: Ptr Float) strict)) + +foreign export ccall "hm_dense_from_list_f32" ffiHmDenseFromListF32 :: CPtrdiff -> CPtrdiff -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListF32 :: CPtrdiff -> CPtrdiff -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListF32 a0 a1 a2 a2Count out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Float) + checked (Right (M.fromList a0Value a1Value a2Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_zero_matrix_f32" ffiHmDenseZeroMatrixF32 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixF32 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixF32 a0 a1 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + checked (Right (M.zeroMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_diagonal_f32" ffiHmDenseDiagonalF32 :: Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalF32 :: Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalF32 a0 a0Count out = boundary $ do + a0Value <- peekArray (fromIntegral a0Count) (castPtr a0 :: Ptr Float) + checked (Right (M.diagonal a0Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_at_f32" ffiHmDenseAtF32 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CFloat -> Ptr CInt -> IO CInt +ffiHmDenseAtF32 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CFloat -> Ptr CInt -> IO CInt +ffiHmDenseAtF32 a0 a1 a2 out found = boundary $ do + a0Value <- getM32 a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + checked (Right (M.at a0Value a1Value a2Value) :: Either MathError (Maybe Float)) $ \result -> case result of + Nothing -> poke found 0 + Just value -> do + strict <- evaluate value + poke out (coerce strict :: CFloat) + poke found 1 + +foreign export ccall "hm_dense_slice_matrix_f32" ffiHmDenseSliceMatrixF32 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixF32 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixF32 a0 a1 a2 a3 a4 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + let a3Value = fromIntegral a3 + a4Value <- getM32 a4 + checked (Right (M.sliceMatrix (a0Value,a1Value) (a2Value,a3Value) a4Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_reshape_f32" ffiHmDenseReshapeF32 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeF32 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeF32 a0 a1 a2 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- getM32 a2 + checked (Right (M.reshape a0Value a1Value a2Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_add_matrix_f32" ffiHmDenseAddMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (Right (M.addMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_subtract_matrix_f32" ffiHmDenseSubtractMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (Right (M.subtractMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_hadamard_f32" ffiHmDenseHadamardF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (Right (M.hadamard a0Value a1Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_multiply_f32" ffiHmDenseMultiplyF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (Right (M.multiply a0Value a1Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_identity_f32" ffiHmDenseIdentityF32 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityF32 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityF32 a0 out = boundary $ do + let a0Value = fromIntegral a0 + checked (Right (M.identity a0Value) :: Either MathError (Maybe (M.Matrix Float))) $ \value -> publishMaybe M32 value out + +foreign export ccall "hm_dense_from_list_checked_f32" ffiHmDenseFromListCheckedF32 :: CPtrdiff -> CPtrdiff -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListCheckedF32 :: CPtrdiff -> CPtrdiff -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListCheckedF32 a0 a1 a2 a2Count out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Float) + checked (M.fromListChecked a0Value a1Value a2Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_zero_matrix_checked_f32" ffiHmDenseZeroMatrixCheckedF32 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixCheckedF32 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixCheckedF32 a0 a1 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + checked (M.zeroMatrixChecked a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_diagonal_checked_f32" ffiHmDenseDiagonalCheckedF32 :: Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalCheckedF32 :: Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalCheckedF32 a0 a0Count out = boundary $ do + a0Value <- peekArray (fromIntegral a0Count) (castPtr a0 :: Ptr Float) + checked (M.diagonalChecked a0Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_at_checked_f32" ffiHmDenseAtCheckedF32 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CFloat -> IO CInt +ffiHmDenseAtCheckedF32 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CFloat -> IO CInt +ffiHmDenseAtCheckedF32 a0 a1 a2 out = boundary $ do + a0Value <- getM32 a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + checked (M.atChecked a0Value a1Value a2Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CFloat) + +foreign export ccall "hm_dense_slice_matrix_checked_f32" ffiHmDenseSliceMatrixCheckedF32 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixCheckedF32 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixCheckedF32 a0 a1 a2 a3 a4 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + let a3Value = fromIntegral a3 + a4Value <- getM32 a4 + checked (M.sliceMatrixChecked (a0Value,a1Value) (a2Value,a3Value) a4Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_reshape_checked_f32" ffiHmDenseReshapeCheckedF32 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeCheckedF32 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeCheckedF32 a0 a1 a2 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- getM32 a2 + checked (M.reshapeChecked a0Value a1Value a2Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_add_matrix_checked_f32" ffiHmDenseAddMatrixCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixCheckedF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (M.addMatrixChecked a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_subtract_matrix_checked_f32" ffiHmDenseSubtractMatrixCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixCheckedF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (M.subtractMatrixChecked a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_hadamard_checked_f32" ffiHmDenseHadamardCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardCheckedF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (M.hadamardChecked a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_multiply_checked_f32" ffiHmDenseMultiplyCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyCheckedF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyCheckedF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (M.multiplyChecked a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_identity_checked_f32" ffiHmDenseIdentityCheckedF32 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityCheckedF32 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityCheckedF32 a0 out = boundary $ do + let a0Value = fromIntegral a0 + checked (M.identityChecked a0Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_scale_matrix_f32" ffiHmDenseScaleMatrixF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseScaleMatrixF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseScaleMatrixF32 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Float) + a1Value <- getM32 a1 + checked (Right (M.scaleMatrix a0Value a1Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_transpose_matrix_f32" ffiHmDenseTransposeMatrixF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseTransposeMatrixF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseTransposeMatrixF32 a0 out = boundary $ do + a0Value <- getM32 a0 + checked (Right (M.transposeMatrix a0Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_lu_lu_decompose_f32" ffiHmDenseLuLuDecomposeF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeF32 a0 out = boundary $ do + a0Value <- getM32 a0 + checked (L.luDecompose a0Value) $ \value -> publish (L32 value) out + +foreign export ccall "hm_dense_lu_lu_decompose_with_tolerance_f32" ffiHmDenseLuLuDecomposeWithToleranceF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeWithToleranceF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeWithToleranceF32 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Float) + a1Value <- getM32 a1 + checked (L.luDecomposeWithTolerance a0Value a1Value) $ \value -> publish (L32 value) out + +foreign export ccall "hm_dense_lu_lu_lower_f32" ffiHmDenseLuLuLowerF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuLowerF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuLowerF32 a0 out = boundary $ do + a0Value <- getL32 a0 + checked (Right (L.luLower a0Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_lu_lu_upper_f32" ffiHmDenseLuLuUpperF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuUpperF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuUpperF32 a0 out = boundary $ do + a0Value <- getL32 a0 + checked (Right (L.luUpper a0Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_lu_lu_permutation_f32" ffiHmDenseLuLuPermutationF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuPermutationF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuPermutationF32 a0 out = boundary $ do + a0Value <- getL32 a0 + checked (Right (L.luPermutation a0Value)) $ \value -> publish (Indices value) out + +foreign export ccall "hm_dense_lu_solve_lu_f32" ffiHmDenseLuSolveLuF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveLuF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveLuF32 a0 a1 a1Count out = boundary $ do + a0Value <- getL32 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Float) + checked (L.solveLU a0Value a1Value) $ \value -> publish (V32 value) out + +foreign export ccall "hm_dense_lu_solve_matrix_lu_f32" ffiHmDenseLuSolveMatrixLuF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixLuF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixLuF32 a0 a1 out = boundary $ do + a0Value <- getL32 a0 + a1Value <- getM32 a1 + checked (L.solveMatrixLU a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_lu_solve_f32" ffiHmDenseLuSolveF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveF32 a0 a1 a1Count out = boundary $ do + a0Value <- getM32 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Float) + checked (L.solve a0Value a1Value) $ \value -> publish (V32 value) out + +foreign export ccall "hm_dense_lu_solve_matrix_f32" ffiHmDenseLuSolveMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (L.solveMatrix a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_lu_determinant_lu_f32" ffiHmDenseLuDeterminantLuF32 :: StablePtr Object -> Ptr CFloat -> IO CInt +ffiHmDenseLuDeterminantLuF32 :: StablePtr Object -> Ptr CFloat -> IO CInt +ffiHmDenseLuDeterminantLuF32 a0 out = boundary $ do + a0Value <- getL32 a0 + checked (L.determinantLU a0Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CFloat) + +foreign export ccall "hm_dense_lu_determinant_f32" ffiHmDenseLuDeterminantF32 :: StablePtr Object -> Ptr CFloat -> IO CInt +ffiHmDenseLuDeterminantF32 :: StablePtr Object -> Ptr CFloat -> IO CInt +ffiHmDenseLuDeterminantF32 a0 out = boundary $ do + a0Value <- getM32 a0 + checked (L.determinant a0Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CFloat) + +foreign export ccall "hm_dense_lu_inverse_f32" ffiHmDenseLuInverseF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuInverseF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuInverseF32 a0 out = boundary $ do + a0Value <- getM32 a0 + checked (L.inverse a0Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_qr_decompose_f32" ffiHmDenseQrQrDecomposeF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeF32 a0 out = boundary $ do + a0Value <- getM32 a0 + checked (Q.qrDecompose a0Value) $ \value -> publish (Q32 value) out + +foreign export ccall "hm_dense_qr_qr_decompose_with_tolerance_f32" ffiHmDenseQrQrDecomposeWithToleranceF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeWithToleranceF32 :: CFloat -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeWithToleranceF32 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Float) + a1Value <- getM32 a1 + checked (Q.qrDecomposeWithTolerance a0Value a1Value) $ \value -> publish (Q32 value) out + +foreign export ccall "hm_dense_qr_qr_q_f32" ffiHmDenseQrQrQF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrQF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrQF32 a0 out = boundary $ do + a0Value <- getQ32 a0 + checked (Right (Q.qrQ a0Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_qr_r_f32" ffiHmDenseQrQrRF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrRF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrRF32 a0 out = boundary $ do + a0Value <- getQ32 a0 + checked (Right (Q.qrR a0Value)) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_qr_permutation_f32" ffiHmDenseQrQrPermutationF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrPermutationF32 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrPermutationF32 a0 out = boundary $ do + a0Value <- getQ32 a0 + checked (Right (Q.qrPermutation a0Value)) $ \value -> publish (Indices value) out + +foreign export ccall "hm_dense_qr_qr_rank_f32" ffiHmDenseQrQrRankF32 :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +ffiHmDenseQrQrRankF32 :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +ffiHmDenseQrQrRankF32 a0 out = boundary $ do + a0Value <- getQ32 a0 + checked (Right (Q.qrRank a0Value)) $ \value -> do + strict <- evaluate value + poke out (fromIntegral strict) + +foreign export ccall "hm_dense_qr_apply_q_f32" ffiHmDenseQrApplyQF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQF32 a0 a1 out = boundary $ do + a0Value <- getQ32 a0 + a1Value <- getM32 a1 + checked (Q.applyQ a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_apply_qt_f32" ffiHmDenseQrApplyQtF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQtF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQtF32 a0 a1 out = boundary $ do + a0Value <- getQ32 a0 + a1Value <- getM32 a1 + checked (Q.applyQT a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_solve_matrix_qr_f32" ffiHmDenseQrSolveMatrixQrF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveMatrixQrF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveMatrixQrF32 a0 a1 out = boundary $ do + a0Value <- getQ32 a0 + a1Value <- getM32 a1 + checked (Q.solveMatrixQR a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_solve_qr_f32" ffiHmDenseQrSolveQrF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveQrF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveQrF32 a0 a1 a1Count out = boundary $ do + a0Value <- getQ32 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Float) + checked (Q.solveQR a0Value a1Value) $ \value -> publish (V32 value) out + +foreign export ccall "hm_dense_qr_least_squares_f32" ffiHmDenseQrLeastSquaresF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresF32 :: StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresF32 a0 a1 a1Count out = boundary $ do + a0Value <- getM32 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Float) + checked (Q.leastSquares a0Value a1Value) $ \value -> publish (V32 value) out + +foreign export ccall "hm_dense_qr_least_squares_matrix_f32" ffiHmDenseQrLeastSquaresMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresMatrixF32 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresMatrixF32 a0 a1 out = boundary $ do + a0Value <- getM32 a0 + a1Value <- getM32 a1 + checked (Q.leastSquaresMatrix a0Value a1Value) $ \value -> publish (M32 value) out + +foreign export ccall "hm_dense_qr_ridge_solve_f32" ffiHmDenseQrRidgeSolveF32 :: CFloat -> StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveF32 :: CFloat -> StablePtr Object -> Ptr CFloat -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveF32 a0 a1 a2 a2Count out = boundary $ do + let a0Value = (coerce a0 :: Float) + a1Value <- getM32 a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Float) + checked (Q.ridgeSolve a0Value a1Value a2Value) $ \value -> publish (V32 value) out + +foreign export ccall "hm_dense_qr_ridge_solve_matrix_f32" ffiHmDenseQrRidgeSolveMatrixF32 :: CFloat -> StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveMatrixF32 :: CFloat -> StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveMatrixF32 a0 a1 a2 out = boundary $ do + let a0Value = (coerce a0 :: Float) + a1Value <- getM32 a1 + a2Value <- getM32 a2 + checked (Q.ridgeSolveMatrix a0Value a1Value a2Value) $ \value -> publish (M32 value) out + +getM64 :: StablePtr Object -> IO (M.Matrix Double) +getM64 pointer = do + value <- deRefStablePtr pointer + case value of + M64 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +getL64 :: StablePtr Object -> IO (L.LU Double) +getL64 pointer = do + value <- deRefStablePtr pointer + case value of + L64 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +getQ64 :: StablePtr Object -> IO (Q.QR Double) +getQ64 pointer = do + value <- deRefStablePtr pointer + case value of + Q64 x -> pure x + _ -> fail "dense object kind/precision mismatch" + +foreign export ccall "hm_dense_values_f64" values64 :: StablePtr Object -> Ptr CDouble -> IO CInt +values64 :: StablePtr Object -> Ptr CDouble -> IO CInt +values64 pointer out = boundary $ do + object <- deRefStablePtr pointer + let values = case object of + M64 m -> M.toList m + V64 xs -> xs + _ -> error "dense values kind/precision mismatch" + strict <- mapM evaluate values + checked (Right ()) (const (pokeArray (castPtr out :: Ptr Double) strict)) + +foreign export ccall "hm_dense_from_list_f64" ffiHmDenseFromListF64 :: CPtrdiff -> CPtrdiff -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListF64 :: CPtrdiff -> CPtrdiff -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListF64 a0 a1 a2 a2Count out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Double) + checked (Right (M.fromList a0Value a1Value a2Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_zero_matrix_f64" ffiHmDenseZeroMatrixF64 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixF64 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixF64 a0 a1 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + checked (Right (M.zeroMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_diagonal_f64" ffiHmDenseDiagonalF64 :: Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalF64 :: Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalF64 a0 a0Count out = boundary $ do + a0Value <- peekArray (fromIntegral a0Count) (castPtr a0 :: Ptr Double) + checked (Right (M.diagonal a0Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_at_f64" ffiHmDenseAtF64 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CDouble -> Ptr CInt -> IO CInt +ffiHmDenseAtF64 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CDouble -> Ptr CInt -> IO CInt +ffiHmDenseAtF64 a0 a1 a2 out found = boundary $ do + a0Value <- getM64 a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + checked (Right (M.at a0Value a1Value a2Value) :: Either MathError (Maybe Double)) $ \result -> case result of + Nothing -> poke found 0 + Just value -> do + strict <- evaluate value + poke out (coerce strict :: CDouble) + poke found 1 + +foreign export ccall "hm_dense_slice_matrix_f64" ffiHmDenseSliceMatrixF64 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixF64 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixF64 a0 a1 a2 a3 a4 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + let a3Value = fromIntegral a3 + a4Value <- getM64 a4 + checked (Right (M.sliceMatrix (a0Value,a1Value) (a2Value,a3Value) a4Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_reshape_f64" ffiHmDenseReshapeF64 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeF64 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeF64 a0 a1 a2 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- getM64 a2 + checked (Right (M.reshape a0Value a1Value a2Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_add_matrix_f64" ffiHmDenseAddMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (Right (M.addMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_subtract_matrix_f64" ffiHmDenseSubtractMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (Right (M.subtractMatrix a0Value a1Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_hadamard_f64" ffiHmDenseHadamardF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (Right (M.hadamard a0Value a1Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_multiply_f64" ffiHmDenseMultiplyF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (Right (M.multiply a0Value a1Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_identity_f64" ffiHmDenseIdentityF64 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityF64 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityF64 a0 out = boundary $ do + let a0Value = fromIntegral a0 + checked (Right (M.identity a0Value) :: Either MathError (Maybe (M.Matrix Double))) $ \value -> publishMaybe M64 value out + +foreign export ccall "hm_dense_from_list_checked_f64" ffiHmDenseFromListCheckedF64 :: CPtrdiff -> CPtrdiff -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListCheckedF64 :: CPtrdiff -> CPtrdiff -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseFromListCheckedF64 a0 a1 a2 a2Count out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Double) + checked (M.fromListChecked a0Value a1Value a2Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_zero_matrix_checked_f64" ffiHmDenseZeroMatrixCheckedF64 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixCheckedF64 :: CPtrdiff -> CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseZeroMatrixCheckedF64 a0 a1 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + checked (M.zeroMatrixChecked a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_diagonal_checked_f64" ffiHmDenseDiagonalCheckedF64 :: Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalCheckedF64 :: Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseDiagonalCheckedF64 a0 a0Count out = boundary $ do + a0Value <- peekArray (fromIntegral a0Count) (castPtr a0 :: Ptr Double) + checked (M.diagonalChecked a0Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_at_checked_f64" ffiHmDenseAtCheckedF64 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CDouble -> IO CInt +ffiHmDenseAtCheckedF64 :: StablePtr Object -> CPtrdiff -> CPtrdiff -> Ptr CDouble -> IO CInt +ffiHmDenseAtCheckedF64 a0 a1 a2 out = boundary $ do + a0Value <- getM64 a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + checked (M.atChecked a0Value a1Value a2Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CDouble) + +foreign export ccall "hm_dense_slice_matrix_checked_f64" ffiHmDenseSliceMatrixCheckedF64 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixCheckedF64 :: CPtrdiff -> CPtrdiff -> CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSliceMatrixCheckedF64 a0 a1 a2 a3 a4 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + let a2Value = fromIntegral a2 + let a3Value = fromIntegral a3 + a4Value <- getM64 a4 + checked (M.sliceMatrixChecked (a0Value,a1Value) (a2Value,a3Value) a4Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_reshape_checked_f64" ffiHmDenseReshapeCheckedF64 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeCheckedF64 :: CPtrdiff -> CPtrdiff -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseReshapeCheckedF64 a0 a1 a2 out = boundary $ do + let a0Value = fromIntegral a0 + let a1Value = fromIntegral a1 + a2Value <- getM64 a2 + checked (M.reshapeChecked a0Value a1Value a2Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_add_matrix_checked_f64" ffiHmDenseAddMatrixCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseAddMatrixCheckedF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (M.addMatrixChecked a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_subtract_matrix_checked_f64" ffiHmDenseSubtractMatrixCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseSubtractMatrixCheckedF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (M.subtractMatrixChecked a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_hadamard_checked_f64" ffiHmDenseHadamardCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseHadamardCheckedF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (M.hadamardChecked a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_multiply_checked_f64" ffiHmDenseMultiplyCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyCheckedF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseMultiplyCheckedF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (M.multiplyChecked a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_identity_checked_f64" ffiHmDenseIdentityCheckedF64 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityCheckedF64 :: CPtrdiff -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseIdentityCheckedF64 a0 out = boundary $ do + let a0Value = fromIntegral a0 + checked (M.identityChecked a0Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_scale_matrix_f64" ffiHmDenseScaleMatrixF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseScaleMatrixF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseScaleMatrixF64 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Double) + a1Value <- getM64 a1 + checked (Right (M.scaleMatrix a0Value a1Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_transpose_matrix_f64" ffiHmDenseTransposeMatrixF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseTransposeMatrixF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseTransposeMatrixF64 a0 out = boundary $ do + a0Value <- getM64 a0 + checked (Right (M.transposeMatrix a0Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_lu_lu_decompose_f64" ffiHmDenseLuLuDecomposeF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeF64 a0 out = boundary $ do + a0Value <- getM64 a0 + checked (L.luDecompose a0Value) $ \value -> publish (L64 value) out + +foreign export ccall "hm_dense_lu_lu_decompose_with_tolerance_f64" ffiHmDenseLuLuDecomposeWithToleranceF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeWithToleranceF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuDecomposeWithToleranceF64 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Double) + a1Value <- getM64 a1 + checked (L.luDecomposeWithTolerance a0Value a1Value) $ \value -> publish (L64 value) out + +foreign export ccall "hm_dense_lu_lu_lower_f64" ffiHmDenseLuLuLowerF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuLowerF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuLowerF64 a0 out = boundary $ do + a0Value <- getL64 a0 + checked (Right (L.luLower a0Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_lu_lu_upper_f64" ffiHmDenseLuLuUpperF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuUpperF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuUpperF64 a0 out = boundary $ do + a0Value <- getL64 a0 + checked (Right (L.luUpper a0Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_lu_lu_permutation_f64" ffiHmDenseLuLuPermutationF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuPermutationF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuLuPermutationF64 a0 out = boundary $ do + a0Value <- getL64 a0 + checked (Right (L.luPermutation a0Value)) $ \value -> publish (Indices value) out + +foreign export ccall "hm_dense_lu_solve_lu_f64" ffiHmDenseLuSolveLuF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveLuF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveLuF64 a0 a1 a1Count out = boundary $ do + a0Value <- getL64 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Double) + checked (L.solveLU a0Value a1Value) $ \value -> publish (V64 value) out + +foreign export ccall "hm_dense_lu_solve_matrix_lu_f64" ffiHmDenseLuSolveMatrixLuF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixLuF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixLuF64 a0 a1 out = boundary $ do + a0Value <- getL64 a0 + a1Value <- getM64 a1 + checked (L.solveMatrixLU a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_lu_solve_f64" ffiHmDenseLuSolveF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveF64 a0 a1 a1Count out = boundary $ do + a0Value <- getM64 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Double) + checked (L.solve a0Value a1Value) $ \value -> publish (V64 value) out + +foreign export ccall "hm_dense_lu_solve_matrix_f64" ffiHmDenseLuSolveMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuSolveMatrixF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (L.solveMatrix a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_lu_determinant_lu_f64" ffiHmDenseLuDeterminantLuF64 :: StablePtr Object -> Ptr CDouble -> IO CInt +ffiHmDenseLuDeterminantLuF64 :: StablePtr Object -> Ptr CDouble -> IO CInt +ffiHmDenseLuDeterminantLuF64 a0 out = boundary $ do + a0Value <- getL64 a0 + checked (L.determinantLU a0Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CDouble) + +foreign export ccall "hm_dense_lu_determinant_f64" ffiHmDenseLuDeterminantF64 :: StablePtr Object -> Ptr CDouble -> IO CInt +ffiHmDenseLuDeterminantF64 :: StablePtr Object -> Ptr CDouble -> IO CInt +ffiHmDenseLuDeterminantF64 a0 out = boundary $ do + a0Value <- getM64 a0 + checked (L.determinant a0Value) $ \value -> do + strict <- evaluate value + poke out (coerce strict :: CDouble) + +foreign export ccall "hm_dense_lu_inverse_f64" ffiHmDenseLuInverseF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuInverseF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseLuInverseF64 a0 out = boundary $ do + a0Value <- getM64 a0 + checked (L.inverse a0Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_qr_decompose_f64" ffiHmDenseQrQrDecomposeF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeF64 a0 out = boundary $ do + a0Value <- getM64 a0 + checked (Q.qrDecompose a0Value) $ \value -> publish (Q64 value) out + +foreign export ccall "hm_dense_qr_qr_decompose_with_tolerance_f64" ffiHmDenseQrQrDecomposeWithToleranceF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeWithToleranceF64 :: CDouble -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrDecomposeWithToleranceF64 a0 a1 out = boundary $ do + let a0Value = (coerce a0 :: Double) + a1Value <- getM64 a1 + checked (Q.qrDecomposeWithTolerance a0Value a1Value) $ \value -> publish (Q64 value) out + +foreign export ccall "hm_dense_qr_qr_q_f64" ffiHmDenseQrQrQF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrQF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrQF64 a0 out = boundary $ do + a0Value <- getQ64 a0 + checked (Right (Q.qrQ a0Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_qr_r_f64" ffiHmDenseQrQrRF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrRF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrRF64 a0 out = boundary $ do + a0Value <- getQ64 a0 + checked (Right (Q.qrR a0Value)) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_qr_permutation_f64" ffiHmDenseQrQrPermutationF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrPermutationF64 :: StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrQrPermutationF64 a0 out = boundary $ do + a0Value <- getQ64 a0 + checked (Right (Q.qrPermutation a0Value)) $ \value -> publish (Indices value) out + +foreign export ccall "hm_dense_qr_qr_rank_f64" ffiHmDenseQrQrRankF64 :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +ffiHmDenseQrQrRankF64 :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +ffiHmDenseQrQrRankF64 a0 out = boundary $ do + a0Value <- getQ64 a0 + checked (Right (Q.qrRank a0Value)) $ \value -> do + strict <- evaluate value + poke out (fromIntegral strict) + +foreign export ccall "hm_dense_qr_apply_q_f64" ffiHmDenseQrApplyQF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQF64 a0 a1 out = boundary $ do + a0Value <- getQ64 a0 + a1Value <- getM64 a1 + checked (Q.applyQ a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_apply_qt_f64" ffiHmDenseQrApplyQtF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQtF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrApplyQtF64 a0 a1 out = boundary $ do + a0Value <- getQ64 a0 + a1Value <- getM64 a1 + checked (Q.applyQT a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_solve_matrix_qr_f64" ffiHmDenseQrSolveMatrixQrF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveMatrixQrF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveMatrixQrF64 a0 a1 out = boundary $ do + a0Value <- getQ64 a0 + a1Value <- getM64 a1 + checked (Q.solveMatrixQR a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_solve_qr_f64" ffiHmDenseQrSolveQrF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveQrF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrSolveQrF64 a0 a1 a1Count out = boundary $ do + a0Value <- getQ64 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Double) + checked (Q.solveQR a0Value a1Value) $ \value -> publish (V64 value) out + +foreign export ccall "hm_dense_qr_least_squares_f64" ffiHmDenseQrLeastSquaresF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresF64 :: StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresF64 a0 a1 a1Count out = boundary $ do + a0Value <- getM64 a0 + a1Value <- peekArray (fromIntegral a1Count) (castPtr a1 :: Ptr Double) + checked (Q.leastSquares a0Value a1Value) $ \value -> publish (V64 value) out + +foreign export ccall "hm_dense_qr_least_squares_matrix_f64" ffiHmDenseQrLeastSquaresMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresMatrixF64 :: StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrLeastSquaresMatrixF64 a0 a1 out = boundary $ do + a0Value <- getM64 a0 + a1Value <- getM64 a1 + checked (Q.leastSquaresMatrix a0Value a1Value) $ \value -> publish (M64 value) out + +foreign export ccall "hm_dense_qr_ridge_solve_f64" ffiHmDenseQrRidgeSolveF64 :: CDouble -> StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveF64 :: CDouble -> StablePtr Object -> Ptr CDouble -> CSize -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveF64 a0 a1 a2 a2Count out = boundary $ do + let a0Value = (coerce a0 :: Double) + a1Value <- getM64 a1 + a2Value <- peekArray (fromIntegral a2Count) (castPtr a2 :: Ptr Double) + checked (Q.ridgeSolve a0Value a1Value a2Value) $ \value -> publish (V64 value) out + +foreign export ccall "hm_dense_qr_ridge_solve_matrix_f64" ffiHmDenseQrRidgeSolveMatrixF64 :: CDouble -> StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveMatrixF64 :: CDouble -> StablePtr Object -> StablePtr Object -> Ptr (StablePtr Object) -> IO CInt +ffiHmDenseQrRidgeSolveMatrixF64 a0 a1 a2 out = boundary $ do + let a0Value = (coerce a0 :: Double) + a1Value <- getM64 a1 + a2Value <- getM64 a2 + checked (Q.ridgeSolveMatrix a0Value a1Value a2Value) $ \value -> publish (M64 value) out diff --git a/src/HMath/FFI/MatrixValue.hs b/src/HMath/FFI/MatrixValue.hs new file mode 100644 index 0000000..560acfd --- /dev/null +++ b/src/HMath/FFI/MatrixValue.hs @@ -0,0 +1,233 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_matrix_value_bindings.py. +module HMath.FFI.MatrixValue where +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Matrix as M +import qualified HMath.FFI.Matrix as Legacy +import qualified HMath.FFI.Value as V +import qualified HMath.Error +import HMath.FFI.Coefficient +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError + +withMatrix :: V.Value -> (forall a. Coefficient a => ScalarType a -> M.Matrix a -> IO V.Value) -> IO V.Value +withMatrix (V.Dense (V.SomeMatrix witness matrix)) action = action witness matrix +withMatrix _ _ = V.invalid "expected Matrix value" +withWitness :: V.Value -> (forall a. Coefficient a => ScalarType a -> IO V.Value) -> IO V.Value +withWitness (V.Scalar witness _) action = action witness +withWitness _ _ = V.invalid "expected scalar coefficient prototype" +asMatrix :: forall a. Coefficient a => V.Value -> IO (M.Matrix a) +asMatrix (V.Dense (V.SomeMatrix _ matrix)) = maybe (V.invalid "Matrix coefficient types differ") pure (cast matrix) +asMatrix _ = V.invalid "expected Matrix value" +scalars :: Coefficient a => V.Value -> IO [a] +scalars value = V.asList value >>= mapM V.asScalar +source :: Either HMath.Error.MathError a -> IO a +source = either (throwIO . CallbackMathError) pure +matrixBoundary :: IO CInt -> IO CInt +matrixBoundary action = B.boundary $ callbackBoundary (\e -> B.checked (Left e) (const (pure ()))) action +apply :: Int -> [V.Value] -> IO V.Value +apply op args = case (op,args) of + (0,[prototype,a0,a1,a2]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- scalars a2 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.fromList a0Value a1Value a2Value)) + (1,[prototype,a0,a1]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.zeroMatrix a0Value a1Value)) + (2,[prototype,a0]) -> withWitness prototype $ \w -> do + a0Value <- scalars a0 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.diagonal a0Value)) + (3,[a0,a1,a2]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + pure (maybe V.None (V.Scalar w) (M.at a0Value a1Value a2Value)) + (4,[a0,a1,a2,a3,a4]) -> withMatrix a4 $ \w m -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + a3Value <- V.asIndex a3 + let a4Value = m + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.sliceMatrix (a0Value,a1Value) (a2Value,a3Value) a4Value)) + (5,[a0,a1,a2]) -> withMatrix a2 $ \w m -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + let a2Value = m + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.reshape a0Value a1Value a2Value)) + (6,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.addMatrix a0Value a1Value)) + (7,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.subtractMatrix a0Value a1Value)) + (8,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.hadamard a0Value a1Value)) + (9,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.multiply a0Value a1Value)) + (10,[prototype,a0]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + pure (maybe V.None (V.Dense . V.SomeMatrix w) (M.identity a0Value)) + (11,[prototype,a0,a1,a2]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- scalars a2 + (V.Dense . V.SomeMatrix w) <$> source (M.fromListChecked a0Value a1Value a2Value) + (12,[prototype,a0,a1]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + (V.Dense . V.SomeMatrix w) <$> source (M.zeroMatrixChecked a0Value a1Value) + (13,[prototype,a0]) -> withWitness prototype $ \w -> do + a0Value <- scalars a0 + (V.Dense . V.SomeMatrix w) <$> source (M.diagonalChecked a0Value) + (14,[a0,a1,a2]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + (V.Scalar w) <$> source (M.atChecked a0Value a1Value a2Value) + (15,[a0,a1,a2,a3,a4]) -> withMatrix a4 $ \w m -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + a3Value <- V.asIndex a3 + let a4Value = m + (V.Dense . V.SomeMatrix w) <$> source (M.sliceMatrixChecked (a0Value,a1Value) (a2Value,a3Value) a4Value) + (16,[a0,a1,a2]) -> withMatrix a2 $ \w m -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + let a2Value = m + (V.Dense . V.SomeMatrix w) <$> source (M.reshapeChecked a0Value a1Value a2Value) + (17,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + (V.Dense . V.SomeMatrix w) <$> source (M.addMatrixChecked a0Value a1Value) + (18,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + (V.Dense . V.SomeMatrix w) <$> source (M.subtractMatrixChecked a0Value a1Value) + (19,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + (V.Dense . V.SomeMatrix w) <$> source (M.hadamardChecked a0Value a1Value) + (20,[a0,a1]) -> withMatrix a0 $ \w m -> do + let a0Value = m + a1Value <- asMatrix a1 + (V.Dense . V.SomeMatrix w) <$> source (M.multiplyChecked a0Value a1Value) + (21,[prototype,a0]) -> withWitness prototype $ \w -> do + a0Value <- V.asIndex a0 + (V.Dense . V.SomeMatrix w) <$> source (M.identityChecked a0Value) + (22,[a0,a1]) -> withMatrix a1 $ \w m -> do + a0Value <- V.asScalar a0 + let a1Value = m + pure ((V.Dense . V.SomeMatrix w) (M.scaleMatrix a0Value a1Value)) + (23,[a0]) -> withMatrix a0 $ \w m -> do + let a0Value = m + pure ((V.Dense . V.SomeMatrix w) (M.transposeMatrix a0Value)) + (100,[matrix]) -> withMatrix matrix $ \w m -> pure (V.List (map (V.Scalar w) (M.toList m))) + (101,[matrix]) -> withMatrix matrix $ \_ m -> let (r,c)=M.shape m in pure (V.Tuple [V.Index r,V.Index c]) + _ -> V.invalid "invalid Matrix Value operation or arity" +foreign export ccall "hm_matrix_value_apply" ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply opcode pointers count out = matrixBoundary $ do + args <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + value <- if any structuralValue args then structuralApply (fromIntegral opcode) args else apply (fromIntegral opcode) args + B.checked (Right ()) (const (V.publish value out)) +foreign export ccall "hm_dense_export_value" exportValue :: StablePtr Legacy.Object -> Ptr (StablePtr V.Value) -> IO CInt +exportValue :: StablePtr Legacy.Object -> Ptr (StablePtr V.Value) -> IO CInt +exportValue pointer out = matrixBoundary $ do + object <- deRefStablePtr pointer + case object of + Legacy.M32 m -> B.checked (Right ()) (const (V.publish (V.Dense (V.SomeMatrix SFloat m)) out)) + Legacy.M64 m -> B.checked (Right ()) (const (V.publish (V.Dense (V.SomeMatrix SDouble m)) out)) + _ -> V.invalid "expected legacy real Matrix owner" +foreign export ccall "hm_dense_import_value" importValue :: StablePtr V.Value -> Ptr (StablePtr Legacy.Object) -> IO CInt +importValue :: StablePtr V.Value -> Ptr (StablePtr Legacy.Object) -> IO CInt +importValue pointer out = matrixBoundary $ do + value <- deRefStablePtr pointer + case value of + V.Dense (V.SomeMatrix SFloat m) -> B.checked (Right ()) (const (Legacy.publish (Legacy.M32 m) out)) + V.Dense (V.SomeMatrix SDouble m) -> B.checked (Right ()) (const (Legacy.publish (Legacy.M64 m) out)) + _ -> V.invalid "legacy typed Matrix import requires Float or Double Matrix" + +-- Original structure-only operations over Bool/String or a captured codec. +structuralValue :: V.Value -> Bool +structuralValue (V.Boolean _) = True +structuralValue (V.Text _) = True +structuralValue (V.Dense(V.StructuralMatrix _ _ _ _ _)) = True +structuralValue _ = False +withStructural :: V.Value -> (forall a. Typeable a => Int -> (a -> IO V.Value) -> (V.Value -> IO a) -> (a -> IO ()) -> IO V.Value) -> IO V.Value +withStructural (V.Boolean _) action = action 16 (pure . V.Boolean) V.asBoolean (\x -> evaluate x >> pure ()) +withStructural (V.Text _) action = action 17 (pure . V.Text) V.asText (mapM_ evaluate) +withStructural (V.Dense(V.StructuralMatrix dtype writer reader force _)) action = action dtype writer reader force +withStructural _ _ = V.invalid "expected structural element prototype/Matrix" +structuralApply :: Int -> [V.Value] -> IO V.Value +structuralApply op args = case(op,args) of + (0,[prototype,a0,a1,a2]) -> withStructural prototype $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- (\x -> V.asList x >>= mapM reader) a2 + pure(maybe V.None (V.Dense . V.StructuralMatrix dtype writer reader force) (M.fromList a0Value a1Value a2Value)) + (3,[a0,a1,a2]) -> withStructural a0 $ \_dtype writer _reader _force -> do + a0Value <- V.asMatrix a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + maybe (pure V.None) writer (M.at a0Value a1Value a2Value) + (4,[a0,a1,a2,a3,a4]) -> withStructural a4 $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + a3Value <- V.asIndex a3 + a4Value <- V.asMatrix a4 + pure(maybe V.None (V.Dense . V.StructuralMatrix dtype writer reader force) (M.sliceMatrix (a0Value,a1Value) (a2Value,a3Value) a4Value)) + (5,[a0,a1,a2]) -> withStructural a2 $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asMatrix a2 + pure(maybe V.None (V.Dense . V.StructuralMatrix dtype writer reader force) (M.reshape a0Value a1Value a2Value)) + (11,[prototype,a0,a1,a2]) -> withStructural prototype $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- (\x -> V.asList x >>= mapM reader) a2 + source (M.fromListChecked a0Value a1Value a2Value) >>= pure . (V.Dense . V.StructuralMatrix dtype writer reader force) + (14,[a0,a1,a2]) -> withStructural a0 $ \_dtype writer _reader _force -> do + a0Value <- V.asMatrix a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + source (M.atChecked a0Value a1Value a2Value) >>= writer + (15,[a0,a1,a2,a3,a4]) -> withStructural a4 $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asIndex a2 + a3Value <- V.asIndex a3 + a4Value <- V.asMatrix a4 + source (M.sliceMatrixChecked (a0Value,a1Value) (a2Value,a3Value) a4Value) >>= pure . (V.Dense . V.StructuralMatrix dtype writer reader force) + (16,[a0,a1,a2]) -> withStructural a2 $ \dtype writer reader force -> do + a0Value <- V.asIndex a0 + a1Value <- V.asIndex a1 + a2Value <- V.asMatrix a2 + source (M.reshapeChecked a0Value a1Value a2Value) >>= pure . (V.Dense . V.StructuralMatrix dtype writer reader force) + (23,[a0]) -> withStructural a0 $ \dtype writer reader force -> do + a0Value <- V.asMatrix a0 + pure((V.Dense . V.StructuralMatrix dtype writer reader force) (M.transposeMatrix a0Value)) + (100,[matrix]) -> withStructural matrix $ \_ writer _ _ -> do + values <- V.asMatrix matrix + V.List <$> mapM writer (M.toList values) + (101,[matrix]) -> withStructural matrix $ \_ _ (_reader :: V.Value -> IO a) _ -> do + values <- (V.asMatrix matrix :: IO(M.Matrix a)) + let (rows,columns)=M.shape values + pure(V.Tuple[V.Index rows,V.Index columns]) + _ -> V.unsupported "original structural element type has no Num instance" diff --git a/src/HMath/FFI/Numeric.hs b/src/HMath/FFI/Numeric.hs new file mode 100644 index 0000000..351de03 --- /dev/null +++ b/src/HMath/FFI/Numeric.hs @@ -0,0 +1,17818 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; do not edit. +module HMath.FFI.Numeric where +import Control.Exception (bracketOnError, evaluate) +import Data.Coerce (coerce) +import Data.Complex (Complex ((:+)), realPart, imagPart) +import Data.Ratio (numerator, denominator, (%)) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import qualified HMath.API.Algebra as APIAlgebra +import qualified HMath.Algorithms as Algorithms +import qualified HMath.Basic as Basic +import qualified HMath.Combinatorics as Combinatorics +import qualified HMath.Complex as Complex +import qualified HMath.Constants as Constants +import qualified HMath.DataStructure as DataStructure +import qualified HMath.DeepLearning.Core as DeepLearningCore +import qualified HMath.DeepLearning.Metrics as DeepLearningMetrics +import qualified HMath.DeepLearning.Precision as DeepLearningPrecision +import qualified HMath.Discrete as Discrete +import qualified HMath.Fourier as Fourier +import qualified HMath.Geometry.Primitives as GeometryPrimitives +import qualified HMath.Graph.Core as GraphCore +import qualified HMath.Image.Color as ImageColor +import qualified HMath.Interpolation as Interpolation +import qualified HMath.Linear as Linear +import qualified HMath.NumberTheory as NumberTheory +import qualified HMath.Numeric as Numeric +import qualified HMath.Optimization.Common as OptimizationCommon +import qualified HMath.Probability as Probability +import qualified HMath.Random as Random +import qualified HMath.Scalar as Scalar +import qualified HMath.Signal as Signal +import qualified HMath.Special as Special +import qualified HMath.Statistics as Statistics +import qualified HMath.Statistics.Advanced as StatisticsAdvanced +import qualified HMath.Tensor as Tensor +import qualified HMath.TimeSeries.Core as TimeSeriesCore +import qualified HMath.TimeSeries.Diagnostics as TimeSeriesDiagnostics +import qualified HMath.Trigonometry as Trigonometry +import qualified HMath.Units as Units + +complexPairs :: [a] -> [Complex a] +complexPairs [] = [] +complexPairs (a : b : rest) = (a :+ b) : complexPairs rest +complexPairs _ = error "invalid complex transport" + +rationalPairs :: [Integer] -> [Rational] +rationalPairs [] = [] +rationalPairs (a : b : rest) = (a % b) : rationalPairs rest +rationalPairs _ = error "invalid Rational transport" + +foreign export ccall "hm_numeric_basic_factorial" ffiBasicFactorial :: + CString -> + Ptr CString -> + IO CInt +ffiBasicFactorial :: + CString -> + Ptr CString -> + IO CInt +ffiBasicFactorial vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Right (Basic.factorial + vNValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_basic_fibonacci" ffiBasicFibonacci :: + CString -> + Ptr CString -> + IO CInt +ffiBasicFibonacci :: + CString -> + Ptr CString -> + IO CInt +ffiBasicFibonacci vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Right (Basic.fibonacci + vNValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_basic_is_prime" ffiBasicIsPrime :: + CString -> + Ptr CInt -> + IO CInt +ffiBasicIsPrime :: + CString -> + Ptr CInt -> + IO CInt +ffiBasicIsPrime vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Right (Basic.isPrime + vNValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_basic_clamp_f32" ffiBasicClampF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicClampF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicClampF32 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (coerce vLow :: Float) + (coerce vHigh :: Float) + (coerce vValue :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_basic_clamp_f64" ffiBasicClampF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicClampF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicClampF64 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (coerce vLow :: Double) + (coerce vHigh :: Double) + (coerce vValue :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_basic_clamp_rational" ffiBasicClampRational :: + CString -> + CString -> + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiBasicClampRational :: + CString -> + CString -> + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiBasicClampRational vLowNumerator vLowDenominator vHighNumerator vHighDenominator vValueNumerator vValueDenominator out0 out1 = boundary $ do + vLowN <- readInteger vLowNumerator + vLowD <- readInteger vLowDenominator + vHighN <- readInteger vHighNumerator + vHighD <- readInteger vHighDenominator + vValueN <- readInteger vValueNumerator + vValueD <- readInteger vValueDenominator + checked (Right (Basic.clamp + (vLowN % vLowD) + (vHighN % vHighD) + (vValueN % vValueD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_basic_clamp_integer" ffiBasicClampInteger :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiBasicClampInteger :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiBasicClampInteger vLow vHigh vValue out0 = boundary $ do + vLowValue <- readInteger vLow + vHighValue <- readInteger vHigh + vValueValue <- readInteger vValue + checked (Right (Basic.clamp + vLowValue + vHighValue + vValueValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_basic_clamp_i8" ffiBasicClampI8 :: + Int8 -> + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiBasicClampI8 :: + Int8 -> + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiBasicClampI8 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Int8) + (vHigh :: Int8) + (vValue :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_basic_clamp_i16" ffiBasicClampI16 :: + Int16 -> + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiBasicClampI16 :: + Int16 -> + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiBasicClampI16 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Int16) + (vHigh :: Int16) + (vValue :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_basic_clamp_i32" ffiBasicClampI32 :: + Int32 -> + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiBasicClampI32 :: + Int32 -> + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiBasicClampI32 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Int32) + (vHigh :: Int32) + (vValue :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_basic_clamp_i64" ffiBasicClampI64 :: + Int64 -> + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiBasicClampI64 :: + Int64 -> + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiBasicClampI64 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Int64) + (vHigh :: Int64) + (vValue :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_basic_clamp_u8" ffiBasicClampU8 :: + Word8 -> + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiBasicClampU8 :: + Word8 -> + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiBasicClampU8 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Word8) + (vHigh :: Word8) + (vValue :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_basic_clamp_u16" ffiBasicClampU16 :: + Word16 -> + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiBasicClampU16 :: + Word16 -> + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiBasicClampU16 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Word16) + (vHigh :: Word16) + (vValue :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_basic_clamp_u32" ffiBasicClampU32 :: + Word32 -> + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiBasicClampU32 :: + Word32 -> + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiBasicClampU32 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Word32) + (vHigh :: Word32) + (vValue :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_basic_clamp_u64" ffiBasicClampU64 :: + Word64 -> + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiBasicClampU64 :: + Word64 -> + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiBasicClampU64 vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Word64) + (vHigh :: Word64) + (vValue :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_basic_clamp_int" ffiBasicClampInt :: + Int -> + Int -> + Int -> + Ptr Int -> + IO CInt +ffiBasicClampInt :: + Int -> + Int -> + Int -> + Ptr Int -> + IO CInt +ffiBasicClampInt vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Int) + (vHigh :: Int) + (vValue :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_basic_clamp_word" ffiBasicClampWord :: + Word -> + Word -> + Word -> + Ptr Word -> + IO CInt +ffiBasicClampWord :: + Word -> + Word -> + Word -> + Ptr Word -> + IO CInt +ffiBasicClampWord vLow vHigh vValue out0 = boundary $ do + checked (Right (Basic.clamp + (vLow :: Word) + (vHigh :: Word) + (vValue :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_basic_lerp_f32" ffiBasicLerpF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicLerpF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicLerpF32 vA vB vT out0 = boundary $ do + checked (Right (Basic.lerp + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vT :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_basic_lerp_f64" ffiBasicLerpF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicLerpF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicLerpF64 vA vB vT out0 = boundary $ do + checked (Right (Basic.lerp + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vT :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_basic_lerp_rational" ffiBasicLerpRational :: + CString -> + CString -> + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiBasicLerpRational :: + CString -> + CString -> + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiBasicLerpRational vANumerator vADenominator vBNumerator vBDenominator vTNumerator vTDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + vTN <- readInteger vTNumerator + vTD <- readInteger vTDenominator + checked (Right (Basic.lerp + (vAN % vAD) + (vBN % vBD) + (vTN % vTD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_basic_lerp_c64" ffiBasicLerpC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicLerpC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiBasicLerpC64 vA0 vA1 vB0 vB1 vT0 vT1 out0 out1 = boundary $ do + checked (Right (Basic.lerp + ((coerce vA0 :: Float) :+ (coerce vA1 :: Float)) + ((coerce vB0 :: Float) :+ (coerce vB1 :: Float)) + ((coerce vT0 :: Float) :+ (coerce vT1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_basic_lerp_c128" ffiBasicLerpC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicLerpC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiBasicLerpC128 vA0 vA1 vB0 vB1 vT0 vT1 out0 out1 = boundary $ do + checked (Right (Basic.lerp + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double)) + ((coerce vT0 :: Double) :+ (coerce vT1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_add_f32" ffiScalarAddF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAddF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAddF32 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (coerce vA :: Float) + (coerce vB :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_add_f64" ffiScalarAddF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAddF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAddF64 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_add_rational" ffiScalarAddRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarAddRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarAddRational vANumerator vADenominator vBNumerator vBDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + checked (Right (Scalar.add + (vAN % vAD) + (vBN % vBD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_add_integer" ffiScalarAddInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarAddInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarAddInteger vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (Scalar.add + vAValue + vBValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_add_i8" ffiScalarAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarAddI8 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_add_i16" ffiScalarAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarAddI16 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_add_i32" ffiScalarAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarAddI32 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_add_i64" ffiScalarAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarAddI64 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_add_u8" ffiScalarAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarAddU8 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_add_u16" ffiScalarAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarAddU16 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_add_u32" ffiScalarAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarAddU32 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_add_u64" ffiScalarAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarAddU64 vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_add_int" ffiScalarAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarAddInt vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_add_word" ffiScalarAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarAddWord vA vB out0 = boundary $ do + checked (Right (Scalar.add + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_add_c64" ffiScalarAddC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAddC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAddC64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.add + ((coerce vA0 :: Float) :+ (coerce vA1 :: Float)) + ((coerce vB0 :: Float) :+ (coerce vB1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_add_c128" ffiScalarAddC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAddC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAddC128 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.add + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_f32" ffiScalarSubtractScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSubtractScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSubtractScalarF32 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (coerce vA :: Float) + (coerce vB :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_f64" ffiScalarSubtractScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSubtractScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSubtractScalarF64 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_rational" ffiScalarSubtractScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarSubtractScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarSubtractScalarRational vANumerator vADenominator vBNumerator vBDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + checked (Right (Scalar.subtractScalar + (vAN % vAD) + (vBN % vBD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_integer" ffiScalarSubtractScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarSubtractScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarSubtractScalarInteger vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (Scalar.subtractScalar + vAValue + vBValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_i8" ffiScalarSubtractScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSubtractScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSubtractScalarI8 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_i16" ffiScalarSubtractScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSubtractScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSubtractScalarI16 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_i32" ffiScalarSubtractScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSubtractScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSubtractScalarI32 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_i64" ffiScalarSubtractScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSubtractScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSubtractScalarI64 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_u8" ffiScalarSubtractScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSubtractScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSubtractScalarU8 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_u16" ffiScalarSubtractScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSubtractScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSubtractScalarU16 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_u32" ffiScalarSubtractScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSubtractScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSubtractScalarU32 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_u64" ffiScalarSubtractScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSubtractScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSubtractScalarU64 vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_int" ffiScalarSubtractScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSubtractScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSubtractScalarInt vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_word" ffiScalarSubtractScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSubtractScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSubtractScalarWord vA vB out0 = boundary $ do + checked (Right (Scalar.subtractScalar + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_c64" ffiScalarSubtractScalarC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSubtractScalarC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSubtractScalarC64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.subtractScalar + ((coerce vA0 :: Float) :+ (coerce vA1 :: Float)) + ((coerce vB0 :: Float) :+ (coerce vB1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_subtract_scalar_c128" ffiScalarSubtractScalarC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSubtractScalarC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSubtractScalarC128 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.subtractScalar + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_multiply_f32" ffiScalarMultiplyF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMultiplyF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMultiplyF32 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (coerce vA :: Float) + (coerce vB :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_multiply_f64" ffiScalarMultiplyF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMultiplyF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMultiplyF64 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_multiply_rational" ffiScalarMultiplyRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMultiplyRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMultiplyRational vANumerator vADenominator vBNumerator vBDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + checked (Right (Scalar.multiply + (vAN % vAD) + (vBN % vBD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_multiply_integer" ffiScalarMultiplyInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMultiplyInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMultiplyInteger vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (Scalar.multiply + vAValue + vBValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_multiply_i8" ffiScalarMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMultiplyI8 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_multiply_i16" ffiScalarMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMultiplyI16 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_multiply_i32" ffiScalarMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMultiplyI32 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_multiply_i64" ffiScalarMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMultiplyI64 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_multiply_u8" ffiScalarMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMultiplyU8 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_multiply_u16" ffiScalarMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMultiplyU16 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_multiply_u32" ffiScalarMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMultiplyU32 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_multiply_u64" ffiScalarMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMultiplyU64 vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_multiply_int" ffiScalarMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMultiplyInt vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_multiply_word" ffiScalarMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMultiplyWord vA vB out0 = boundary $ do + checked (Right (Scalar.multiply + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_multiply_c64" ffiScalarMultiplyC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMultiplyC64 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMultiplyC64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.multiply + ((coerce vA0 :: Float) :+ (coerce vA1 :: Float)) + ((coerce vB0 :: Float) :+ (coerce vB1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_multiply_c128" ffiScalarMultiplyC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMultiplyC128 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMultiplyC128 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Right (Scalar.multiply + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_f32" ffiScalarMinimumScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMinimumScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMinimumScalarF32 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (coerce vA :: Float) + (coerce vB :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_f64" ffiScalarMinimumScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMinimumScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMinimumScalarF64 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_rational" ffiScalarMinimumScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMinimumScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMinimumScalarRational vANumerator vADenominator vBNumerator vBDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + checked (Right (Scalar.minimumScalar + (vAN % vAD) + (vBN % vBD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_integer" ffiScalarMinimumScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMinimumScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMinimumScalarInteger vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (Scalar.minimumScalar + vAValue + vBValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_i8" ffiScalarMinimumScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMinimumScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMinimumScalarI8 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_i16" ffiScalarMinimumScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMinimumScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMinimumScalarI16 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_i32" ffiScalarMinimumScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMinimumScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMinimumScalarI32 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_i64" ffiScalarMinimumScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMinimumScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMinimumScalarI64 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_u8" ffiScalarMinimumScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMinimumScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMinimumScalarU8 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_u16" ffiScalarMinimumScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMinimumScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMinimumScalarU16 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_u32" ffiScalarMinimumScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMinimumScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMinimumScalarU32 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_u64" ffiScalarMinimumScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMinimumScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMinimumScalarU64 vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_int" ffiScalarMinimumScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMinimumScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMinimumScalarInt vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_minimum_scalar_word" ffiScalarMinimumScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMinimumScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMinimumScalarWord vA vB out0 = boundary $ do + checked (Right (Scalar.minimumScalar + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_f32" ffiScalarMaximumScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMaximumScalarF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarMaximumScalarF32 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (coerce vA :: Float) + (coerce vB :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_f64" ffiScalarMaximumScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMaximumScalarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarMaximumScalarF64 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_rational" ffiScalarMaximumScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMaximumScalarRational :: + CString -> + CString -> + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarMaximumScalarRational vANumerator vADenominator vBNumerator vBDenominator out0 out1 = boundary $ do + vAN <- readInteger vANumerator + vAD <- readInteger vADenominator + vBN <- readInteger vBNumerator + vBD <- readInteger vBDenominator + checked (Right (Scalar.maximumScalar + (vAN % vAD) + (vBN % vBD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_integer" ffiScalarMaximumScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMaximumScalarInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarMaximumScalarInteger vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (Scalar.maximumScalar + vAValue + vBValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_i8" ffiScalarMaximumScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMaximumScalarI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarMaximumScalarI8 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_i16" ffiScalarMaximumScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMaximumScalarI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarMaximumScalarI16 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_i32" ffiScalarMaximumScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMaximumScalarI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarMaximumScalarI32 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_i64" ffiScalarMaximumScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMaximumScalarI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarMaximumScalarI64 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_u8" ffiScalarMaximumScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMaximumScalarU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarMaximumScalarU8 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_u16" ffiScalarMaximumScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMaximumScalarU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarMaximumScalarU16 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_u32" ffiScalarMaximumScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMaximumScalarU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarMaximumScalarU32 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_u64" ffiScalarMaximumScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMaximumScalarU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarMaximumScalarU64 vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_int" ffiScalarMaximumScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMaximumScalarInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarMaximumScalarInt vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_maximum_scalar_word" ffiScalarMaximumScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMaximumScalarWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarMaximumScalarWord vA vB out0 = boundary $ do + checked (Right (Scalar.maximumScalar + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_absolute_f32" ffiScalarAbsoluteF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteF32 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_absolute_f64" ffiScalarAbsoluteF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteF64 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_absolute_rational" ffiScalarAbsoluteRational :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarAbsoluteRational :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarAbsoluteRational vXNumerator vXDenominator out0 out1 = boundary $ do + vXN <- readInteger vXNumerator + vXD <- readInteger vXDenominator + checked (Right (Scalar.absolute + (vXN % vXD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_absolute_integer" ffiScalarAbsoluteInteger :: + CString -> + Ptr CString -> + IO CInt +ffiScalarAbsoluteInteger :: + CString -> + Ptr CString -> + IO CInt +ffiScalarAbsoluteInteger vX out0 = boundary $ do + vXValue <- readInteger vX + checked (Right (Scalar.absolute + vXValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_absolute_i8" ffiScalarAbsoluteI8 :: + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarAbsoluteI8 :: + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarAbsoluteI8 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_absolute_i16" ffiScalarAbsoluteI16 :: + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarAbsoluteI16 :: + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarAbsoluteI16 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_absolute_i32" ffiScalarAbsoluteI32 :: + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarAbsoluteI32 :: + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarAbsoluteI32 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_absolute_i64" ffiScalarAbsoluteI64 :: + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarAbsoluteI64 :: + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarAbsoluteI64 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_absolute_u8" ffiScalarAbsoluteU8 :: + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarAbsoluteU8 :: + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarAbsoluteU8 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_absolute_u16" ffiScalarAbsoluteU16 :: + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarAbsoluteU16 :: + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarAbsoluteU16 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_absolute_u32" ffiScalarAbsoluteU32 :: + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarAbsoluteU32 :: + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarAbsoluteU32 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_absolute_u64" ffiScalarAbsoluteU64 :: + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarAbsoluteU64 :: + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarAbsoluteU64 vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_absolute_int" ffiScalarAbsoluteInt :: + Int -> + Ptr Int -> + IO CInt +ffiScalarAbsoluteInt :: + Int -> + Ptr Int -> + IO CInt +ffiScalarAbsoluteInt vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_absolute_word" ffiScalarAbsoluteWord :: + Word -> + Ptr Word -> + IO CInt +ffiScalarAbsoluteWord :: + Word -> + Ptr Word -> + IO CInt +ffiScalarAbsoluteWord vX out0 = boundary $ do + checked (Right (Scalar.absolute + (vX :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_absolute_c64" ffiScalarAbsoluteC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteC64 vX0 vX1 out0 out1 = boundary $ do + checked (Right (Scalar.absolute + ((coerce vX0 :: Float) :+ (coerce vX1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_absolute_c128" ffiScalarAbsoluteC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteC128 vX0 vX1 out0 out1 = boundary $ do + checked (Right (Scalar.absolute + ((coerce vX0 :: Double) :+ (coerce vX1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_sign_f32" ffiScalarSignF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSignF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSignF32 vX out0 = boundary $ do + checked (Right (Scalar.sign + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_sign_f64" ffiScalarSignF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSignF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSignF64 vX out0 = boundary $ do + checked (Right (Scalar.sign + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_sign_rational" ffiScalarSignRational :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarSignRational :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarSignRational vXNumerator vXDenominator out0 out1 = boundary $ do + vXN <- readInteger vXNumerator + vXD <- readInteger vXDenominator + checked (Right (Scalar.sign + (vXN % vXD))) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_sign_integer" ffiScalarSignInteger :: + CString -> + Ptr CString -> + IO CInt +ffiScalarSignInteger :: + CString -> + Ptr CString -> + IO CInt +ffiScalarSignInteger vX out0 = boundary $ do + vXValue <- readInteger vX + checked (Right (Scalar.sign + vXValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_sign_i8" ffiScalarSignI8 :: + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSignI8 :: + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSignI8 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_sign_i16" ffiScalarSignI16 :: + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSignI16 :: + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSignI16 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_sign_i32" ffiScalarSignI32 :: + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSignI32 :: + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSignI32 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_sign_i64" ffiScalarSignI64 :: + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSignI64 :: + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSignI64 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_sign_u8" ffiScalarSignU8 :: + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSignU8 :: + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSignU8 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_sign_u16" ffiScalarSignU16 :: + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSignU16 :: + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSignU16 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_sign_u32" ffiScalarSignU32 :: + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSignU32 :: + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSignU32 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_sign_u64" ffiScalarSignU64 :: + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSignU64 :: + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSignU64 vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_sign_int" ffiScalarSignInt :: + Int -> + Ptr Int -> + IO CInt +ffiScalarSignInt :: + Int -> + Ptr Int -> + IO CInt +ffiScalarSignInt vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_sign_word" ffiScalarSignWord :: + Word -> + Ptr Word -> + IO CInt +ffiScalarSignWord :: + Word -> + Ptr Word -> + IO CInt +ffiScalarSignWord vX out0 = boundary $ do + checked (Right (Scalar.sign + (vX :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_sign_c64" ffiScalarSignC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSignC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSignC64 vX0 vX1 out0 out1 = boundary $ do + checked (Right (Scalar.sign + ((coerce vX0 :: Float) :+ (coerce vX1 :: Float)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_sign_c128" ffiScalarSignC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSignC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSignC128 vX0 vX1 out0 out1 = boundary $ do + checked (Right (Scalar.sign + ((coerce vX0 :: Double) :+ (coerce vX1 :: Double)))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_divide_f32" ffiScalarDivideF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarDivideF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarDivideF32 vA vB out0 = boundary $ do + checked (Scalar.divide + (coerce vA :: Float) + (coerce vB :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_divide_f64" ffiScalarDivideF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarDivideF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarDivideF64 vA vB out0 = boundary $ do + checked (Scalar.divide + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_power_f32" ffiScalarPowerF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarPowerF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarPowerF32 vA vB out0 = boundary $ do + checked (Scalar.power + (coerce vA :: Float) + (coerce vB :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_power_f64" ffiScalarPowerF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarPowerF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarPowerF64 vA vB out0 = boundary $ do + checked (Scalar.power + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_hypot_f32" ffiScalarHypotF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarHypotF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarHypotF32 vA vB out0 = boundary $ do + checked (Scalar.hypot + (coerce vA :: Float) + (coerce vB :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_hypot_f64" ffiScalarHypotF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarHypotF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarHypotF64 vA vB out0 = boundary $ do + checked (Scalar.hypot + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_clamp_checked_f32" ffiScalarClampCheckedF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarClampCheckedF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarClampCheckedF32 vLow vHigh vValue out0 = boundary $ do + checked (Scalar.clampChecked + (coerce vLow :: Float) + (coerce vHigh :: Float) + (coerce vValue :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_clamp_checked_f64" ffiScalarClampCheckedF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarClampCheckedF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarClampCheckedF64 vLow vHigh vValue out0 = boundary $ do + checked (Scalar.clampChecked + (coerce vLow :: Double) + (coerce vHigh :: Double) + (coerce vValue :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_lerp_checked_f32" ffiScalarLerpCheckedF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLerpCheckedF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLerpCheckedF32 vA vB vT out0 = boundary $ do + checked (Scalar.lerpChecked + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vT :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_lerp_checked_f64" ffiScalarLerpCheckedF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLerpCheckedF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLerpCheckedF64 vA vB vT out0 = boundary $ do + checked (Scalar.lerpChecked + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vT :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_inverse_lerp_f32" ffiScalarInverseLerpF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarInverseLerpF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarInverseLerpF32 vA vB vX out0 = boundary $ do + checked (Scalar.inverseLerp + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_inverse_lerp_f64" ffiScalarInverseLerpF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarInverseLerpF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarInverseLerpF64 vA vB vX out0 = boundary $ do + checked (Scalar.inverseLerp + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_smoothstep_f32" ffiScalarSmoothstepF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSmoothstepF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSmoothstepF32 vA vB vX out0 = boundary $ do + checked (Scalar.smoothstep + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_smoothstep_f64" ffiScalarSmoothstepF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSmoothstepF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSmoothstepF64 vA vB vX out0 = boundary $ do + checked (Scalar.smoothstep + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_smootherstep_f32" ffiScalarSmootherstepF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSmootherstepF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSmootherstepF32 vA vB vX out0 = boundary $ do + checked (Scalar.smootherstep + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_smootherstep_f64" ffiScalarSmootherstepF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSmootherstepF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSmootherstepF64 vA vB vX out0 = boundary $ do + checked (Scalar.smootherstep + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_remap_f32" ffiScalarRemapF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRemapF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRemapF32 vA vB vC vD vX out0 = boundary $ do + checked (Scalar.remap + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vC :: Float) + (coerce vD :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_remap_f64" ffiScalarRemapF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRemapF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRemapF64 vA vB vC vD vX out0 = boundary $ do + checked (Scalar.remap + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vC :: Double) + (coerce vD :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_step_f32" ffiScalarStepF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarStepF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarStepF32 vEdge vX out0 = boundary $ do + checked (Scalar.step + (coerce vEdge :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_step_f64" ffiScalarStepF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarStepF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarStepF64 vEdge vX out0 = boundary $ do + checked (Scalar.step + (coerce vEdge :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_sqrt_checked_f32" ffiScalarSqrtCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSqrtCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarSqrtCheckedF32 vX out0 = boundary $ do + checked (Scalar.sqrtChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_sqrt_checked_f64" ffiScalarSqrtCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSqrtCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarSqrtCheckedF64 vX out0 = boundary $ do + checked (Scalar.sqrtChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_cube_root_f32" ffiScalarCubeRootF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarCubeRootF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarCubeRootF32 vX out0 = boundary $ do + checked (Scalar.cubeRoot + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_cube_root_f64" ffiScalarCubeRootF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarCubeRootF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarCubeRootF64 vX out0 = boundary $ do + checked (Scalar.cubeRoot + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_reciprocal_sqrt_f32" ffiScalarReciprocalSqrtF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarReciprocalSqrtF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarReciprocalSqrtF32 vX out0 = boundary $ do + checked (Scalar.reciprocalSqrt + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_reciprocal_sqrt_f64" ffiScalarReciprocalSqrtF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarReciprocalSqrtF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarReciprocalSqrtF64 vX out0 = boundary $ do + checked (Scalar.reciprocalSqrt + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_exp_checked_f32" ffiScalarExpCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarExpCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarExpCheckedF32 vX out0 = boundary $ do + checked (Scalar.expChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_exp_checked_f64" ffiScalarExpCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarExpCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarExpCheckedF64 vX out0 = boundary $ do + checked (Scalar.expChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_log_checked_f32" ffiScalarLogCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLogCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLogCheckedF32 vX out0 = boundary $ do + checked (Scalar.logChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_log_checked_f64" ffiScalarLogCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLogCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLogCheckedF64 vX out0 = boundary $ do + checked (Scalar.logChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_expm1_f32" ffiScalarExpm1F32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarExpm1F32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarExpm1F32 vX out0 = boundary $ do + checked (Scalar.expm1 + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_expm1_f64" ffiScalarExpm1F64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarExpm1F64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarExpm1F64 vX out0 = boundary $ do + checked (Scalar.expm1 + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_log1p_f32" ffiScalarLog1PF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLog1PF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarLog1PF32 vX out0 = boundary $ do + checked (Scalar.log1p + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_log1p_f64" ffiScalarLog1PF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLog1PF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarLog1PF64 vX out0 = boundary $ do + checked (Scalar.log1p + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_integer_power_f32" ffiScalarIntegerPowerF32 :: + CFloat -> + CString -> + Ptr CFloat -> + IO CInt +ffiScalarIntegerPowerF32 :: + CFloat -> + CString -> + Ptr CFloat -> + IO CInt +ffiScalarIntegerPowerF32 vA vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.integerPower + (coerce vA :: Float) + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_integer_power_f64" ffiScalarIntegerPowerF64 :: + CDouble -> + CString -> + Ptr CDouble -> + IO CInt +ffiScalarIntegerPowerF64 :: + CDouble -> + CString -> + Ptr CDouble -> + IO CInt +ffiScalarIntegerPowerF64 vA vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.integerPower + (coerce vA :: Double) + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_nth_root_f32" ffiScalarNthRootF32 :: + CPtrdiff -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarNthRootF32 :: + CPtrdiff -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarNthRootF32 vN vX out0 = boundary $ do + checked (Scalar.nthRoot + (fromIntegral vN) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_nth_root_f64" ffiScalarNthRootF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarNthRootF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarNthRootF64 vN vX out0 = boundary $ do + checked (Scalar.nthRoot + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_round_digits_f32" ffiScalarRoundDigitsF32 :: + CPtrdiff -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRoundDigitsF32 :: + CPtrdiff -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRoundDigitsF32 vN vX out0 = boundary $ do + checked (Scalar.roundDigits + (fromIntegral vN) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_round_digits_f64" ffiScalarRoundDigitsF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRoundDigitsF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRoundDigitsF64 vN vX out0 = boundary $ do + checked (Scalar.roundDigits + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_absolute_error_f32" ffiScalarAbsoluteErrorF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteErrorF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarAbsoluteErrorF32 vActual vExpected out0 = boundary $ do + checked (Scalar.absoluteError + (coerce vActual :: Float) + (coerce vExpected :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_absolute_error_f64" ffiScalarAbsoluteErrorF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteErrorF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarAbsoluteErrorF64 vActual vExpected out0 = boundary $ do + checked (Scalar.absoluteError + (coerce vActual :: Double) + (coerce vExpected :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_relative_error_f32" ffiScalarRelativeErrorF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRelativeErrorF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarRelativeErrorF32 vActual vExpected out0 = boundary $ do + checked (Scalar.relativeError + (coerce vActual :: Float) + (coerce vExpected :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_relative_error_f64" ffiScalarRelativeErrorF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRelativeErrorF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarRelativeErrorF64 vActual vExpected out0 = boundary $ do + checked (Scalar.relativeError + (coerce vActual :: Double) + (coerce vExpected :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_fused_multiply_add_f32" ffiScalarFusedMultiplyAddF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarFusedMultiplyAddF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarFusedMultiplyAddF32 vA vB vC out0 = boundary $ do + checked (Scalar.fusedMultiplyAdd + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vC :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_fused_multiply_add_f64" ffiScalarFusedMultiplyAddF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarFusedMultiplyAddF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarFusedMultiplyAddF64 vA vB vC out0 = boundary $ do + checked (Scalar.fusedMultiplyAdd + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vC :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_checked_float_multiply_f32" ffiScalarCheckedFloatMultiplyF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarCheckedFloatMultiplyF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiScalarCheckedFloatMultiplyF32 vA vB out0 = boundary $ do + checked (Scalar.checkedFloatMultiply + (coerce vA :: Float) + (coerce vB :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_scalar_checked_float_multiply_f64" ffiScalarCheckedFloatMultiplyF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarCheckedFloatMultiplyF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiScalarCheckedFloatMultiplyF64 vA vB out0 = boundary $ do + checked (Scalar.checkedFloatMultiply + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_floor_checked_f32" ffiScalarFloorCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarFloorCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarFloorCheckedF32 vX out0 = boundary $ do + checked (Scalar.floorChecked + (coerce vX :: Float)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_floor_checked_f64" ffiScalarFloorCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarFloorCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarFloorCheckedF64 vX out0 = boundary $ do + checked (Scalar.floorChecked + (coerce vX :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_ceil_checked_f32" ffiScalarCeilCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarCeilCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarCeilCheckedF32 vX out0 = boundary $ do + checked (Scalar.ceilChecked + (coerce vX :: Float)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_ceil_checked_f64" ffiScalarCeilCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarCeilCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarCeilCheckedF64 vX out0 = boundary $ do + checked (Scalar.ceilChecked + (coerce vX :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_round_checked_f32" ffiScalarRoundCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarRoundCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarRoundCheckedF32 vX out0 = boundary $ do + checked (Scalar.roundChecked + (coerce vX :: Float)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_round_checked_f64" ffiScalarRoundCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarRoundCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarRoundCheckedF64 vX out0 = boundary $ do + checked (Scalar.roundChecked + (coerce vX :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_truncate_checked_f32" ffiScalarTruncateCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarTruncateCheckedF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarTruncateCheckedF32 vX out0 = boundary $ do + checked (Scalar.truncateChecked + (coerce vX :: Float)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_truncate_checked_f64" ffiScalarTruncateCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarTruncateCheckedF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarTruncateCheckedF64 vX out0 = boundary $ do + checked (Scalar.truncateChecked + (coerce vX :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_bankers_round_f32" ffiScalarBankersRoundF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarBankersRoundF32 :: + CFloat -> + Ptr CString -> + IO CInt +ffiScalarBankersRoundF32 vX out0 = boundary $ do + checked (Scalar.bankersRound + (coerce vX :: Float)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_bankers_round_f64" ffiScalarBankersRoundF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarBankersRoundF64 :: + CDouble -> + Ptr CString -> + IO CInt +ffiScalarBankersRoundF64 vX out0 = boundary $ do + checked (Scalar.bankersRound + (coerce vX :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_integer_fraction_f32" ffiScalarIntegerFractionF32 :: + CFloat -> + Ptr CString -> + Ptr CFloat -> + IO CInt +ffiScalarIntegerFractionF32 :: + CFloat -> + Ptr CString -> + Ptr CFloat -> + IO CInt +ffiScalarIntegerFractionF32 vX out0 out1 = boundary $ do + checked (Scalar.integerFraction + (coerce vX :: Float)) $ \(first, second) -> do + strict1 <- evaluate (second) + writeStrings [show (first)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_scalar_integer_fraction_f64" ffiScalarIntegerFractionF64 :: + CDouble -> + Ptr CString -> + Ptr CDouble -> + IO CInt +ffiScalarIntegerFractionF64 :: + CDouble -> + Ptr CString -> + Ptr CDouble -> + IO CInt +ffiScalarIntegerFractionF64 vX out0 out1 = boundary $ do + checked (Scalar.integerFraction + (coerce vX :: Double)) $ \(first, second) -> do + strict1 <- evaluate (second) + writeStrings [show (first)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_scalar_quotient_remainder" ffiScalarQuotientRemainder :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarQuotientRemainder :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarQuotientRemainder vA vB out0 out1 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Scalar.quotientRemainder + vAValue + vBValue) $ \(first, second) -> do + writeStrings [show (first), show (second)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_euclidean_division" ffiScalarEuclideanDivision :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarEuclideanDivision :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarEuclideanDivision vA vB out0 out1 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Scalar.euclideanDivision + vAValue + vBValue) $ \(first, second) -> do + writeStrings [show (first), show (second)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_positive_modulo_integer" ffiScalarPositiveModuloInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPositiveModuloInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPositiveModuloInteger vA vModulus out0 = boundary $ do + vAValue <- readInteger vA + vModulusValue <- readInteger vModulus + checked (Scalar.positiveModulo + vAValue + vModulusValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_positive_modulo_i8" ffiScalarPositiveModuloI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarPositiveModuloI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarPositiveModuloI8 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Int8) + (vModulus :: Int8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_positive_modulo_i16" ffiScalarPositiveModuloI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarPositiveModuloI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarPositiveModuloI16 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Int16) + (vModulus :: Int16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_positive_modulo_i32" ffiScalarPositiveModuloI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarPositiveModuloI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarPositiveModuloI32 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Int32) + (vModulus :: Int32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_positive_modulo_i64" ffiScalarPositiveModuloI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarPositiveModuloI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarPositiveModuloI64 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Int64) + (vModulus :: Int64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_positive_modulo_u8" ffiScalarPositiveModuloU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarPositiveModuloU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarPositiveModuloU8 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Word8) + (vModulus :: Word8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_positive_modulo_u16" ffiScalarPositiveModuloU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarPositiveModuloU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarPositiveModuloU16 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Word16) + (vModulus :: Word16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_positive_modulo_u32" ffiScalarPositiveModuloU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarPositiveModuloU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarPositiveModuloU32 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Word32) + (vModulus :: Word32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_positive_modulo_u64" ffiScalarPositiveModuloU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarPositiveModuloU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarPositiveModuloU64 vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Word64) + (vModulus :: Word64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_positive_modulo_int" ffiScalarPositiveModuloInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarPositiveModuloInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarPositiveModuloInt vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Int) + (vModulus :: Int)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_positive_modulo_word" ffiScalarPositiveModuloWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarPositiveModuloWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarPositiveModuloWord vA vModulus out0 = boundary $ do + checked (Scalar.positiveModulo + (vA :: Word) + (vModulus :: Word)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_positive_modulo" ffiScalarPositiveModulo :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPositiveModulo :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPositiveModulo vA vModulus out0 = boundary $ do + vAValue <- readInteger vA + vModulusValue <- readInteger vModulus + checked (Scalar.positiveModulo + vAValue + vModulusValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_modular_power" ffiScalarModularPower :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarModularPower :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarModularPower vA vN vModulus out0 = boundary $ do + vAValue <- readInteger vA + vNValue <- readInteger vN + vModulusValue <- readInteger vModulus + checked (Scalar.modularPower + vAValue + vNValue + vModulusValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_factorial_checked" ffiScalarFactorialChecked :: + CString -> + Ptr CString -> + IO CInt +ffiScalarFactorialChecked :: + CString -> + Ptr CString -> + IO CInt +ffiScalarFactorialChecked vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.factorialChecked + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_double_factorial" ffiScalarDoubleFactorial :: + CString -> + Ptr CString -> + IO CInt +ffiScalarDoubleFactorial :: + CString -> + Ptr CString -> + IO CInt +ffiScalarDoubleFactorial vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.doubleFactorial + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_fibonacci_checked" ffiScalarFibonacciChecked :: + CString -> + Ptr CString -> + IO CInt +ffiScalarFibonacciChecked :: + CString -> + Ptr CString -> + IO CInt +ffiScalarFibonacciChecked vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.fibonacciChecked + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_lucas" ffiScalarLucas :: + CString -> + Ptr CString -> + IO CInt +ffiScalarLucas :: + CString -> + Ptr CString -> + IO CInt +ffiScalarLucas vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.lucas + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_catalan" ffiScalarCatalan :: + CString -> + Ptr CString -> + IO CInt +ffiScalarCatalan :: + CString -> + Ptr CString -> + IO CInt +ffiScalarCatalan vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.catalan + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_rising_factorial" ffiScalarRisingFactorial :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarRisingFactorial :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarRisingFactorial vX vN out0 = boundary $ do + vXValue <- readInteger vX + vNValue <- readInteger vN + checked (Scalar.risingFactorial + vXValue + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_falling_factorial" ffiScalarFallingFactorial :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarFallingFactorial :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarFallingFactorial vX vN out0 = boundary $ do + vXValue <- readInteger vX + vNValue <- readInteger vN + checked (Scalar.fallingFactorial + vXValue + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_permutations" ffiScalarPermutations :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPermutations :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarPermutations vN vK out0 = boundary $ do + vNValue <- readInteger vN + vKValue <- readInteger vK + checked (Scalar.permutations + vNValue + vKValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_combinations" ffiScalarCombinations :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarCombinations :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiScalarCombinations vN vK out0 = boundary $ do + vNValue <- readInteger vN + vKValue <- readInteger vK + checked (Scalar.combinations + vNValue + vKValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_scalar_bernoulli" ffiScalarBernoulli :: + CPtrdiff -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarBernoulli :: + CPtrdiff -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarBernoulli vN out0 out1 = boundary $ do + checked (Scalar.bernoulli + (fromIntegral vN)) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_harmonic" ffiScalarHarmonic :: + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarHarmonic :: + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiScalarHarmonic vN out0 out1 = boundary $ do + vNValue <- readInteger vN + checked (Scalar.harmonic + vNValue) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_f32" ffiScalarCumulativeSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarCumulativeSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarCumulativeSumF32 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Scalar.cumulativeSum + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Float) strict0 + +foreign export ccall "hm_numeric_scalar_cumulative_sum_f64" ffiScalarCumulativeSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarCumulativeSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarCumulativeSumF64 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Scalar.cumulativeSum + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Double) strict0 + +foreign export ccall "hm_numeric_scalar_cumulative_sum_rational" ffiScalarCumulativeSumRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumRational vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_integer" ffiScalarCumulativeSumInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumInteger vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (fromIntegral vValuesCount) vValues + vValuesValue <- mapM readInteger vValuesRaw + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_i8" ffiScalarCumulativeSumI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_i16" ffiScalarCumulativeSumI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_i32" ffiScalarCumulativeSumI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_i64" ffiScalarCumulativeSumI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumI64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_u8" ffiScalarCumulativeSumU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_u16" ffiScalarCumulativeSumU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_u32" ffiScalarCumulativeSumU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_u64" ffiScalarCumulativeSumU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumU64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_int" ffiScalarCumulativeSumInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumInt vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_word" ffiScalarCumulativeSumWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumWord vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_c64" ffiScalarCumulativeSumC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumC64 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_sum_c128" ffiScalarCumulativeSumC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeSumC128 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.cumulativeSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_f32" ffiScalarCumulativeProductF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarCumulativeProductF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarCumulativeProductF32 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Scalar.cumulativeProduct + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Float) strict0 + +foreign export ccall "hm_numeric_scalar_cumulative_product_f64" ffiScalarCumulativeProductF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarCumulativeProductF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarCumulativeProductF64 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Scalar.cumulativeProduct + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Double) strict0 + +foreign export ccall "hm_numeric_scalar_cumulative_product_rational" ffiScalarCumulativeProductRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductRational vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_integer" ffiScalarCumulativeProductInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductInteger vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (fromIntegral vValuesCount) vValues + vValuesValue <- mapM readInteger vValuesRaw + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_i8" ffiScalarCumulativeProductI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_i16" ffiScalarCumulativeProductI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_i32" ffiScalarCumulativeProductI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_i64" ffiScalarCumulativeProductI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductI64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_u8" ffiScalarCumulativeProductU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_u16" ffiScalarCumulativeProductU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_u32" ffiScalarCumulativeProductU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_u64" ffiScalarCumulativeProductU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductU64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_int" ffiScalarCumulativeProductInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductInt vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_word" ffiScalarCumulativeProductWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductWord vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_c64" ffiScalarCumulativeProductC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductC64 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_cumulative_product_c128" ffiScalarCumulativeProductC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarCumulativeProductC128 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.cumulativeProduct vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_f32" ffiScalarPrefixSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarPrefixSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + IO CInt +ffiScalarPrefixSumF32 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Scalar.prefixSum + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Float) strict0 + +foreign export ccall "hm_numeric_scalar_prefix_sum_f64" ffiScalarPrefixSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarPrefixSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + IO CInt +ffiScalarPrefixSumF64 vValues vValuesCount out0 _outCapacity = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Scalar.prefixSum + vValuesValue)) $ \value -> do + strict0 <- mapM evaluate value + pokeArray (castPtr out0 :: Ptr Double) strict0 + +foreign export ccall "hm_numeric_scalar_prefix_sum_rational" ffiScalarPrefixSumRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumRational :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumRational vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_integer" ffiScalarPrefixSumInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumInteger :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumInteger vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (fromIntegral vValuesCount) vValues + vValuesValue <- mapM readInteger vValuesRaw + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_i8" ffiScalarPrefixSumI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI8 :: + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_i16" ffiScalarPrefixSumI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI16 :: + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_i32" ffiScalarPrefixSumI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI32 :: + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_i64" ffiScalarPrefixSumI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI64 :: + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumI64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_u8" ffiScalarPrefixSumU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU8 :: + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU8 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_u16" ffiScalarPrefixSumU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU16 :: + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU16 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_u32" ffiScalarPrefixSumU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU32 :: + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU32 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_u64" ffiScalarPrefixSumU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU64 :: + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumU64 vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_int" ffiScalarPrefixSumInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumInt :: + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumInt vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_word" ffiScalarPrefixSumWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumWord :: + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumWord vValues vValuesCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) vValues + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_c64" ffiScalarPrefixSumC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumC64 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_scalar_prefix_sum_c128" ffiScalarPrefixSumC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiScalarPrefixSumC128 vValues vValuesCount outData outCount = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Scalar.prefixSum vValuesValue)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_trigonometry_sin_checked_f32" ffiTrigonometrySinCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySinCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySinCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.sinChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sin_checked_f64" ffiTrigonometrySinCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySinCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySinCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.sinChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_cos_checked_f32" ffiTrigonometryCosCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCosCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCosCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.cosChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_cos_checked_f64" ffiTrigonometryCosCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCosCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCosCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.cosChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_tan_checked_f32" ffiTrigonometryTanCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryTanCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryTanCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.tanChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_tan_checked_f64" ffiTrigonometryTanCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryTanCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryTanCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.tanChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_asin_checked_f32" ffiTrigonometryAsinCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsinCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsinCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.asinChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_asin_checked_f64" ffiTrigonometryAsinCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsinCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsinCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.asinChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acos_checked_f32" ffiTrigonometryAcosCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcosCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcosCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.acosChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acos_checked_f64" ffiTrigonometryAcosCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcosCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcosCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.acosChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_atan_checked_f32" ffiTrigonometryAtanCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtanCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtanCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.atanChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_atan_checked_f64" ffiTrigonometryAtanCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtanCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtanCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.atanChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_sec_f32" ffiTrigonometrySecF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySecF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySecF32 vX out0 = boundary $ do + checked (Trigonometry.sec + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sec_f64" ffiTrigonometrySecF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySecF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySecF64 vX out0 = boundary $ do + checked (Trigonometry.sec + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_csc_f32" ffiTrigonometryCscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCscF32 vX out0 = boundary $ do + checked (Trigonometry.csc + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_csc_f64" ffiTrigonometryCscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCscF64 vX out0 = boundary $ do + checked (Trigonometry.csc + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_cot_f32" ffiTrigonometryCotF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCotF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCotF32 vX out0 = boundary $ do + checked (Trigonometry.cot + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_cot_f64" ffiTrigonometryCotF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCotF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCotF64 vX out0 = boundary $ do + checked (Trigonometry.cot + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_asec_f32" ffiTrigonometryAsecF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsecF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsecF32 vX out0 = boundary $ do + checked (Trigonometry.asec + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_asec_f64" ffiTrigonometryAsecF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsecF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsecF64 vX out0 = boundary $ do + checked (Trigonometry.asec + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acsc_f32" ffiTrigonometryAcscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcscF32 vX out0 = boundary $ do + checked (Trigonometry.acsc + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acsc_f64" ffiTrigonometryAcscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcscF64 vX out0 = boundary $ do + checked (Trigonometry.acsc + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acot_f32" ffiTrigonometryAcotF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcotF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcotF32 vX out0 = boundary $ do + checked (Trigonometry.acot + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acot_f64" ffiTrigonometryAcotF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcotF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcotF64 vX out0 = boundary $ do + checked (Trigonometry.acot + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_sinh_checked_f32" ffiTrigonometrySinhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySinhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySinhCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.sinhChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sinh_checked_f64" ffiTrigonometrySinhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySinhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySinhCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.sinhChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_cosh_checked_f32" ffiTrigonometryCoshCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCoshCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCoshCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.coshChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_cosh_checked_f64" ffiTrigonometryCoshCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCoshCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCoshCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.coshChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_tanh_checked_f32" ffiTrigonometryTanhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryTanhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryTanhCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.tanhChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_tanh_checked_f64" ffiTrigonometryTanhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryTanhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryTanhCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.tanhChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_asinh_checked_f32" ffiTrigonometryAsinhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsinhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsinhCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.asinhChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_asinh_checked_f64" ffiTrigonometryAsinhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsinhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsinhCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.asinhChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acosh_checked_f32" ffiTrigonometryAcoshCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcoshCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcoshCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.acoshChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acosh_checked_f64" ffiTrigonometryAcoshCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcoshCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcoshCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.acoshChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_atanh_checked_f32" ffiTrigonometryAtanhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtanhCheckedF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtanhCheckedF32 vX out0 = boundary $ do + checked (Trigonometry.atanhChecked + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_atanh_checked_f64" ffiTrigonometryAtanhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtanhCheckedF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtanhCheckedF64 vX out0 = boundary $ do + checked (Trigonometry.atanhChecked + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_sech_f32" ffiTrigonometrySechF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySechF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySechF32 vX out0 = boundary $ do + checked (Trigonometry.sech + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sech_f64" ffiTrigonometrySechF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySechF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySechF64 vX out0 = boundary $ do + checked (Trigonometry.sech + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_csch_f32" ffiTrigonometryCschF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCschF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCschF32 vX out0 = boundary $ do + checked (Trigonometry.csch + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_csch_f64" ffiTrigonometryCschF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCschF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCschF64 vX out0 = boundary $ do + checked (Trigonometry.csch + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_coth_f32" ffiTrigonometryCothF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCothF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCothF32 vX out0 = boundary $ do + checked (Trigonometry.coth + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_coth_f64" ffiTrigonometryCothF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCothF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCothF64 vX out0 = boundary $ do + checked (Trigonometry.coth + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_asech_f32" ffiTrigonometryAsechF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsechF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAsechF32 vX out0 = boundary $ do + checked (Trigonometry.asech + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_asech_f64" ffiTrigonometryAsechF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsechF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAsechF64 vX out0 = boundary $ do + checked (Trigonometry.asech + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acsch_f32" ffiTrigonometryAcschF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcschF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcschF32 vX out0 = boundary $ do + checked (Trigonometry.acsch + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acsch_f64" ffiTrigonometryAcschF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcschF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcschF64 vX out0 = boundary $ do + checked (Trigonometry.acsch + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_acoth_f32" ffiTrigonometryAcothF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcothF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAcothF32 vX out0 = boundary $ do + checked (Trigonometry.acoth + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_acoth_f64" ffiTrigonometryAcothF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcothF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAcothF64 vX out0 = boundary $ do + checked (Trigonometry.acoth + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_normalize_angle_f32" ffiTrigonometryNormalizeAngleF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryNormalizeAngleF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryNormalizeAngleF32 vX out0 = boundary $ do + checked (Trigonometry.normalizeAngle + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_normalize_angle_f64" ffiTrigonometryNormalizeAngleF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryNormalizeAngleF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryNormalizeAngleF64 vX out0 = boundary $ do + checked (Trigonometry.normalizeAngle + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_normalize_signed_angle_f32" ffiTrigonometryNormalizeSignedAngleF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryNormalizeSignedAngleF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryNormalizeSignedAngleF32 vX out0 = boundary $ do + checked (Trigonometry.normalizeSignedAngle + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_normalize_signed_angle_f64" ffiTrigonometryNormalizeSignedAngleF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryNormalizeSignedAngleF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryNormalizeSignedAngleF64 vX out0 = boundary $ do + checked (Trigonometry.normalizeSignedAngle + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_versine_f32" ffiTrigonometryVersineF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryVersineF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryVersineF32 vX out0 = boundary $ do + checked (Trigonometry.versine + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_versine_f64" ffiTrigonometryVersineF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryVersineF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryVersineF64 vX out0 = boundary $ do + checked (Trigonometry.versine + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_haversine_f32" ffiTrigonometryHaversineF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryHaversineF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryHaversineF32 vX out0 = boundary $ do + checked (Trigonometry.haversine + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_haversine_f64" ffiTrigonometryHaversineF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryHaversineF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryHaversineF64 vX out0 = boundary $ do + checked (Trigonometry.haversine + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_sinc_f32" ffiTrigonometrySincF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySincF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySincF32 vX out0 = boundary $ do + checked (Trigonometry.sinc + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sinc_f64" ffiTrigonometrySincF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySincF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySincF64 vX out0 = boundary $ do + checked (Trigonometry.sinc + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_cosc_f32" ffiTrigonometryCoscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCoscF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryCoscF32 vX out0 = boundary $ do + checked (Trigonometry.cosc + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_cosc_f64" ffiTrigonometryCoscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCoscF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryCoscF64 vX out0 = boundary $ do + checked (Trigonometry.cosc + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_atan2_checked_f32" ffiTrigonometryAtan2CheckedF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtan2CheckedF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAtan2CheckedF32 vY vX out0 = boundary $ do + checked (Trigonometry.atan2Checked + (coerce vY :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_atan2_checked_f64" ffiTrigonometryAtan2CheckedF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtan2CheckedF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAtan2CheckedF64 vY vX out0 = boundary $ do + checked (Trigonometry.atan2Checked + (coerce vY :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_sincos_f32" ffiTrigonometrySincosF32 :: + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySincosF32 :: + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySincosF32 vX out0 out1 = boundary $ do + checked (Trigonometry.sincos + (coerce vX :: Float)) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_sincos_f64" ffiTrigonometrySincosF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySincosF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySincosF64 vX out0 out1 = boundary $ do + checked (Trigonometry.sincos + (coerce vX :: Double)) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_wrap_f32" ffiTrigonometryWrapF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryWrapF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryWrapF32 vLow vHigh vX out0 = boundary $ do + checked (Trigonometry.wrap + (coerce vLow :: Float) + (coerce vHigh :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_wrap_f64" ffiTrigonometryWrapF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryWrapF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryWrapF64 vLow vHigh vX out0 = boundary $ do + checked (Trigonometry.wrap + (coerce vLow :: Double) + (coerce vHigh :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_angle_difference_f32" ffiTrigonometryAngleDifferenceF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAngleDifferenceF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryAngleDifferenceF32 vA vB out0 = boundary $ do + checked (Trigonometry.angleDifference + (coerce vA :: Float) + (coerce vB :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_angle_difference_f64" ffiTrigonometryAngleDifferenceF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAngleDifferenceF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryAngleDifferenceF64 vA vB out0 = boundary $ do + checked (Trigonometry.angleDifference + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_great_circle_angle_f32" ffiTrigonometryGreatCircleAngleF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryGreatCircleAngleF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryGreatCircleAngleF32 vA0 vA1 vB0 vB1 out0 = boundary $ do + checked (Trigonometry.greatCircleAngle + ((coerce vA0 :: Float), (coerce vA1 :: Float)) + ((coerce vB0 :: Float), (coerce vB1 :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_great_circle_angle_f64" ffiTrigonometryGreatCircleAngleF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryGreatCircleAngleF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryGreatCircleAngleF64 vA0 vA1 vB0 vB1 out0 = boundary $ do + checked (Trigonometry.greatCircleAngle + ((coerce vA0 :: Double), (coerce vA1 :: Double)) + ((coerce vB0 :: Double), (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_great_circle_distance_f32" ffiTrigonometryGreatCircleDistanceF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryGreatCircleDistanceF32 :: + CFloat -> + CFloat -> + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryGreatCircleDistanceF32 vRadius vA0 vA1 vB0 vB1 out0 = boundary $ do + checked (Trigonometry.greatCircleDistance + (coerce vRadius :: Float) + ((coerce vA0 :: Float), (coerce vA1 :: Float)) + ((coerce vB0 :: Float), (coerce vB1 :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_great_circle_distance_f64" ffiTrigonometryGreatCircleDistanceF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryGreatCircleDistanceF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryGreatCircleDistanceF64 vRadius vA0 vA1 vB0 vB1 out0 = boundary $ do + checked (Trigonometry.greatCircleDistance + (coerce vRadius :: Double) + ((coerce vA0 :: Double), (coerce vA1 :: Double)) + ((coerce vB0 :: Double), (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_spherical_side_f32" ffiTrigonometrySphericalSideF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalSideF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalSideF32 vA vB vIncluded out0 = boundary $ do + checked (Trigonometry.sphericalSide + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vIncluded :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_spherical_side_f64" ffiTrigonometrySphericalSideF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalSideF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalSideF64 vA vB vIncluded out0 = boundary $ do + checked (Trigonometry.sphericalSide + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vIncluded :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_spherical_angles_f32" ffiTrigonometrySphericalAnglesF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalAnglesF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalAnglesF32 vA vB vC out0 out1 out2 = boundary $ do + checked (Trigonometry.sphericalAngles + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vC :: Float)) $ \(first, second, third) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + strict2 <- evaluate (third) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + poke out2 (coerce strict2 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_spherical_angles_f64" ffiTrigonometrySphericalAnglesF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalAnglesF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalAnglesF64 vA vB vC out0 out1 out2 = boundary $ do + checked (Trigonometry.sphericalAngles + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vC :: Double)) $ \(first, second, third) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + strict2 <- evaluate (third) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_spherical_excess_f32" ffiTrigonometrySphericalExcessF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalExcessF32 :: + CFloat -> + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometrySphericalExcessF32 vA vB vC out0 = boundary $ do + checked (Trigonometry.sphericalExcess + (coerce vA :: Float) + (coerce vB :: Float) + (coerce vC :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_spherical_excess_f64" ffiTrigonometrySphericalExcessF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalExcessF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometrySphericalExcessF64 vA vB vC out0 = boundary $ do + checked (Trigonometry.sphericalExcess + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vC :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_sin_f32" ffiTrigonometryComplexSinF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexSinF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexSinF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexSin + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_sin_f64" ffiTrigonometryComplexSinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexSinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexSinF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexSin + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_cos_f32" ffiTrigonometryComplexCosF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexCosF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexCosF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexCos + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_cos_f64" ffiTrigonometryComplexCosF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexCosF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexCosF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexCos + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_tan_f32" ffiTrigonometryComplexTanF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexTanF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexTanF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexTan + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_tan_f64" ffiTrigonometryComplexTanF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexTanF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexTanF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexTan + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_asin_f32" ffiTrigonometryComplexAsinF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAsinF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAsinF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAsin + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_asin_f64" ffiTrigonometryComplexAsinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAsinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAsinF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAsin + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_acos_f32" ffiTrigonometryComplexAcosF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAcosF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAcosF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAcos + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_acos_f64" ffiTrigonometryComplexAcosF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAcosF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAcosF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAcos + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_atan_f32" ffiTrigonometryComplexAtanF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAtanF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAtanF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAtan + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_atan_f64" ffiTrigonometryComplexAtanF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAtanF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAtanF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAtan + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_sinh_f32" ffiTrigonometryComplexSinhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexSinhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexSinhF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexSinh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_sinh_f64" ffiTrigonometryComplexSinhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexSinhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexSinhF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexSinh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_cosh_f32" ffiTrigonometryComplexCoshF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexCoshF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexCoshF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexCosh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_cosh_f64" ffiTrigonometryComplexCoshF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexCoshF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexCoshF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexCosh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_tanh_f32" ffiTrigonometryComplexTanhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexTanhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexTanhF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexTanh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_tanh_f64" ffiTrigonometryComplexTanhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexTanhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexTanhF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexTanh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_asinh_f32" ffiTrigonometryComplexAsinhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAsinhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAsinhF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAsinh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_asinh_f64" ffiTrigonometryComplexAsinhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAsinhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAsinhF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAsinh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_acosh_f32" ffiTrigonometryComplexAcoshF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAcoshF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAcoshF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAcosh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_acosh_f64" ffiTrigonometryComplexAcoshF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAcoshF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAcoshF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAcosh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_complex_atanh_f32" ffiTrigonometryComplexAtanhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAtanhF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryComplexAtanhF32 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAtanh + ((coerce vZ0 :: Float) :+ (coerce vZ1 :: Float))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_complex_atanh_f64" ffiTrigonometryComplexAtanhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAtanhF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryComplexAtanhF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Trigonometry.complexAtanh + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_periodic_sawtooth_f32" ffiTrigonometryPeriodicSawtoothF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicSawtoothF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicSawtoothF32 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicSawtooth + (coerce vPeriod :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_periodic_sawtooth_f64" ffiTrigonometryPeriodicSawtoothF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicSawtoothF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicSawtoothF64 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicSawtooth + (coerce vPeriod :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_periodic_triangle_f32" ffiTrigonometryPeriodicTriangleF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicTriangleF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicTriangleF32 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicTriangle + (coerce vPeriod :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_periodic_triangle_f64" ffiTrigonometryPeriodicTriangleF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicTriangleF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicTriangleF64 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicTriangle + (coerce vPeriod :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_trigonometry_periodic_square_f32" ffiTrigonometryPeriodicSquareF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicSquareF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiTrigonometryPeriodicSquareF32 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicSquare + (coerce vPeriod :: Float) + (coerce vX :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_trigonometry_periodic_square_f64" ffiTrigonometryPeriodicSquareF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicSquareF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiTrigonometryPeriodicSquareF64 vPeriod vX out0 = boundary $ do + checked (Trigonometry.periodicSquare + (coerce vPeriod :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_mean_f32" ffiStatisticsMeanF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsMeanF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsMeanF32 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Statistics.mean + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_statistics_mean_f64" ffiStatisticsMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsMeanF64 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Statistics.mean + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_mean_rational" ffiStatisticsMeanRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsMeanRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsMeanRational vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Statistics.mean + vValuesValue)) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_statistics_mean_c64" ffiStatisticsMeanC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsMeanC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsMeanC64 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.mean + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_statistics_mean_c128" ffiStatisticsMeanC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsMeanC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsMeanC128 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.mean + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_statistics_variance_f32" ffiStatisticsVarianceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsVarianceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsVarianceF32 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Statistics.variance + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_statistics_variance_f64" ffiStatisticsVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsVarianceF64 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Statistics.variance + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_variance_rational" ffiStatisticsVarianceRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsVarianceRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsVarianceRational vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Statistics.variance + vValuesValue)) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_statistics_variance_c64" ffiStatisticsVarianceC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsVarianceC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsVarianceC64 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.variance + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_statistics_variance_c128" ffiStatisticsVarianceC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsVarianceC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsVarianceC128 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.variance + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_statistics_standard_deviation_f32" ffiStatisticsStandardDeviationF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsStandardDeviationF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsStandardDeviationF32 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Statistics.standardDeviation + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_statistics_standard_deviation_f64" ffiStatisticsStandardDeviationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsStandardDeviationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsStandardDeviationF64 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Statistics.standardDeviation + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_standard_deviation_c64" ffiStatisticsStandardDeviationC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsStandardDeviationC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiStatisticsStandardDeviationC64 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.standardDeviation + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_statistics_standard_deviation_c128" ffiStatisticsStandardDeviationC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsStandardDeviationC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsStandardDeviationC128 vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + let vValuesValue = complexPairs vValuesRaw + checked (Right (Statistics.standardDeviation + vValuesValue)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_statistics_median_f32" ffiStatisticsMedianF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsMedianF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiStatisticsMedianF32 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Float) + checked (Right (Statistics.median + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_statistics_median_f64" ffiStatisticsMedianF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsMedianF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsMedianF64 vValues vValuesCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + checked (Right (Statistics.median + vValuesValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_median_rational" ffiStatisticsMedianRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsMedianRational :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiStatisticsMedianRational vValues vValuesCount out0 out1 = boundary $ do + vValuesRaw <- peekArray (2 * fromIntegral vValuesCount) vValues >>= mapM readInteger + let vValuesValue = rationalPairs vValuesRaw + checked (Right (Statistics.median + vValuesValue)) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_constants_pi_constant_f32" ffiConstantsPiConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsPiConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsPiConstantF32 out0 = boundary $ do + checked (Right (Constants.piConstant :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_pi_constant_f64" ffiConstantsPiConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsPiConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsPiConstantF64 out0 = boundary $ do + checked (Right (Constants.piConstant :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_e_constant_f32" ffiConstantsEConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsEConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsEConstantF32 out0 = boundary $ do + checked (Right (Constants.eConstant :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_e_constant_f64" ffiConstantsEConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsEConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsEConstantF64 out0 = boundary $ do + checked (Right (Constants.eConstant :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_tau_f32" ffiConstantsTauF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsTauF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsTauF32 out0 = boundary $ do + checked (Right (Constants.tau :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_tau_f64" ffiConstantsTauF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsTauF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsTauF64 out0 = boundary $ do + checked (Right (Constants.tau :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_golden_ratio_f32" ffiConstantsGoldenRatioF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsGoldenRatioF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsGoldenRatioF32 out0 = boundary $ do + checked (Right (Constants.goldenRatio :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_golden_ratio_f64" ffiConstantsGoldenRatioF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsGoldenRatioF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsGoldenRatioF64 out0 = boundary $ do + checked (Right (Constants.goldenRatio :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_euler_mascheroni_f32" ffiConstantsEulerMascheroniF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsEulerMascheroniF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsEulerMascheroniF32 out0 = boundary $ do + checked (Right (Constants.eulerMascheroni :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_euler_mascheroni_f64" ffiConstantsEulerMascheroniF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsEulerMascheroniF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsEulerMascheroniF64 out0 = boundary $ do + checked (Right (Constants.eulerMascheroni :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_catalan_constant_f32" ffiConstantsCatalanConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsCatalanConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsCatalanConstantF32 out0 = boundary $ do + checked (Right (Constants.catalanConstant :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_catalan_constant_f64" ffiConstantsCatalanConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsCatalanConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsCatalanConstantF64 out0 = boundary $ do + checked (Right (Constants.catalanConstant :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_apery_constant_f32" ffiConstantsAperyConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsAperyConstantF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsAperyConstantF32 out0 = boundary $ do + checked (Right (Constants.aperyConstant :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_apery_constant_f64" ffiConstantsAperyConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsAperyConstantF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsAperyConstantF64 out0 = boundary $ do + checked (Right (Constants.aperyConstant :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_sqrt2_f32" ffiConstantsSqrt2F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsSqrt2F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsSqrt2F32 out0 = boundary $ do + checked (Right (Constants.sqrt2 :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_sqrt2_f64" ffiConstantsSqrt2F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsSqrt2F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsSqrt2F64 out0 = boundary $ do + checked (Right (Constants.sqrt2 :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_sqrt3_f32" ffiConstantsSqrt3F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsSqrt3F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsSqrt3F32 out0 = boundary $ do + checked (Right (Constants.sqrt3 :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_sqrt3_f64" ffiConstantsSqrt3F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsSqrt3F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsSqrt3F64 out0 = boundary $ do + checked (Right (Constants.sqrt3 :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_ln2_f32" ffiConstantsLn2F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsLn2F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsLn2F32 out0 = boundary $ do + checked (Right (Constants.ln2 :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_ln2_f64" ffiConstantsLn2F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsLn2F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsLn2F64 out0 = boundary $ do + checked (Right (Constants.ln2 :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_ln10_f32" ffiConstantsLn10F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsLn10F32 :: + Ptr CFloat -> + IO CInt +ffiConstantsLn10F32 out0 = boundary $ do + checked (Right (Constants.ln10 :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_ln10_f64" ffiConstantsLn10F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsLn10F64 :: + Ptr CDouble -> + IO CInt +ffiConstantsLn10F64 out0 = boundary $ do + checked (Right (Constants.ln10 :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_infinity_f32" ffiConstantsInfinityF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsInfinityF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsInfinityF32 out0 = boundary $ do + checked (Right (Constants.infinity :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_infinity_f64" ffiConstantsInfinityF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsInfinityF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsInfinityF64 out0 = boundary $ do + checked (Right (Constants.infinity :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_constants_nan_f32" ffiConstantsNanF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsNanF32 :: + Ptr CFloat -> + IO CInt +ffiConstantsNanF32 out0 = boundary $ do + checked (Right (Constants.nan :: Float)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_constants_nan_f64" ffiConstantsNanF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsNanF64 :: + Ptr CDouble -> + IO CInt +ffiConstantsNanF64 out0 = boundary $ do + checked (Right (Constants.nan :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_multinomial" ffiScalarMultinomial :: + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiScalarMultinomial :: + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiScalarMultinomial vKs vKsCount out0 = boundary $ do + vKsRaw <- peekArray (fromIntegral vKsCount) vKs + vKsValue <- mapM readInteger vKsRaw + checked (Scalar.multinomial + vKsValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_gcd_integer" ffiNumbertheoryGcdInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryGcdInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryGcdInteger vArgument1 vArgument2 out0 = boundary $ do + vArgument1Value <- readInteger vArgument1 + vArgument2Value <- readInteger vArgument2 + checked (Right (NumberTheory.gcdInteger + vArgument1Value + vArgument2Value)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_lcm_integer" ffiNumbertheoryLcmInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLcmInteger :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLcmInteger vArgument1 vArgument2 out0 = boundary $ do + vArgument1Value <- readInteger vArgument1 + vArgument2Value <- readInteger vArgument2 + checked (Right (NumberTheory.lcmInteger + vArgument1Value + vArgument2Value)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_extended_g_c_d" ffiNumbertheoryExtendedGCD :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryExtendedGCD :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryExtendedGCD vA vB out0 out1 out2 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (NumberTheory.extendedGCD + vAValue + vBValue)) $ \(first, second, third) -> do + writeStrings [show (first), show (second), show (third)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + poke out2 (textPointers !! 2) + +foreign export ccall "hm_numeric_numbertheory_bezout" ffiNumbertheoryBezout :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryBezout :: + CString -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryBezout vA vB out0 out1 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (Right (NumberTheory.bezout + vAValue + vBValue)) $ \(first, second) -> do + writeStrings [show (first), show (second)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_numbertheory_mod_pow" ffiNumbertheoryModPow :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryModPow :: + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryModPow vA vE vM out0 = boundary $ do + vAValue <- readInteger vA + vEValue <- readInteger vE + vMValue <- readInteger vM + checked (NumberTheory.modPow + vAValue + vEValue + vMValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_mod_inverse" ffiNumbertheoryModInverse :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryModInverse :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryModInverse vA vM out0 = boundary $ do + vAValue <- readInteger vA + vMValue <- readInteger vM + checked (NumberTheory.modInverse + vAValue + vMValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_integer_square_root" ffiNumbertheoryIntegerSquareRoot :: + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryIntegerSquareRoot :: + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryIntegerSquareRoot vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.integerSquareRoot + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_is_prime_exact" ffiNumbertheoryIsPrimeExact :: + CPtrdiff -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryIsPrimeExact :: + CPtrdiff -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryIsPrimeExact vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.isPrimeExact + (fromIntegral vBudget) + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numbertheory_next_prime" ffiNumbertheoryNextPrime :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryNextPrime :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryNextPrime vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.nextPrime + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_miller_rabin" ffiNumbertheoryMillerRabin :: + Ptr CString -> + CSize -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryMillerRabin :: + Ptr CString -> + CSize -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryMillerRabin vBases vBasesCount vN out0 = boundary $ do + vBasesRaw <- peekArray (fromIntegral vBasesCount) vBases + vBasesValue <- mapM readInteger vBasesRaw + vNValue <- readInteger vN + checked (NumberTheory.millerRabin + vBasesValue + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numbertheory_baillie_p_s_w" ffiNumbertheoryBailliePSW :: + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryBailliePSW :: + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryBailliePSW vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.bailliePSW + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numbertheory_sieve_eratosthenes" ffiNumbertheorySieveEratosthenes :: + CPtrdiff -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySieveEratosthenes :: + CPtrdiff -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySieveEratosthenes vBound outData outCount = boundary $ do + checked (Right (NumberTheory.sieveEratosthenes (fromIntegral vBound))) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_sieve_atkin" ffiNumbertheorySieveAtkin :: + CPtrdiff -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySieveAtkin :: + CPtrdiff -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySieveAtkin vBound outData outCount = boundary $ do + checked (Right (NumberTheory.sieveAtkin (fromIntegral vBound))) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_segmented_sieve" ffiNumbertheorySegmentedSieve :: + CString -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySegmentedSieve :: + CString -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheorySegmentedSieve vLo vHi outData outCount = boundary $ do + vLoValue <- readInteger vLo + vHiValue <- readInteger vHi + checked (NumberTheory.segmentedSieve vLoValue vHiValue) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_pollard_rho" ffiNumbertheoryPollardRho :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPollardRho :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPollardRho vBudget vSeed vN out0 = boundary $ do + vSeedValue <- readInteger vSeed + vNValue <- readInteger vN + checked (NumberTheory.pollardRho + (fromIntegral vBudget) + vSeedValue + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_pollard_p_minus_one" ffiNumbertheoryPollardPMinusOne :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPollardPMinusOne :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPollardPMinusOne vBound vBase vN out0 = boundary $ do + vBaseValue <- readInteger vBase + vNValue <- readInteger vN + checked (NumberTheory.pollardPMinusOne + (fromIntegral vBound) + vBaseValue + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_fermat_factor" ffiNumbertheoryFermatFactor :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFermatFactor :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFermatFactor vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.fermatFactor + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_divisors" ffiNumbertheoryDivisors :: + CPtrdiff -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryDivisors :: + CPtrdiff -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryDivisors vBudget vN outData outCount = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.divisors (fromIntegral vBudget) vNValue) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_divisor_sum" ffiNumbertheoryDivisorSum :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDivisorSum :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDivisorSum vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.divisorSum + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_divisor_count" ffiNumbertheoryDivisorCount :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDivisorCount :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDivisorCount vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.divisorCount + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_euler_totient" ffiNumbertheoryEulerTotient :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryEulerTotient :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryEulerTotient vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.eulerTotient + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_carmichael" ffiNumbertheoryCarmichael :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryCarmichael :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryCarmichael vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.carmichael + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_mobius" ffiNumbertheoryMobius :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryMobius :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryMobius vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.mobius + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_liouville" ffiNumbertheoryLiouville :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLiouville :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLiouville vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.liouville + (fromIntegral vBudget) + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_multiplicative_order" ffiNumbertheoryMultiplicativeOrder :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryMultiplicativeOrder :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryMultiplicativeOrder vBudget vA vM out0 = boundary $ do + vAValue <- readInteger vA + vMValue <- readInteger vM + checked (NumberTheory.multiplicativeOrder + (fromIntegral vBudget) + vAValue + vMValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_primitive_root" ffiNumbertheoryPrimitiveRoot :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPrimitiveRoot :: + CPtrdiff -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPrimitiveRoot vBudget vM out0 = boundary $ do + vMValue <- readInteger vM + checked (NumberTheory.primitiveRoot + (fromIntegral vBudget) + vMValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_discrete_log" ffiNumbertheoryDiscreteLog :: + CPtrdiff -> + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDiscreteLog :: + CPtrdiff -> + CString -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryDiscreteLog vBudget vA vB vM out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + vMValue <- readInteger vM + checked (NumberTheory.discreteLog + (fromIntegral vBudget) + vAValue + vBValue + vMValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_legendre_symbol" ffiNumbertheoryLegendreSymbol :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLegendreSymbol :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryLegendreSymbol vBudget vA vP out0 = boundary $ do + vAValue <- readInteger vA + vPValue <- readInteger vP + checked (NumberTheory.legendreSymbol + (fromIntegral vBudget) + vAValue + vPValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_jacobi_symbol" ffiNumbertheoryJacobiSymbol :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryJacobiSymbol :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryJacobiSymbol vA vN out0 = boundary $ do + vAValue <- readInteger vA + vNValue <- readInteger vN + checked (NumberTheory.jacobiSymbol + vAValue + vNValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_kronecker_symbol" ffiNumbertheoryKroneckerSymbol :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryKroneckerSymbol :: + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryKroneckerSymbol vA vN out0 = boundary $ do + vAValue <- readInteger vA + vNValue <- readInteger vN + checked (Right (NumberTheory.kroneckerSymbol + vAValue + vNValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_tonelli_shanks" ffiNumbertheoryTonelliShanks :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryTonelliShanks :: + CPtrdiff -> + CString -> + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryTonelliShanks vBudget vA vP out0 = boundary $ do + vAValue <- readInteger vA + vPValue <- readInteger vP + checked (NumberTheory.tonelliShanks + (fromIntegral vBudget) + vAValue + vPValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_continued_fraction" ffiNumbertheoryContinuedFraction :: + CString -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryContinuedFraction :: + CString -> + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryContinuedFraction vRNumerator vRDenominator outData outCount = boundary $ do + vRN <- readInteger vRNumerator + vRD <- readInteger vRDenominator + checked (Right (NumberTheory.continuedFraction (vRN % vRD))) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_from_continued_fraction" ffiNumbertheoryFromContinuedFraction :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFromContinuedFraction :: + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFromContinuedFraction vArgument1 vArgument1Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + checked (NumberTheory.fromContinuedFraction + vArgument1Value) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_numbertheory_convergents" ffiNumbertheoryConvergents :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryConvergents :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryConvergents vXs vXsCount outData outCount = boundary $ do + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + vXsValue <- mapM readInteger vXsRaw + checked (NumberTheory.convergents vXsValue) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_farey" ffiNumbertheoryFarey :: + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryFarey :: + CString -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiNumbertheoryFarey vN outData outCount = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.farey vNValue) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_numbertheory_pell_fundamental" ffiNumbertheoryPellFundamental :: + CPtrdiff -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPellFundamental :: + CPtrdiff -> + CString -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryPellFundamental vBudget vD out0 out1 = boundary $ do + vDValue <- readInteger vD + checked (NumberTheory.pellFundamental + (fromIntegral vBudget) + vDValue) $ \(first, second) -> do + writeStrings [show (first), show (second)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_numbertheory_is_perfect_number" ffiNumbertheoryIsPerfectNumber :: + CPtrdiff -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryIsPerfectNumber :: + CPtrdiff -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryIsPerfectNumber vBudget vN out0 = boundary $ do + vNValue <- readInteger vN + checked (NumberTheory.isPerfectNumber + (fromIntegral vBudget) + vNValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numbertheory_are_amicable" ffiNumbertheoryAreAmicable :: + CPtrdiff -> + CString -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryAreAmicable :: + CPtrdiff -> + CString -> + CString -> + Ptr CInt -> + IO CInt +ffiNumbertheoryAreAmicable vBudget vA vB out0 = boundary $ do + vAValue <- readInteger vA + vBValue <- readInteger vB + checked (NumberTheory.areAmicable + (fromIntegral vBudget) + vAValue + vBValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numbertheory_partition_count" ffiNumbertheoryPartitionCount :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiNumbertheoryPartitionCount :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiNumbertheoryPartitionCount vN out0 = boundary $ do + checked (NumberTheory.partitionCount + (fromIntegral vN)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numbertheory_fibonacci_fast" ffiNumbertheoryFibonacciFast :: + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFibonacciFast :: + CString -> + Ptr CString -> + IO CInt +ffiNumbertheoryFibonacciFast vN out0 = boundary $ do + vNValue <- readInteger vN + checked (Right (NumberTheory.fibonacciFast + vNValue)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_permutations_count" ffiCombinatoricsPermutationsCount :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsPermutationsCount :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsPermutationsCount vN vK out0 = boundary $ do + checked (Combinatorics.permutationsCount + (fromIntegral vN) + (fromIntegral vK)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_combinations_count" ffiCombinatoricsCombinationsCount :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsCombinationsCount :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsCombinationsCount vN vK out0 = boundary $ do + checked (Combinatorics.combinationsCount + (fromIntegral vN) + (fromIntegral vK)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_multinomial" ffiCombinatoricsMultinomial :: + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultinomial :: + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultinomial vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + let vArgument1Value = map fromIntegral vArgument1Raw + checked (Combinatorics.multinomial + vArgument1Value) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_rank_permutation" ffiCombinatoricsRankPermutation :: + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsRankPermutation :: + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsRankPermutation vP vPCount out0 = boundary $ do + vPRaw <- peekArray (fromIntegral vPCount) vP + let vPValue = map fromIntegral vPRaw + checked (Combinatorics.rankPermutation + vPValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_unrank_permutation" ffiCombinatoricsUnrankPermutation :: + CPtrdiff -> + CString -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsUnrankPermutation :: + CPtrdiff -> + CString -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsUnrankPermutation vN vR outData outCount = boundary $ do + vRValue <- readInteger vR + checked (Combinatorics.unrankPermutation (fromIntegral vN) vRValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_combinatorics_rank_combination" ffiCombinatoricsRankCombination :: + CPtrdiff -> + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsRankCombination :: + CPtrdiff -> + Ptr CPtrdiff -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsRankCombination vN vXs vXsCount out0 = boundary $ do + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + let vXsValue = map fromIntegral vXsRaw + checked (Combinatorics.rankCombination + (fromIntegral vN) + vXsValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_unrank_combination" ffiCombinatoricsUnrankCombination :: + CPtrdiff -> + CPtrdiff -> + CString -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsUnrankCombination :: + CPtrdiff -> + CPtrdiff -> + CString -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsUnrankCombination vN vK vR outData outCount = boundary $ do + vRValue <- readInteger vR + checked (Combinatorics.unrankCombination (fromIntegral vN) (fromIntegral vK) vRValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_combinatorics_derangement_count" ffiCombinatoricsDerangementCount :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsDerangementCount :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsDerangementCount vN out0 = boundary $ do + checked (Combinatorics.derangementCount + (fromIntegral vN)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_stirling_first" ffiCombinatoricsStirlingFirst :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsStirlingFirst :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsStirlingFirst vArgument1 vArgument2 out0 = boundary $ do + checked (Combinatorics.stirlingFirst + (fromIntegral vArgument1) + (fromIntegral vArgument2)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_stirling_second" ffiCombinatoricsStirlingSecond :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsStirlingSecond :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsStirlingSecond vArgument1 vArgument2 out0 = boundary $ do + checked (Combinatorics.stirlingSecond + (fromIntegral vArgument1) + (fromIntegral vArgument2)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_bell_number" ffiCombinatoricsBellNumber :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsBellNumber :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsBellNumber vN out0 = boundary $ do + checked (Combinatorics.bellNumber + (fromIntegral vN)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_eulerian_number" ffiCombinatoricsEulerianNumber :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsEulerianNumber :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsEulerianNumber vArgument1 vArgument2 out0 = boundary $ do + checked (Combinatorics.eulerianNumber + (fromIntegral vArgument1) + (fromIntegral vArgument2)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_lah_number" ffiCombinatoricsLahNumber :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsLahNumber :: + CPtrdiff -> + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsLahNumber vN vK out0 = boundary $ do + checked (Combinatorics.lahNumber + (fromIntegral vN) + (fromIntegral vK)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_catalan_number" ffiCombinatoricsCatalanNumber :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsCatalanNumber :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsCatalanNumber vArgument1 out0 = boundary $ do + checked (Combinatorics.catalanNumber + (fromIntegral vArgument1)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_fibonacci" ffiCombinatoricsFibonacci :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsFibonacci :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsFibonacci vN out0 = boundary $ do + checked (Combinatorics.fibonacci + (fromIntegral vN)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_lucas" ffiCombinatoricsLucas :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsLucas :: + CPtrdiff -> + Ptr CString -> + IO CInt +ffiCombinatoricsLucas vN out0 = boundary $ do + checked (Combinatorics.lucas + (fromIntegral vN)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_inclusion_exclusion" ffiCombinatoricsInclusionExclusion :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsInclusionExclusion :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsInclusionExclusion vN vSizes vSizesCount out0 = boundary $ do + vSizesRaw <- peekArray (fromIntegral vSizesCount) vSizes + vSizesValue <- mapM readInteger vSizesRaw + checked (Combinatorics.inclusionExclusion + (fromIntegral vN) + vSizesValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_multiset_count_f32" ffiCombinatoricsMultisetCountF32 :: + Ptr CFloat -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultisetCountF32 :: + Ptr CFloat -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultisetCountF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Combinatorics.multisetCount + vArgument1Value) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_multiset_count_f64" ffiCombinatoricsMultisetCountF64 :: + Ptr CDouble -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultisetCountF64 :: + Ptr CDouble -> + CSize -> + Ptr CString -> + IO CInt +ffiCombinatoricsMultisetCountF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Combinatorics.multisetCount + vArgument1Value) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_combinatorics_linear_recurrence" ffiCombinatoricsLinearRecurrence :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsLinearRecurrence :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsLinearRecurrence vN vCs vCsCount vInitial vInitialCount outData outCount = boundary $ do + vCsRaw <- peekArray (fromIntegral vCsCount) vCs + vCsValue <- mapM readInteger vCsRaw + vInitialRaw <- peekArray (fromIntegral vInitialCount) vInitial + vInitialValue <- mapM readInteger vInitialRaw + checked (Combinatorics.linearRecurrence (fromIntegral vN) vCsValue vInitialValue) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_combinatorics_convolve_series" ffiCombinatoricsConvolveSeries :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsConvolveSeries :: + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiCombinatoricsConvolveSeries vN vA vACount vB vBCount outData outCount = boundary $ do + vARaw <- peekArray (fromIntegral vACount) vA + vAValue <- mapM readInteger vARaw + vBRaw <- peekArray (fromIntegral vBCount) vB + vBValue <- mapM readInteger vBRaw + checked (Combinatorics.convolveSeries (fromIntegral vN) vAValue vBValue) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_combinatorics_finite_sum_f32" ffiCombinatoricsFiniteSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiCombinatoricsFiniteSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiCombinatoricsFiniteSumF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Combinatorics.finiteSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_combinatorics_finite_sum_f64" ffiCombinatoricsFiniteSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiCombinatoricsFiniteSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiCombinatoricsFiniteSumF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Combinatorics.finiteSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_linear_dot_f32" ffiLinearDotF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearDotF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearDotF32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_linear_dot_f64" ffiLinearDotF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearDotF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearDotF64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_linear_dot_rational" ffiLinearDotRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiLinearDotRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiLinearDotRational vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) vArgument1 >>= mapM readInteger + let vArgument1Value = rationalPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_linear_dot_integer" ffiLinearDotInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiLinearDotInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiLinearDotInteger vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_linear_dot_i8" ffiLinearDotI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr Int8 -> + IO CInt +ffiLinearDotI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr Int8 -> + IO CInt +ffiLinearDotI8 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_linear_dot_i16" ffiLinearDotI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr Int16 -> + IO CInt +ffiLinearDotI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr Int16 -> + IO CInt +ffiLinearDotI16 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_linear_dot_i32" ffiLinearDotI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr Int32 -> + IO CInt +ffiLinearDotI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr Int32 -> + IO CInt +ffiLinearDotI32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_linear_dot_i64" ffiLinearDotI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr Int64 -> + IO CInt +ffiLinearDotI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr Int64 -> + IO CInt +ffiLinearDotI64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_linear_dot_u8" ffiLinearDotU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr Word8 -> + IO CInt +ffiLinearDotU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr Word8 -> + IO CInt +ffiLinearDotU8 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_linear_dot_u16" ffiLinearDotU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr Word16 -> + IO CInt +ffiLinearDotU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr Word16 -> + IO CInt +ffiLinearDotU16 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_linear_dot_u32" ffiLinearDotU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr Word32 -> + IO CInt +ffiLinearDotU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr Word32 -> + IO CInt +ffiLinearDotU32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_linear_dot_u64" ffiLinearDotU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr Word64 -> + IO CInt +ffiLinearDotU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr Word64 -> + IO CInt +ffiLinearDotU64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_linear_dot_int" ffiLinearDotInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr Int -> + IO CInt +ffiLinearDotInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr Int -> + IO CInt +ffiLinearDotInt vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_linear_dot_word" ffiLinearDotWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr Word -> + IO CInt +ffiLinearDotWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr Word -> + IO CInt +ffiLinearDotWord vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_linear_dot_c64" ffiLinearDotC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearDotC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearDotC64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_linear_dot_c128" ffiLinearDotC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearDotC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearDotC128 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.dot + vArgument1Value + vArgument2Value)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_linear_dot_checked_f32" ffiLinearDotCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearDotCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearDotCheckedF32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_linear_dot_checked_f64" ffiLinearDotCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearDotCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearDotCheckedF64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_linear_dot_checked_rational" ffiLinearDotCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiLinearDotCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + Ptr CString -> + IO CInt +ffiLinearDotCheckedRational vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) vArgument1 >>= mapM readInteger + let vArgument1Value = rationalPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + writeStrings [show (numerator value), show (denominator value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + poke out1 (textPointers !! 1) + +foreign export ccall "hm_numeric_linear_dot_checked_integer" ffiLinearDotCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiLinearDotCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiLinearDotCheckedInteger vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_linear_dot_checked_i8" ffiLinearDotCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr Int8 -> + IO CInt +ffiLinearDotCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr Int8 -> + IO CInt +ffiLinearDotCheckedI8 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_linear_dot_checked_i16" ffiLinearDotCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr Int16 -> + IO CInt +ffiLinearDotCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr Int16 -> + IO CInt +ffiLinearDotCheckedI16 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_linear_dot_checked_i32" ffiLinearDotCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr Int32 -> + IO CInt +ffiLinearDotCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr Int32 -> + IO CInt +ffiLinearDotCheckedI32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_linear_dot_checked_i64" ffiLinearDotCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr Int64 -> + IO CInt +ffiLinearDotCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr Int64 -> + IO CInt +ffiLinearDotCheckedI64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_linear_dot_checked_u8" ffiLinearDotCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr Word8 -> + IO CInt +ffiLinearDotCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr Word8 -> + IO CInt +ffiLinearDotCheckedU8 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_linear_dot_checked_u16" ffiLinearDotCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr Word16 -> + IO CInt +ffiLinearDotCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr Word16 -> + IO CInt +ffiLinearDotCheckedU16 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_linear_dot_checked_u32" ffiLinearDotCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr Word32 -> + IO CInt +ffiLinearDotCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr Word32 -> + IO CInt +ffiLinearDotCheckedU32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_linear_dot_checked_u64" ffiLinearDotCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr Word64 -> + IO CInt +ffiLinearDotCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr Word64 -> + IO CInt +ffiLinearDotCheckedU64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_linear_dot_checked_int" ffiLinearDotCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr Int -> + IO CInt +ffiLinearDotCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr Int -> + IO CInt +ffiLinearDotCheckedInt vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_linear_dot_checked_word" ffiLinearDotCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr Word -> + IO CInt +ffiLinearDotCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr Word -> + IO CInt +ffiLinearDotCheckedWord vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_linear_dot_checked_c64" ffiLinearDotCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearDotCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearDotCheckedC64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_linear_dot_checked_c128" ffiLinearDotCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearDotCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearDotCheckedC128 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.dotChecked + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_linear_magnitude_f32" ffiLinearMagnitudeF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearMagnitudeF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiLinearMagnitudeF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Linear.magnitude + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_linear_magnitude_f64" ffiLinearMagnitudeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearMagnitudeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiLinearMagnitudeF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Linear.magnitude + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_linear_magnitude_c64" ffiLinearMagnitudeC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearMagnitudeC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + Ptr CFloat -> + IO CInt +ffiLinearMagnitudeC64 vArgument1 vArgument1Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + checked (Right (Linear.magnitude + vArgument1Value)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CFloat) + poke out1 (coerce strict1 :: CFloat) + +foreign export ccall "hm_numeric_linear_magnitude_c128" ffiLinearMagnitudeC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearMagnitudeC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiLinearMagnitudeC128 vArgument1 vArgument1Count out0 out1 = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + checked (Right (Linear.magnitude + vArgument1Value)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_linear_normalize_f32" ffiLinearNormalizeF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Linear.normalize vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_normalize_f64" ffiLinearNormalizeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Linear.normalize vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_normalize_c64" ffiLinearNormalizeC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeC64 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeC64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + checked (Right (Linear.normalize vArgument1Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_normalize_c128" ffiLinearNormalizeC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeC128 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearNormalizeC128 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + checked (Right (Linear.normalize vArgument1Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_f32" ffiLinearAddF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddF32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_f64" ffiLinearAddF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddF64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_rational" ffiLinearAddRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddRational vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) vArgument1 >>= mapM readInteger + let vArgument1Value = rationalPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_integer" ffiLinearAddInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddInteger vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_i8" ffiLinearAddI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearAddI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearAddI8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_i16" ffiLinearAddI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearAddI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearAddI16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_i32" ffiLinearAddI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearAddI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearAddI32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_i64" ffiLinearAddI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearAddI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearAddI64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_u8" ffiLinearAddU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearAddU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearAddU8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_u16" ffiLinearAddU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearAddU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearAddU16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_u32" ffiLinearAddU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearAddU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearAddU32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_u64" ffiLinearAddU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearAddU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearAddU64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_int" ffiLinearAddInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearAddInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearAddInt vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_word" ffiLinearAddWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearAddWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearAddWord vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_c64" ffiLinearAddC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddC64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_c128" ffiLinearAddC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddC128 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_checked_f32" ffiLinearAddCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedF32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_f64" ffiLinearAddCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedF64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_rational" ffiLinearAddCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedRational vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) vArgument1 >>= mapM readInteger + let vArgument1Value = rationalPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_checked_integer" ffiLinearAddCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedInteger vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_checked_i8" ffiLinearAddCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_i16" ffiLinearAddCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_i32" ffiLinearAddCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_i64" ffiLinearAddCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedI64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_u8" ffiLinearAddCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_u16" ffiLinearAddCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_u32" ffiLinearAddCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_u64" ffiLinearAddCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedU64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_int" ffiLinearAddCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedInt vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_word" ffiLinearAddCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedWord vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_add_checked_c64" ffiLinearAddCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedC64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_add_checked_c128" ffiLinearAddCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearAddCheckedC128 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.addChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_subtract_checked_f32" ffiLinearSubtractCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedF32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_f64" ffiLinearSubtractCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedF64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_rational" ffiLinearSubtractCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedRational :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedRational vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) vArgument1 >>= mapM readInteger + let vArgument1Value = rationalPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_subtract_checked_integer" ffiLinearSubtractCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedInteger :: + Ptr CString -> + CSize -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedInteger vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_subtract_checked_i8" ffiLinearSubtractCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI8 :: + Ptr Int8 -> + CSize -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_i16" ffiLinearSubtractCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI16 :: + Ptr Int16 -> + CSize -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_i32" ffiLinearSubtractCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI32 :: + Ptr Int32 -> + CSize -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_i64" ffiLinearSubtractCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI64 :: + Ptr Int64 -> + CSize -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedI64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_u8" ffiLinearSubtractCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU8 :: + Ptr Word8 -> + CSize -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU8 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_u16" ffiLinearSubtractCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU16 :: + Ptr Word16 -> + CSize -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU16 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_u32" ffiLinearSubtractCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU32 :: + Ptr Word32 -> + CSize -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU32 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_u64" ffiLinearSubtractCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU64 :: + Ptr Word64 -> + CSize -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedU64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_int" ffiLinearSubtractCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedInt :: + Ptr Int -> + CSize -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedInt vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_word" ffiLinearSubtractCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedWord :: + Ptr Word -> + CSize -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedWord vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_subtract_checked_c64" ffiLinearSubtractCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedC64 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedC64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_subtract_checked_c128" ffiLinearSubtractCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedC128 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearSubtractCheckedC128 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (2 * fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + let vArgument1Value = complexPairs vArgument1Raw + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Linear.subtractChecked vArgument1Value vArgument2Value) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_scale_f32" ffiLinearScaleF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearScaleF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearScaleF32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Right (Linear.scale (coerce vArgument1 :: Float) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_f64" ffiLinearScaleF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearScaleF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearScaleF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (Linear.scale (coerce vArgument1 :: Double) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_rational" ffiLinearScaleRational :: + CString -> + CString -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearScaleRational :: + CString -> + CString -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearScaleRational vArgument1Numerator vArgument1Denominator vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1N <- readInteger vArgument1Numerator + vArgument1D <- readInteger vArgument1Denominator + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) vArgument2 >>= mapM readInteger + let vArgument2Value = rationalPairs vArgument2Raw + checked (Right (Linear.scale (vArgument1N % vArgument1D) vArgument2Value)) $ \value -> do + writeStrings (concatMap (\r -> [show (numerator r), show (denominator r)]) value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_scale_integer" ffiLinearScaleInteger :: + CString -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearScaleInteger :: + CString -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiLinearScaleInteger vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- readInteger vArgument1 + vArgument2Raw <- peekArray (fromIntegral vArgument2Count) vArgument2 + vArgument2Value <- mapM readInteger vArgument2Raw + checked (Right (Linear.scale vArgument1Value vArgument2Value)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_scale_i8" ffiLinearScaleI8 :: + Int8 -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI8 :: + Int8 -> + Ptr Int8 -> + CSize -> + Ptr (Ptr Int8) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI8 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Int8) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_i16" ffiLinearScaleI16 :: + Int16 -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI16 :: + Int16 -> + Ptr Int16 -> + CSize -> + Ptr (Ptr Int16) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI16 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Int16) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_i32" ffiLinearScaleI32 :: + Int32 -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI32 :: + Int32 -> + Ptr Int32 -> + CSize -> + Ptr (Ptr Int32) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Int32) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_i64" ffiLinearScaleI64 :: + Int64 -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI64 :: + Int64 -> + Ptr Int64 -> + CSize -> + Ptr (Ptr Int64) -> + Ptr CSize -> + IO CInt +ffiLinearScaleI64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Int64) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_u8" ffiLinearScaleU8 :: + Word8 -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU8 :: + Word8 -> + Ptr Word8 -> + CSize -> + Ptr (Ptr Word8) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU8 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Word8) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word8]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_u16" ffiLinearScaleU16 :: + Word16 -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU16 :: + Word16 -> + Ptr Word16 -> + CSize -> + Ptr (Ptr Word16) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU16 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Word16) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word16]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_u32" ffiLinearScaleU32 :: + Word32 -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU32 :: + Word32 -> + Ptr Word32 -> + CSize -> + Ptr (Ptr Word32) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Word32) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word32]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_u64" ffiLinearScaleU64 :: + Word64 -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU64 :: + Word64 -> + Ptr Word64 -> + CSize -> + Ptr (Ptr Word64) -> + Ptr CSize -> + IO CInt +ffiLinearScaleU64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Word64) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word64]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_int" ffiLinearScaleInt :: + Int -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearScaleInt :: + Int -> + Ptr Int -> + CSize -> + Ptr (Ptr Int) -> + Ptr CSize -> + IO CInt +ffiLinearScaleInt vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Int) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_word" ffiLinearScaleWord :: + Word -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearScaleWord :: + Word -> + Ptr Word -> + CSize -> + Ptr (Ptr Word) -> + Ptr CSize -> + IO CInt +ffiLinearScaleWord vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) vArgument2 + checked (Right (Linear.scale (vArgument1 :: Word) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Word]) + bracketOnError (newArray (strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_linear_scale_c64" ffiLinearScaleC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearScaleC64 :: + CFloat -> + CFloat -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiLinearScaleC64 vArgument10 vArgument11 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.scale ((coerce vArgument10 :: Float) :+ (coerce vArgument11 :: Float)) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_linear_scale_c128" ffiLinearScaleC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearScaleC128 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiLinearScaleC128 vArgument10 vArgument11 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Raw <- peekArray (2 * fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + let vArgument2Value = complexPairs vArgument2Raw + checked (Right (Linear.scale ((coerce vArgument10 :: Double) :+ (coerce vArgument11 :: Double)) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (concatMap (\z -> [realPart z, imagPart z]) value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_special_gamma_f64" ffiSpecialGammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaF64 vX out0 = boundary $ do + checked (Special.gamma + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_log_gamma_f64" ffiSpecialLogGammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogGammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogGammaF64 vX out0 = boundary $ do + checked (Special.logGamma + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_log_beta_f64" ffiSpecialLogBetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogBetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogBetaF64 vA vB out0 = boundary $ do + checked (Special.logBeta + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_beta_f64" ffiSpecialBetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBetaF64 vA vB out0 = boundary $ do + checked (Special.beta + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_gamma_p_f64" ffiSpecialGammaPF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaPF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaPF64 vA vX out0 = boundary $ do + checked (Special.gammaP + (coerce vA :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_gamma_q_f64" ffiSpecialGammaQF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaQF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGammaQF64 vA vX out0 = boundary $ do + checked (Special.gammaQ + (coerce vA :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_incomplete_gamma_f64" ffiSpecialIncompleteGammaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialIncompleteGammaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialIncompleteGammaF64 vA vX out0 = boundary $ do + checked (Special.incompleteGamma + (coerce vA :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_beta_i_f64" ffiSpecialBetaIF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBetaIF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBetaIF64 vA vB vX out0 = boundary $ do + checked (Special.betaI + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_incomplete_beta_f64" ffiSpecialIncompleteBetaF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialIncompleteBetaF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialIncompleteBetaF64 vA vB vX out0 = boundary $ do + checked (Special.incompleteBeta + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_digamma_f64" ffiSpecialDigammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDigammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDigammaF64 vX out0 = boundary $ do + checked (Special.digamma + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_trigamma_f64" ffiSpecialTrigammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialTrigammaF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialTrigammaF64 vArgument1 out0 = boundary $ do + checked (Special.trigamma + (coerce vArgument1 :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_polygamma_f64" ffiSpecialPolygammaF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialPolygammaF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialPolygammaF64 vN vX out0 = boundary $ do + checked (Special.polygamma + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_erf_f64" ffiSpecialErfF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfF64 vX out0 = boundary $ do + checked (Special.erf + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_erfc_f64" ffiSpecialErfcF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfcF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfcF64 vX out0 = boundary $ do + checked (Special.erfc + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_erfcx_f64" ffiSpecialErfcxF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfcxF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialErfcxF64 vX out0 out1 = boundary $ do + checked (Special.erfcx + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_normal_c_d_f_f64" ffiSpecialNormalCDFF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialNormalCDFF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialNormalCDFF64 vX out0 = boundary $ do + checked (Special.normalCDF + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_normal_quantile_f64" ffiSpecialNormalQuantileF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialNormalQuantileF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialNormalQuantileF64 vP out0 = boundary $ do + checked (Special.normalQuantile + (coerce vP :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_inverse_erf_f64" ffiSpecialInverseErfF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialInverseErfF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialInverseErfF64 vX out0 = boundary $ do + checked (Special.inverseErf + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_dawson_f64" ffiSpecialDawsonF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDawsonF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDawsonF64 vX out0 out1 = boundary $ do + checked (Special.dawson + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_exponential_integral_f64" ffiSpecialExponentialIntegralF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialExponentialIntegralF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialExponentialIntegralF64 vN vX out0 out1 = boundary $ do + checked (Special.exponentialIntegral + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_logarithmic_integral_f64" ffiSpecialLogarithmicIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogarithmicIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLogarithmicIntegralF64 vX out0 out1 = boundary $ do + checked (Special.logarithmicIntegral + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_sine_integral_f64" ffiSpecialSineIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSineIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSineIntegralF64 vX out0 out1 = boundary $ do + checked (Special.sineIntegral + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_cosine_integral_f64" ffiSpecialCosineIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialCosineIntegralF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialCosineIntegralF64 vX out0 out1 = boundary $ do + checked (Special.cosineIntegral + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_fresnel_f64" ffiSpecialFresnelF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialFresnelF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialFresnelF64 vX out0 out1 out2 out3 = boundary $ do + checked (Special.fresnel + (coerce vX :: Double)) $ \(first, second) -> do + strict0 <- evaluate (Special.sfValue first) + strict1 <- evaluate (Special.sfError first) + strict2 <- evaluate (Special.sfValue second) + strict3 <- evaluate (Special.sfError second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + poke out3 (coerce strict3 :: CDouble) + +foreign export ccall "hm_numeric_special_elliptic_f_f64" ffiSpecialEllipticFF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticFF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticFF64 vPhi vM out0 out1 = boundary $ do + checked (Special.ellipticF + (coerce vPhi :: Double) + (coerce vM :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_elliptic_e_f64" ffiSpecialEllipticEF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticEF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticEF64 vPhi vM out0 out1 = boundary $ do + checked (Special.ellipticE + (coerce vPhi :: Double) + (coerce vM :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_elliptic_pi_f64" ffiSpecialEllipticPiF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticPiF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEllipticPiF64 vN vPhi vM out0 out1 = boundary $ do + checked (Special.ellipticPi + (coerce vN :: Double) + (coerce vPhi :: Double) + (coerce vM :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_jacobi_elliptic_f64" ffiSpecialJacobiEllipticF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialJacobiEllipticF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialJacobiEllipticF64 vU vM out0 out1 out2 = boundary $ do + checked (Special.jacobiElliptic + (coerce vU :: Double) + (coerce vM :: Double)) $ \(first, second, third) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + strict2 <- evaluate (third) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + +foreign export ccall "hm_numeric_special_bessel_j_f64" ffiSpecialBesselJF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselJF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselJF64 vN vX out0 = boundary $ do + checked (Special.besselJ + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_bessel_y_f64" ffiSpecialBesselYF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselYF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselYF64 vN vX out0 = boundary $ do + checked (Special.besselY + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_bessel_i_f64" ffiSpecialBesselIF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselIF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselIF64 vN vX out0 out1 = boundary $ do + checked (Special.besselI + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_scaled_bessel_i_f64" ffiSpecialScaledBesselIF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialScaledBesselIF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialScaledBesselIF64 vN vX out0 out1 = boundary $ do + checked (Special.scaledBesselI + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_bessel_k_f64" ffiSpecialBesselKF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselKF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBesselKF64 vN vX out0 out1 = boundary $ do + checked (Special.besselK + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_scaled_bessel_k_f64" ffiSpecialScaledBesselKF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialScaledBesselKF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialScaledBesselKF64 vN vX out0 out1 = boundary $ do + checked (Special.scaledBesselK + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_spherical_bessel_j_f64" ffiSpecialSphericalBesselJF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalBesselJF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalBesselJF64 vN vX out0 = boundary $ do + checked (Special.sphericalBesselJ + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_spherical_bessel_y_f64" ffiSpecialSphericalBesselYF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalBesselYF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalBesselYF64 vN vX out0 = boundary $ do + checked (Special.sphericalBesselY + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_airy_f64" ffiSpecialAiryF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialAiryF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialAiryF64 vX out0 out1 out2 out3 out4 out5 out6 out7 = boundary $ do + checked (Special.airy + (coerce vX :: Double)) $ \(first, second, third, fourth) -> do + strict0 <- evaluate (Special.sfValue first) + strict1 <- evaluate (Special.sfError first) + strict2 <- evaluate (Special.sfValue second) + strict3 <- evaluate (Special.sfError second) + strict4 <- evaluate (Special.sfValue third) + strict5 <- evaluate (Special.sfError third) + strict6 <- evaluate (Special.sfValue fourth) + strict7 <- evaluate (Special.sfError fourth) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + poke out3 (coerce strict3 :: CDouble) + poke out4 (coerce strict4 :: CDouble) + poke out5 (coerce strict5 :: CDouble) + poke out6 (coerce strict6 :: CDouble) + poke out7 (coerce strict7 :: CDouble) + +foreign export ccall "hm_numeric_special_struve_f64" ffiSpecialStruveF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialStruveF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialStruveF64 vNu vX out0 out1 = boundary $ do + checked (Special.struve + (coerce vNu :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_hypergeometric_f64" ffiSpecialHypergeometricF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometricF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometricF64 vAs vAsCount vBs vBsCount vZ out0 out1 = boundary $ do + vAsValue <- peekArray (fromIntegral vAsCount) (castPtr vAs :: Ptr Double) + vBsValue <- peekArray (fromIntegral vBsCount) (castPtr vBs :: Ptr Double) + checked (Special.hypergeometric + vAsValue + vBsValue + (coerce vZ :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_hypergeometric1_f1_f64" ffiSpecialHypergeometric1F1F64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometric1F1F64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometric1F1F64 vA vB vZ out0 out1 = boundary $ do + checked (Special.hypergeometric1F1 + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vZ :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_hypergeometric2_f1_f64" ffiSpecialHypergeometric2F1F64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometric2F1F64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHypergeometric2F1F64 vA vB vC vZ out0 out1 = boundary $ do + checked (Special.hypergeometric2F1 + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vC :: Double) + (coerce vZ :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_legendre_f64" ffiSpecialLegendreF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLegendreF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLegendreF64 vN vX out0 = boundary $ do + checked (Special.legendre + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_associated_legendre_f64" ffiSpecialAssociatedLegendreF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialAssociatedLegendreF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialAssociatedLegendreF64 vL vM vX out0 = boundary $ do + checked (Special.associatedLegendre + (fromIntegral vL) + (fromIntegral vM) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_hurwitz_zeta_f64" ffiSpecialHurwitzZetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHurwitzZetaF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHurwitzZetaF64 vS vQ out0 out1 = boundary $ do + checked (Special.hurwitzZeta + (coerce vS :: Double) + (coerce vQ :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_riemann_zeta_f64" ffiSpecialRiemannZetaF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialRiemannZetaF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialRiemannZetaF64 vS out0 out1 = boundary $ do + checked (Special.riemannZeta + (coerce vS :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_polylogarithm_f64" ffiSpecialPolylogarithmF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialPolylogarithmF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialPolylogarithmF64 vS vZ out0 out1 = boundary $ do + checked (Special.polylogarithm + (coerce vS :: Double) + (coerce vZ :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_dilogarithm_f64" ffiSpecialDilogarithmF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDilogarithmF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDilogarithmF64 vX out0 out1 = boundary $ do + checked (Special.dilogarithm + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_lambert_w_f64" ffiSpecialLambertWF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLambertWF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialLambertWF64 vBranch vX out0 out1 = boundary $ do + checked (Special.lambertW + (fromIntegral vBranch) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_debye_f64" ffiSpecialDebyeF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDebyeF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialDebyeF64 vN vX out0 out1 = boundary $ do + checked (Special.debye + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_clausen_f64" ffiSpecialClausenF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialClausenF64 :: + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialClausenF64 vTheta out0 out1 = boundary $ do + checked (Special.clausen + (coerce vTheta :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_fermi_dirac_f64" ffiSpecialFermiDiracF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialFermiDiracF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialFermiDiracF64 vOrder vEta out0 out1 = boundary $ do + checked (Special.fermiDirac + (coerce vOrder :: Double) + (coerce vEta :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_bose_einstein_f64" ffiSpecialBoseEinsteinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBoseEinsteinF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBoseEinsteinF64 vOrder vEta out0 out1 = boundary $ do + checked (Special.boseEinstein + (coerce vOrder :: Double) + (coerce vEta :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_coulomb_wave_f64" ffiSpecialCoulombWaveF64 :: + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialCoulombWaveF64 :: + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialCoulombWaveF64 vL vEta vRho out0 out1 out2 out3 = boundary $ do + checked (Special.coulombWave + (fromIntegral vL) + (coerce vEta :: Double) + (coerce vRho :: Double)) $ \(first, second) -> do + strict0 <- evaluate (Special.sfValue first) + strict1 <- evaluate (Special.sfError first) + strict2 <- evaluate (Special.sfValue second) + strict3 <- evaluate (Special.sfError second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + poke out3 (coerce strict3 :: CDouble) + +foreign export ccall "hm_numeric_special_gegenbauer_f64" ffiSpecialGegenbauerF64 :: + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGegenbauerF64 :: + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialGegenbauerF64 vN vA vX out0 = boundary $ do + checked (Special.gegenbauer + (fromIntegral vN) + (coerce vA :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_parabolic_cylinder_f64" ffiSpecialParabolicCylinderF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialParabolicCylinderF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialParabolicCylinderF64 vNu vX out0 out1 = boundary $ do + checked (Special.parabolicCylinder + (coerce vNu :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (Special.sfValue value) + strict1 <- evaluate (Special.sfError value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_mathieu_f64" ffiSpecialMathieuF64 :: + CInt -> + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialMathieuF64 :: + CInt -> + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialMathieuF64 vEvenMode vN vQ vX out0 out1 out2 = boundary $ do + checked (Special.mathieu + (vEvenMode /= 0) + (fromIntegral vN) + (coerce vQ :: Double) + (coerce vX :: Double)) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (Special.sfValue second) + strict2 <- evaluate (Special.sfError second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + poke out2 (coerce strict2 :: CDouble) + +foreign export ccall "hm_numeric_special_bernoulli_polynomial_f64" ffiSpecialBernoulliPolynomialF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBernoulliPolynomialF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialBernoulliPolynomialF64 vN vX out0 = boundary $ do + checked (Special.bernoulliPolynomial + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_euler_polynomial_f64" ffiSpecialEulerPolynomialF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEulerPolynomialF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialEulerPolynomialF64 vN vX out0 = boundary $ do + checked (Special.eulerPolynomial + (fromIntegral vN) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_wigner3j_f64" ffiSpecialWigner3JF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner3JF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner3JF64 vJ1 vJ2 vJ3 vM1 vM2 vM3 out0 = boundary $ do + checked (Special.wigner3j + (fromIntegral vJ1) + (fromIntegral vJ2) + (fromIntegral vJ3) + (fromIntegral vM1) + (fromIntegral vM2) + (fromIntegral vM3)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_wigner6j_f64" ffiSpecialWigner6JF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner6JF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner6JF64 vA vB vC vD vE vF out0 = boundary $ do + checked (Special.wigner6j + (fromIntegral vA) + (fromIntegral vB) + (fromIntegral vC) + (fromIntegral vD) + (fromIntegral vE) + (fromIntegral vF)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_wigner9j_f64" ffiSpecialWigner9JF64 :: + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner9JF64 :: + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSpecialWigner9JF64 vJs vJsCount out0 = boundary $ do + vJsRaw <- peekArray (fromIntegral vJsCount) vJs + let vJsValue = map fromIntegral vJsRaw + checked (Special.wigner9j + vJsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_special_clebsch_gordan_f64" ffiSpecialClebschGordanF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialClebschGordanF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiSpecialClebschGordanF64 vJ1 vM1 vJ2 vM2 vJ vM out0 = boundary $ do + checked (Special.clebschGordan + (fromIntegral vJ1) + (fromIntegral vM1) + (fromIntegral vJ2) + (fromIntegral vM2) + (fromIntegral vJ) + (fromIntegral vM)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_complex_to_polar_f64" ffiComplexToPolarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexToPolarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexToPolarF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Complex.toPolar + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_probability_gamma_poisson_update_f64" ffiProbabilityGammaPoissonUpdateF64 :: + CDouble -> + CDouble -> + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityGammaPoissonUpdateF64 :: + CDouble -> + CDouble -> + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityGammaPoissonUpdateF64 vShapePrior vRatePrior vXs vXsCount out0 out1 = boundary $ do + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + let vXsValue = map fromIntegral vXsRaw + checked (Probability.gammaPoissonUpdate + (coerce vShapePrior :: Double) + (coerce vRatePrior :: Double) + vXsValue) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_probability_normal_normal_update_f64" ffiProbabilityNormalNormalUpdateF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityNormalNormalUpdateF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityNormalNormalUpdateF64 vMu vPriorVariance vObservationVariance vXs vXsCount out0 out1 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Probability.normalNormalUpdate + (coerce vMu :: Double) + (coerce vPriorVariance :: Double) + (coerce vObservationVariance :: Double) + vXsValue) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_probability_conditional_probability_f64" ffiProbabilityConditionalProbabilityF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityConditionalProbabilityF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiProbabilityConditionalProbabilityF64 vJoint vGiven out0 = boundary $ do + checked (Probability.conditionalProbability + (coerce vJoint :: Double) + (coerce vGiven :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_probability_bayes_f64" ffiProbabilityBayesF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiProbabilityBayesF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiProbabilityBayesF64 vPriors vPriorsCount vLikelihoods vLikelihoodsCount outData outCount = boundary $ do + vPriorsValue <- peekArray (fromIntegral vPriorsCount) (castPtr vPriors :: Ptr Double) + vLikelihoodsValue <- peekArray (fromIntegral vLikelihoodsCount) (castPtr vLikelihoods :: Ptr Double) + checked (Probability.bayes vPriorsValue vLikelihoodsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_probability_multinomial_p_m_f_f64" ffiProbabilityMultinomialPMFF64 :: + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + IO CInt +ffiProbabilityMultinomialPMFF64 :: + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + CSize -> + Ptr CDouble -> + IO CInt +ffiProbabilityMultinomialPMFF64 vPs vPsCount vCounts vCountsCount out0 = boundary $ do + vPsValue <- peekArray (fromIntegral vPsCount) (castPtr vPs :: Ptr Double) + vCountsRaw <- peekArray (fromIntegral vCountsCount) vCounts + let vCountsValue = map fromIntegral vCountsRaw + checked (Probability.multinomialPMF + vPsValue + vCountsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_probability_dirichlet_density_f64" ffiProbabilityDirichletDensityF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiProbabilityDirichletDensityF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiProbabilityDirichletDensityF64 vAs vAsCount vXs vXsCount out0 = boundary $ do + vAsValue <- peekArray (fromIntegral vAsCount) (castPtr vAs :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Probability.dirichletDensity + vAsValue + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_complex_complex_f64" ffiComplexComplexF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexComplexF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexComplexF64 vReal vImaginary out0 out1 = boundary $ do + checked (Complex.complex + (coerce vReal :: Double) + (coerce vImaginary :: Double)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_reciprocal_f64" ffiComplexReciprocalF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexReciprocalF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexReciprocalF64 vZ0 vZ1 out0 out1 = boundary $ do + checked (Complex.reciprocal + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_add_f64" ffiComplexAddF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexAddF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexAddF64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Complex.add + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_subtract_complex_f64" ffiComplexSubtractComplexF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexSubtractComplexF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexSubtractComplexF64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Complex.subtractComplex + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_multiply_f64" ffiComplexMultiplyF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexMultiplyF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexMultiplyF64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Complex.multiply + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_divide_f64" ffiComplexDivideF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexDivideF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexDivideF64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Complex.divide + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_power_f64" ffiComplexPowerF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexPowerF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexPowerF64 vA0 vA1 vB0 vB1 out0 out1 = boundary $ do + checked (Complex.power + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_from_polar_f64" ffiComplexFromPolarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexFromPolarF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexFromPolarF64 vRadius vAngle out0 out1 = boundary $ do + checked (Complex.fromPolar + (coerce vRadius :: Double) + (coerce vAngle :: Double)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_complex_rotate_f64" ffiComplexRotateF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexRotateF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiComplexRotateF64 vAngle vZ0 vZ1 out0 out1 = boundary $ do + checked (Complex.rotate + (coerce vAngle :: Double) + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_hankel_f64" ffiSpecialHankelF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHankelF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialHankelF64 vKind vOrder vX out0 out1 = boundary $ do + checked (Special.hankel + (fromIntegral vKind) + (fromIntegral vOrder) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_spherical_harmonic_f64" ffiSpecialSphericalHarmonicF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalHarmonicF64 :: + CPtrdiff -> + CPtrdiff -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialSphericalHarmonicF64 vDegree vOrder vTheta vPhi out0 out1 = boundary $ do + checked (Special.sphericalHarmonic + (fromIntegral vDegree) + (fromIntegral vOrder) + (coerce vTheta :: Double) + (coerce vPhi :: Double)) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_special_complex1_f1_f64" ffiSpecialComplex1F1F64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialComplex1F1F64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiSpecialComplex1F1F64 vA0 vA1 vB0 vB1 vZ0 vZ1 out0 out1 = boundary $ do + checked (Special.complex1F1 + ((coerce vA0 :: Double) :+ (coerce vA1 :: Double)) + ((coerce vB0 :: Double) :+ (coerce vB1 :: Double)) + ((coerce vZ0 :: Double) :+ (coerce vZ1 :: Double))) $ \value -> do + strict0 <- evaluate (realPart value) + strict1 <- evaluate (imagPart value) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_api_algebra_inner_product_f32" ffiApiAlgebraInnerProductF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiApiAlgebraInnerProductF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiApiAlgebraInnerProductF32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (APIAlgebra.innerProduct + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_api_algebra_inner_product_f64" ffiApiAlgebraInnerProductF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiApiAlgebraInnerProductF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiApiAlgebraInnerProductF64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (APIAlgebra.innerProduct + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_algorithms_lower_bound_f32" ffiAlgorithmsLowerBoundF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsLowerBoundF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsLowerBoundF32 vX vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Float) + checked (Algorithms.lowerBound + (coerce vX :: Float) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_algorithms_lower_bound_f64" ffiAlgorithmsLowerBoundF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsLowerBoundF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsLowerBoundF64 vX vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.lowerBound + (coerce vX :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_algorithms_upper_bound_f32" ffiAlgorithmsUpperBoundF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsUpperBoundF32 :: + CFloat -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsUpperBoundF32 vX vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Float) + checked (Algorithms.upperBound + (coerce vX :: Float) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_algorithms_upper_bound_f64" ffiAlgorithmsUpperBoundF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsUpperBoundF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsUpperBoundF64 vX vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.upperBound + (coerce vX :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_algorithms_quickselect_f32" ffiAlgorithmsQuickselectF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiAlgorithmsQuickselectF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiAlgorithmsQuickselectF32 vK vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Float) + checked (Algorithms.quickselect + (fromIntegral vK) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_algorithms_quickselect_f64" ffiAlgorithmsQuickselectF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsQuickselectF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsQuickselectF64 vK vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.quickselect + (fromIntegral vK) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_algorithms_introselect_f32" ffiAlgorithmsIntroselectF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiAlgorithmsIntroselectF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiAlgorithmsIntroselectF32 vK vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Float) + checked (Algorithms.introselect + (fromIntegral vK) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_algorithms_introselect_f64" ffiAlgorithmsIntroselectF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsIntroselectF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsIntroselectF64 vK vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.introselect + (fromIntegral vK) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_algorithms_partial_sort_f32" ffiAlgorithmsPartialSortF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPartialSortF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPartialSortF32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Algorithms.partialSort (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_partial_sort_f64" ffiAlgorithmsPartialSortF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPartialSortF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPartialSortF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Algorithms.partialSort (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_merge_sort_f32" ffiAlgorithmsMergeSortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsMergeSortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsMergeSortF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.mergeSort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_merge_sort_f64" ffiAlgorithmsMergeSortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsMergeSortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsMergeSortF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.mergeSort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_quicksort_f32" ffiAlgorithmsQuicksortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsQuicksortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsQuicksortF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.quicksort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_quicksort_f64" ffiAlgorithmsQuicksortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsQuicksortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsQuicksortF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.quicksort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_heapsort_f32" ffiAlgorithmsHeapsortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsHeapsortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsHeapsortF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.heapsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_heapsort_f64" ffiAlgorithmsHeapsortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsHeapsortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsHeapsortF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.heapsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_introsort_f32" ffiAlgorithmsIntrosortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsIntrosortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsIntrosortF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.introsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_introsort_f64" ffiAlgorithmsIntrosortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsIntrosortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsIntrosortF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.introsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_counting_sort" ffiAlgorithmsCountingSort :: + CPtrdiff -> + Ptr CPtrdiff -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsCountingSort :: + CPtrdiff -> + Ptr CPtrdiff -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsCountingSort vBudget vXs vXsCount outData outCount = boundary $ do + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + let vXsValue = map fromIntegral vXsRaw + checked (Algorithms.countingSort (fromIntegral vBudget) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_radix_sort" ffiAlgorithmsRadixSort :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsRadixSort :: + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsRadixSort vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Raw <- peekArray (fromIntegral vArgument1Count) vArgument1 + vArgument1Value <- mapM readInteger vArgument1Raw + checked (Right (Algorithms.radixSort vArgument1Value)) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_algorithms_bucket_sort_f64" ffiAlgorithmsBucketSortF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsBucketSortF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsBucketSortF64 vBuckets vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.bucketSort (fromIntegral vBuckets) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_argsort_f32" ffiAlgorithmsArgsortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsArgsortF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsArgsortF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.argsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_argsort_f64" ffiAlgorithmsArgsortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsArgsortF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsArgsortF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.argsort vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_top_k_f32" ffiAlgorithmsTopKF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsTopKF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsTopKF32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (Algorithms.topK (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_top_k_f64" ffiAlgorithmsTopKF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsTopKF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsTopKF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Algorithms.topK (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_quantile_select_f64" ffiAlgorithmsQuantileSelectF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsQuantileSelectF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiAlgorithmsQuantileSelectF64 vQ vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Algorithms.quantileSelect + (coerce vQ :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_algorithms_deduplicate_f32" ffiAlgorithmsDeduplicateF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDeduplicateF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDeduplicateF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.deduplicate vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_deduplicate_f64" ffiAlgorithmsDeduplicateF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDeduplicateF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDeduplicateF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.deduplicate vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_prefix_sums_f32" ffiAlgorithmsPrefixSumsF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPrefixSumsF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPrefixSumsF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.prefixSums vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_prefix_sums_f64" ffiAlgorithmsPrefixSumsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPrefixSumsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsPrefixSumsF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.prefixSums vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_suffix_sums_f32" ffiAlgorithmsSuffixSumsF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsSuffixSumsF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsSuffixSumsF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.suffixSums vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_suffix_sums_f64" ffiAlgorithmsSuffixSumsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsSuffixSumsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsSuffixSumsF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.suffixSums vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_difference_array_f32" ffiAlgorithmsDifferenceArrayF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDifferenceArrayF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDifferenceArrayF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.differenceArray vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_difference_array_f64" ffiAlgorithmsDifferenceArrayF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDifferenceArrayF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsDifferenceArrayF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.differenceArray vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_apply_differences_f32" ffiAlgorithmsApplyDifferencesF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsApplyDifferencesF32 :: + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsApplyDifferencesF32 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Algorithms.applyDifferences vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_apply_differences_f64" ffiAlgorithmsApplyDifferencesF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsApplyDifferencesF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsApplyDifferencesF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Algorithms.applyDifferences vArgument1Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_algorithms_binary_lift" ffiAlgorithmsBinaryLift :: + Ptr CPtrdiff -> + CSize -> + CString -> + CPtrdiff -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsBinaryLift :: + Ptr CPtrdiff -> + CSize -> + CString -> + CPtrdiff -> + Ptr CPtrdiff -> + IO CInt +ffiAlgorithmsBinaryLift vNext vNextCount vSteps vStart out0 = boundary $ do + vNextRaw <- peekArray (fromIntegral vNextCount) vNext + let vNextValue = map fromIntegral vNextRaw + vStepsValue <- readInteger vSteps + checked (Algorithms.binaryLift + vNextValue + vStepsValue + (fromIntegral vStart)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_algorithms_polynomial_hash" ffiAlgorithmsPolynomialHash :: + CString -> + CString -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiAlgorithmsPolynomialHash :: + CString -> + CString -> + Ptr CString -> + CSize -> + Ptr CString -> + IO CInt +ffiAlgorithmsPolynomialHash vBase vModulus vXs vXsCount out0 = boundary $ do + vBaseValue <- readInteger vBase + vModulusValue <- readInteger vModulus + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + vXsValue <- mapM readInteger vXsRaw + checked (Algorithms.polynomialHash + vBaseValue + vModulusValue + vXsValue) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_algorithms_rolling_hashes" ffiAlgorithmsRollingHashes :: + CString -> + CString -> + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsRollingHashes :: + CString -> + CString -> + CPtrdiff -> + Ptr CString -> + CSize -> + Ptr (Ptr CString) -> + Ptr CSize -> + IO CInt +ffiAlgorithmsRollingHashes vBase vModulus vWidth vXs vXsCount outData outCount = boundary $ do + vBaseValue <- readInteger vBase + vModulusValue <- readInteger vModulus + vXsRaw <- peekArray (fromIntegral vXsCount) vXs + vXsValue <- mapM readInteger vXsRaw + checked (Algorithms.rollingHashes vBaseValue vModulusValue (fromIntegral vWidth) vXsValue) $ \value -> do + writeStrings (map show value) $ \textPointers -> + bracketOnError (newArray textPointers) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length value)) + +foreign export ccall "hm_numeric_datastructure_monotonic_minima_f32" ffiDatastructureMonotonicMinimaF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDatastructureMonotonicMinimaF32 :: + CPtrdiff -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDatastructureMonotonicMinimaF32 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (DataStructure.monotonicMinima (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_datastructure_monotonic_minima_f64" ffiDatastructureMonotonicMinimaF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDatastructureMonotonicMinimaF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDatastructureMonotonicMinimaF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (DataStructure.monotonicMinima (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_deeplearning_core_log_softmax_f64" ffiDeeplearningCoreLogSoftmaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreLogSoftmaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreLogSoftmaxF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (DeepLearningCore.logSoftmax vArgument1Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_deeplearning_core_softmax_f64" ffiDeeplearningCoreSoftmaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreSoftmaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreSoftmaxF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (DeepLearningCore.softmax vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_deeplearning_core_sparsemax_f64" ffiDeeplearningCoreSparsemaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreSparsemaxF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreSparsemaxF64 vArgument1 vArgument1Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (DeepLearningCore.sparsemax vArgument1Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_deeplearning_core_gated_linear_unit_f64" ffiDeeplearningCoreGatedLinearUnitF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreGatedLinearUnitF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningCoreGatedLinearUnitF64 vValues vValuesCount vGate vGateCount outData outCount = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + vGateValue <- peekArray (fromIntegral vGateCount) (castPtr vGate :: Ptr Double) + checked (DeepLearningCore.gatedLinearUnit vValuesValue vGateValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_deeplearning_core_categorical_cross_entropy_logits_f64" ffiDeeplearningCoreCategoricalCrossEntropyLogitsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreCategoricalCrossEntropyLogitsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreCategoricalCrossEntropyLogitsF64 vTarget vTargetCount vLogits vLogitsCount out0 = boundary $ do + vTargetValue <- peekArray (fromIntegral vTargetCount) (castPtr vTarget :: Ptr Double) + vLogitsValue <- peekArray (fromIntegral vLogitsCount) (castPtr vLogits :: Ptr Double) + checked (DeepLearningCore.categoricalCrossEntropyLogits + vTargetValue + vLogitsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_regularization_f64" ffiDeeplearningCoreRegularizationF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreRegularizationF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreRegularizationF64 vL1 vL2 vWeights vWeightsCount out0 = boundary $ do + vWeightsValue <- peekArray (fromIntegral vWeightsCount) (castPtr vWeights :: Ptr Double) + checked (DeepLearningCore.regularization + (coerce vL1 :: Double) + (coerce vL2 :: Double) + vWeightsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_contrastive_loss_f64" ffiDeeplearningCoreContrastiveLossF64 :: + CDouble -> + CInt -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreContrastiveLossF64 :: + CDouble -> + CInt -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreContrastiveLossF64 vMargin vSimilar vA vACount vB vBCount out0 = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (DeepLearningCore.contrastiveLoss + (coerce vMargin :: Double) + (vSimilar /= 0) + vAValue + vBValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_triplet_loss_f64" ffiDeeplearningCoreTripletLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreTripletLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreTripletLossF64 vMargin vAnchor vAnchorCount vPositive vPositiveCount vNegative vNegativeCount out0 = boundary $ do + vAnchorValue <- peekArray (fromIntegral vAnchorCount) (castPtr vAnchor :: Ptr Double) + vPositiveValue <- peekArray (fromIntegral vPositiveCount) (castPtr vPositive :: Ptr Double) + vNegativeValue <- peekArray (fromIntegral vNegativeCount) (castPtr vNegative :: Ptr Double) + checked (DeepLearningCore.tripletLoss + (coerce vMargin :: Double) + vAnchorValue + vPositiveValue + vNegativeValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_focal_loss_f64" ffiDeeplearningCoreFocalLossF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreFocalLossF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreFocalLossF64 vAlpha vGamma vTarget vTargetCount vPrediction vPredictionCount out0 = boundary $ do + vTargetValue <- peekArray (fromIntegral vTargetCount) (castPtr vTarget :: Ptr Double) + vPredictionValue <- peekArray (fromIntegral vPredictionCount) (castPtr vPrediction :: Ptr Double) + checked (DeepLearningCore.focalLoss + (coerce vAlpha :: Double) + (coerce vGamma :: Double) + vTargetValue + vPredictionValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_dice_loss_f64" ffiDeeplearningCoreDiceLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreDiceLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreDiceLossF64 vSmooth vTarget vTargetCount vPrediction vPredictionCount out0 = boundary $ do + vTargetValue <- peekArray (fromIntegral vTargetCount) (castPtr vTarget :: Ptr Double) + vPredictionValue <- peekArray (fromIntegral vPredictionCount) (castPtr vPrediction :: Ptr Double) + checked (DeepLearningCore.diceLoss + (coerce vSmooth :: Double) + vTargetValue + vPredictionValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_core_iou_loss_f64" ffiDeeplearningCoreIouLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreIouLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningCoreIouLossF64 vSmooth vTarget vTargetCount vPrediction vPredictionCount out0 = boundary $ do + vTargetValue <- peekArray (fromIntegral vTargetCount) (castPtr vTarget :: Ptr Double) + vPredictionValue <- peekArray (fromIntegral vPredictionCount) (castPtr vPrediction :: Ptr Double) + checked (DeepLearningCore.iouLoss + (coerce vSmooth :: Double) + vTargetValue + vPredictionValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_metrics_perplexity_f64" ffiDeeplearningMetricsPerplexityF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningMetricsPerplexityF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningMetricsPerplexityF64 vLogs vLogsCount out0 = boundary $ do + vLogsValue <- peekArray (fromIntegral vLogsCount) (castPtr vLogs :: Ptr Double) + checked (DeepLearningMetrics.perplexity + vLogsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_metrics_margin_ranking_loss_f64" ffiDeeplearningMetricsMarginRankingLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningMetricsMarginRankingLossF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningMetricsMarginRankingLossF64 vMargin vLabels vLabelsCount vLeft vLeftCount vRight vRightCount out0 = boundary $ do + vLabelsValue <- peekArray (fromIntegral vLabelsCount) (castPtr vLabels :: Ptr Double) + vLeftValue <- peekArray (fromIntegral vLeftCount) (castPtr vLeft :: Ptr Double) + vRightValue <- peekArray (fromIntegral vRightCount) (castPtr vRight :: Ptr Double) + checked (DeepLearningMetrics.marginRankingLoss + (coerce vMargin :: Double) + vLabelsValue + vLeftValue + vRightValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_precision_gradient_norm_f64" ffiDeeplearningPrecisionGradientNormF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningPrecisionGradientNormF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiDeeplearningPrecisionGradientNormF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (DeepLearningPrecision.gradientNorm + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_deeplearning_precision_clip_gradients_f64" ffiDeeplearningPrecisionClipGradientsF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningPrecisionClipGradientsF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDeeplearningPrecisionClipGradientsF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (DeepLearningPrecision.clipGradients (coerce vArgument1 :: Double) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_union_f32" ffiDiscreteSetUnionF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetUnionF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetUnionF32 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Float) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Float) + checked (Right (Discrete.setUnion vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_union_f64" ffiDiscreteSetUnionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetUnionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetUnionF64 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (Right (Discrete.setUnion vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_intersection_f32" ffiDiscreteSetIntersectionF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetIntersectionF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetIntersectionF32 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Float) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Float) + checked (Right (Discrete.setIntersection vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_intersection_f64" ffiDiscreteSetIntersectionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetIntersectionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetIntersectionF64 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (Right (Discrete.setIntersection vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_difference_f32" ffiDiscreteSetDifferenceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetDifferenceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetDifferenceF32 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Float) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Float) + checked (Right (Discrete.setDifference vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_set_difference_f64" ffiDiscreteSetDifferenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetDifferenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSetDifferenceF64 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (Right (Discrete.setDifference vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_symmetric_difference_f32" ffiDiscreteSymmetricDifferenceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSymmetricDifferenceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr (Ptr CFloat) -> + Ptr CSize -> + IO CInt +ffiDiscreteSymmetricDifferenceF32 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Float) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Float) + checked (Right (Discrete.symmetricDifference vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Float]) + bracketOnError (newArray (map (coerce :: Float -> CFloat) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_discrete_symmetric_difference_f64" ffiDiscreteSymmetricDifferenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSymmetricDifferenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiDiscreteSymmetricDifferenceF64 vA vACount vB vBCount outData outCount = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (Right (Discrete.symmetricDifference vAValue vBValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_frequencies_f64" ffiFourierFrequenciesF64 :: + CPtrdiff -> + CDouble -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierFrequenciesF64 :: + CPtrdiff -> + CDouble -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierFrequenciesF64 vN vSpacing outData outCount = boundary $ do + checked (Fourier.frequencies (fromIntegral vN) (coerce vSpacing :: Double)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_fft_shift_f64" ffiFourierFftShiftF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierFftShiftF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierFftShiftF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Right (Fourier.fftShift vXsValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_ifft_shift_f64" ffiFourierIfftShiftF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierIfftShiftF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierIfftShiftF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Right (Fourier.ifftShift vXsValue)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_hartley_f64" ffiFourierHartleyF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierHartleyF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierHartleyF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Fourier.hartley vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_periodogram_f64" ffiFourierPeriodogramF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierPeriodogramF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierPeriodogramF64 vRate vWindow vWindowCount vXs vXsCount outData outCount = boundary $ do + vWindowValue <- peekArray (fromIntegral vWindowCount) (castPtr vWindow :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Fourier.periodogram (coerce vRate :: Double) vWindowValue vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_welch_f64" ffiFourierWelchF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierWelchF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierWelchF64 vRate vWindow vWindowCount vHop vXs vXsCount outData outCount = boundary $ do + vWindowValue <- peekArray (fromIntegral vWindowCount) (castPtr vWindow :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Fourier.welch (coerce vRate :: Double) vWindowValue (fromIntegral vHop) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_cepstrum_f64" ffiFourierCepstrumF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierCepstrumF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierCepstrumF64 vFloorValue vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Fourier.cepstrum (coerce vFloorValue :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_fourier_hilbert_f64" ffiFourierHilbertF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierHilbertF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiFourierHilbertF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Fourier.hilbert vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_geometry_primitives_hamming_distance_f32" ffiGeometryPrimitivesHammingDistanceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiGeometryPrimitivesHammingDistanceF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiGeometryPrimitivesHammingDistanceF32 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Float) + checked (GeometryPrimitives.hammingDistance + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_geometry_primitives_hamming_distance_f64" ffiGeometryPrimitivesHammingDistanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiGeometryPrimitivesHammingDistanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiGeometryPrimitivesHammingDistanceF64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (GeometryPrimitives.hammingDistance + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_geometry_primitives_jaccard_distance_f64" ffiGeometryPrimitivesJaccardDistanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiGeometryPrimitivesJaccardDistanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiGeometryPrimitivesJaccardDistanceF64 vArgument1 vArgument1Count vArgument2 vArgument2Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (GeometryPrimitives.jaccardDistance + vArgument1Value + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_graph_core_finite_f64" ffiGraphCoreFiniteF64 :: + CDouble -> + Ptr CInt -> + IO CInt +ffiGraphCoreFiniteF64 :: + CDouble -> + Ptr CInt -> + IO CInt +ffiGraphCoreFiniteF64 vX out0 = boundary $ do + checked (Right (GraphCore.finite + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_image_color_srgb_to_linear_f64" ffiImageColorSrgbToLinearF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiImageColorSrgbToLinearF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiImageColorSrgbToLinearF64 vX out0 = boundary $ do + checked (ImageColor.srgbToLinear + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_image_color_linear_to_srgb_f64" ffiImageColorLinearToSrgbF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiImageColorLinearToSrgbF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiImageColorLinearToSrgbF64 vX out0 = boundary $ do + checked (ImageColor.linearToSrgb + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_interpolation_evaluate_chebyshev_f64" ffiInterpolationEvaluateChebyshevF64 :: + Ptr CDouble -> + CSize -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiInterpolationEvaluateChebyshevF64 :: + Ptr CDouble -> + CSize -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiInterpolationEvaluateChebyshevF64 vCs vCsCount vA vB vX out0 = boundary $ do + vCsValue <- peekArray (fromIntegral vCsCount) (castPtr vCs :: Ptr Double) + checked (Interpolation.evaluateChebyshev + vCsValue + (coerce vA :: Double) + (coerce vB :: Double) + (coerce vX :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_next_after_f32" ffiNumericNextAfterF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiNumericNextAfterF32 :: + CFloat -> + CFloat -> + Ptr CFloat -> + IO CInt +ffiNumericNextAfterF32 vArgument1 vArgument2 out0 = boundary $ do + checked (Right (Numeric.nextAfter + (coerce vArgument1 :: Float) + (coerce vArgument2 :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_next_after_f64" ffiNumericNextAfterF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiNumericNextAfterF64 :: + CDouble -> + CDouble -> + Ptr CDouble -> + IO CInt +ffiNumericNextAfterF64 vArgument1 vArgument2 out0 = boundary $ do + checked (Right (Numeric.nextAfter + (coerce vArgument1 :: Double) + (coerce vArgument2 :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_ldexp_f32" ffiNumericLdexpF32 :: + CFloat -> + CPtrdiff -> + Ptr CFloat -> + IO CInt +ffiNumericLdexpF32 :: + CFloat -> + CPtrdiff -> + Ptr CFloat -> + IO CInt +ffiNumericLdexpF32 vArgument1 vArgument2 out0 = boundary $ do + checked (Right (Numeric.ldexp + (coerce vArgument1 :: Float) + (fromIntegral vArgument2))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_ldexp_f64" ffiNumericLdexpF64 :: + CDouble -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiNumericLdexpF64 :: + CDouble -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiNumericLdexpF64 vArgument1 vArgument2 out0 = boundary $ do + checked (Right (Numeric.ldexp + (coerce vArgument1 :: Double) + (fromIntegral vArgument2))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_ulp_distance_f64" ffiNumericUlpDistanceF64 :: + CDouble -> + CDouble -> + Ptr CString -> + IO CInt +ffiNumericUlpDistanceF64 :: + CDouble -> + CDouble -> + Ptr CString -> + IO CInt +ffiNumericUlpDistanceF64 vA vB out0 = boundary $ do + checked (Numeric.ulpDistance + (coerce vA :: Double) + (coerce vB :: Double)) $ \value -> do + writeStrings [show (value)] $ \textPointers -> do + poke out0 (textPointers !! 0) + +foreign export ccall "hm_numeric_numeric_within_u_l_ps_f64" ffiNumericWithinULPsF64 :: + CString -> + CDouble -> + CDouble -> + Ptr CInt -> + IO CInt +ffiNumericWithinULPsF64 :: + CString -> + CDouble -> + CDouble -> + Ptr CInt -> + IO CInt +ffiNumericWithinULPsF64 vN vA vB out0 = boundary $ do + vNValue <- readInteger vN + checked (Right (Numeric.withinULPs + vNValue + (coerce vA :: Double) + (coerce vB :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (if strict0 then 1 else 0) + +foreign export ccall "hm_numeric_numeric_kahan_sum_f32" ffiNumericKahanSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericKahanSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericKahanSumF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Numeric.kahanSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_kahan_sum_f64" ffiNumericKahanSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericKahanSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericKahanSumF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Numeric.kahanSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_neumaier_sum_f32" ffiNumericNeumaierSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericNeumaierSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericNeumaierSumF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Numeric.neumaierSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_neumaier_sum_f64" ffiNumericNeumaierSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericNeumaierSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericNeumaierSumF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Numeric.neumaierSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_pairwise_sum_f32" ffiNumericPairwiseSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericPairwiseSumF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericPairwiseSumF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Right (Numeric.pairwiseSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_pairwise_sum_f64" ffiNumericPairwiseSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericPairwiseSumF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericPairwiseSumF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Right (Numeric.pairwiseSum + vArgument1Value)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_logsumexp_f32" ffiNumericLogsumexpF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericLogsumexpF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericLogsumexpF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Numeric.logsumexp + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_logsumexp_f64" ffiNumericLogsumexpF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericLogsumexpF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericLogsumexpF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Numeric.logsumexp + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_numeric_sum_error_bound_f32" ffiNumericSumErrorBoundF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericSumErrorBoundF32 :: + Ptr CFloat -> + CSize -> + Ptr CFloat -> + IO CInt +ffiNumericSumErrorBoundF32 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Float) + checked (Numeric.sumErrorBound + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_numeric_sum_error_bound_f64" ffiNumericSumErrorBoundF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericSumErrorBoundF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiNumericSumErrorBoundF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (Numeric.sumErrorBound + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_optimization_common_dot_f64" ffiOptimizationCommonDotF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiOptimizationCommonDotF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiOptimizationCommonDotF64 vA vACount vB vBCount out0 = boundary $ do + vAValue <- peekArray (fromIntegral vACount) (castPtr vA :: Ptr Double) + vBValue <- peekArray (fromIntegral vBCount) (castPtr vB :: Ptr Double) + checked (Right (OptimizationCommon.dot + vAValue + vBValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_optimization_common_norm_f64" ffiOptimizationCommonNormF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiOptimizationCommonNormF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiOptimizationCommonNormF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Right (OptimizationCommon.norm + vXsValue)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_optimization_common_add_f64" ffiOptimizationCommonAddF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonAddF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonAddF64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (OptimizationCommon.add vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_optimization_common_sub_f64" ffiOptimizationCommonSubF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonSubF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonSubF64 vArgument1 vArgument1Count vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (OptimizationCommon.sub vArgument1Value vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_optimization_common_scale_f64" ffiOptimizationCommonScaleF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonScaleF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiOptimizationCommonScaleF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Right (OptimizationCommon.scale (coerce vArgument1 :: Double) vArgument2Value)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_random_importance_f64" ffiRandomImportanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiRandomImportanceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiRandomImportanceF64 vValues vValuesCount vWeights vWeightsCount out0 = boundary $ do + vValuesValue <- peekArray (fromIntegral vValuesCount) (castPtr vValues :: Ptr Double) + vWeightsValue <- peekArray (fromIntegral vWeightsCount) (castPtr vWeights :: Ptr Double) + checked (Random.importance + vValuesValue + vWeightsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_random_halton_f64" ffiRandomHaltonF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomHaltonF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomHaltonF64 vDimension vIndex outData outCount = boundary $ do + checked (Random.halton (fromIntegral vDimension) (fromIntegral vIndex)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_random_sobol_f64" ffiRandomSobolF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomSobolF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomSobolF64 vDimension vIndex outData outCount = boundary $ do + checked (Random.sobol (fromIntegral vDimension) (fromIntegral vIndex)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_random_faure_f64" ffiRandomFaureF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomFaureF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiRandomFaureF64 vD vIx outData outCount = boundary $ do + checked (Random.faure (fromIntegral vD) (fromIntegral vIx)) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_convolution_f64" ffiSignalConvolutionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalConvolutionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalConvolutionF64 vXs vXsCount vYs vYsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (Signal.convolution vXsValue vYsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_circular_convolution_f64" ffiSignalCircularConvolutionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalCircularConvolutionF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalCircularConvolutionF64 vX vXCount vY vYCount outData outCount = boundary $ do + vXValue <- peekArray (fromIntegral vXCount) (castPtr vX :: Ptr Double) + vYValue <- peekArray (fromIntegral vYCount) (castPtr vY :: Ptr Double) + checked (Signal.circularConvolution vXValue vYValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_correlation_f64" ffiSignalCorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalCorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalCorrelationF64 vX vXCount vY vYCount outData outCount = boundary $ do + vXValue <- peekArray (fromIntegral vXCount) (castPtr vX :: Ptr Double) + vYValue <- peekArray (fromIntegral vYCount) (castPtr vY :: Ptr Double) + checked (Signal.correlation vXValue vYValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_autocorrelation_f64" ffiSignalAutocorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalAutocorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalAutocorrelationF64 vX vXCount outData outCount = boundary $ do + vXValue <- peekArray (fromIntegral vXCount) (castPtr vX :: Ptr Double) + checked (Signal.autocorrelation vXValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_overlap_add_f64" ffiSignalOverlapAddF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalOverlapAddF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalOverlapAddF64 vBlock vKernel vKernelCount vXs vXsCount outData outCount = boundary $ do + vKernelValue <- peekArray (fromIntegral vKernelCount) (castPtr vKernel :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.overlapAdd (fromIntegral vBlock) vKernelValue vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_overlap_save_f64" ffiSignalOverlapSaveF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalOverlapSaveF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalOverlapSaveF64 vFftLength vKernel vKernelCount vXs vXsCount outData outCount = boundary $ do + vKernelValue <- peekArray (fromIntegral vKernelCount) (castPtr vKernel :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.overlapSave (fromIntegral vFftLength) vKernelValue vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_moving_average_f64" ffiSignalMovingAverageF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalMovingAverageF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalMovingAverageF64 vCount vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.movingAverage (fromIntegral vCount) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_median_filter_f64" ffiSignalMedianFilterF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalMedianFilterF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalMedianFilterF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Signal.medianFilter (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_gaussian_filter_f64" ffiSignalGaussianFilterF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalGaussianFilterF64 :: + CPtrdiff -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalGaussianFilterF64 vWidth vSigma vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.gaussianFilter (fromIntegral vWidth) (coerce vSigma :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_savitzky_golay_f64" ffiSignalSavitzkyGolayF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalSavitzkyGolayF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalSavitzkyGolayF64 vWidth vDegree vDerivative vSpacing vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.savitzkyGolay (fromIntegral vWidth) (fromIntegral vDegree) (fromIntegral vDerivative) (coerce vSpacing :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_downsample_f64" ffiSignalDownsampleF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalDownsampleF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalDownsampleF64 vFactor vOffset vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.downsample (fromIntegral vFactor) (fromIntegral vOffset) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_upsample_f64" ffiSignalUpsampleF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalUpsampleF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalUpsampleF64 vFactor vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.upsample (fromIntegral vFactor) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_resample_polyphase_f64" ffiSignalResamplePolyphaseF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalResamplePolyphaseF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalResamplePolyphaseF64 vUp vDown vKernel vKernelCount vXs vXsCount outData outCount = boundary $ do + vKernelValue <- peekArray (fromIntegral vKernelCount) (castPtr vKernel :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.resamplePolyphase (fromIntegral vUp) (fromIntegral vDown) vKernelValue vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_resample_f64" ffiSignalResampleF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalResampleF64 :: + CPtrdiff -> + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalResampleF64 vUp vDown vTaps vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.resample (fromIntegral vUp) (fromIntegral vDown) (fromIntegral vTaps) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_anti_alias_f64" ffiSignalAntiAliasF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalAntiAliasF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalAntiAliasF64 vFactor vTaps vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.antiAlias (fromIntegral vFactor) (fromIntegral vTaps) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_zero_crossings_f64" ffiSignalZeroCrossingsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalZeroCrossingsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalZeroCrossingsF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.zeroCrossings vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_envelope_f64" ffiSignalEnvelopeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalEnvelopeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalEnvelopeF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.envelope vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_unwrap_phase_f64" ffiSignalUnwrapPhaseF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalUnwrapPhaseF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalUnwrapPhaseF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.unwrapPhase vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_detrend_f64" ffiSignalDetrendF64 :: + CInt -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalDetrendF64 :: + CInt -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalDetrendF64 vLinear vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.detrend (vLinear /= 0) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_normalize_f64" ffiSignalNormalizeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalNormalizeF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalNormalizeF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.normalize vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_smooth_f64" ffiSignalSmoothF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalSmoothF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiSignalSmoothF64 vArgument1 vArgument2 vArgument2Count outData outCount = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (Signal.smooth (fromIntegral vArgument1) vArgument2Value) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_signal_noise_estimate_f64" ffiSignalNoiseEstimateF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalNoiseEstimateF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalNoiseEstimateF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.noiseEstimate + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_signal_signal_to_noise_f64" ffiSignalSignalToNoiseF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalSignalToNoiseF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalSignalToNoiseF64 vSignal vSignalCount vNoise vNoiseCount out0 = boundary $ do + vSignalValue <- peekArray (fromIntegral vSignalCount) (castPtr vSignal :: Ptr Double) + vNoiseValue <- peekArray (fromIntegral vNoiseCount) (castPtr vNoise :: Ptr Double) + checked (Signal.signalToNoise + vSignalValue + vNoiseValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_signal_rms_f64" ffiSignalRmsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalRmsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiSignalRmsF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (Signal.rms + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_arithmetic_mean_f64" ffiStatisticsAdvancedArithmeticMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedArithmeticMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedArithmeticMeanF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.arithmeticMean + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_weighted_mean_f64" ffiStatisticsAdvancedWeightedMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedWeightedMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedWeightedMeanF64 vXs vXsCount vWs vWsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vWsValue <- peekArray (fromIntegral vWsCount) (castPtr vWs :: Ptr Double) + checked (StatisticsAdvanced.weightedMean + vXsValue + vWsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_geometric_mean_f64" ffiStatisticsAdvancedGeometricMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedGeometricMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedGeometricMeanF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.geometricMean + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_harmonic_mean_f64" ffiStatisticsAdvancedHarmonicMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedHarmonicMeanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedHarmonicMeanF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.harmonicMean + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_rms_f64" ffiStatisticsAdvancedRmsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedRmsF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedRmsF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.rms + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_trimmed_mean_f64" ffiStatisticsAdvancedTrimmedMeanF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedTrimmedMeanF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedTrimmedMeanF64 vFraction vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.trimmedMean + (coerce vFraction :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_winsorized_mean_f64" ffiStatisticsAdvancedWinsorizedMeanF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedWinsorizedMeanF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedWinsorizedMeanF64 vFraction vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.winsorizedMean + (coerce vFraction :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_quantile_f64" ffiStatisticsAdvancedQuantileF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedQuantileF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedQuantileF64 vP vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.quantile + (coerce vP :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_median_f64" ffiStatisticsAdvancedMedianF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedMedianF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedMedianF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (StatisticsAdvanced.median + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_percentile_f64" ffiStatisticsAdvancedPercentileF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPercentileF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPercentileF64 vArgument1 vArgument2 vArgument2Count out0 = boundary $ do + vArgument2Value <- peekArray (fromIntegral vArgument2Count) (castPtr vArgument2 :: Ptr Double) + checked (StatisticsAdvanced.percentile + (coerce vArgument1 :: Double) + vArgument2Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_modes_f64" ffiStatisticsAdvancedModesF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedModesF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedModesF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.modes vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_interquartile_range_f64" ffiStatisticsAdvancedInterquartileRangeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedInterquartileRangeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedInterquartileRangeF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.interquartileRange + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_median_absolute_deviation_f64" ffiStatisticsAdvancedMedianAbsoluteDeviationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedMedianAbsoluteDeviationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedMedianAbsoluteDeviationF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.medianAbsoluteDeviation + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_data_range_f64" ffiStatisticsAdvancedDataRangeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedDataRangeF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedDataRangeF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.dataRange + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_central_moment_f64" ffiStatisticsAdvancedCentralMomentF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCentralMomentF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCentralMomentF64 vK vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.centralMoment + (fromIntegral vK) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_population_variance_f64" ffiStatisticsAdvancedPopulationVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPopulationVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPopulationVarianceF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (StatisticsAdvanced.populationVariance + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_sample_variance_f64" ffiStatisticsAdvancedSampleVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSampleVarianceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSampleVarianceF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.sampleVariance + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_population_s_d_f64" ffiStatisticsAdvancedPopulationSDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPopulationSDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedPopulationSDF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (StatisticsAdvanced.populationSD + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_sample_s_d_f64" ffiStatisticsAdvancedSampleSDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSampleSDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSampleSDF64 vArgument1 vArgument1Count out0 = boundary $ do + vArgument1Value <- peekArray (fromIntegral vArgument1Count) (castPtr vArgument1 :: Ptr Double) + checked (StatisticsAdvanced.sampleSD + vArgument1Value) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_coefficient_of_variation_f64" ffiStatisticsAdvancedCoefficientOfVariationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCoefficientOfVariationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCoefficientOfVariationF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.coefficientOfVariation + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_skewness_f64" ffiStatisticsAdvancedSkewnessF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSkewnessF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSkewnessF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.skewness + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_kurtosis_f64" ffiStatisticsAdvancedKurtosisF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKurtosisF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKurtosisF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.kurtosis + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_covariance_f64" ffiStatisticsAdvancedCovarianceF64 :: + CInt -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCovarianceF64 :: + CInt -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCovarianceF64 vSampleCorrection vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.covariance + (vSampleCorrection /= 0) + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_correlation_f64" ffiStatisticsAdvancedCorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCorrelationF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCorrelationF64 vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.correlation + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_spearman_f64" ffiStatisticsAdvancedSpearmanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSpearmanF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedSpearmanF64 vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.spearman + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_kendall_f64" ffiStatisticsAdvancedKendallF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKendallF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKendallF64 vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.kendall + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_autocorrelation_f64" ffiStatisticsAdvancedAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedAutocorrelationF64 vLag vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.autocorrelation + (fromIntegral vLag) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_cross_correlation_f64" ffiStatisticsAdvancedCrossCorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCrossCorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCrossCorrelationF64 vLag vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.crossCorrelation + (fromIntegral vLag) + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_moving_average_f64" ffiStatisticsAdvancedMovingAverageF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedMovingAverageF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedMovingAverageF64 vWindow vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.movingAverage (fromIntegral vWindow) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_moving_variance_f64" ffiStatisticsAdvancedMovingVarianceF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedMovingVarianceF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedMovingVarianceF64 vWindow vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.movingVariance (fromIntegral vWindow) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_exponential_moving_average_f64" ffiStatisticsAdvancedExponentialMovingAverageF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedExponentialMovingAverageF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedExponentialMovingAverageF64 vAlpha vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.exponentialMovingAverage (coerce vAlpha :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_entropy_f64" ffiStatisticsAdvancedEntropyF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedEntropyF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedEntropyF64 vPs vPsCount out0 = boundary $ do + vPsValue <- peekArray (fromIntegral vPsCount) (castPtr vPs :: Ptr Double) + checked (StatisticsAdvanced.entropy + vPsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_kl_divergence_f64" ffiStatisticsAdvancedKlDivergenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKlDivergenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedKlDivergenceF64 vP vPCount vQ vQCount out0 = boundary $ do + vPValue <- peekArray (fromIntegral vPCount) (castPtr vP :: Ptr Double) + vQValue <- peekArray (fromIntegral vQCount) (castPtr vQ :: Ptr Double) + checked (StatisticsAdvanced.klDivergence + vPValue + vQValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_js_divergence_f64" ffiStatisticsAdvancedJsDivergenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedJsDivergenceF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedJsDivergenceF64 vP vPCount vQ vQCount out0 = boundary $ do + vPValue <- peekArray (fromIntegral vPCount) (castPtr vP :: Ptr Double) + vQValue <- peekArray (fromIntegral vQCount) (castPtr vQ :: Ptr Double) + checked (StatisticsAdvanced.jsDivergence + vPValue + vQValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_z_scores_f64" ffiStatisticsAdvancedZScoresF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedZScoresF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedZScoresF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.zScores vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_standard_error_f64" ffiStatisticsAdvancedStandardErrorF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedStandardErrorF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedStandardErrorF64 vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.standardError + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_confidence_interval_f64" ffiStatisticsAdvancedConfidenceIntervalF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedConfidenceIntervalF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedConfidenceIntervalF64 vLevel vXs vXsCount out0 out1 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.confidenceInterval + (coerce vLevel :: Double) + vXsValue) $ \(first, second) -> do + strict0 <- evaluate (first) + strict1 <- evaluate (second) + poke out0 (coerce strict0 :: CDouble) + poke out1 (coerce strict1 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_bonferroni_f64" ffiStatisticsAdvancedBonferroniF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedBonferroniF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedBonferroniF64 vPs vPsCount outData outCount = boundary $ do + vPsValue <- peekArray (fromIntegral vPsCount) (castPtr vPs :: Ptr Double) + checked (StatisticsAdvanced.bonferroni vPsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_benjamini_hochberg_f64" ffiStatisticsAdvancedBenjaminiHochbergF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedBenjaminiHochbergF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedBenjaminiHochbergF64 vPs vPsCount outData outCount = boundary $ do + vPsValue <- peekArray (fromIntegral vPsCount) (castPtr vPs :: Ptr Double) + checked (StatisticsAdvanced.benjaminiHochberg vPsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_cohens_d_f64" ffiStatisticsAdvancedCohensDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCohensDF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedCohensDF64 vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (StatisticsAdvanced.cohensD + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_normal_test_power_f64" ffiStatisticsAdvancedNormalTestPowerF64 :: + CDouble -> + CDouble -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedNormalTestPowerF64 :: + CDouble -> + CDouble -> + CPtrdiff -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedNormalTestPowerF64 vAlpha vStandardizedEffect vN out0 = boundary $ do + checked (StatisticsAdvanced.normalTestPower + (coerce vAlpha :: Double) + (coerce vStandardizedEffect :: Double) + (fromIntegral vN)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_statistics_advanced_normal_sample_size_f64" ffiStatisticsAdvancedNormalSampleSizeF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CPtrdiff -> + IO CInt +ffiStatisticsAdvancedNormalSampleSizeF64 :: + CDouble -> + CDouble -> + CDouble -> + Ptr CPtrdiff -> + IO CInt +ffiStatisticsAdvancedNormalSampleSizeF64 vAlpha vPower vEffect out0 = boundary $ do + checked (StatisticsAdvanced.normalSampleSize + (coerce vAlpha :: Double) + (coerce vPower :: Double) + (coerce vEffect :: Double)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_statistics_advanced_tukey_outliers_f64" ffiStatisticsAdvancedTukeyOutliersF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedTukeyOutliersF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiStatisticsAdvancedTukeyOutliersF64 vMultiplier vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.tukeyOutliers (coerce vMultiplier :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_statistics_advanced_huber_location_f64" ffiStatisticsAdvancedHuberLocationF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedHuberLocationF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiStatisticsAdvancedHuberLocationF64 vTuning vXs vXsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (StatisticsAdvanced.huberLocation + (coerce vTuning :: Double) + vXsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_tensor_shape_size" ffiTensorShapeSize :: + Ptr CPtrdiff -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiTensorShapeSize :: + Ptr CPtrdiff -> + CSize -> + Ptr CPtrdiff -> + IO CInt +ffiTensorShapeSize vDims vDimsCount out0 = boundary $ do + vDimsRaw <- peekArray (fromIntegral vDimsCount) vDims + let vDimsValue = map fromIntegral vDimsRaw + checked (Tensor.shapeSize + vDimsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (fromIntegral strict0) + +foreign export ccall "hm_numeric_tensor_infer_broadcast" ffiTensorInferBroadcast :: + Ptr CPtrdiff -> + CSize -> + Ptr CPtrdiff -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTensorInferBroadcast :: + Ptr CPtrdiff -> + CSize -> + Ptr CPtrdiff -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTensorInferBroadcast vAs vAsCount vBs vBsCount outData outCount = boundary $ do + vAsRaw <- peekArray (fromIntegral vAsCount) vAs + let vAsValue = map fromIntegral vAsRaw + vBsRaw <- peekArray (fromIntegral vBsCount) vBs + let vBsValue = map fromIntegral vBsRaw + checked (Tensor.inferBroadcast vAsValue vBsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_exponential_average_f64" ffiTimeseriesCoreExponentialAverageF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreExponentialAverageF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreExponentialAverageF64 vAlpha vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.exponentialAverage (coerce vAlpha :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_weighted_average_f64" ffiTimeseriesCoreWeightedAverageF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreWeightedAverageF64 :: + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreWeightedAverageF64 vWs vWsCount vXs vXsCount outData outCount = boundary $ do + vWsValue <- peekArray (fromIntegral vWsCount) (castPtr vWs :: Ptr Double) + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.weightedAverage vWsValue vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_cumulative_returns_f64" ffiTimeseriesCoreCumulativeReturnsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreCumulativeReturnsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreCumulativeReturnsF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.cumulativeReturns vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_logarithmic_returns_f64" ffiTimeseriesCoreLogarithmicReturnsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreLogarithmicReturnsF64 :: + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreLogarithmicReturnsF64 vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.logarithmicReturns vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_difference_f64" ffiTimeseriesCoreDifferenceF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreDifferenceF64 :: + CPtrdiff -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreDifferenceF64 vOrder vLag vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.difference (fromIntegral vOrder) (fromIntegral vLag) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_autocorrelation_f64" ffiTimeseriesCoreAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCoreAutocorrelationF64 vLags vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.autocorrelation (fromIntegral vLags) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_core_cross_correlation_f64" ffiTimeseriesCoreCrossCorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiTimeseriesCoreCrossCorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + CSize -> + Ptr CDouble -> + IO CInt +ffiTimeseriesCoreCrossCorrelationF64 vLag vXs vXsCount vYs vYsCount out0 = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + vYsValue <- peekArray (fromIntegral vYsCount) (castPtr vYs :: Ptr Double) + checked (TimeSeriesCore.crossCorrelation + (fromIntegral vLag) + vXsValue + vYsValue) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_timeseries_core_partial_autocorrelation_f64" ffiTimeseriesCorePartialAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCorePartialAutocorrelationF64 :: + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CDouble) -> + Ptr CSize -> + IO CInt +ffiTimeseriesCorePartialAutocorrelationF64 vOrder vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesCore.partialAutocorrelation (fromIntegral vOrder) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Double]) + bracketOnError (newArray (map (coerce :: Double -> CDouble) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_diagnostics_change_points_f64" ffiTimeseriesDiagnosticsChangePointsF64 :: + CDouble -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsChangePointsF64 :: + CDouble -> + CPtrdiff -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsChangePointsF64 vPenalty vMinSegment vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesDiagnostics.changePoints (coerce vPenalty :: Double) (fromIntegral vMinSegment) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_diagnostics_cusum_f64" ffiTimeseriesDiagnosticsCusumF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsCusumF64 :: + CDouble -> + CDouble -> + CDouble -> + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsCusumF64 vMean vSd vDrift vThreshold vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesDiagnostics.cusum (coerce vMean :: Double) (coerce vSd :: Double) (coerce vDrift :: Double) (coerce vThreshold :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_timeseries_diagnostics_anomalies_f64" ffiTimeseriesDiagnosticsAnomaliesF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsAnomaliesF64 :: + CDouble -> + Ptr CDouble -> + CSize -> + Ptr (Ptr CPtrdiff) -> + Ptr CSize -> + IO CInt +ffiTimeseriesDiagnosticsAnomaliesF64 vThreshold vXs vXsCount outData outCount = boundary $ do + vXsValue <- peekArray (fromIntegral vXsCount) (castPtr vXs :: Ptr Double) + checked (TimeSeriesDiagnostics.anomalies (coerce vThreshold :: Double) vXsValue) $ \value -> do + strict <- mapM evaluate (value :: [Int]) + bracketOnError (newArray (map (fromIntegral :: Int -> CPtrdiff) strict)) free $ \pointer -> do + poke outData pointer + poke outCount (fromIntegral (length strict)) + +foreign export ccall "hm_numeric_units_radians_to_degrees_f32" ffiUnitsRadiansToDegreesF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsRadiansToDegreesF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsRadiansToDegreesF32 vX out0 = boundary $ do + checked (Right (Units.radiansToDegrees + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_units_radians_to_degrees_f64" ffiUnitsRadiansToDegreesF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsRadiansToDegreesF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsRadiansToDegreesF64 vX out0 = boundary $ do + checked (Right (Units.radiansToDegrees + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_units_degrees_to_radians_f32" ffiUnitsDegreesToRadiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsDegreesToRadiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsDegreesToRadiansF32 vX out0 = boundary $ do + checked (Right (Units.degreesToRadians + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_units_degrees_to_radians_f64" ffiUnitsDegreesToRadiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsDegreesToRadiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsDegreesToRadiansF64 vX out0 = boundary $ do + checked (Right (Units.degreesToRadians + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_units_radians_to_gradians_f32" ffiUnitsRadiansToGradiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsRadiansToGradiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsRadiansToGradiansF32 vX out0 = boundary $ do + checked (Right (Units.radiansToGradians + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_units_radians_to_gradians_f64" ffiUnitsRadiansToGradiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsRadiansToGradiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsRadiansToGradiansF64 vX out0 = boundary $ do + checked (Right (Units.radiansToGradians + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_units_gradians_to_radians_f32" ffiUnitsGradiansToRadiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsGradiansToRadiansF32 :: + CFloat -> + Ptr CFloat -> + IO CInt +ffiUnitsGradiansToRadiansF32 vX out0 = boundary $ do + checked (Right (Units.gradiansToRadians + (coerce vX :: Float))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CFloat) + +foreign export ccall "hm_numeric_units_gradians_to_radians_f64" ffiUnitsGradiansToRadiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsGradiansToRadiansF64 :: + CDouble -> + Ptr CDouble -> + IO CInt +ffiUnitsGradiansToRadiansF64 vX out0 = boundary $ do + checked (Right (Units.gradiansToRadians + (coerce vX :: Double))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: CDouble) + +foreign export ccall "hm_numeric_scalar_saturating_add_i8" ffiScalarSaturatingAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingAddI8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_saturating_add_i16" ffiScalarSaturatingAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingAddI16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_saturating_add_i32" ffiScalarSaturatingAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingAddI32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_saturating_add_i64" ffiScalarSaturatingAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingAddI64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_saturating_add_u8" ffiScalarSaturatingAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingAddU8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_saturating_add_u16" ffiScalarSaturatingAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingAddU16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_saturating_add_u32" ffiScalarSaturatingAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingAddU32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_saturating_add_u64" ffiScalarSaturatingAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingAddU64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_saturating_add_int" ffiScalarSaturatingAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingAddInt vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_saturating_add_word" ffiScalarSaturatingAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingAddWord vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingAdd + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_i8" ffiScalarSaturatingSubtractI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingSubtractI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingSubtractI8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_i16" ffiScalarSaturatingSubtractI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingSubtractI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingSubtractI16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_i32" ffiScalarSaturatingSubtractI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingSubtractI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingSubtractI32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_i64" ffiScalarSaturatingSubtractI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingSubtractI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingSubtractI64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_u8" ffiScalarSaturatingSubtractU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingSubtractU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingSubtractU8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_u16" ffiScalarSaturatingSubtractU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingSubtractU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingSubtractU16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_u32" ffiScalarSaturatingSubtractU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingSubtractU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingSubtractU32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_u64" ffiScalarSaturatingSubtractU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingSubtractU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingSubtractU64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_int" ffiScalarSaturatingSubtractInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingSubtractInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingSubtractInt vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_saturating_subtract_word" ffiScalarSaturatingSubtractWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingSubtractWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingSubtractWord vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingSubtract + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_i8" ffiScalarSaturatingMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarSaturatingMultiplyI8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Int8) + (vB :: Int8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_i16" ffiScalarSaturatingMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarSaturatingMultiplyI16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Int16) + (vB :: Int16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_i32" ffiScalarSaturatingMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarSaturatingMultiplyI32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Int32) + (vB :: Int32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_i64" ffiScalarSaturatingMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarSaturatingMultiplyI64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Int64) + (vB :: Int64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_u8" ffiScalarSaturatingMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarSaturatingMultiplyU8 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Word8) + (vB :: Word8))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_u16" ffiScalarSaturatingMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarSaturatingMultiplyU16 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Word16) + (vB :: Word16))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_u32" ffiScalarSaturatingMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarSaturatingMultiplyU32 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Word32) + (vB :: Word32))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_u64" ffiScalarSaturatingMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarSaturatingMultiplyU64 vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Word64) + (vB :: Word64))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_int" ffiScalarSaturatingMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarSaturatingMultiplyInt vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Int) + (vB :: Int))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_saturating_multiply_word" ffiScalarSaturatingMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarSaturatingMultiplyWord vA vB out0 = boundary $ do + checked (Right (Scalar.saturatingMultiply + (vA :: Word) + (vB :: Word))) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_checked_add_i8" ffiScalarCheckedAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedAddI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedAddI8 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Int8) + (vB :: Int8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_checked_add_i16" ffiScalarCheckedAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedAddI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedAddI16 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Int16) + (vB :: Int16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_checked_add_i32" ffiScalarCheckedAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedAddI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedAddI32 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Int32) + (vB :: Int32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_checked_add_i64" ffiScalarCheckedAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedAddI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedAddI64 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Int64) + (vB :: Int64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_checked_add_u8" ffiScalarCheckedAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedAddU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedAddU8 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Word8) + (vB :: Word8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_checked_add_u16" ffiScalarCheckedAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedAddU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedAddU16 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Word16) + (vB :: Word16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_checked_add_u32" ffiScalarCheckedAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedAddU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedAddU32 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Word32) + (vB :: Word32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_checked_add_u64" ffiScalarCheckedAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedAddU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedAddU64 vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Word64) + (vB :: Word64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_checked_add_int" ffiScalarCheckedAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedAddInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedAddInt vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Int) + (vB :: Int)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_checked_add_word" ffiScalarCheckedAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedAddWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedAddWord vA vB out0 = boundary $ do + checked (Scalar.checkedAdd + (vA :: Word) + (vB :: Word)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_checked_subtract_i8" ffiScalarCheckedSubtractI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedSubtractI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedSubtractI8 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Int8) + (vB :: Int8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_checked_subtract_i16" ffiScalarCheckedSubtractI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedSubtractI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedSubtractI16 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Int16) + (vB :: Int16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_checked_subtract_i32" ffiScalarCheckedSubtractI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedSubtractI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedSubtractI32 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Int32) + (vB :: Int32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_checked_subtract_i64" ffiScalarCheckedSubtractI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedSubtractI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedSubtractI64 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Int64) + (vB :: Int64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_checked_subtract_u8" ffiScalarCheckedSubtractU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedSubtractU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedSubtractU8 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Word8) + (vB :: Word8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_checked_subtract_u16" ffiScalarCheckedSubtractU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedSubtractU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedSubtractU16 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Word16) + (vB :: Word16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_checked_subtract_u32" ffiScalarCheckedSubtractU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedSubtractU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedSubtractU32 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Word32) + (vB :: Word32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_checked_subtract_u64" ffiScalarCheckedSubtractU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedSubtractU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedSubtractU64 vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Word64) + (vB :: Word64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_checked_subtract_int" ffiScalarCheckedSubtractInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedSubtractInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedSubtractInt vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Int) + (vB :: Int)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_checked_subtract_word" ffiScalarCheckedSubtractWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedSubtractWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedSubtractWord vA vB out0 = boundary $ do + checked (Scalar.checkedSubtract + (vA :: Word) + (vB :: Word)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) + +foreign export ccall "hm_numeric_scalar_checked_multiply_i8" ffiScalarCheckedMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedMultiplyI8 :: + Int8 -> + Int8 -> + Ptr Int8 -> + IO CInt +ffiScalarCheckedMultiplyI8 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Int8) + (vB :: Int8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int8) + +foreign export ccall "hm_numeric_scalar_checked_multiply_i16" ffiScalarCheckedMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedMultiplyI16 :: + Int16 -> + Int16 -> + Ptr Int16 -> + IO CInt +ffiScalarCheckedMultiplyI16 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Int16) + (vB :: Int16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int16) + +foreign export ccall "hm_numeric_scalar_checked_multiply_i32" ffiScalarCheckedMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedMultiplyI32 :: + Int32 -> + Int32 -> + Ptr Int32 -> + IO CInt +ffiScalarCheckedMultiplyI32 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Int32) + (vB :: Int32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int32) + +foreign export ccall "hm_numeric_scalar_checked_multiply_i64" ffiScalarCheckedMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedMultiplyI64 :: + Int64 -> + Int64 -> + Ptr Int64 -> + IO CInt +ffiScalarCheckedMultiplyI64 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Int64) + (vB :: Int64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int64) + +foreign export ccall "hm_numeric_scalar_checked_multiply_u8" ffiScalarCheckedMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedMultiplyU8 :: + Word8 -> + Word8 -> + Ptr Word8 -> + IO CInt +ffiScalarCheckedMultiplyU8 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Word8) + (vB :: Word8)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word8) + +foreign export ccall "hm_numeric_scalar_checked_multiply_u16" ffiScalarCheckedMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedMultiplyU16 :: + Word16 -> + Word16 -> + Ptr Word16 -> + IO CInt +ffiScalarCheckedMultiplyU16 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Word16) + (vB :: Word16)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word16) + +foreign export ccall "hm_numeric_scalar_checked_multiply_u32" ffiScalarCheckedMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedMultiplyU32 :: + Word32 -> + Word32 -> + Ptr Word32 -> + IO CInt +ffiScalarCheckedMultiplyU32 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Word32) + (vB :: Word32)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word32) + +foreign export ccall "hm_numeric_scalar_checked_multiply_u64" ffiScalarCheckedMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedMultiplyU64 :: + Word64 -> + Word64 -> + Ptr Word64 -> + IO CInt +ffiScalarCheckedMultiplyU64 vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Word64) + (vB :: Word64)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word64) + +foreign export ccall "hm_numeric_scalar_checked_multiply_int" ffiScalarCheckedMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedMultiplyInt :: + Int -> + Int -> + Ptr Int -> + IO CInt +ffiScalarCheckedMultiplyInt vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Int) + (vB :: Int)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Int) + +foreign export ccall "hm_numeric_scalar_checked_multiply_word" ffiScalarCheckedMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedMultiplyWord :: + Word -> + Word -> + Ptr Word -> + IO CInt +ffiScalarCheckedMultiplyWord vA vB out0 = boundary $ do + checked (Scalar.checkedMultiply + (vA :: Word) + (vB :: Word)) $ \value -> do + strict0 <- evaluate (value) + poke out0 (coerce strict0 :: Word) diff --git a/src/HMath/FFI/NumericObjects.hs b/src/HMath/FFI/NumericObjects.hs new file mode 100644 index 0000000..9ae3238 --- /dev/null +++ b/src/HMath/FFI/NumericObjects.hs @@ -0,0 +1,135 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Typed instances of existing generic functions. The source functions and +-- original instance dictionaries determine all arithmetic, ordering and errors. +module HMath.FFI.NumericObjects where +import Data.Proxy(Proxy(..)) +import Data.Typeable(Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Basic as B +import qualified HMath.Scalar as S +import qualified HMath.Linear as L +import qualified HMath.Statistics as T +import qualified HMath.Autodiff as A +import qualified HMath.Geometry.Primitives as G +import qualified HMath.FFI.Autodiff as D +import qualified HMath.FFI.AutodiffValue as AD +import qualified HMath.FFI.Coefficient as C +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.FoundationCodec as F +import HMath.FFI.Ordering + +-- Expr has Num/Fractional/Floating but deliberately has no Eq or Ord. Numeric +-- Dual/Quaternion and AD Dual use their distinct original instance families. +data Domain a=Domain { + writeValue :: a -> V.Value, + readValue :: V.Value -> IO a, + fractional :: Maybe(C.Dict(Fractional a)), + floating :: Maybe(C.Dict(Floating a)), + equality :: Maybe(C.Dict(Eq a)), + ordering :: Maybe(C.Dict(Ord a)), + integral :: Maybe(C.Dict(Integral a)), + bounded :: Maybe(C.Dict(Bounded a))} +data SomeDomain where + SomeDomain :: (Typeable a,Num a) => Domain a -> SomeDomain +fromADDict :: Maybe(D.Dict c) -> Maybe(C.Dict c) +fromADDict(Just D.Dict)=Just C.Dict +fromADDict Nothing=Nothing +coefficientDomain :: forall a. C.Coefficient a => C.ScalarType a -> Domain a +coefficientDomain witness=Domain(V.Scalar witness)V.asScalar(C.fractionalDict proxy)(C.floatingDict proxy)(Just C.Dict)(C.orderingDict proxy)(C.integralDict proxy)(C.boundedDict proxy) + where proxy=Proxy::Proxy a +asTower :: forall a. Typeable a => V.Value -> IO a +asTower value=do + D.Tower x <- AD.asADTower value + maybe(V.invalid "original AD Dual coefficient types differ")pure(cast x) +domain :: V.Value -> IO SomeDomain +domain value=case value of + V.Scalar witness _ -> pure(SomeDomain(coefficientDomain witness)) + V.Opaque 289 _ _ _ _ -> do + D.Tower(_::a) <- AD.asADTower value + let proxy=Proxy::Proxy a + pure(SomeDomain(Domain(AD.fromADTower . D.Tower)asTower(fromADDict(D.fractionalDict proxy))(fromADDict(D.floatingDict proxy))(Just C.Dict)(fromADDict(D.orderingDict proxy)) Nothing Nothing)) + V.Opaque 287 _ _ _ _ -> pure(SomeDomain(Domain AD.fromADExpr AD.asADExpr (Just C.Dict)(Just C.Dict)Nothing Nothing Nothing Nothing :: Domain A.Expr)) + _ -> V.unsupported "generic numeric operation needs an actual numeric scalar, Numeric Dual/Quaternion, AD Dual or AD Expr prototype" +withDict :: String -> Maybe(C.Dict c) -> (c => IO r) -> IO r +withDict _ (Just C.Dict) action=action +withDict name Nothing _=V.unsupported("original type has no "++name++" instance") + +-- Native primitive and recursively nested coefficient witnesses are retained. +-- A raw literal is not implicitly promoted to a different coefficient domain. +numeric :: forall a. (Typeable a,Num a) => Domain a -> Int -> [V.Value] -> IO V.Value +numeric d operation values=case(operation,values)of + (1,[a,b,t]) -> withDict "Fractional" (fractional d) $ do x <- readValue d a;y <- readValue d b;z <- readValue d t;pure(writeValue d(B.lerp x y z)) + (2,[a,b]) -> binary S.add a b + (3,[a,b]) -> binary S.subtractScalar a b + (4,[a,b]) -> binary S.multiply a b + (7,[a]) -> unary S.absolute a + (8,[a]) -> unary S.sign a + (9,[a,b]) -> withDict "Integral" (integral d) $ do x <- readValue d a;y <- readValue d b;F.source(S.positiveModulo x y) >>= pure . writeValue d + (10,[a]) -> listUnary S.cumulativeSum a + (11,[a]) -> listUnary S.cumulativeProduct a + (12,[a]) -> listUnary S.prefixSum a + (13,[a]) -> withDict "Fractional" (fractional d) $ scalarList T.mean a + (14,[a]) -> withDict "Fractional" (fractional d) $ scalarList T.variance a + (15,[a]) -> withDict "Floating" (floating d) $ scalarList T.standardDeviation a + (16,[a]) -> withDict "Fractional" (fractional d) $ withDict "Ord" (ordering d) $ scalarList T.median a + (17,[a,b]) -> scalarBinaryList L.dot a b + (18,[a,b]) -> do xs <- readElements a;ys <- readElements b;F.source(L.dotChecked xs ys) >>= pure . writeValue d + (19,[a]) -> withDict "Floating" (floating d) $ scalarList L.magnitude a + (20,[a]) -> withDict "Floating" (floating d) $ withDict "Eq" (equality d) $ listUnary L.normalize a + (21,[a,b]) -> listBinary L.add a b + (22,[a,b]) -> checkedList L.addChecked a b + (23,[a,b]) -> checkedList L.subtractChecked a b + (24,[a,b]) -> do x <- readValue d a;ys <- readElements b;pure(writeList(L.scale x ys)) + (25,[a,b]) -> boundedBinary (\x y -> pure(S.saturatingAdd x y)) a b + (26,[a,b]) -> boundedBinary (\x y -> pure(S.saturatingSubtract x y)) a b + (27,[a,b]) -> boundedBinary (\x y -> pure(S.saturatingMultiply x y)) a b + (28,[a,b]) -> boundedBinary (\x y -> F.source(S.checkedAdd x y)) a b + (29,[a,b]) -> boundedBinary (\x y -> F.source(S.checkedSubtract x y)) a b + (30,[a,b]) -> boundedBinary (\x y -> F.source(S.checkedMultiply x y)) a b + _ -> V.invalid "generic numeric argument shape differs" + where + readElements value=V.asList value >>= mapM(readValue d) + writeList=V.List . map(writeValue d) + unary f value=writeValue d . f <$> readValue d value + binary f left right=do x <- readValue d left;y <- readValue d right;pure(writeValue d(f x y)) + scalarList f value=writeValue d . f <$> readElements value + listUnary f value=writeList . f <$> readElements value + listBinary f left right=do xs <- readElements left;ys <- readElements right;pure(writeList(f xs ys)) + scalarBinaryList f left right=do xs <- readElements left;ys <- readElements right;pure(writeValue d(f xs ys)) + checkedList f left right=do xs <- readElements left;ys <- readElements right;F.source(f xs ys) >>= pure . writeList + boundedBinary :: ((Integral a,Bounded a) => a -> a -> IO a) -> V.Value -> V.Value -> IO V.Value + boundedBinary f left right=withDict "Integral" (integral d) $ withDict "Bounded" (bounded d) $ do + x <- readValue d left;y <- readValue d right;f x y >>= pure . writeValue d + +ordered :: Int -> V.Value -> [V.Value] -> IO V.Value +ordered operation prototype values=do + let examples=case prototype of V.None -> values;_ -> prototype:values + SomeOrdered write readOrdered <- orderedWith[F.foundationOrdering] examples + case(operation,values)of + (0,[a,b,c]) -> do x <- readOrdered a;y <- readOrdered b;z <- readOrdered c;write(B.clamp x y z) + (5,[a,b]) -> do x <- readOrdered a;y <- readOrdered b;write(S.minimumScalar x y) + (6,[a,b]) -> do x <- readOrdered a;y <- readOrdered b;write(S.maximumScalar x y) + _ -> V.invalid "generic ordered argument shape differs" +foreign export ccall "hm_numeric_objects_apply" apply :: CInt -> StablePtr V.Value -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +apply :: CInt -> StablePtr V.Value -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +apply operation inputPrototype input arity out=F.foundationBoundary $ do + prototype <- deRefStablePtr inputPrototype + values <- peekArray(fromIntegral arity) input >>= mapM deRefStablePtr + result <- if operation `elem` [31,32] + then case values of + [left,right] -> do + xs <- V.asList left >>= mapM F.readEquality + ys <- V.asList right >>= mapM F.readEquality + if operation==31 then V.Index <$> F.source(G.hammingDistance xs ys) + else V.Scalar C.SDouble <$> F.source(G.jaccardDistance xs ys) + _ -> V.invalid "generic equality argument shape differs" + else if operation `elem` [0,5,6] + then ordered(fromIntegral operation) prototype values + else do SomeDomain witness <- domain prototype;numeric witness(fromIntegral operation) values + V.publish result out + pure 0 diff --git a/src/HMath/FFI/NumericTypes.hs b/src/HMath/FFI/NumericTypes.hs new file mode 100644 index 0000000..8b28810 --- /dev/null +++ b/src/HMath/FFI/NumericTypes.hs @@ -0,0 +1,959 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_numeric_types.py. +module HMath.FFI.NumericTypes where +import HMath.FFI.NumericTypes.Core +import HMath.FFI.Boundary (checked, readInteger) +import HMath.FFI.Coefficient +import qualified HMath.Numeric as N +import qualified HMath.Constants as K +import Data.Coerce (coerce) +import Data.Ratio ((%)) +import Foreign +import Foreign.C + +foreign export ccall "hm_numeric_types_type_name" ffiTypeName :: Handle -> Ptr Handle -> IO CInt +ffiTypeName :: Handle -> Ptr Handle -> IO CInt +ffiTypeName rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- pure (Text (objectType value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_binary" ffiBinary :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiBinary :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiBinary rawOperation rawA rawB out = numericBoundary $ do + let operation = rawOperation + aObject <- dereference rawA + let a = aObject + bObject <- dereference rawB + let b = bObject + result <- binary operation a b + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_unary" ffiUnary :: CInt -> Handle -> Ptr Handle -> IO CInt +ffiUnary :: CInt -> Handle -> Ptr Handle -> IO CInt +ffiUnary rawOperation rawValue out = numericBoundary $ do + let operation = rawOperation + valueObject <- dereference rawValue + let value = valueObject + result <- unary operation value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_literal_integer" ffiLiteralInteger :: Handle -> CString -> Ptr Handle -> IO CInt +ffiLiteralInteger :: Handle -> CString -> Ptr Handle -> IO CInt +ffiLiteralInteger rawLike rawvalue out = numericBoundary $ do + likeObject <- dereference rawLike + let like = likeObject + valueValue <- readInteger rawvalue + let value = valueValue + result <- literalInteger like value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_literal_rational" ffiLiteralRational :: Handle -> CString -> CString -> Ptr Handle -> IO CInt +ffiLiteralRational :: Handle -> CString -> CString -> Ptr Handle -> IO CInt +ffiLiteralRational rawLike rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + likeObject <- dereference rawLike + let like = likeObject + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- literalRational like value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_integer_power" ffiIntegerPower :: Handle -> CString -> Ptr Handle -> IO CInt +ffiIntegerPower :: Handle -> CString -> Ptr Handle -> IO CInt +ffiIntegerPower rawValue rawpower out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + powerValue <- readInteger rawpower + let power = powerValue + result <- integerPower value power + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_equal" ffiEqual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiEqual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiEqual rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + let a = aObject + bObject <- dereference rawB + let b = bObject + result <- pure (Boolean (a == b)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_sequence_get" ffiSequenceGet :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiSequenceGet :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiSequenceGet rawValue rawIndex out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let index = rawIndex + result <- sequenceItem index value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_round_rational" ffiRoundRational :: CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiRoundRational :: CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiRoundRational rawMode rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + mode <- roundingMode rawMode + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- pure (ninteger (N.roundRational mode value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_classify" ffiClassify :: Handle -> Ptr Handle -> IO CInt +ffiClassify :: Handle -> Ptr Handle -> IO CInt +ffiClassify rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- classify value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_frexp" ffiFrexp :: Handle -> Ptr Handle -> IO CInt +ffiFrexp :: Handle -> Ptr Handle -> IO CInt +ffiFrexp rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- frexp value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_numeric_limits" ffiNumericLimits :: Handle -> Ptr Handle -> IO CInt +ffiNumericLimits :: Handle -> Ptr Handle -> IO CInt +ffiNumericLimits rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- numericLimits value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_integer_limits" ffiIntegerLimits :: Handle -> Ptr Handle -> IO CInt +ffiIntegerLimits :: Handle -> Ptr Handle -> IO CInt +ffiIntegerLimits rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- integerLimits value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_float16_limits" ffiFloat16Limits :: Ptr Handle -> IO CInt +ffiFloat16Limits :: Ptr Handle -> IO CInt +ffiFloat16Limits out = numericBoundary $ do + result <- pure (limits SDouble N.float16Limits) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_bfloat16_limits" ffiBfloat16Limits :: Ptr Handle -> IO CInt +ffiBfloat16Limits :: Ptr Handle -> IO CInt +ffiBfloat16Limits out = numericBoundary $ do + result <- pure (limits SDouble N.bfloat16Limits) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_numeric_limits_record" ffiNumericLimitsRecord :: Handle -> Handle -> Handle -> Handle -> CPtrdiff -> CPtrdiff -> CPtrdiff -> Ptr Handle -> IO CInt +ffiNumericLimitsRecord :: Handle -> Handle -> Handle -> Handle -> CPtrdiff -> CPtrdiff -> CPtrdiff -> Ptr Handle -> IO CInt +ffiNumericLimitsRecord rawNormal rawSubnormal rawMaximum_value rawEpsilon rawDigits rawLow rawHigh out = numericBoundary $ do + normalObject <- dereference rawNormal + let normal = normalObject + subnormalObject <- dereference rawSubnormal + let subnormal = subnormalObject + maximum_valueObject <- dereference rawMaximum_value + let maximum_value = maximum_valueObject + epsilonObject <- dereference rawEpsilon + let epsilon = epsilonObject + let digits = rawDigits + let low = rawLow + let high = rawHigh + result <- makeLimits normal subnormal maximum_value epsilon digits low high + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_minimum_normal" ffiMinimumNormal :: Handle -> Ptr Handle -> IO CInt +ffiMinimumNormal :: Handle -> Ptr Handle -> IO CInt +ffiMinimumNormal rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 0 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_minimum_subnormal" ffiMinimumSubnormal :: Handle -> Ptr Handle -> IO CInt +ffiMinimumSubnormal :: Handle -> Ptr Handle -> IO CInt +ffiMinimumSubnormal rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 1 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_maximum_finite" ffiMaximumFinite :: Handle -> Ptr Handle -> IO CInt +ffiMaximumFinite :: Handle -> Ptr Handle -> IO CInt +ffiMaximumFinite rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 2 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_machine_epsilon" ffiMachineEpsilon :: Handle -> Ptr Handle -> IO CInt +ffiMachineEpsilon :: Handle -> Ptr Handle -> IO CInt +ffiMachineEpsilon rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 3 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_significand_digits" ffiSignificandDigits :: Handle -> Ptr Handle -> IO CInt +ffiSignificandDigits :: Handle -> Ptr Handle -> IO CInt +ffiSignificandDigits rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 4 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_minimum_exponent" ffiMinimumExponent :: Handle -> Ptr Handle -> IO CInt +ffiMinimumExponent :: Handle -> Ptr Handle -> IO CInt +ffiMinimumExponent rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 5 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_maximum_exponent" ffiMaximumExponent :: Handle -> Ptr Handle -> IO CInt +ffiMaximumExponent :: Handle -> Ptr Handle -> IO CInt +ffiMaximumExponent rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- limitsField 6 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_safe_integral_cast" ffiSafeIntegralCast :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiSafeIntegralCast :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiSafeIntegralCast rawValue rawDtype out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let dtype = rawDtype + result <- boundedCast False dtype value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_saturating_cast" ffiSaturatingCast :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiSaturatingCast :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiSaturatingCast rawValue rawDtype out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let dtype = rawDtype + result <- boundedCast True dtype value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_real_to_integral" ffiRealToIntegral :: CInt -> Handle -> CInt -> Ptr Handle -> IO CInt +ffiRealToIntegral :: CInt -> Handle -> CInt -> Ptr Handle -> IO CInt +ffiRealToIntegral rawMode rawValue rawDtype out = numericBoundary $ do + mode <- roundingMode rawMode + valueObject <- dereference rawValue + let value = valueObject + let dtype = rawDtype + result <- realToIntegral mode dtype value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_narrow_float" ffiNarrowFloat :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiNarrowFloat :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiNarrowFloat rawValue rawDtype out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let dtype = rawDtype + result <- narrowFloat dtype value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_float16" ffiFloat16 :: CInt -> CDouble -> Ptr Handle -> IO CInt +ffiFloat16 :: CInt -> CDouble -> Ptr Handle -> IO CInt +ffiFloat16 rawMode rawValue out = numericBoundary $ do + mode <- roundingMode rawMode + let value = coerce rawValue + result <- pure (rounded Half (N.float16 mode value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_bfloat16" ffiBfloat16 :: CInt -> CDouble -> Ptr Handle -> IO CInt +ffiBfloat16 :: CInt -> CDouble -> Ptr Handle -> IO CInt +ffiBfloat16 rawMode rawValue out = numericBoundary $ do + mode <- roundingMode rawMode + let value = coerce rawValue + result <- pure (rounded BHalf (N.bfloat16 mode value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_float16_from_bits" ffiFloat16FromBits :: Word16 -> Ptr Handle -> IO CInt +ffiFloat16FromBits :: Word16 -> Ptr Handle -> IO CInt +ffiFloat16FromBits rawBits out = numericBoundary $ do + let bits = rawBits + result <- pure (Half (N.float16FromBits bits)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_bfloat16_from_bits" ffiBfloat16FromBits :: Word16 -> Ptr Handle -> IO CInt +ffiBfloat16FromBits :: Word16 -> Ptr Handle -> IO CInt +ffiBfloat16FromBits rawBits out = numericBoundary $ do + let bits = rawBits + result <- pure (BHalf (N.bfloat16FromBits bits)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_float16_bits" ffiFloat16Bits :: Handle -> Ptr Handle -> IO CInt +ffiFloat16Bits :: Handle -> Ptr Handle -> IO CInt +ffiFloat16Bits rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getHalf valueObject + result <- pure (scalar SWord16 (N.float16Bits value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_bfloat16_bits" ffiBfloat16Bits :: Handle -> Ptr Handle -> IO CInt +ffiBfloat16Bits :: Handle -> Ptr Handle -> IO CInt +ffiBfloat16Bits rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBHalf valueObject + result <- pure (scalar SWord16 (N.bfloat16Bits value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_from_float16" ffiFromFloat16 :: Handle -> Ptr Handle -> IO CInt +ffiFromFloat16 :: Handle -> Ptr Handle -> IO CInt +ffiFromFloat16 rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getHalf valueObject + result <- pure (ndouble (N.fromFloat16 value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_from_bfloat16" ffiFromBfloat16 :: Handle -> Ptr Handle -> IO CInt +ffiFromBfloat16 :: Handle -> Ptr Handle -> IO CInt +ffiFromBfloat16 rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBHalf valueObject + result <- pure (ndouble (N.fromBFloat16 value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_rounded" ffiRounded :: Handle -> Ptr CInt -> CSize -> Ptr Handle -> IO CInt +ffiRounded :: Handle -> Ptr CInt -> CSize -> Ptr Handle -> IO CInt +ffiRounded rawValue rawFlags rawFlagsCount out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + flags <- peekArray (fromIntegral rawFlagsCount) rawFlags >>= mapM exception + result <- pure (makeRounded value flags) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_rounded_value" ffiRoundedValue :: Handle -> Ptr Handle -> IO CInt +ffiRoundedValue :: Handle -> Ptr Handle -> IO CInt +ffiRoundedValue rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- roundedValue value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_numerical_exceptions" ffiNumericalExceptions :: Handle -> Ptr Handle -> IO CInt +ffiNumericalExceptions :: Handle -> Ptr Handle -> IO CInt +ffiNumericalExceptions rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- numericalExceptions value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_float" ffiBigFloat :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiBigFloat :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiBigFloat rawPrecision rawMode rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + let precision = rawPrecision + mode <- roundingMode rawMode + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- pure (rounded Big <$> N.bigFloat (fromIntegral precision) mode value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_extended" ffiExtended :: CString -> CString -> Ptr Handle -> IO CInt +ffiExtended :: CString -> CString -> Ptr Handle -> IO CInt +ffiExtended rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- pure (Big <$> N.extended value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_precision" ffiBigPrecision :: Handle -> Ptr Handle -> IO CInt +ffiBigPrecision :: Handle -> Ptr Handle -> IO CInt +ffiBigPrecision rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (nint (N.bigPrecision value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_rational" ffiBigRational :: Handle -> Ptr Handle -> IO CInt +ffiBigRational :: Handle -> Ptr Handle -> IO CInt +ffiBigRational rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (nrational (N.bigRational value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_to_double" ffiBigToDouble :: Handle -> Ptr Handle -> IO CInt +ffiBigToDouble :: Handle -> Ptr Handle -> IO CInt +ffiBigToDouble rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (ndouble (N.bigToDouble value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_add" ffiBigAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigAdd rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + bObject <- dereference rawB + b <- getBig bObject + result <- pure (Big <$> N.bigAdd a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_subtract" ffiBigSubtract :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigSubtract :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigSubtract rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + bObject <- dereference rawB + b <- getBig bObject + result <- pure (Big <$> N.bigSubtract a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_multiply" ffiBigMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigMultiply rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + bObject <- dereference rawB + b <- getBig bObject + result <- pure (Big <$> N.bigMultiply a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_divide" ffiBigDivide :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigDivide :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiBigDivide rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + bObject <- dereference rawB + b <- getBig bObject + result <- pure (Big <$> N.bigDivide a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_sqrt" ffiBigSqrt :: Handle -> Ptr Handle -> IO CInt +ffiBigSqrt :: Handle -> Ptr Handle -> IO CInt +ffiBigSqrt rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (Big <$> N.bigSqrt value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_exp" ffiBigExp :: Handle -> Ptr Handle -> IO CInt +ffiBigExp :: Handle -> Ptr Handle -> IO CInt +ffiBigExp rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (Big <$> N.bigExp value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_big_log" ffiBigLog :: Handle -> Ptr Handle -> IO CInt +ffiBigLog :: Handle -> Ptr Handle -> IO CInt +ffiBigLog rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getBig valueObject + result <- pure (Big <$> N.bigLog value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_mixed_add" ffiMixedAdd :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiMixedAdd :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiMixedAdd rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + let b = coerce rawB + result <- pure (Big <$> N.mixedAdd a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_mixed_multiply" ffiMixedMultiply :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiMixedMultiply :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiMixedMultiply rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getBig aObject + let b = coerce rawB + result <- pure (Big <$> N.mixedMultiply a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed" ffiFixed :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiFixed :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiFixed rawScale rawMode rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + let scale = rawScale + mode <- roundingMode rawMode + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- pure (rounded Fixed <$> N.fixed (fromIntegral scale) mode value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_rational" ffiFixedRational :: Handle -> Ptr Handle -> IO CInt +ffiFixedRational :: Handle -> Ptr Handle -> IO CInt +ffiFixedRational rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getFixed valueObject + result <- pure (nrational (N.fixedRational value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_add" ffiFixedAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedAdd rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getFixed aObject + bObject <- dereference rawB + b <- getFixed bObject + result <- pure (rounded Fixed <$> N.fixedAdd a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_multiply" ffiFixedMultiply :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedMultiply :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedMultiply rawMode rawA rawB out = numericBoundary $ do + mode <- roundingMode rawMode + aObject <- dereference rawA + a <- getFixed aObject + bObject <- dereference rawB + b <- getFixed bObject + result <- pure (rounded Fixed <$> N.fixedMultiply mode a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_divide" ffiFixedDivide :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedDivide :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiFixedDivide rawMode rawA rawB out = numericBoundary $ do + mode <- roundingMode rawMode + aObject <- dereference rawA + a <- getFixed aObject + bObject <- dereference rawB + b <- getFixed bObject + result <- pure (rounded Fixed <$> N.fixedDivide mode a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_decimal" ffiDecimal :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiDecimal :: CPtrdiff -> CInt -> CString -> CString -> Ptr Handle -> IO CInt +ffiDecimal rawScale rawMode rawvalueXnumerator rawvalueXdenominator out = numericBoundary $ do + let scale = rawScale + mode <- roundingMode rawMode + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + result <- pure (rounded Decimal <$> N.decimal (fromIntegral scale) mode value) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_decimal_rational" ffiDecimalRational :: Handle -> Ptr Handle -> IO CInt +ffiDecimalRational :: Handle -> Ptr Handle -> IO CInt +ffiDecimalRational rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getDecimal valueObject + result <- pure (nrational (N.decimalRational value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_decimal_add" ffiDecimalAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalAdd rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getDecimal aObject + bObject <- dereference rawB + b <- getDecimal bObject + result <- pure (rounded Decimal <$> N.decimalAdd a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_decimal_multiply" ffiDecimalMultiply :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalMultiply :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalMultiply rawMode rawA rawB out = numericBoundary $ do + mode <- roundingMode rawMode + aObject <- dereference rawA + a <- getDecimal aObject + bObject <- dereference rawB + b <- getDecimal bObject + result <- pure (rounded Decimal <$> N.decimalMultiply mode a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_decimal_divide" ffiDecimalDivide :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalDivide :: CInt -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiDecimalDivide rawMode rawA rawB out = numericBoundary $ do + mode <- roundingMode rawMode + aObject <- dereference rawA + a <- getDecimal aObject + bObject <- dereference rawB + b <- getDecimal bObject + result <- pure (rounded Decimal <$> N.decimalDivide mode a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_scale" ffiFixedScale :: Handle -> Ptr Handle -> IO CInt +ffiFixedScale :: Handle -> Ptr Handle -> IO CInt +ffiFixedScale rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getFixed valueObject + result <- pure (nint (N.fixedScale value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_fixed_coefficient" ffiFixedCoefficient :: Handle -> Ptr Handle -> IO CInt +ffiFixedCoefficient :: Handle -> Ptr Handle -> IO CInt +ffiFixedCoefficient rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getFixed valueObject + result <- pure (ninteger (N.fixedCoefficient value)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval" ffiInterval :: CDouble -> CDouble -> Ptr Handle -> IO CInt +ffiInterval :: CDouble -> CDouble -> Ptr Handle -> IO CInt +ffiInterval rawLow rawHigh out = numericBoundary $ do + let low = coerce rawLow + let high = coerce rawHigh + result <- pure (Interval <$> N.interval low high) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_bounds" ffiIntervalBounds :: Handle -> Ptr Handle -> IO CInt +ffiIntervalBounds :: Handle -> Ptr Handle -> IO CInt +ffiIntervalBounds rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getInterval valueObject + result <- let (a,b)=N.intervalBounds value in pure (Sequence True "" [ndouble a,ndouble b]) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_contains" ffiIntervalContains :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiIntervalContains :: Handle -> CDouble -> Ptr Handle -> IO CInt +ffiIntervalContains rawValue rawPoint out = numericBoundary $ do + valueObject <- dereference rawValue + value <- getInterval valueObject + let point = coerce rawPoint + result <- pure (Boolean (N.intervalContains value point)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_add" ffiIntervalAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalAdd rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getInterval aObject + bObject <- dereference rawB + b <- getInterval bObject + result <- pure (Interval <$> N.intervalAdd a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_subtract" ffiIntervalSubtract :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalSubtract :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalSubtract rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getInterval aObject + bObject <- dereference rawB + b <- getInterval bObject + result <- pure (Interval <$> N.intervalSubtract a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_multiply" ffiIntervalMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalMultiply rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getInterval aObject + bObject <- dereference rawB + b <- getInterval bObject + result <- pure (Interval <$> N.intervalMultiply a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_interval_divide" ffiIntervalDivide :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalDivide :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiIntervalDivide rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + a <- getInterval aObject + bObject <- dereference rawB + b <- getInterval bObject + result <- pure (Interval <$> N.intervalDivide a b) + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_dual" ffiDual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDual rawPrimal_value rawTangent_value out = numericBoundary $ do + primal_valueObject <- dereference rawPrimal_value + let primal_value = primal_valueObject + tangent_valueObject <- dereference rawTangent_value + let tangent_value = tangent_valueObject + result <- makeDual primal_value tangent_value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_primal" ffiPrimal :: Handle -> Ptr Handle -> IO CInt +ffiPrimal :: Handle -> Ptr Handle -> IO CInt +ffiPrimal rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- primal value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_tangent" ffiTangent :: Handle -> Ptr Handle -> IO CInt +ffiTangent :: Handle -> Ptr Handle -> IO CInt +ffiTangent rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- tangent value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_derivative" ffiDerivative :: FunPtr NumericCallback -> Ptr () -> Handle -> Ptr Handle -> IO CInt +ffiDerivative :: FunPtr NumericCallback -> Ptr () -> Handle -> Ptr Handle -> IO CInt +ffiDerivative function functionUserdata rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- derivative function functionUserdata value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_quaternion" ffiQuaternion :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternion :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternion rawReal rawI rawJ rawK out = numericBoundary $ do + realObject <- dereference rawReal + let real = realObject + iObject <- dereference rawI + let i = iObject + jObject <- dereference rawJ + let j = jObject + kObject <- dereference rawK + let k = kObject + result <- makeQuaternion real i j k + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_quaternion_conjugate" ffiQuaternionConjugate :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionConjugate :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionConjugate rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- quaternionConjugate value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_quaternion_norm" ffiQuaternionNorm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNorm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNorm rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- quaternionNorm value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_quaternion_inverse" ffiQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionInverse rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- quaternionInverse value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_quaternion_component" ffiQuaternionComponent :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiQuaternionComponent :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiQuaternionComponent rawValue rawIndex out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let index = rawIndex + result <- quaternionComponent index value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_dual_quaternion" ffiDualQuaternion :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDualQuaternion :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDualQuaternion rawReal rawDual out = numericBoundary $ do + realObject <- dereference rawReal + let real = realObject + dualObject <- dereference rawDual + let dual = dualObject + result <- makeDualQuaternion real dual + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_dual_quaternion_component" ffiDualQuaternionComponent :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiDualQuaternionComponent :: Handle -> CPtrdiff -> Ptr Handle -> IO CInt +ffiDualQuaternionComponent rawValue rawIndex out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let index = rawIndex + result <- dualQuaternionComponent index value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_dual_quaternion_multiply" ffiDualQuaternionMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDualQuaternionMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiDualQuaternionMultiply rawA rawB out = numericBoundary $ do + aObject <- dereference rawA + let a = aObject + bObject <- dereference rawB + let b = bObject + result <- dualQuaternionMultiply a b + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_dual_quaternion_inverse" ffiDualQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiDualQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiDualQuaternionInverse rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- dualQuaternionInverse value + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_rotate_vector" ffiRotateVector :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotateVector :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotateVector rawValue rawX rawY rawZ out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + xObject <- dereference rawX + let x = xObject + yObject <- dereference rawY + let y = yObject + zObject <- dereference rawZ + let z = zObject + result <- rotateVector value x y z + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_rigid_transform" ffiRigidTransform :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRigidTransform :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRigidTransform rawValue rawX rawY rawZ out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + xObject <- dereference rawX + let x = xObject + yObject <- dereference rawY + let y = yObject + zObject <- dereference rawZ + let z = zObject + result <- rigidTransform value x y z + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_transform_point" ffiTransformPoint :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiTransformPoint :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiTransformPoint rawValue rawX rawY rawZ out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + xObject <- dereference rawX + let x = xObject + yObject <- dereference rawY + let y = yObject + zObject <- dereference rawZ + let z = zObject + result <- transformPoint value x y z + checked (result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant" ffiConstant :: Ptr Word32 -> CSize -> CString -> CString -> CString -> CString -> CString -> CString -> Ptr Word32 -> CSize -> Ptr Word32 -> CSize -> Ptr Handle -> IO CInt +ffiConstant :: Ptr Word32 -> CSize -> CString -> CString -> CString -> CString -> CString -> CString -> Ptr Word32 -> CSize -> Ptr Word32 -> CSize -> Ptr Handle -> IO CInt +ffiConstant rawName rawNameCount rawvalueXnumerator rawvalueXdenominator rawuncertaintyXnumerator rawuncertaintyXdenominator rawapproximationXnumerator rawapproximationXdenominator rawUnit rawUnitCount rawSource rawSourceCount out = numericBoundary $ do + nameObject <- readText rawName rawNameCount + name <- getText nameObject + valueXnumeratorValue <- readInteger rawvalueXnumerator + valueXdenominatorValue <- readInteger rawvalueXdenominator + let value = valueXnumeratorValue % valueXdenominatorValue + uncertaintyXnumeratorValue <- readInteger rawuncertaintyXnumerator + uncertaintyXdenominatorValue <- readInteger rawuncertaintyXdenominator + let uncertainty = uncertaintyXnumeratorValue % uncertaintyXdenominatorValue + approximationXnumeratorValue <- readInteger rawapproximationXnumerator + approximationXdenominatorValue <- readInteger rawapproximationXdenominator + let approximation = approximationXnumeratorValue % approximationXdenominatorValue + unitObject <- readText rawUnit rawUnitCount + unit <- getText unitObject + sourceObject <- readText rawSource rawSourceCount + source <- getText sourceObject + result <- pure (Constant (K.Constant name value uncertainty approximation unit source)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_name" ffiConstantName :: Handle -> Ptr Handle -> IO CInt +ffiConstantName :: Handle -> Ptr Handle -> IO CInt +ffiConstantName rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 0 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_value" ffiConstantValue :: Handle -> Ptr Handle -> IO CInt +ffiConstantValue :: Handle -> Ptr Handle -> IO CInt +ffiConstantValue rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 1 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_standard_uncertainty" ffiStandardUncertainty :: Handle -> Ptr Handle -> IO CInt +ffiStandardUncertainty :: Handle -> Ptr Handle -> IO CInt +ffiStandardUncertainty rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 2 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_approximation_bound" ffiApproximationBound :: Handle -> Ptr Handle -> IO CInt +ffiApproximationBound :: Handle -> Ptr Handle -> IO CInt +ffiApproximationBound rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 3 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_unit" ffiConstantUnit :: Handle -> Ptr Handle -> IO CInt +ffiConstantUnit :: Handle -> Ptr Handle -> IO CInt +ffiConstantUnit rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 4 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_source" ffiConstantSource :: Handle -> Ptr Handle -> IO CInt +ffiConstantSource :: Handle -> Ptr Handle -> IO CInt +ffiConstantSource rawValue out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + result <- constantField 5 value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_as" ffiConstantAs :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiConstantAs :: Handle -> CInt -> Ptr Handle -> IO CInt +ffiConstantAs rawValue rawDtype out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + let dtype = rawDtype + result <- constantAs dtype value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_constant_as_like" ffiConstantAsLike :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiConstantAsLike :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiConstantAsLike rawValue rawPrototype out = numericBoundary $ do + valueObject <- dereference rawValue + let value = valueObject + prototypeObject <- dereference rawPrototype + let prototype = prototypeObject + result <- constantAsLike prototype value + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_mathematical_constants" ffiMathematicalConstants :: Ptr Handle -> IO CInt +ffiMathematicalConstants :: Ptr Handle -> IO CInt +ffiMathematicalConstants out = numericBoundary $ do + result <- pure (Sequence False "Constant" (map Constant K.mathematicalConstants)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_physical_constants" ffiPhysicalConstants :: Ptr Handle -> IO CInt +ffiPhysicalConstants :: Ptr Handle -> IO CInt +ffiPhysicalConstants out = numericBoundary $ do + result <- pure (Sequence False "Constant" (map Constant K.physicalConstants)) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_speed_of_light" ffiSpeedOfLight :: Ptr Handle -> IO CInt +ffiSpeedOfLight :: Ptr Handle -> IO CInt +ffiSpeedOfLight out = numericBoundary $ do + result <- pure (Constant K.speedOfLight) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_planck_constant" ffiPlanckConstant :: Ptr Handle -> IO CInt +ffiPlanckConstant :: Ptr Handle -> IO CInt +ffiPlanckConstant out = numericBoundary $ do + result <- pure (Constant K.planckConstant) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_elementary_charge" ffiElementaryCharge :: Ptr Handle -> IO CInt +ffiElementaryCharge :: Ptr Handle -> IO CInt +ffiElementaryCharge out = numericBoundary $ do + result <- pure (Constant K.elementaryCharge) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_boltzmann_constant" ffiBoltzmannConstant :: Ptr Handle -> IO CInt +ffiBoltzmannConstant :: Ptr Handle -> IO CInt +ffiBoltzmannConstant out = numericBoundary $ do + result <- pure (Constant K.boltzmannConstant) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_avogadro_constant" ffiAvogadroConstant :: Ptr Handle -> IO CInt +ffiAvogadroConstant :: Ptr Handle -> IO CInt +ffiAvogadroConstant out = numericBoundary $ do + result <- pure (Constant K.avogadroConstant) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_gravitational_constant" ffiGravitationalConstant :: Ptr Handle -> IO CInt +ffiGravitationalConstant :: Ptr Handle -> IO CInt +ffiGravitationalConstant out = numericBoundary $ do + result <- pure (Constant K.gravitationalConstant) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_electron_mass" ffiElectronMass :: Ptr Handle -> IO CInt +ffiElectronMass :: Ptr Handle -> IO CInt +ffiElectronMass out = numericBoundary $ do + result <- pure (Constant K.electronMass) + checked (Right result) (`publish` out) + +foreign export ccall "hm_numeric_types_astronomical_unit" ffiAstronomicalUnit :: Ptr Handle -> IO CInt +ffiAstronomicalUnit :: Ptr Handle -> IO CInt +ffiAstronomicalUnit out = numericBoundary $ do + result <- pure (Constant K.astronomicalUnit) + checked (Right result) (`publish` out) diff --git a/src/HMath/FFI/NumericTypes/Core.hs b/src/HMath/FFI/NumericTypes/Core.hs new file mode 100644 index 0000000..0e38778 --- /dev/null +++ b/src/HMath/FFI/NumericTypes/Core.hs @@ -0,0 +1,575 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Typed opaque storage. Numerical operations call HMath.Numeric directly. +module HMath.FFI.NumericTypes.Core where + +import Control.Exception (Exception, bracket, catch, evaluate, throw, throwIO) +import Data.Char (chr) +import Data.Proxy (Proxy (..)) +import Data.Typeable (cast, typeOf) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import HMath.Error (MathError) +import HMath.FFI.Boundary (boundary, checked) +import HMath.FFI.Coefficient +import qualified HMath.FFI.Value as V +import qualified HMath.Numeric as N +import qualified HMath.Constants as K + +-- Generic records carry their original Haskell record constructors with boxed +-- fields; fields are representation adapters, never converted through Double. +data Object + = Scalar SomeCoefficient + | Half N.Float16 + | BHalf N.BFloat16 + | Big N.BigFloat + | Fixed N.Fixed + | Decimal N.Decimal + | Interval N.Interval + | Rounded (N.Rounded Object) + | Limits (N.NumericLimits Object) + | Constant K.Constant + | Sequence Bool String [Object] + | Class N.IEEEClass + | Flag N.NumericException + | Boolean Bool + | Text String + | QuaternionData SomeQuaternion + | DualQuaternionData SomeDualQuaternion + | Raw V.Value + +data SomeQuaternion where + SomeQuaternion :: Coefficient a => ScalarType a -> N.Quaternion a -> SomeQuaternion +data SomeDualQuaternion where + SomeDualQuaternion :: Coefficient a => ScalarType a -> N.DualQuaternion a -> SomeDualQuaternion + +data BindingError = BindingError CInt String deriving (Show) +instance Exception BindingError +data CallbackStatus = CallbackStatus CInt deriving (Show) +instance Exception CallbackStatus +foreign import ccall unsafe "hm_error" setError :: CInt -> CString -> IO CInt + +numericBoundary :: IO CInt -> IO CInt +numericBoundary action = boundary $ + (action `catch` (\(BindingError code message) -> withCString message (setError code))) + `catch` (\(CallbackStatus code) -> pure code) +bad :: String -> IO a +bad = throwIO . BindingError 1 +unsupported :: String -> IO a +unsupported = throwIO . BindingError 10 + +scalar :: Coefficient a => ScalarType a -> a -> Object +scalar witness value = Scalar (SomeCoefficient witness value) +nint :: Int -> Object +nint = scalar SInt +ninteger :: Integer -> Object +ninteger = scalar SInteger +nrational :: Rational -> Object +nrational = scalar SRational +nfloat :: Float -> Object +nfloat = scalar SFloat +ndouble :: Double -> Object +ndouble = scalar SDouble + +getScalar :: Object -> IO SomeCoefficient +getScalar (Scalar value) = pure value +getScalar (QuaternionData (SomeQuaternion witness (value :: N.Quaternion a))) = + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> pure (SomeCoefficient (SQuaternion witness) value) + Nothing -> unsupported "Quaternion Num requires a RealFloat component type" +getScalar _ = bad "expected a numeric coefficient" +getAs :: forall a. Coefficient a => Object -> IO a +getAs object = do + SomeCoefficient _ value <- getScalar object + maybe (bad "coefficient types differ") pure (cast value) +getRational :: Object -> IO Rational +getRational = getAs +getBig :: Object -> IO N.BigFloat +getBig (Big value) = pure value +getBig _ = bad "expected BigFloat" +getFixed :: Object -> IO N.Fixed +getFixed (Fixed value) = pure value +getFixed _ = bad "expected Fixed" +getDecimal :: Object -> IO N.Decimal +getDecimal (Decimal value) = pure value +getDecimal _ = bad "expected Decimal" +getInterval :: Object -> IO N.Interval +getInterval (Interval value) = pure value +getInterval _ = bad "expected Interval" +getConstant :: Object -> IO K.Constant +getConstant (Constant value) = pure value +getConstant _ = bad "expected Constant" +getText :: Object -> IO String +getText (Text value) = pure value +getText _ = bad "expected text" +getSequence :: Object -> IO [Object] +getSequence (Sequence _ _ values) = pure values +getSequence _ = bad "expected sequence" +getQuaternion :: Object -> IO SomeQuaternion +getQuaternion (QuaternionData value) = pure value +getQuaternion (Scalar (SomeCoefficient (SQuaternion witness) value)) = pure (SomeQuaternion witness value) +getQuaternion _ = bad "expected Quaternion" +getDualQuaternion :: Object -> IO SomeDualQuaternion +getDualQuaternion (DualQuaternionData value) = pure value +getDualQuaternion _ = bad "expected DualQuaternion" + +forceObject :: Object -> IO () +forceObject object = case object of + Raw value -> V.forceValue value + Scalar (SomeCoefficient _ value) -> forceCoefficient value + Half value -> evaluate (N.float16Bits value) >> pure () + BHalf value -> evaluate (N.bfloat16Bits value) >> pure () + Big value -> evaluate (N.bigPrecision value) >> forceCoefficient (N.bigRational value) + Fixed value -> evaluate (N.fixedScale value) >> evaluate (N.fixedCoefficient value) >> pure () + Decimal value -> forceCoefficient (N.decimalRational value) + Interval value -> let (a,b)=N.intervalBounds value in evaluate a >> evaluate b >> pure () + Rounded value -> forceObject (N.roundedValue value) >> mapM_ evaluate (N.numericalExceptions value) + Limits value -> mapM_ forceObject [N.minimumNormal value,N.minimumSubnormal value,N.maximumFinite value,N.machineEpsilon value] >> mapM_ evaluate [N.significandDigits value,N.minimumExponent value,N.maximumExponent value] + Constant value -> mapM_ (evaluate . length) [K.constantName value,K.constantUnit value,K.constantSource value] >> mapM_ forceCoefficient [K.constantValue value,K.standardUncertainty value,K.approximationBound value] + Sequence _ _ values -> mapM_ forceObject values + Class value -> evaluate value >> pure () + Flag value -> evaluate value >> pure () + Boolean value -> evaluate value >> pure () + Text value -> evaluate (length value) >> pure () + QuaternionData (SomeQuaternion _ (N.Quaternion a b c d)) -> mapM_ forceCoefficient [a,b,c,d] + DualQuaternionData (SomeDualQuaternion witness (N.DualQuaternion a b)) -> forceObject (QuaternionData (SomeQuaternion witness a)) >> forceObject (QuaternionData (SomeQuaternion witness b)) + +publish :: Object -> Ptr (Handle) -> IO () +publish value out = V.publish (sharedObject value) out +rounded :: (a -> Object) -> N.Rounded a -> Object +rounded wrap value = Rounded (N.Rounded (wrap (N.roundedValue value)) (N.numericalExceptions value)) +limits :: Coefficient a => ScalarType a -> N.NumericLimits a -> Object +limits witness value = Limits (N.NumericLimits (scalar witness (N.minimumNormal value)) (scalar witness (N.minimumSubnormal value)) (scalar witness (N.maximumFinite value)) (scalar witness (N.machineEpsilon value)) (N.significandDigits value) (N.minimumExponent value) (N.maximumExponent value)) + +roundingMode :: CInt -> IO N.RoundingMode +roundingMode value = case value of + 0 -> pure N.NearestEven + 1 -> pure N.TowardZero + 2 -> pure N.TowardPositive + 3 -> pure N.TowardNegative + _ -> bad "invalid RoundingMode" +exception :: CInt -> IO N.NumericException +exception value = case value of + 0 -> pure N.InvalidOperation + 1 -> pure N.DivisionByZero + 2 -> pure N.NumericOverflow + 3 -> pure N.NumericUnderflow + 4 -> pure N.Inexact + _ -> bad "invalid NumericException" +exceptionCode :: N.NumericException -> CInt +exceptionCode value = case value of N.InvalidOperation -> 0; N.DivisionByZero -> 1; N.NumericOverflow -> 2; N.NumericUnderflow -> 3; N.Inexact -> 4 +classCode :: N.IEEEClass -> CInt +classCode value = case value of N.NotANumber -> 0; N.PositiveInfinity -> 1; N.NegativeInfinity -> 2; N.PositiveZero -> 3; N.NegativeZero -> 4; N.Subnormal -> 5; N.Normal -> 6 + +foreign export ccall "hm_numeric_types_free" release :: Handle -> IO () +release :: Handle -> IO () +release = freeStablePtr +foreign export ccall "hm_numeric_types_clone" clone :: Handle -> Ptr (Handle) -> IO CInt +clone :: Handle -> Ptr (Handle) -> IO CInt +clone pointer out = numericBoundary $ dereference pointer >>= \value -> checked (Right value) (`publish` out) + +scalarCode :: Object -> IO Int +scalarCode object = do SomeCoefficient witness _ <- getScalar object; pure (scalarTypeCode witness) +objectType :: Object -> String +objectType object = case object of + Raw value -> let (kind,dtype,_) = V.valueInfo value in "Value " ++ show kind ++ ":" ++ show dtype + Scalar (SomeCoefficient _ value) -> show (typeOf value) + QuaternionData (SomeQuaternion _ value) -> show (typeOf value) + DualQuaternionData (SomeDualQuaternion _ value) -> show (typeOf value) + Half _ -> "Float16"; BHalf _ -> "BFloat16"; Big _ -> "BigFloat"; Fixed _ -> "Fixed"; Decimal _ -> "Decimal"; Interval _ -> "Interval" + Rounded value -> "Rounded (" ++ objectType (N.roundedValue value) ++ ")" + Limits value -> "NumericLimits (" ++ objectType (N.minimumNormal value) ++ ")" + Constant _ -> "Constant" + Sequence tuple element _ -> (if tuple then "Tuple " else "List ") ++ element + Class _ -> "IEEEClass"; Flag _ -> "NumericException"; Boolean _ -> "Bool"; Text _ -> "String" + +-- Original numeric instance operations, including recursive Numeric.Dual. +binary :: CInt -> Object -> Object -> IO Object +binary operation first second = do + SomeCoefficient witness (a :: a) <- getScalar first + b <- getAs second :: IO a + case operation of + 0 -> pure (scalar witness (a+b)) + 1 -> pure (scalar witness (a-b)) + 2 -> pure (scalar witness (a*b)) + 3 -> case fractionalDict (Proxy :: Proxy a) of Just Dict -> pure (scalar witness (a/b)); Nothing -> unsupported "Fractional instance unavailable" + 4 -> case floatingDict (Proxy :: Proxy a) of Just Dict -> pure (scalar witness (a**b)); Nothing -> unsupported "Floating instance unavailable" + _ -> bad "invalid numeric binary operation" +unary :: CInt -> Object -> IO Object +unary operation first = do + SomeCoefficient witness (a :: a) <- getScalar first + case operation of + 0 -> pure (scalar witness (negate a)) + 1 -> pure (scalar witness (abs a)) + 2 -> pure (scalar witness (signum a)) + 3 -> case fractionalDict (Proxy :: Proxy a) of Just Dict -> pure (scalar witness (recip a)); Nothing -> unsupported "Fractional instance unavailable" + _ -> case floatingDict (Proxy :: Proxy a) of + Nothing -> unsupported "Floating instance unavailable" + Just Dict -> case operation of + 4 -> pure (scalar witness (exp a)); 5 -> pure (scalar witness (log a)); 6 -> pure (scalar witness (sqrt a)); 7 -> pure (scalar witness (sin a)); 8 -> pure (scalar witness (cos a)); 9 -> pure (scalar witness (tan a)); 10 -> pure (scalar witness (asin a)); 11 -> pure (scalar witness (acos a)); 12 -> pure (scalar witness (atan a)); 13 -> pure (scalar witness (sinh a)); 14 -> pure (scalar witness (cosh a)); 15 -> pure (scalar witness (tanh a)); 16 -> pure (scalar witness (asinh a)); 17 -> pure (scalar witness (acosh a)); 18 -> pure (scalar witness (atanh a)); _ -> bad "invalid numeric unary operation" + +makeDual :: Object -> Object -> IO Object +makeDual first second = do + SomeCoefficient witness (a :: a) <- getScalar first + b <- getAs second :: IO a + pure (scalar (SDual witness) (N.Dual a b)) +primal :: Object -> IO Object +primal (Scalar (SomeCoefficient (SDual witness) value)) = case coefficientDict witness of Dict -> pure (scalar witness (N.primal value)) +primal _ = bad "expected Numeric.Dual" +tangent :: Object -> IO Object +tangent (Scalar (SomeCoefficient (SDual witness) value)) = case coefficientDict witness of Dict -> pure (scalar witness (N.tangent value)) +tangent _ = bad "expected Numeric.Dual" + +getQuaternionAs :: forall a. Coefficient a => Object -> IO (N.Quaternion a) +getQuaternionAs object = do SomeQuaternion _ value <- getQuaternion object; maybe (bad "Quaternion component types differ") pure (cast value) +getDualQuaternionAs :: forall a. Coefficient a => Object -> IO (N.DualQuaternion a) +getDualQuaternionAs object = do SomeDualQuaternion _ value <- getDualQuaternion object; maybe (bad "DualQuaternion component types differ") pure (cast value) +makeQuaternion :: Object -> Object -> Object -> Object -> IO Object +makeQuaternion first second third fourth = do + SomeCoefficient witness (a :: a) <- getScalar first + b <- getAs second :: IO a; c <- getAs third; d <- getAs fourth + pure (QuaternionData (SomeQuaternion witness (N.Quaternion a b c d))) +makeDualQuaternion :: Object -> Object -> IO Object +makeDualQuaternion first second = do + SomeQuaternion witness (a :: N.Quaternion a) <- getQuaternion first + b <- getQuaternionAs second :: IO (N.Quaternion a) + pure (DualQuaternionData (SomeDualQuaternion witness (N.DualQuaternion a b))) +quaternionConjugate :: Object -> IO Object +quaternionConjugate object = do SomeQuaternion witness value <- getQuaternion object; pure (QuaternionData (SomeQuaternion witness (N.quaternionConjugate value))) +quaternionNorm :: Object -> IO Object +quaternionNorm object = do + SomeQuaternion witness (value :: N.Quaternion a) <- getQuaternion object + case realFloatDict (Proxy :: Proxy a) of Just Dict -> pure (scalar witness (N.quaternionNorm value)); Nothing -> unsupported "RealFloat Quaternion component required" +quaternionInverse :: Object -> IO (Either MathError Object) +quaternionInverse object = do + SomeQuaternion witness (value :: N.Quaternion a) <- getQuaternion object + case realFloatDict (Proxy :: Proxy a) of Just Dict -> pure (QuaternionData . SomeQuaternion witness <$> N.quaternionInverse value); Nothing -> unsupported "RealFloat Quaternion component required" +quaternionComponent :: CPtrdiff -> Object -> IO Object +quaternionComponent index object = do + SomeQuaternion witness (N.Quaternion a b c d) <- getQuaternion object + case index of 0 -> pure (scalar witness a); 1 -> pure (scalar witness b); 2 -> pure (scalar witness c); 3 -> pure (scalar witness d); _ -> bad "Quaternion component index" +dualQuaternionComponent :: CPtrdiff -> Object -> IO Object +dualQuaternionComponent index object = do + SomeDualQuaternion witness (N.DualQuaternion a b) <- getDualQuaternion object + case index of 0 -> pure (QuaternionData (SomeQuaternion witness a)); 1 -> pure (QuaternionData (SomeQuaternion witness b)); _ -> bad "DualQuaternion component index" + +makeLimits :: Object -> Object -> Object -> Object -> CPtrdiff -> CPtrdiff -> CPtrdiff -> IO Object +makeLimits a b c d digits lo hi = do + if any ((/= objectType a) . objectType) [b,c,d] then bad "NumericLimits field types differ" else pure () + pure (Limits (N.NumericLimits a b c d (fromIntegral digits) (fromIntegral lo) (fromIntegral hi))) +numericLimits :: Object -> IO Object +numericLimits object = do + SomeCoefficient witness (value :: a) <- getScalar object + case realFloatDict (Proxy :: Proxy a) of Just Dict -> pure (limits witness (N.numericLimits value)); Nothing -> unsupported "RealFloat witness required" + +readText :: Ptr Word32 -> CSize -> IO Object +readText dataPointer count = Text . map (chr . fromIntegral) <$> peekArray (fromIntegral count) dataPointer + +boundedCast :: Bool -> CInt -> Object -> IO (Either MathError Object) +boundedCast saturate target object = do + SomeCoefficient _ (value :: a) <- getScalar object + case integralDict (Proxy :: Proxy a) of + Nothing -> unsupported "Integral source required" + Just Dict -> boundedDestination target $ \witness -> + pure $ if saturate then Right (scalar witness (N.saturatingCast value)) else scalar witness <$> N.safeIntegralCast value + +boundedDestination :: CInt -> (forall a. (Coefficient a, Integral a, Bounded a) => ScalarType a -> IO r) -> IO r +boundedDestination target action = case target of + 6 -> action SInt8; 7 -> action SInt16; 8 -> action SInt32; 9 -> action SInt64 + 10 -> action SWord8; 11 -> action SWord16; 12 -> action SWord32; 13 -> action SWord64 + 14 -> action SInt; 15 -> action SWord + _ -> bad "bounded integral destination dtype required" + +realToIntegral :: N.RoundingMode -> CInt -> Object -> IO (Either MathError Object) +realToIntegral mode target object = do + SomeCoefficient _ (value :: a) <- getScalar object + case realFloatDict (Proxy :: Proxy a) of + Nothing -> unsupported "RealFloat source required" + Just Dict -> boundedDestination target $ \witness -> pure (scalar witness <$> N.realToIntegral mode value) + +narrowFloat :: CInt -> Object -> IO (Either MathError Object) +narrowFloat target object = do + SomeCoefficient _ (value :: a) <- getScalar object + case realFloatDict (Proxy :: Proxy a) of + Nothing -> unsupported "RealFloat source required" + Just Dict -> case target of + 0 -> pure (ndouble <$> N.narrowFloat value) + 1 -> pure (nfloat <$> N.narrowFloat value) + _ -> bad "Float or Double destination required" + +classify :: Object -> IO Object +classify object = do + SomeCoefficient _ (value :: a) <- getScalar object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> pure (Class (N.classify value)) + Nothing -> unsupported "RealFloat value required" +frexp :: Object -> IO Object +frexp object = do + SomeCoefficient witness (value :: a) <- getScalar object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> let (mantissa,power)=N.frexp value in pure (Sequence True "" [scalar witness mantissa,nint power]) + Nothing -> unsupported "RealFloat value required" +integerLimits :: Object -> IO Object +integerLimits object = do + SomeCoefficient _ (value :: a) <- getScalar object + case (integralDict (Proxy :: Proxy a), boundedDict (Proxy :: Proxy a)) of + (Just Dict,Just Dict) -> let (lo,hi)=N.integerLimits value in pure (Sequence True "" [ninteger lo,ninteger hi]) + _ -> unsupported "Bounded Integral witness required" + +makeRounded :: Object -> [N.NumericException] -> Object +makeRounded value flags = Rounded (N.Rounded value flags) +roundedValue :: Object -> IO Object +roundedValue (Rounded value) = pure (N.roundedValue value) +roundedValue _ = bad "expected Rounded" +numericalExceptions :: Object -> IO Object +numericalExceptions (Rounded value) = pure (Sequence False "NumericException" (map Flag (N.numericalExceptions value))) +numericalExceptions _ = bad "expected Rounded" +limitsField :: CInt -> Object -> IO Object +limitsField field (Limits value) = case field of + 0 -> pure (N.minimumNormal value); 1 -> pure (N.minimumSubnormal value); 2 -> pure (N.maximumFinite value); 3 -> pure (N.machineEpsilon value) + 4 -> pure (nint (N.significandDigits value)); 5 -> pure (nint (N.minimumExponent value)); 6 -> pure (nint (N.maximumExponent value)); _ -> bad "invalid NumericLimits field" +limitsField _ _ = bad "expected NumericLimits" + +constantAs :: CInt -> Object -> IO Object +constantAs target object = do + value <- getConstant object + case target of + 0 -> pure (ndouble (K.constantAs value)) + 1 -> pure (nfloat (K.constantAs value)) + 3 -> pure (nrational (K.constantAs value)) + 4 -> pure (scalar SComplexDouble (K.constantAs value)) + 5 -> pure (scalar SComplexFloat (K.constantAs value)) + _ -> bad "constantAs requires a supported Fractional dtype" + +constantAsLike :: Object -> Object -> IO Object +constantAsLike prototype object = do + value <- getConstant object + SomeCoefficient witness (_ :: a) <- getScalar prototype + case fractionalDict (Proxy :: Proxy a) of + Just Dict -> pure (scalar witness (K.constantAs value :: a)) + Nothing -> unsupported "constantAs requires a Fractional prototype" + +getVector :: forall a. Coefficient a => Object -> Object -> Object -> IO (a,a,a) +getVector x y z = (,,) <$> getAs x <*> getAs y <*> getAs z +vectorObject :: Coefficient a => ScalarType a -> (a,a,a) -> Object +vectorObject witness (x,y,z) = Sequence True "" [scalar witness x,scalar witness y,scalar witness z] +rotateVector :: Object -> Object -> Object -> Object -> IO (Either MathError Object) +rotateVector object x y z = do + SomeQuaternion witness (value :: N.Quaternion a) <- getQuaternion object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> do vector <- getVector x y z :: IO (a,a,a); pure (vectorObject witness <$> N.rotateVector value vector) + Nothing -> unsupported "RealFloat Quaternion component required" +rigidTransform :: Object -> Object -> Object -> Object -> IO (Either MathError Object) +rigidTransform object x y z = do + SomeQuaternion witness (value :: N.Quaternion a) <- getQuaternion object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> do vector <- getVector x y z :: IO (a,a,a); pure (DualQuaternionData . SomeDualQuaternion witness <$> N.rigidTransform value vector) + Nothing -> unsupported "RealFloat Quaternion component required" +transformPoint :: Object -> Object -> Object -> Object -> IO (Either MathError Object) +transformPoint object x y z = do + SomeDualQuaternion witness (value :: N.DualQuaternion a) <- getDualQuaternion object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> do vector <- getVector x y z :: IO (a,a,a); pure (vectorObject witness <$> N.transformPoint value vector) + Nothing -> unsupported "RealFloat DualQuaternion component required" +dualQuaternionMultiply :: Object -> Object -> IO Object +dualQuaternionMultiply first second = do + SomeDualQuaternion witness (value :: N.DualQuaternion a) <- getDualQuaternion first + other <- getDualQuaternionAs second :: IO (N.DualQuaternion a) + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> pure (DualQuaternionData (SomeDualQuaternion witness (N.dualQuaternionMultiply value other))) + Nothing -> unsupported "RealFloat DualQuaternion component required" +dualQuaternionInverse :: Object -> IO (Either MathError Object) +dualQuaternionInverse object = do + SomeDualQuaternion witness (value :: N.DualQuaternion a) <- getDualQuaternion object + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> pure (DualQuaternionData . SomeDualQuaternion witness <$> N.dualQuaternionInverse value) + Nothing -> unsupported "RealFloat DualQuaternion component required" + +literalInteger :: Object -> Integer -> IO Object +literalInteger object integer = do SomeCoefficient witness (_ :: a) <- getScalar object; pure (scalar witness (fromInteger integer :: a)) +literalRational :: Object -> Rational -> IO Object +literalRational object rational = do + SomeCoefficient witness (_ :: a) <- getScalar object + case fractionalDict (Proxy :: Proxy a) of Just Dict -> pure (scalar witness (fromRational rational :: a)); Nothing -> unsupported "Fractional instance unavailable" + +integerPower :: Object -> Integer -> IO Object +integerPower object power = do + SomeCoefficient witness (value :: a) <- getScalar object + if power >= 0 then pure (scalar witness (value ^ power)) else + case fractionalDict (Proxy :: Proxy a) of + Just Dict -> pure (scalar witness (value ^^ power)) + Nothing -> unsupported "negative exponent requires a Fractional instance" + +sequenceItem :: CPtrdiff -> Object -> IO Object +sequenceItem index (Sequence _ _ values) + | index < 0 || toInteger index >= toInteger (length values) = throwIO (BindingError 8 "sequence index out of bounds") + | otherwise = pure (values !! fromIntegral index) +sequenceItem _ _ = bad "expected sequence" + +makeConstant :: Object -> Object -> Object -> Object -> Object -> Object -> IO Object +makeConstant name value uncertainty approximation unit source = do + name' <- getText name; value' <- getRational value + uncertainty' <- getRational uncertainty; approximation' <- getRational approximation + unit' <- getText unit; source' <- getText source + pure (Constant (K.Constant name' value' uncertainty' approximation' unit' source')) +constantField :: CInt -> Object -> IO Object +constantField field object = do + value <- getConstant object + case field of + 0 -> pure (Text (K.constantName value)); 1 -> pure (nrational (K.constantValue value)) + 2 -> pure (nrational (K.standardUncertainty value)); 3 -> pure (nrational (K.approximationBound value)) + 4 -> pure (Text (K.constantUnit value)); 5 -> pure (Text (K.constantSource value)) + _ -> bad "invalid Constant field" + +instance Eq Object where + Scalar (SomeCoefficient _ a) == Scalar (SomeCoefficient _ b) = maybe False (a ==) (cast b) + Half a == Half b = a == b + BHalf a == BHalf b = a == b + Big a == Big b = a == b + Fixed a == Fixed b = a == b + Decimal a == Decimal b = a == b + Interval a == Interval b = a == b + Rounded a == Rounded b = a == b + Limits a == Limits b = a == b + Constant a == Constant b = a == b + Sequence tuple element a == Sequence tuple' element' b = tuple == tuple' && element == element' && a == b + Class a == Class b = a == b + Flag a == Flag b = a == b + Boolean a == Boolean b = a == b + Text a == Text b = a == b + QuaternionData (SomeQuaternion _ a) == QuaternionData (SomeQuaternion _ b) = maybe False (a ==) (cast b) + DualQuaternionData (SomeDualQuaternion _ a) == DualQuaternionData (SomeDualQuaternion _ b) = maybe False (a ==) (cast b) + Raw V.None == Raw V.None = True + Raw (V.Dense (V.SomeMatrix _ a)) == Raw (V.Dense (V.SomeMatrix _ b)) = maybe False (a ==) (cast b) + Raw _ == Raw _ = throw (BindingError 10 "Eq dictionary unavailable for foreign opaque values") + _ == _ = False + +-- The callback runs only when the original Numeric.derivative evaluates its +-- supplied function. Its immutable argument/result are actual Numeric.Duals. +type NumericCallback = Ptr () -> Ptr () -> Ptr (Ptr ()) -> IO CInt +foreign import ccall safe "hm_numeric_types_invoke" + invokeCallback :: FunPtr NumericCallback -> Ptr () -> Handle -> Ptr (Handle) -> IO CInt + +callbackObject :: FunPtr NumericCallback -> Ptr () -> Object -> IO Object +callbackObject callback userdata input = do + forceObject input + pointer <- newStablePtr (sharedObject input) + -- C consumes pointer on every path; on success it returns a new stable + -- reference cloned before releasing the callback's transferred result. + alloca $ \out -> do + code <- invokeCallback callback userdata pointer out + -- Preserve the callback's thread-local structured MathError payload. + -- Reporting a new generic error here would erase that original record. + if code /= 0 then throwIO (CallbackStatus code) else pure () + result <- peek out + bracket (pure result) freeStablePtr dereference + +derivative :: FunPtr NumericCallback -> Ptr () -> Object -> IO Object +derivative callback userdata object = do + SomeCoefficient witness (value :: a) <- getScalar object + let function dual = unsafePerformIO $ do + result <- callbackObject callback userdata (scalar (SDual witness) dual) + getAs result :: IO (N.Dual a) + pure (scalar witness (N.derivative function value)) +getHalf :: Object -> IO N.Float16 +getHalf (Half value) = pure value +getHalf _ = bad "expected Float16" +getBHalf :: Object -> IO N.BFloat16 +getBHalf (BHalf value) = pure value +getBHalf _ = bad "expected BFloat16" + + +type Handle = StablePtr V.Value + +dereference :: Handle -> IO Object +dereference pointer = deRefStablePtr pointer >>= objectFromShared + +objectFromShared :: V.Value -> IO Object +objectFromShared value = case value of + V.Scalar witness number -> pure (scalar witness number) + V.Index number -> pure (nint number) + V.Boolean result -> pure (Boolean result) + V.Text text -> pure (Text text) + V.List values -> Sequence False "" <$> mapM objectFromShared values + V.Tuple values -> Sequence True "" <$> mapM objectFromShared values + V.Opaque kind _ _ _ payload | kind >= 40 && kind <= 59 -> maybe (bad "NumericTypes payload mismatch") pure (cast payload) + _ -> pure (Raw value) + +sharedObject :: Object -> V.Value +sharedObject object = case object of + Raw value -> value + Scalar (SomeCoefficient witness number) -> V.Scalar witness number + Boolean result -> V.Boolean result + Text text -> V.Text text + Sequence tuple _ values -> (if tuple then V.Tuple else V.List) (map sharedObject values) + QuaternionData (SomeQuaternion witness (value :: N.Quaternion a)) -> + case realFloatDict (Proxy :: Proxy a) of + Just Dict -> V.Scalar (SQuaternion witness) value + Nothing -> opaque 52 object + Half _ -> opaque 40 object + BHalf _ -> opaque 41 object + Big _ -> opaque 42 object + Fixed _ -> opaque 43 object + Decimal _ -> opaque 44 object + Interval _ -> opaque 45 object + Rounded _ -> opaque 46 object + Limits _ -> opaque 47 object + Constant _ -> opaque 48 object + Class _ -> opaque 49 object + Flag _ -> opaque 50 object + DualQuaternionData _ -> opaque 53 object + where + opaque kind payload = V.Opaque kind (-1) 0 (forceObject payload) payload + +foreign export ccall "hm_numeric_types_enum_value" enumValue :: Handle -> Ptr CInt -> IO CInt +enumValue :: Handle -> Ptr CInt -> IO CInt +enumValue pointer out = numericBoundary $ do + object <- dereference pointer + value <- case object of Class x -> pure (classCode x); Flag x -> pure (exceptionCode x); _ -> bad "expected IEEEClass or NumericException" + checked (Right value) (poke out) + +-- | Equality transport for generic Eq callers. Existing source records retain +-- their original Eq dictionaries; opaque generic fields recurse through the +-- caller's native value equality resolver, avoiding a dependency cycle. +equalValueWith :: (V.Value -> V.Value -> IO Bool) -> V.Value -> V.Value -> IO Bool +equalValueWith recurse left right = do + a <- objectFromShared left + b <- objectFromShared right + equalObjectWith recurse a b + +data EqualityObject = EqualityObject (Object -> Object -> IO Bool) Object +instance Eq EqualityObject where + EqualityObject compareObject a == EqualityObject _ b = unsafePerformIO(compareObject a b) + +equalObjectWith :: (V.Value -> V.Value -> IO Bool) -> Object -> Object -> IO Bool +equalObjectWith recurse left right = case(left,right)of + (Scalar(SomeCoefficient _ a),Scalar(SomeCoefficient _ b)) -> maybe (V.invalid "numeric equality coefficient types differ") (pure . (a==)) (cast b) + (Half a,Half b) -> pure(a==b) + (BHalf a,BHalf b) -> pure(a==b) + (Big a,Big b) -> pure(a==b) + (Fixed a,Fixed b) -> pure(a==b) + (Decimal a,Decimal b) -> pure(a==b) + (Interval a,Interval b) -> pure(a==b) + (Rounded a,Rounded b) -> pure(mapRounded a==mapRounded b) + (Limits a,Limits b) -> pure(mapLimits a==mapLimits b) + (Constant a,Constant b) -> pure(a==b) + (Class a,Class b) -> pure(a==b) + (Flag a,Flag b) -> pure(a==b) + (Boolean a,Boolean b) -> pure(a==b) + (Text a,Text b) -> pure(a==b) + (Sequence tuple _ a,Sequence other _ b) + | tuple==other -> pure(map field a==map field b) + | otherwise -> V.invalid "numeric equality sequence types differ" + (QuaternionData(SomeQuaternion _ a),QuaternionData(SomeQuaternion _ b)) -> maybe (V.invalid "numeric quaternion equality coefficient types differ") (pure . (a==)) (cast b) + (DualQuaternionData(SomeDualQuaternion _ a),DualQuaternionData(SomeDualQuaternion _ b)) -> maybe (V.invalid "numeric dual-quaternion equality coefficient types differ") (pure . (a==)) (cast b) + (Raw a,Raw b) -> recurse a b + _ -> V.invalid "numeric equality source types differ" + where + field=EqualityObject(equalObjectWith recurse) + mapRounded value=N.Rounded(field(N.roundedValue value))(N.numericalExceptions value) + mapLimits value=N.NumericLimits(field(N.minimumNormal value))(field(N.minimumSubnormal value))(field(N.maximumFinite value))(field(N.machineEpsilon value))(N.significandDigits value)(N.minimumExponent value)(N.maximumExponent value) diff --git a/src/HMath/FFI/NumericalAll.hs b/src/HMath/FFI/NumericalAll.hs new file mode 100644 index 0000000..9740d52 --- /dev/null +++ b/src/HMath/FFI/NumericalAll.hs @@ -0,0 +1,274 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated representation adapters; numerical functions are the originals. +module HMath.FFI.NumericalAll where +import Foreign +import Foreign.C +import qualified HMath.FFI.Boundary as B +import HMath.FFI.NumericalCodec +import qualified HMath.FFI.Value as V +import qualified HMath.Calculus as C +import qualified HMath.Root as R +import qualified HMath.ODE as O +import qualified HMath.PDE as P +instance From C.Tolerance where from = unbox 201 +instance To C.Tolerance where + to value = pure (box 201 value [to (C.absoluteTolerance value),to (C.relativeTolerance value),to (C.maximumEvaluations value)]) +instance From C.Difference where from = unbox 202 +instance To C.Difference where + to value = pure (box 202 value []) +instance From C.Quadrature where from = unbox 203 +instance To C.Quadrature where + to value = pure (box 203 value []) +instance From R.RootOptions where from = unbox 204 +instance To R.RootOptions where + to value = pure (box 204 value [to (R.rootMaxIterations value),to (R.rootMaxEvaluations value),to (R.rootTolerance value),to (R.rootStepTolerance value)]) +instance From R.RootResult where from = unbox 205 +instance To R.RootResult where + to value = pure (box 205 value [to (R.rootValue value),to (R.rootResidual value),to (R.rootErrorBound value),to (R.rootIterations value),to (R.rootEvaluations value)]) +instance From R.Bracket where from = unbox 206 +instance To R.Bracket where + to value = pure (box 206 value []) +instance From R.BracketMethod where from = unbox 207 +instance To R.BracketMethod where + to value = pure (box 207 value []) +instance From R.DerivativeMethod where from = unbox 208 +instance To R.DerivativeMethod where + to value = pure (box 208 value []) +instance From R.FixedPointMethod where from = unbox 209 +instance To R.FixedPointMethod where + to value = pure (box 209 value []) +instance From R.SystemMethod where from = unbox 210 +instance To R.SystemMethod where + to value = pure (box 210 value []) +instance From R.SystemRootResult where from = unbox 211 +instance To R.SystemRootResult where + to value = pure (box 211 value [to (R.systemRoot value),to (R.systemResidual value),to (R.systemIterations value),to (R.systemEvaluations value)]) +instance From O.Method where from = unbox 212 +instance To O.Method where + to value = pure (box 212 value []) +instance From O.ODEOptions where from = unbox 213 +instance To O.ODEOptions where + to value = pure (box 213 value [to (O.odeAbsoluteTolerance value),to (O.odeRelativeTolerance value),to (O.initialStep value),to (O.minimumStep value),to (O.maximumStep value),to (O.maximumSteps value),to (O.newtonIterations value)]) +instance From O.Trajectory where from = unbox 214 +instance To O.Trajectory where + to value = pure (box 214 value [to (O.trajectoryTimes value),to (O.trajectoryStates value),to (O.trajectoryDerivatives value)]) +instance From O.EventDirection where from = unbox 215 +instance To O.EventDirection where + to value = pure (box 215 value []) +instance From O.Event where from = unbox 216 +instance To O.Event where + to value = pure (box 216 value [to (O.eventTime value),to (O.eventState value)]) +instance From O.HamiltonianMethod where from = unbox 217 +instance To O.HamiltonianMethod where + to value = pure (box 217 value []) +instance From P.Grid where from = unbox 218 +instance To P.Grid where + to value = pure (box 218 value [to (P.gridShape value),to (P.gridSpacing value)]) +instance From P.Boundary where from = unbox 219 +instance To P.Boundary where + to value = pure (box 219 value []) +instance From P.Discretization where from = unbox 220 +instance To P.Discretization where + to value = pure (box 220 value []) +instance From P.PDEOperator where from = unbox 221 +instance To P.PDEOperator where + to value = pure (box 221 value [to (P.pdeStiffness value),to (P.pdeMass value),to (P.pdeBoundaryLoad value)]) +instance From P.PDEResult where from = unbox 222 +instance To P.PDEResult where + to value = pure (box 222 value [to (P.pdeValues value),to (P.pdeResidual value),to (P.pdeErrorEstimate value)]) +foreign export ccall "hm_numerical_apply" dispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +dispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +dispatch operation input arity out = B.boundary $ do + values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr + result <- case operation of + 0 -> apply (C.Estimate :: V.Value -> Double -> Int -> C.Estimate V.Value) values + 1 -> apply (C.estimateValue :: C.Estimate V.Value -> V.Value) values + 2 -> apply (C.estimateError :: C.Estimate V.Value -> Double) values + 3 -> apply (C.evaluations :: C.Estimate V.Value -> Int) values + 4 -> apply C.Tolerance values + 5 -> apply C.absoluteTolerance values + 6 -> apply C.relativeTolerance values + 7 -> apply C.maximumEvaluations values + 8 -> apply C.defaultTolerance values + 9 -> apply C.Forward values + 10 -> apply C.Backward values + 11 -> apply C.Central values + 12 -> apply C.Trapezoidal values + 13 -> apply C.Simpson values + 14 -> apply C.ThreeEighths values + 15 -> apply C.derivative values + 16 -> apply C.derivativeN values + 17 -> apply C.complexDerivative values + 18 -> apply C.richardson values + 19 -> apply C.ridders values + 20 -> apply C.limit values + 21 -> apply C.partialDerivative values + 22 -> apply C.gradient values + 23 -> apply C.jacobian values + 24 -> apply C.hessian values + 25 -> apply C.directionalDerivative values + 26 -> apply C.jvp values + 27 -> apply C.vjp values + 28 -> apply C.hvp values + 29 -> apply C.divergence values + 30 -> apply C.curl values + 31 -> apply C.laplacian values + 32 -> apply C.integrateComposite values + 33 -> apply C.romberg values + 34 -> apply C.gaussLegendre values + 35 -> apply C.gaussHermite values + 36 -> apply C.gaussLaguerre values + 37 -> apply C.gaussChebyshev values + 38 -> apply C.gaussKronrod values + 39 -> apply C.adaptiveIntegrate values + 40 -> apply C.clenshawCurtis values + 41 -> apply C.tanhSinh values + 42 -> apply C.integrateInfinite values + 43 -> apply C.integrateOscillatory values + 44 -> apply C.integrateND values + 45 -> apply C.monteCarlo values + 46 -> apply C.quasiMonteCarlo values + 47 -> apply C.cumulativeIntegral values + 48 -> apply C.pathIntegral values + 49 -> apply C.lineIntegral values + 50 -> apply C.surfaceIntegral values + 51 -> apply C.volumeIntegral values + 52 -> apply R.RootOptions values + 53 -> apply R.rootMaxIterations values + 54 -> apply R.rootMaxEvaluations values + 55 -> apply R.rootTolerance values + 56 -> apply R.rootStepTolerance values + 57 -> apply R.defaultRootOptions values + 58 -> apply R.RootResult values + 59 -> apply R.rootValue values + 60 -> apply R.rootResidual values + 61 -> apply R.rootErrorBound values + 62 -> apply R.rootIterations values + 63 -> apply R.rootEvaluations values + 64 -> apply R.Bisection values + 65 -> apply R.RegulaFalsi values + 66 -> apply R.Illinois values + 67 -> apply R.Brent values + 68 -> apply R.Ridder values + 69 -> apply R.Newton values + 70 -> apply R.Halley values + 71 -> apply R.Householder3 values + 72 -> apply R.Picard values + 73 -> apply R.Aitken values + 74 -> apply R.SteffensenFixed values + 75 -> apply R.MultivariateNewton values + 76 -> apply R.NewtonTrustRegion values + 77 -> apply R.Broyden values + 78 -> apply R.SystemRootResult values + 79 -> apply R.systemRoot values + 80 -> apply R.systemResidual values + 81 -> apply R.systemIterations values + 82 -> apply R.systemEvaluations values + 83 -> apply R.bracket values + 84 -> apply R.solveBracket values + 85 -> apply R.bracketScan values + 86 -> apply R.isolateIntervals values + 87 -> apply R.solveDerivative values + 88 -> apply R.secant values + 89 -> apply R.steffensen values + 90 -> apply R.fixedPoint values + 91 -> apply R.anderson values + 92 -> apply R.solveSystem values + 93 -> apply R.polynomialRoots values + 94 -> apply R.realPolynomialRoots values + 95 -> apply O.Euler values + 96 -> apply O.Heun values + 97 -> apply O.Midpoint values + 98 -> apply O.RK2 values + 99 -> apply O.RK4 values + 100 -> apply O.RK23 values + 101 -> apply O.RK45 values + 102 -> apply O.DormandPrince values + 103 -> apply O.DOP853 values + 104 -> apply O.AdamsBashforth values + 105 -> apply O.AdamsMoulton values + 106 -> apply O.PredictorCorrector values + 107 -> apply O.BackwardEuler values + 108 -> apply O.BDF values + 109 -> apply O.Radau values + 110 -> apply O.Rosenbrock values + 111 -> apply O.ODEOptions values + 112 -> apply O.odeAbsoluteTolerance values + 113 -> apply O.odeRelativeTolerance values + 114 -> apply O.initialStep values + 115 -> apply O.minimumStep values + 116 -> apply O.maximumStep values + 117 -> apply O.maximumSteps values + 118 -> apply O.newtonIterations values + 119 -> apply O.defaultODEOptions values + 120 -> apply O.Trajectory values + 121 -> apply O.trajectoryTimes values + 122 -> apply O.trajectoryStates values + 123 -> apply O.trajectoryDerivatives values + 124 -> apply O.solveIVP values + 125 -> apply O.solveAdaptive values + 126 -> apply O.interpolateTrajectory values + 127 -> apply O.AnyDirection values + 128 -> apply O.Rising values + 129 -> apply O.Falling values + 130 -> apply O.Event values + 131 -> apply O.eventTime values + 132 -> apply O.eventState values + 133 -> apply O.locateEvents values + 134 -> apply O.solveBoundary values + 135 -> apply O.solveDAE values + 136 -> apply O.SymplecticEuler values + 137 -> apply O.Verlet values + 138 -> apply O.Leapfrog values + 139 -> apply O.solveHamiltonian values + 140 -> apply O.solveNystrom values + 141 -> apply O.sensitivities values + 142 -> apply O.equilibrium values + 143 -> apply O.phaseTrajectories values + 144 -> apply O.lyapunovExponents values + 145 -> apply P.Dirichlet values + 146 -> apply P.Neumann values + 147 -> apply P.Robin values + 148 -> apply P.Periodic values + 149 -> apply P.FiniteDifference values + 150 -> apply P.FiniteVolume values + 151 -> apply P.FiniteElement values + 152 -> apply P.PDEResult values + 153 -> apply P.pdeValues values + 154 -> apply P.pdeResidual values + 155 -> apply P.pdeErrorEstimate values + 156 -> apply P.grid values + 157 -> apply P.gridShape values + 158 -> apply P.gridSpacing values + 159 -> apply P.flattenIndex values + 160 -> apply P.unflattenIndex values + 161 -> apply P.gridCoordinates values + 162 -> apply P.assemblePDE values + 163 -> apply P.pdeStiffness values + 164 -> apply P.pdeMass values + 165 -> apply P.pdeBoundaryLoad values + 166 -> apply P.solveElliptic values + 167 -> apply P.poisson values + 168 -> apply P.laplace values + 169 -> apply P.helmholtz values + 170 -> apply P.spatialGradient values + 171 -> apply P.laplacianStencil values + 172 -> apply P.spectralDerivative values + 173 -> apply P.spectralLaplacian values + 174 -> apply P.spectralPoisson values + 175 -> apply P.pseudoSpectralDiffusion values + 176 -> apply P.methodOfLines values + 177 -> apply P.heat values + 178 -> apply P.diffusion values + 179 -> apply P.wave values + 180 -> apply P.advection values + 181 -> apply P.advectionDiffusion values + 182 -> apply P.stabilityLimit values + 183 -> apply P.cflNumber values + 184 -> apply P.manufacturedError values + _ -> V.invalid "unknown numerical operation" + V.forceValue result + B.checked (Right ()) (\_ -> V.publish result out) diff --git a/src/HMath/FFI/NumericalCodec.hs b/src/HMath/FFI/NumericalCodec.hs new file mode 100644 index 0000000..d7c0967 --- /dev/null +++ b/src/HMath/FFI/NumericalCodec.hs @@ -0,0 +1,139 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE UndecidableInstances #-} + +-- SPDX-License-Identifier: MPL-2.0 +-- | Typed representation and callbacks; numerical algorithms remain in HMath. +module HMath.FFI.NumericalCodec where + +import Control.Exception (catch, evaluate, throwIO) +import Data.Complex (Complex) +import Data.Typeable (Typeable, cast) +import Data.Word (Word64) +import System.IO.Unsafe (unsafePerformIO) +import HMath.Error (MathError) +import HMath.FFI.Coefficient +import HMath.FFI.MathError (CallbackFailure(..)) +import qualified HMath.FFI.GraphCodec as W +import qualified HMath.FFI.LinearCodec as L +import qualified HMath.FFI.Polynomial as P +import qualified HMath.FFI.Value as V +import qualified HMath.Matrix as M +import qualified HMath.Polynomial as Polynomial +import qualified HMath.Sparse as S +import qualified HMath.Calculus as C + +class From a where from :: V.Value -> IO a +class To a where to :: a -> IO V.Value + +instance From V.Value where from = pure +instance To V.Value where to = pure +instance From Double where from = V.asScalar +instance To Double where to = pure . V.Scalar SDouble +instance From Rational where from = V.asScalar +instance To Rational where to = pure . V.Scalar SRational +instance From Integer where from = V.asScalar +instance To Integer where to = pure . V.Scalar SInteger +instance From Word64 where from = W.unwire +instance To Word64 where to = pure . V.Scalar SWord64 +instance From (Complex Double) where from = V.asScalar +instance To (Complex Double) where to = pure . V.Scalar SComplexDouble +instance From Int where from = V.asIndex +instance To Int where to = pure . V.Index +instance From Bool where from = V.asBoolean +instance To Bool where to = pure . V.Boolean +instance From () where from value = V.asTuple 0 value >> pure () +instance To () where to () = pure (V.Tuple []) +instance {-# OVERLAPPING #-} From String where from = V.asText +instance {-# OVERLAPPING #-} To String where to = pure . V.Text +instance {-# OVERLAPPABLE #-} From a => From [a] where from value = V.asList value >>= mapM from +instance {-# OVERLAPPABLE #-} To a => To [a] where to values = V.List <$> mapM to values +instance From a => From (Maybe a) where + from V.None = pure Nothing + from value = Just <$> from value +instance To a => To (Maybe a) where to = maybe (pure V.None) to +instance To a => To (Either MathError a) where + to (Left errorValue) = throwIO (CallbackMathError errorValue) + to (Right value) = to value +instance (From a,From b) => From (a,b) where + from value = do + fields <- V.asTuple 2 value + case fields of + [a,b] -> (,) <$> from a <*> from b + _ -> V.invalid "numerical pair arity differs" +instance (To a,To b) => To (a,b) where to (a,b) = V.Tuple <$> sequence [to a,to b] +instance (From a,From b,From c) => From (a,b,c) where + from value = do + fields <- V.asTuple 3 value + case fields of + [a,b,c] -> (,,) <$> from a <*> from b <*> from c + _ -> V.invalid "numerical triple arity differs" +instance (To a,To b,To c) => To (a,b,c) where to (a,b,c) = V.Tuple <$> sequence [to a,to b,to c] +instance From (M.Matrix Double) where from = L.asMatrix +instance To (M.Matrix Double) where to = pure . V.Dense . V.SomeMatrix SDouble +instance From (S.Sparse Double) where from = L.unbox "HMath.Sparse.Sparse" +instance To (S.Sparse Double) where to = L.encodeSparse SDouble +instance From (Polynomial.Polynomial Rational) where from = P.asPolynomial +instance To (Polynomial.Polynomial Rational) where to = pure . P.poly SRational +instance From (Polynomial.Polynomial (Complex Double)) where from = P.asPolynomial +instance To (Polynomial.Polynomial (Complex Double)) where to = pure . P.poly SComplexDouble + +-- Estimate's public parameter remains arbitrary: preserve its payload as an +-- original Estimate Value rather than imposing a floating-point conversion. +instance From a => From (C.Estimate a) where + from value = do + original <- unbox 200 value :: IO (C.Estimate V.Value) + payload <- from (C.estimateValue original) + pure (C.Estimate payload (C.estimateError original) (C.evaluations original)) +instance To a => To (C.Estimate a) where + to original = do + payload <- to (C.estimateValue original) + let value = C.Estimate payload (C.estimateError original) (C.evaluations original) + pure (box 200 value [pure payload,to (C.estimateError original),to (C.evaluations original)]) + +box :: Typeable a => Int -> a -> [IO V.Value] -> V.Value +box kind value fields = V.Opaque kind (-1) 0 force value + where + force = evaluate value >> sequence fields >>= mapM_ V.forceValue +unbox :: Typeable a => Int -> V.Value -> IO a +unbox kind (V.Opaque actual _ _ _ value) + | actual == kind = maybe (V.invalid "numerical payload type differs") pure (cast value) +unbox _ _ = V.invalid "numerical object kind differs" + +class Apply a where apply :: a -> [V.Value] -> IO V.Value +instance {-# OVERLAPPABLE #-} To a => Apply a where + apply value [] = to value + apply _ _ = V.invalid "too many numerical arguments" +instance {-# OVERLAPPING #-} (From a,Apply b) => Apply (a -> b) where + apply operation (value:rest) = from value >>= \argument -> apply (operation argument) rest + apply _ [] = V.invalid "missing numerical argument" + +-- Curried Haskell callbacks use a flat tuple of positional arguments in C. +-- Only an actual source Either recovers MathError into Left. Other failures +-- unwind to the outer native boundary after all borrowed handles are freed. +class Function a where function :: V.Value -> [IO V.Value] -> a +instance {-# OVERLAPPABLE #-} From a => Function a where + function = pureCallbackResult +instance {-# OVERLAPPING #-} (To a,Function b) => Function (a -> b) where + function callback arguments argument = function callback (arguments ++ [to argument]) +instance {-# OVERLAPPING #-} From a => Function (Either MathError a) where + function callback arguments = unsafePerformIO $ + (Right <$> (callbackResult callback arguments >>= from)) `catch` recover + where + recover (CallbackMathError errorValue) = pure (Left errorValue) + recover other = throwIO other +instance {-# OVERLAPPING #-} (To a,Function b) => From (a -> b) where + from callback = pure (function callback []) + +{-# NOINLINE callbackResult #-} +callbackResult :: V.Value -> [IO V.Value] -> IO V.Value +callbackResult callback arguments = do + input <- V.Tuple <$> sequence arguments + V.forceValue input + L.callbackValue callback input + +{-# NOINLINE pureCallbackResult #-} +pureCallbackResult :: From a => V.Value -> [IO V.Value] -> a +pureCallbackResult callback arguments = unsafePerformIO (callbackResult callback arguments >>= from) diff --git a/src/HMath/FFI/OptimizationAll.hs b/src/HMath/FFI/OptimizationAll.hs new file mode 100644 index 0000000..ef3890b --- /dev/null +++ b/src/HMath/FFI/OptimizationAll.hs @@ -0,0 +1,311 @@ +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Original optimization functions with typed value/record/callback adapters. +module HMath.FFI.OptimizationAll where +import Control.Exception (bracket, bracketOnError, evaluate, throwIO) +import Data.Typeable (Typeable, cast) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import HMath.Error (MathError) +import HMath.FFI.Boundary +import HMath.FFI.MathError +import HMath.FFI.Coefficient (ScalarType (SDouble,SWord64)) +import HMath.FFI.Value (Value (..), asIndex, asList, asScalar, invalid, publish, forceValue) +import qualified HMath.Optimization.Common as C +import qualified HMath.Optimization.FirstOrder as F +import qualified HMath.Optimization.Local as L +import qualified HMath.Optimization.Constrained as K +import qualified HMath.Optimization.Global as G + +class FromValue a where fromValue :: Value -> IO a +class ToValue a where toValue :: a -> IO Value +instance FromValue Value where fromValue = pure +instance ToValue Value where toValue = pure +instance FromValue Double where fromValue = asScalar +instance ToValue Double where toValue = pure . Scalar SDouble +instance FromValue Int where fromValue = asIndex +instance ToValue Int where toValue = pure . Index +instance FromValue Word64 where fromValue = asScalar +instance ToValue Word64 where toValue = pure . Scalar SWord64 +instance FromValue Bool where + fromValue (Boolean value) = pure value + fromValue _ = invalid "expected Bool" +instance ToValue Bool where toValue = pure . Boolean +instance ToValue () where toValue () = pure None +instance (FromValue a) => FromValue [a] where fromValue value = asList value >>= mapM fromValue +instance (ToValue a) => ToValue [a] where toValue values = List <$> mapM toValue values +instance (FromValue a) => FromValue (Maybe a) where + fromValue None = pure Nothing + fromValue value = Just <$> fromValue value +instance (ToValue a) => ToValue (Maybe a) where toValue = maybe (pure None) toValue +instance (ToValue a) => ToValue (Either MathError a) where + toValue (Left err) = throwIO (CallbackMathError err) + toValue (Right value) = toValue value +instance (ToValue a,ToValue b) => ToValue (a,b) where toValue (a,b) = Tuple <$> sequence [toValue a,toValue b] +instance (ToValue a,ToValue b,ToValue c,ToValue d) => ToValue (a,b,c,d) where + toValue (a,b,c,d) = Tuple <$> sequence [toValue a,toValue b,toValue c,toValue d] + +opaque :: Typeable a => Int -> Int -> a -> IO () -> Value +opaque kind count value force = Opaque kind (-1) count force value +unbox :: forall a. Typeable a => Int -> Value -> IO a +unbox kind (Opaque actual _ _ _ value) | kind == actual = maybe (invalid "optimization object type differs") pure (cast value) +unbox _ _ = invalid "optimization object kind differs" +forceFields :: [IO Value] -> IO () +forceFields fields = sequence fields >>= mapM_ forceValue + +instance FromValue C.OptimizeOptions where fromValue = unbox 20 +instance ToValue C.OptimizeOptions where + toValue value = pure (opaque 20 4 value (forceFields [toValue(C.optMaxIterations value),toValue(C.optMaxEvaluations value),toValue(C.optTolerance value),toValue(C.optLearningRate value)])) +instance FromValue C.OptimizeResult where fromValue = unbox 21 +instance ToValue C.OptimizeResult where + toValue value = pure (opaque 21 6 value (forceFields [toValue(C.optPoint value),toValue(C.optValue value),toValue(C.optGradientNorm value),toValue(C.optIterations value),toValue(C.optEvaluations value),toValue(C.optConverged value)])) +instance FromValue K.LPResult where fromValue = unbox 22 +instance ToValue K.LPResult where + toValue value = pure (opaque 22 4 value (forceFields [toValue(K.lpPoint value),toValue(K.lpValue value),toValue(K.lpBasis value),toValue(K.lpIterations value)])) +instance FromValue C.LearningRate where fromValue = unbox 23 +instance ToValue C.LearningRate where toValue value = pure (opaque 23 0 value (evaluate value >> pure ())) +instance FromValue C.EarlyStopping where fromValue = unbox 24 +instance ToValue C.EarlyStopping where + toValue value = pure (opaque 24 3 value (forceFields [toValue(C.bestScore value),toValue(C.staleSteps value),toValue(C.stopped value)])) +instance FromValue F.GradientMethod where fromValue = unbox 25 +instance ToValue F.GradientMethod where toValue value = pure (opaque 25 0 value (evaluate value >> pure ())) +instance FromValue L.ScalarMethod where fromValue = unbox 26 +instance ToValue L.ScalarMethod where toValue value = pure (opaque 26 0 value (evaluate value >> pure ())) +instance FromValue L.QuasiNewton where fromValue = unbox 27 +instance ToValue L.QuasiNewton where toValue value = pure (opaque 27 0 value (evaluate value >> pure ())) +instance FromValue L.NewtonMethod where fromValue = unbox 28 +instance ToValue L.NewtonMethod where toValue value = pure (opaque 28 0 value (evaluate value >> pure ())) +instance FromValue L.LeastSquaresLoss where fromValue = unbox 29 +instance ToValue L.LeastSquaresLoss where toValue value = pure (opaque 29 0 value (evaluate value >> pure ())) +instance FromValue K.Constraint where fromValue = unbox 30 +instance ToValue K.Constraint where toValue value = pure (opaque 30 0 value (evaluate value >> pure ())) +instance FromValue K.PenaltyMethod where fromValue = unbox 31 +instance ToValue K.PenaltyMethod where toValue value = pure (opaque 31 0 value (evaluate value >> pure ())) +instance FromValue G.GlobalMethod where fromValue = unbox 32 +instance ToValue G.GlobalMethod where toValue value = pure (opaque 32 0 value (evaluate value >> pure ())) +instance FromValue C.LineSearch where fromValue = unbox 33 +instance ToValue C.LineSearch where toValue value = pure (opaque 33 0 value (evaluate value >> pure ())) +instance FromValue F.OptimizerState where fromValue = unbox 34 +instance ToValue F.OptimizerState where toValue value = pure (opaque 34 0 value (evaluate value >> pure ())) + +data Function + = ObjectiveFn C.Objective + | GradientFn C.Gradient + | HessianFn C.Hessian + | ProxFn (Double -> [Double] -> Either MathError [Double]) + | MonitorFn (C.OptimizeResult -> Either MathError Bool) +functionValue :: Function -> Value +functionValue function = Opaque 35 (-1) (case function of { ObjectiveFn _ -> 0; GradientFn _ -> 1; HessianFn _ -> 2; ProxFn _ -> 3; MonitorFn _ -> 4 }) (pure ()) function +instance FromValue Function where fromValue = unbox 35 +instance FromValue ([Double] -> Either MathError Double) where + fromValue value = do f <- fromValue value; case f of { ObjectiveFn g -> pure g; _ -> invalid "expected Objective callback" } +instance FromValue (Double -> Either MathError Double) where + fromValue value = do f <- fromValue value; case f of { ObjectiveFn g -> pure (\x -> g [x]); _ -> invalid "expected scalar Objective callback" } +instance FromValue ([Double] -> Either MathError [Double]) where + fromValue value = do f <- fromValue value; case f of { GradientFn g -> pure g; _ -> invalid "expected Gradient/projection callback" } +instance FromValue ([Double] -> Either MathError [[Double]]) where + fromValue value = do f <- fromValue value; case f of { HessianFn g -> pure g; _ -> invalid "expected Hessian/Jacobian callback" } +instance FromValue (Double -> [Double] -> Either MathError [Double]) where + fromValue value = do f <- fromValue value; case f of { ProxFn g -> pure g; _ -> invalid "expected proximal callback" } +instance FromValue (C.OptimizeResult -> Either MathError Bool) where + fromValue value = do f <- fromValue value; case f of { MonitorFn g -> pure g; _ -> invalid "expected monitor callback" } + +class Apply a where apply :: a -> [Value] -> IO Value +instance {-# OVERLAPPABLE #-} (ToValue a) => Apply a where + apply value [] = toValue value + apply _ _ = invalid "too many optimization arguments" +instance {-# OVERLAPPING #-} (FromValue a,Apply b) => Apply (a -> b) where + apply function (value:rest) = fromValue value >>= \argument -> apply (function argument) rest + apply _ [] = invalid "missing optimization argument" + +-- The C helper passes an owned result and independent borrowed input handle. +foreign import ccall safe "hm_opt_invoke_callback" + invokeCallback :: FunPtr () -> Ptr () -> StablePtr Value -> Ptr (StablePtr Value) -> Ptr () -> IO CInt +{-# NOINLINE callback #-} +callback :: (ToValue a,FromValue b) => FunPtr () -> Ptr () -> a -> Either MathError b +callback function userdata argument = unsafePerformIO $ do + encoded <- toValue argument + forceValue encoded + bracket (newStablePtr encoded) freeStablePtr $ \input -> + alloca $ \out -> withMathErrorWire $ \errorWire -> do + status <- invokeCallback function userdata input out errorWire + if status == 11 then Left <$> readMathError errorWire + else if status /= 0 then readCallbackFailure status errorWire >>= throwIO + else do + pointer <- peek out + bracket (pure pointer) freeStablePtr $ \result -> deRefStablePtr result >>= fmap Right . fromValue + +foreign export ccall "hm_opt_callback" + createCallback :: CInt -> FunPtr () -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +createCallback :: CInt -> FunPtr () -> Ptr () -> Ptr (StablePtr Value) -> IO CInt +createCallback kind function userdata out = boundary $ do + let result = case kind of + 0 -> ObjectiveFn (callback function userdata) + 1 -> GradientFn (callback function userdata) + 2 -> HessianFn (callback function userdata) + 3 -> ProxFn (\rate point -> callback function userdata (rate,point)) + 4 -> MonitorFn (callback function userdata) + _ -> error "invalid optimization callback kind" + checked (Right ()) $ \_ -> publish (functionValue result) out + +-- Callback arguments include pairs; tuple decoding is structural and lossless. +instance (FromValue a,FromValue b) => FromValue (a,b) where + fromValue (Tuple [a,b]) = (,) <$> fromValue a <*> fromValue b + fromValue _ = invalid "expected pair" + +foreign export ccall "hm_opt_invoke" + invoke :: CString -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +invoke :: CString -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +invoke namePointer arguments count out = boundary $ do + name <- peekCString namePointer + values <- peekArray (fromIntegral count) arguments >>= mapM deRefStablePtr + result <- dispatch name values + checked (Right ()) $ \_ -> publish result out + +foreign export ccall "hm_opt_clone" cloneValue :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +cloneValue :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +cloneValue pointer out = boundary $ deRefStablePtr pointer >>= \value -> checked (Right ()) (\_ -> publish value out) + +foreign export ccall "hm_opt_import_state" + importState :: StablePtr F.OptimizerState -> Ptr (StablePtr Value) -> IO CInt +importState :: StablePtr F.OptimizerState -> Ptr (StablePtr Value) -> IO CInt +importState pointer out = boundary $ do value <- deRefStablePtr pointer; encoded <- toValue value; checked (Right ()) $ \_ -> publish encoded out +foreign export ccall "hm_opt_export_state" + exportState :: StablePtr Value -> Ptr (StablePtr F.OptimizerState) -> IO CInt +exportState :: StablePtr Value -> Ptr (StablePtr F.OptimizerState) -> IO CInt +exportState pointer out = boundary $ do + state <- deRefStablePtr pointer >>= fromValue + checked (Right ()) $ \_ -> bracketOnError (newStablePtr state) freeStablePtr (\p -> poke out p >> pure ()) + +dispatch :: String -> [Value] -> IO Value +dispatch name arguments = case name of + "OptimizeOptions" -> apply C.OptimizeOptions arguments + "defaultOptimizeOptions" -> apply C.defaultOptimizeOptions arguments + "OptimizeResult" -> apply C.OptimizeResult arguments + "EarlyStopping" -> apply C.EarlyStopping arguments + "ConstantRate" -> apply C.ConstantRate arguments + "StepDecay" -> apply C.StepDecay arguments + "ExponentialDecay" -> apply C.ExponentialDecay arguments + "CosineAnnealing" -> apply C.CosineAnnealing arguments + "Warmup" -> apply C.Warmup arguments + "Armijo" -> apply C.Armijo arguments + "StrongWolfe" -> apply C.StrongWolfe arguments + "checkedOptions" -> apply C.checkedOptions arguments + "checkedPoint" -> apply C.checkedPoint arguments + "checkedValue" -> apply C.checkedValue arguments + "checkedGradient" -> apply C.checkedGradient arguments + "checkBudget" -> apply C.checkBudget arguments + "dot" -> apply C.dot arguments + "add" -> apply C.add arguments + "sub" -> apply C.sub arguments + "outer" -> apply C.outer arguments + "norm" -> apply C.norm arguments + "scale" -> apply C.scale arguments + "identity" -> apply C.identity arguments + "matVec" -> apply C.matVec arguments + "matMul" -> apply C.matMul arguments + "transpose" -> apply (C.transpose :: [[Value]] -> [[Value]]) arguments + "solveDense" -> apply C.solveDense arguments + "result" -> apply C.result arguments + "learningRate" -> apply C.learningRate arguments + "earlyStopping" -> apply C.earlyStopping arguments + "lineSearch" -> apply C.lineSearch arguments + "optMaxIterations" -> apply C.optMaxIterations arguments + "optMaxEvaluations" -> apply C.optMaxEvaluations arguments + "optTolerance" -> apply C.optTolerance arguments + "optLearningRate" -> apply C.optLearningRate arguments + "optPoint" -> apply C.optPoint arguments + "optValue" -> apply C.optValue arguments + "optGradientNorm" -> apply C.optGradientNorm arguments + "optIterations" -> apply C.optIterations arguments + "optEvaluations" -> apply C.optEvaluations arguments + "optConverged" -> apply C.optConverged arguments + "bestScore" -> apply C.bestScore arguments + "staleSteps" -> apply C.staleSteps arguments + "stopped" -> apply C.stopped arguments + "GradientDescent" -> apply F.GradientDescent arguments + "Momentum" -> apply F.Momentum arguments + "Nesterov" -> apply F.Nesterov arguments + "AdaGrad" -> apply F.AdaGrad arguments + "RMSProp" -> apply F.RMSProp arguments + "AdaDelta" -> apply F.AdaDelta arguments + "Adam" -> apply F.Adam arguments + "AdamW" -> apply F.AdamW arguments + "AMSGrad" -> apply F.AMSGrad arguments + "AdaMax" -> apply F.AdaMax arguments + "Nadam" -> apply F.Nadam arguments + "RAdam" -> apply F.RAdam arguments + "initializeOptimizer" -> apply F.initializeOptimizer arguments + "optimizerStep" -> apply F.optimizerStep arguments + "minimizeGradient" -> apply F.minimizeGradient arguments + "minimizeGradientWithCallback" -> apply F.minimizeGradientWithCallback arguments + "stochasticGradient" -> apply F.stochasticGradient arguments + "miniBatchGradient" -> apply (\values -> functionValue (GradientFn (F.miniBatchGradient values))) arguments + "projectedGradient" -> apply F.projectedGradient arguments + "proximalGradient" -> apply F.proximalGradient arguments + "fista" -> apply F.fista arguments + "coordinateDescent" -> apply F.coordinateDescent arguments + "GoldenSection" -> apply L.GoldenSection arguments + "TernarySearch" -> apply L.TernarySearch arguments + "BrentSearch" -> apply L.BrentSearch arguments + "minimizeScalar" -> apply L.minimizeScalar arguments + "BFGS" -> apply L.BFGS arguments + "DFP" -> apply L.DFP arguments + "SR1" -> apply L.SR1 arguments + "LBFGS" -> apply L.LBFGS arguments + "minimizeQuasiNewton" -> apply L.minimizeQuasiNewton arguments + "Newton" -> apply L.Newton arguments + "NewtonCG" -> apply L.NewtonCG arguments + "TrustRegion" -> apply L.TrustRegion arguments + "Dogleg" -> apply L.Dogleg arguments + "minimizeNewton" -> apply L.minimizeNewton arguments + "nonlinearCG" -> apply L.nonlinearCG arguments + "SquaredLoss" -> apply L.SquaredLoss arguments + "HuberLoss" -> apply L.HuberLoss arguments + "CauchyLoss" -> apply L.CauchyLoss arguments + "SoftL1" -> apply L.SoftL1 arguments + "leastSquares" -> apply L.leastSquares arguments + "nelderMead" -> apply L.nelderMead arguments + "powell" -> apply L.powell arguments + "Equality" -> apply K.Equality arguments + "LessEqual" -> apply K.LessEqual arguments + "feasibility" -> apply K.feasibility arguments + "QuadraticPenalty" -> apply K.QuadraticPenalty arguments + "LogBarrier" -> apply K.LogBarrier arguments + "InteriorPoint" -> apply K.InteriorPoint arguments + "AugmentedLagrangian" -> apply K.AugmentedLagrangian arguments + "constrainedMinimize" -> apply K.constrainedMinimize arguments + "LPResult" -> apply K.LPResult arguments + "linearProgramming" -> apply K.linearProgramming arguments + "revisedSimplex" -> apply K.revisedSimplex arguments + "quadraticProgramming" -> apply K.quadraticProgramming arguments + "slsqp" -> apply K.slsqp arguments + "cobyla" -> apply K.cobyla arguments + "weightedObjective" -> apply (\weights functions -> functionValue (ObjectiveFn (K.weightedObjective weights functions))) arguments + "paretoFront" -> apply K.paretoFront arguments + "lpPoint" -> apply K.lpPoint arguments + "lpValue" -> apply K.lpValue arguments + "lpBasis" -> apply K.lpBasis arguments + "lpIterations" -> apply K.lpIterations arguments + "SimulatedAnnealing" -> apply G.SimulatedAnnealing arguments + "DifferentialEvolution" -> apply G.DifferentialEvolution arguments + "GeneticAlgorithm" -> apply G.GeneticAlgorithm arguments + "ParticleSwarm" -> apply G.ParticleSwarm arguments + "CMAES" -> apply G.CMAES arguments + "globalMinimize" -> apply G.globalMinimize arguments + "basinHopping" -> apply G.basinHopping arguments + "__apply" -> case arguments of + function:rest -> do + target <- fromValue function + case target of + ObjectiveFn f -> apply f rest + GradientFn f -> apply f rest + HessianFn f -> apply f rest + ProxFn f -> apply f rest + MonitorFn f -> apply f rest + _ -> invalid "missing function argument" + _ -> invalid "unknown optimization operation" diff --git a/src/HMath/FFI/Optimizer.hs b/src/HMath/FFI/Optimizer.hs new file mode 100644 index 0000000..defec85 --- /dev/null +++ b/src/HMath/FFI/Optimizer.hs @@ -0,0 +1,46 @@ +{-# LANGUAGE ForeignFunctionInterface #-} + +-- SPDX-License-Identifier: MPL-2.0 +-- | Preserve the original immutable optimizer state and update semantics. +module HMath.FFI.Optimizer where + +import Control.Exception (bracketOnError, evaluate) +import Data.Coerce (coerce) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import qualified HMath.Optimization.FirstOrder as O + +foreign export ccall "hm_optimizer_initialize" + initialize :: CPtrdiff -> Ptr (StablePtr O.OptimizerState) -> IO CInt + +initialize :: CPtrdiff -> Ptr (StablePtr O.OptimizerState) -> IO CInt +initialize dimension out = boundary $ + checked (O.initializeOptimizer (fromIntegral dimension)) $ \state -> + bracketOnError (newStablePtr state) freeStablePtr (poke out) + +foreign export ccall "hm_optimizer_free" release :: StablePtr O.OptimizerState -> IO () + +release :: StablePtr O.OptimizerState -> IO () +release = freeStablePtr + +foreign export ccall "hm_optimizer_step" + step :: + CInt -> CDouble -> StablePtr O.OptimizerState -> + Ptr CDouble -> CSize -> Ptr CDouble -> CSize -> + Ptr CDouble -> Ptr (StablePtr O.OptimizerState) -> IO CInt + +step :: + CInt -> CDouble -> StablePtr O.OptimizerState -> + Ptr CDouble -> CSize -> Ptr CDouble -> CSize -> + Ptr CDouble -> Ptr (StablePtr O.OptimizerState) -> IO CInt +step method rate statePointer xs count gs gradientCount out outState = boundary $ do + state <- deRefStablePtr statePointer + parameters <- peekArray (fromIntegral count) (castPtr xs) + gradient <- peekArray (fromIntegral gradientCount) (castPtr gs) + checked (O.optimizerStep (toEnum (fromIntegral method)) (coerce rate) state parameters gradient) $ + \(next, nextState) -> do + values <- mapM evaluate next + bracketOnError (newStablePtr nextState) freeStablePtr $ \pointer -> do + pokeArray (castPtr out) values + poke outState pointer diff --git a/src/HMath/FFI/Ordering.hs b/src/HMath/FFI/Ordering.hs new file mode 100644 index 0000000..406a239 --- /dev/null +++ b/src/HMath/FFI/Ordering.hs @@ -0,0 +1,344 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Recover actual native Ord dictionaries for language-polymorphic APIs. +-- This module transports values; it defines no substitute comparison relation. +module HMath.FFI.Ordering + (SomeOrdered(..),Resolver,orderedFor,orderedWith,orderedFromPrototype,orderedMaybe) where + +import Data.List (transpose) +import Data.Proxy (Proxy(..)) +import Data.Typeable (Typeable,cast) +import qualified HMath.Backend as B +import qualified HMath.Expression as E +import qualified HMath.Geometry as G +import qualified HMath.Graph.Core as Graph +import qualified HMath.Interchange.Array as Interchange +import qualified HMath.FFI.Autodiff as AD +import qualified HMath.FFI.AutodiffValue as ADV +import HMath.FFI.Coefficient +import qualified HMath.FFI.GraphCodec as W +import qualified HMath.FFI.LinearCodec as L +import qualified HMath.FFI.Value as V + +data SomeOrdered where + SomeOrdered :: (Typeable a,Ord a) => (a -> IO V.Value) -> (V.Value -> IO a) -> SomeOrdered + +type Resolver = V.Value -> IO (Maybe SomeOrdered) + +orderedFor :: [V.Value] -> IO SomeOrdered +orderedFor = orderedWith [] + +-- A prototype is a representative value of the desired native type, not data +-- added to the original algorithm. Empty arrays/None alone do not invent an +-- element type. Callers must supply a concrete nested example when necessary. +orderedFromPrototype :: V.Value -> IO SomeOrdered +orderedFromPrototype prototype = orderedFor [prototype] + +orderedMaybe :: SomeOrdered -> SomeOrdered +orderedMaybe (SomeOrdered write readValue) = SomeOrdered + (maybe (pure V.None) write) + (\value -> case value of V.None -> pure Nothing;_ -> Just <$> readValue value) + +orderedOpaque :: forall a. (Typeable a,Ord a) => Proxy a -> Int -> SomeOrdered +orderedOpaque _ kind = SomeOrdered (pure . W.boxed kind) (W.unboxed kind :: V.Value -> IO a) + +readCoefficient :: forall a. Coefficient a => V.Value -> IO a +readCoefficient (V.Index value) = maybe (V.invalid "Haskell Int category type differs") pure (cast value) +readCoefficient value = V.asScalar value + +-- Extensions can recognize their own typed envelopes without making this +-- shared module import every foundation/domain adapter (and create cycles). +orderedWith :: [Resolver] -> [V.Value] -> IO SomeOrdered +orderedWith _ [] = V.invalid "Ord category type cannot be inferred from an empty collection; provide a prototype" +orderedWith resolvers values@(first:_) = do + extension <- tryResolvers resolvers first + case extension of + Just result -> pure result + Nothing -> infer + where + recurse = orderedWith resolvers + tryResolvers [] _ = pure Nothing + tryResolvers (resolver:rest) value = do + result <- resolver value + case result of Just _ -> pure result;Nothing -> tryResolvers rest value + nonmissing = [value | value <- values,case value of V.None -> False;_ -> True] + infer + | length nonmissing /= length values = + if null nonmissing + then V.invalid "optional Ord category type requires a nonmissing prototype" + else orderedMaybe <$> recurse nonmissing + | otherwise = case first of + V.Scalar witness (_ :: a) -> case orderingDict (Proxy :: Proxy a) of + Just Dict -> pure (SomeOrdered (pure . V.Scalar witness) (readCoefficient :: V.Value -> IO a)) + Nothing -> V.unsupported "the original coefficient type has no Ord instance" + V.Index _ -> pure (SomeOrdered (pure . V.Index) V.asIndex) + V.Boolean _ -> pure (SomeOrdered (pure . V.Boolean) V.asBoolean) + V.Text _ -> pure (SomeOrdered (pure . V.Text) V.asText) + V.List _ -> do + groups <- mapM V.asList values + SomeOrdered write readValue <- recurse (concat groups) + pure (SomeOrdered (fmap V.List . mapM write) (\value -> V.asList value >>= mapM readValue)) + V.Tuple fields -> tupleOrdered (length fields) + V.Opaque 458 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy Interchange.DType) 458) + V.Opaque 61 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy Graph.Edge) 61) + V.Opaque 80 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy E.Expr) 80) + V.Opaque 81 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy E.ExprNode) 81) + V.Opaque 169 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy G.Point2) 169) + V.Opaque 170 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy G.Point3) 170) + V.Opaque 171 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy G.PointND) 171) + V.Opaque 188 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy G.Orientation) 188) + V.Opaque 189 _ _ _ _ -> pure (orderedOpaque (Proxy :: Proxy G.Location) 189) + V.Opaque 289 _ _ _ _ -> do + AD.Tower (_ :: a) <- ADV.asADTower first + case AD.orderingDict (Proxy :: Proxy a) of + Nothing -> V.unsupported "the original Autodiff type has no Ord instance" + Just AD.Dict -> pure (SomeOrdered + (pure . ADV.fromADTower . AD.Tower) + (\value -> do + AD.Tower other <- ADV.asADTower value + maybe (V.invalid "Autodiff category types differ") pure (cast other :: Maybe a))) + V.Opaque 100 _ _ _ _ -> do + name <- L.objectName first + case name of + "HMath.Backend.Provider" -> pure (SomeOrdered L.encodeProvider (L.unbox name :: V.Value -> IO B.Provider)) + "HMath.Backend.IntegerABI" -> pure (SomeOrdered L.encodeIntegerABI (L.unbox name :: V.Value -> IO B.IntegerABI)) + _ -> V.unsupported "original Ord dictionary unavailable for this linear-domain type" + _ -> V.unsupported "original Ord dictionary unavailable for this native type" + tupleOrdered count = do + rows <- mapM (V.asTuple count) values + let columns=transpose rows + case count of + 0 -> pure (SomeOrdered (\() -> pure (V.Tuple [])) (\value -> V.asTuple 0 value >> pure ())) + 2 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + pure (SomeOrdered + (\(a0,a1) -> V.Tuple <$> sequence [write0 a0,write1 a1]) + (\value -> do + items <- V.asTuple 2 value + case items of + [v0,v1] -> (,) <$> read0 v0 <*> read1 v1 + _ -> V.invalid "category tuple arity differs")) + 3 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + pure (SomeOrdered + (\(a0,a1,a2) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2]) + (\value -> do + items <- V.asTuple 3 value + case items of + [v0,v1,v2] -> (,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 + _ -> V.invalid "category tuple arity differs")) + 4 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + pure (SomeOrdered + (\(a0,a1,a2,a3) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3]) + (\value -> do + items <- V.asTuple 4 value + case items of + [v0,v1,v2,v3] -> (,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 + _ -> V.invalid "category tuple arity differs")) + 5 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4]) + (\value -> do + items <- V.asTuple 5 value + case items of + [v0,v1,v2,v3,v4] -> (,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 + _ -> V.invalid "category tuple arity differs")) + 6 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5]) + (\value -> do + items <- V.asTuple 6 value + case items of + [v0,v1,v2,v3,v4,v5] -> (,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 + _ -> V.invalid "category tuple arity differs")) + 7 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6]) + (\value -> do + items <- V.asTuple 7 value + case items of + [v0,v1,v2,v3,v4,v5,v6] -> (,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 + _ -> V.invalid "category tuple arity differs")) + 8 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7]) + (\value -> do + items <- V.asTuple 8 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7] -> (,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 + _ -> V.invalid "category tuple arity differs")) + 9 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8]) + (\value -> do + items <- V.asTuple 9 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8] -> (,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 + _ -> V.invalid "category tuple arity differs")) + 10 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9]) + (\value -> do + items <- V.asTuple 10 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9] -> (,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 + _ -> V.invalid "category tuple arity differs")) + 11 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + SomeOrdered write10 read10 <- recurse (columns !! 10) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9,write10 a10]) + (\value -> do + items <- V.asTuple 11 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10] -> (,,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 <*> read10 v10 + _ -> V.invalid "category tuple arity differs")) + 12 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + SomeOrdered write10 read10 <- recurse (columns !! 10) + SomeOrdered write11 read11 <- recurse (columns !! 11) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9,write10 a10,write11 a11]) + (\value -> do + items <- V.asTuple 12 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11] -> (,,,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 <*> read10 v10 <*> read11 v11 + _ -> V.invalid "category tuple arity differs")) + 13 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + SomeOrdered write10 read10 <- recurse (columns !! 10) + SomeOrdered write11 read11 <- recurse (columns !! 11) + SomeOrdered write12 read12 <- recurse (columns !! 12) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9,write10 a10,write11 a11,write12 a12]) + (\value -> do + items <- V.asTuple 13 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12] -> (,,,,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 <*> read10 v10 <*> read11 v11 <*> read12 v12 + _ -> V.invalid "category tuple arity differs")) + 14 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + SomeOrdered write10 read10 <- recurse (columns !! 10) + SomeOrdered write11 read11 <- recurse (columns !! 11) + SomeOrdered write12 read12 <- recurse (columns !! 12) + SomeOrdered write13 read13 <- recurse (columns !! 13) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9,write10 a10,write11 a11,write12 a12,write13 a13]) + (\value -> do + items <- V.asTuple 14 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13] -> (,,,,,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 <*> read10 v10 <*> read11 v11 <*> read12 v12 <*> read13 v13 + _ -> V.invalid "category tuple arity differs")) + 15 -> do + SomeOrdered write0 read0 <- recurse (columns !! 0) + SomeOrdered write1 read1 <- recurse (columns !! 1) + SomeOrdered write2 read2 <- recurse (columns !! 2) + SomeOrdered write3 read3 <- recurse (columns !! 3) + SomeOrdered write4 read4 <- recurse (columns !! 4) + SomeOrdered write5 read5 <- recurse (columns !! 5) + SomeOrdered write6 read6 <- recurse (columns !! 6) + SomeOrdered write7 read7 <- recurse (columns !! 7) + SomeOrdered write8 read8 <- recurse (columns !! 8) + SomeOrdered write9 read9 <- recurse (columns !! 9) + SomeOrdered write10 read10 <- recurse (columns !! 10) + SomeOrdered write11 read11 <- recurse (columns !! 11) + SomeOrdered write12 read12 <- recurse (columns !! 12) + SomeOrdered write13 read13 <- recurse (columns !! 13) + SomeOrdered write14 read14 <- recurse (columns !! 14) + pure (SomeOrdered + (\(a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14) -> V.Tuple <$> sequence [write0 a0,write1 a1,write2 a2,write3 a3,write4 a4,write5 a5,write6 a6,write7 a7,write8 a8,write9 a9,write10 a10,write11 a11,write12 a12,write13 a13,write14 a14]) + (\value -> do + items <- V.asTuple 15 value + case items of + [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14] -> (,,,,,,,,,,,,,,) <$> read0 v0 <*> read1 v1 <*> read2 v2 <*> read3 v3 <*> read4 v4 <*> read5 v5 <*> read6 v6 <*> read7 v7 <*> read8 v8 <*> read9 v9 <*> read10 v10 <*> read11 v11 <*> read12 v12 <*> read13 v13 <*> read14 v14 + _ -> V.invalid "category tuple arity differs")) + _ -> V.unsupported "Ord category tuple arity must be zero or between two and fifteen (standard Prelude instances)" diff --git a/src/HMath/FFI/Polynomial.hs b/src/HMath/FFI/Polynomial.hs new file mode 100644 index 0000000..6406316 --- /dev/null +++ b/src/HMath/FFI/Polynomial.hs @@ -0,0 +1,207 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Representation adapters only; every mathematical operation calls the public source module. +module HMath.FFI.Polynomial where +import Control.Exception (throwIO) +import Data.Coerce (coerce) +import Data.Proxy (Proxy (..)) +import Data.Typeable (cast) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Polynomial as P +import HMath.Error (MathError) +import HMath.FFI.Coefficient +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError + +data SomePolynomial where + SomePolynomial :: Coefficient a => ScalarType a -> P.Polynomial a -> SomePolynomial +data SomeSeries where + SomeSeries :: Coefficient a => ScalarType a -> P.PowerSeries a -> SomeSeries + +poly :: Coefficient a => ScalarType a -> P.Polynomial a -> V.Value +poly witness p = V.Opaque 6 (scalarTypeCode witness) (length (P.coefficients p)) (mapM_ forceCoefficient (P.coefficients p)) (SomePolynomial witness p) +series :: Coefficient a => ScalarType a -> P.PowerSeries a -> V.Value +series witness p = V.Opaque 7 (scalarTypeCode witness) (length (P.seriesCoefficients p)) (mapM_ forceCoefficient (P.seriesCoefficients p)) (SomeSeries witness p) +rationalFunction :: P.RationalFunction -> V.Value +rationalFunction f = V.Opaque 8 3 0 (V.forceValue (poly SRational (P.rationalNumerator f)) >> V.forceValue (poly SRational (P.rationalDenominator f))) f +withPolynomial :: V.Value -> (forall a. Coefficient a => ScalarType a -> P.Polynomial a -> IO V.Value) -> IO V.Value +withPolynomial (V.Opaque 6 _ _ _ payload) action = case cast payload of + Just (SomePolynomial witness p) -> action witness p + Nothing -> V.invalid "invalid Polynomial payload" +withPolynomial _ _ = V.invalid "expected Polynomial" +withSeries :: V.Value -> (forall a. Coefficient a => ScalarType a -> P.PowerSeries a -> IO V.Value) -> IO V.Value +withSeries (V.Opaque 7 _ _ _ payload) action = case cast payload of + Just (SomeSeries witness p) -> action witness p + Nothing -> V.invalid "invalid PowerSeries payload" +withSeries _ _ = V.invalid "expected PowerSeries" +asPolynomial :: forall a. Coefficient a => V.Value -> IO (P.Polynomial a) +asPolynomial (V.Opaque 6 _ _ _ payload) = case cast payload of + Just (SomePolynomial _ p) -> maybe (V.invalid "Polynomial coefficient types differ") pure (cast p) + Nothing -> V.invalid "invalid Polynomial payload" +asPolynomial _ = V.invalid "expected Polynomial" +asSeries :: forall a. Coefficient a => V.Value -> IO (P.PowerSeries a) +asSeries (V.Opaque 7 _ _ _ payload) = case cast payload of + Just (SomeSeries _ p) -> maybe (V.invalid "PowerSeries coefficient types differ") pure (cast p) + Nothing -> V.invalid "invalid PowerSeries payload" +asSeries _ = V.invalid "expected PowerSeries" +asRationalFunction :: V.Value -> IO P.RationalFunction +asRationalFunction (V.Opaque 8 _ _ _ payload) = maybe (V.invalid "invalid RationalFunction payload") pure (cast payload) +asRationalFunction _ = V.invalid "expected RationalFunction" +withWitness :: V.Value -> (forall a. Coefficient a => ScalarType a -> IO V.Value) -> IO V.Value +withWitness (V.Scalar witness _) action = action witness +withWitness _ _ = V.invalid "expected typed coefficient prototype" +scalars :: Coefficient a => V.Value -> IO [a] +scalars input = V.asList input >>= mapM V.asScalar +points :: Coefficient a => V.Value -> IO [(a,a)] +points input = V.asList input >>= mapM (\v -> do + pair <- V.asTuple 2 v + case pair of + [a,b] -> (,) <$> V.asScalar a <*> V.asScalar b + _ -> V.invalid "point tuple arity differs") +source :: Either MathError a -> IO a +source = either (throwIO . CallbackMathError) pure +fractional :: forall a. Coefficient a => ScalarType a -> (Fractional a => IO V.Value) -> IO V.Value +fractional _ action = case fractionalDict (Proxy :: Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "operation requires the original Fractional coefficient instance" +floating :: forall a. Coefficient a => ScalarType a -> (Floating a => IO V.Value) -> IO V.Value +floating _ action = case floatingDict (Proxy :: Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "operation requires the original Floating coefficient instance" +realFloat :: forall a. Coefficient a => ScalarType a -> (RealFloat a => IO V.Value) -> IO V.Value +realFloat _ action = case realFloatDict (Proxy :: Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "operation requires the original RealFloat coefficient instance" +ordered :: forall a. Coefficient a => ScalarType a -> (Ord a => IO V.Value) -> IO V.Value +ordered _ action = case orderingDict (Proxy :: Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "operation requires the original Ord coefficient instance" +factors :: [(P.Polynomial Rational,Int)] -> V.Value +factors = V.List . map (\(p,n) -> V.Tuple [poly SRational p,V.Index n]) + +apply :: Int -> [V.Value] -> IO V.Value +apply op args = case (op,args) of + (0,[prototype,xs]) -> withWitness prototype $ \w -> poly w . P.polynomial <$> scalars xs + (1,[p]) -> withPolynomial p $ \w x -> pure (V.List (map (V.Scalar w) (P.coefficients x))) + (2,[p]) -> withPolynomial p $ \_ x -> pure (maybe V.None V.Index (P.polynomialDegree x)) + (3,[p,x]) -> withPolynomial p $ \w a -> V.Scalar w . P.evaluatePolynomial a <$> V.asScalar x + (4,[p,q]) -> withPolynomial p $ \w a -> poly w . P.addPolynomial a <$> asPolynomial q + (5,[p,q]) -> withPolynomial p $ \w a -> poly w . P.subtractPolynomial a <$> asPolynomial q + (6,[x,p]) -> withPolynomial p $ \w a -> (\s -> poly w (P.scalePolynomial s a)) <$> V.asScalar x + (7,[p,q]) -> withPolynomial p $ \w a -> poly w . P.multiplyPolynomial a <$> asPolynomial q + (8,[p,q]) -> withPolynomial p $ \w a -> poly w . P.composePolynomial a <$> asPolynomial q + (9,[p,q]) -> withPolynomial p $ \w a -> fractional w $ do + b <- asPolynomial q + (quotient,remainder) <- source (P.dividePolynomial a b) + pure (V.Tuple [poly w quotient,poly w remainder]) + (10,[p]) -> withPolynomial p $ \w a -> fractional w $ pure (poly w (P.monicPolynomial a)) + (11,[p,q]) -> withPolynomial p $ \w a -> fractional w $ poly w . P.gcdPolynomial a <$> asPolynomial q + (12,[p]) -> withPolynomial p $ \w a -> pure (poly w (P.differentiatePolynomial a)) + (13,[c,p]) -> withPolynomial p $ \w a -> fractional w $ (\x -> poly w (P.integratePolynomial x a)) <$> V.asScalar c + (14,[p]) -> factors . P.squareFreeFactors <$> asPolynomial p + (15,[budget,p]) -> do + n <- V.asIndex budget; a <- asPolynomial p + result <- source (P.rationalRoots n a) + pure (V.List [V.Tuple [V.Scalar SRational root,V.Index count] | (root,count) <- result]) + (16,[budget,p]) -> do + n <- V.asIndex budget; a <- asPolynomial p + (coefficient,result) <- source (P.factorRationalPolynomial n a) + pure (V.Tuple [V.Scalar SRational coefficient,factors result]) + (17,[p]) -> asPolynomial p >>= source . P.sturmSequence >>= pure . V.List . map (poly SRational) + (18,[p,left,right]) -> do + a <- asPolynomial p; b <- V.asScalar left; c <- V.asScalar right + V.Index <$> source (P.countRealRoots a b c) + (19,[depth,width,p]) -> do + d <- V.asIndex depth; w <- V.asScalar width; a <- asPolynomial p + result <- source (P.isolateRealRoots d w a) + pure (V.List [V.Tuple [V.Scalar SRational left,V.Scalar SRational right] | (left,right) <- result]) + (20,[iterations,tolerance,p]) -> roots P.durandKerner iterations tolerance p + (21,[iterations,tolerance,p]) -> roots P.aberthEhrlich iterations tolerance p + (22,[p]) -> withPolynomial p $ \w a -> fractional w $ V.Dense . V.SomeMatrix w <$> source (P.companionMatrix a) + (23,[prototype,ps]) -> withWitness prototype $ \w -> fractional w $ points ps >>= source . P.lagrangeInterpolation >>= pure . poly w + (24,[prototype,ps]) -> withWitness prototype $ \w -> fractional w $ points ps >>= source . P.newtonInterpolation >>= pure . poly w + (25,[prototype,degree]) -> orthogonal P.chebyshevPolynomial prototype degree + (26,[prototype,degree]) -> orthogonal P.legendrePolynomial prototype degree + (27,[prototype,degree]) -> orthogonal P.hermitePolynomial prototype degree + (28,[prototype,degree]) -> orthogonal P.laguerrePolynomial prototype degree + (29,[prototype,degree,index]) -> withWitness prototype $ \w -> fractional w $ do + n <- V.asIndex degree; k <- V.asIndex index + poly w <$> source (P.bernsteinPolynomial n k) + (30,[prototype,degree,ps]) -> withWitness prototype $ \w -> realFloat w $ do + n <- V.asIndex degree; values <- points ps + poly w <$> source (P.polynomialRegression n values) + (31,[prototype,xs]) -> withWitness prototype $ \w -> series w . P.powerSeries <$> scalars xs + (32,[s]) -> withSeries s $ \w a -> pure (V.List (map (V.Scalar w) (P.seriesCoefficients a))) + (33,[p,q]) -> withSeries p $ \w a -> series w . P.addSeries a <$> asSeries q + (34,[p,q]) -> withSeries p $ \w a -> series w . P.multiplySeries a <$> asSeries q + (35,[p]) -> withSeries p $ \w a -> fractional w $ series w <$> source (P.reciprocalSeries a) + (36,[p,q]) -> withSeries p $ \w a -> fractional w $ asSeries q >>= source . P.divideSeries a >>= pure . series w + (37,[p,q]) -> withSeries p $ \w a -> asSeries q >>= source . P.composeSeries a >>= pure . series w + (38,[p]) -> withSeries p $ \w a -> pure (series w (P.differentiateSeries a)) + (39,[c,p]) -> withSeries p $ \w a -> fractional w $ (\x -> series w (P.integrateSeries x a)) <$> V.asScalar c + (40,[p]) -> withSeries p $ \w a -> floating w $ pure (series w (P.expSeries a)) + (41,[p]) -> withSeries p $ \w a -> floating w $ ordered w $ series w <$> source (P.logSeries a) + (42,[p,q]) -> do + a <- asPolynomial p; b <- asPolynomial q + rationalFunction <$> source (P.rationalFunction a b) + (43,[f]) -> poly SRational . P.rationalNumerator <$> asRationalFunction f + (44,[f]) -> poly SRational . P.rationalDenominator <$> asRationalFunction f + (45,[f,x]) -> do + a <- asRationalFunction f; b <- V.asScalar x + V.Scalar SRational <$> source (P.evaluateRationalFunction a b) + (46,[f,g]) -> do + a <- asRationalFunction f; b <- asRationalFunction g + rationalFunction <$> source (P.addRationalFunction a b) + (47,[f,g]) -> do + a <- asRationalFunction f; b <- asRationalFunction g + rationalFunction <$> source (P.multiplyRationalFunction a b) + (48,[budget,f]) -> do + n <- V.asIndex budget; a <- asRationalFunction f + (whole,result) <- source (P.partialFractions n a) + pure (V.Tuple [poly SRational whole,V.List [V.Tuple [poly SRational p,poly SRational q,V.Index k] | (p,q,k) <- result]]) + (49,[p,q]) -> withPolynomial p $ \_ a -> V.Boolean . (a==) <$> asPolynomial q + (50,[p,q]) -> withSeries p $ \_ a -> V.Boolean . (a==) <$> asSeries q + (51,[f,g]) -> do + a <- asRationalFunction f; b <- asRationalFunction g + pure (V.Boolean (a==b)) + _ -> V.invalid "invalid Polynomial operation or argument count" + where + roots algorithm iterations tolerance p = do + n <- V.asIndex iterations; t <- V.asScalar tolerance; a <- asPolynomial p + result <- source (algorithm n t a) + pure (V.List (map (V.Scalar SComplexDouble) result)) + +orthogonal :: (forall a. (Eq a,Fractional a) => Int -> Either MathError (P.Polynomial a)) -> V.Value -> V.Value -> IO V.Value +orthogonal algorithm prototype degree = withWitness prototype $ \w -> fractional w $ do + n <- V.asIndex degree + poly w <$> source (algorithm n) + +polynomialBoundary :: IO CInt -> IO CInt +polynomialBoundary action = B.boundary $ callbackBoundary (\e -> B.checked (Left e) (const (pure ()))) action +foreign export ccall "hm_polynomial_apply" ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply opcode pointers count out = polynomialBoundary $ do + args <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + value <- apply (fromIntegral opcode) args + B.checked (Right ()) (const (V.publish value out)) + +type ApproximationCallback = CDouble -> Ptr CDouble -> Ptr () -> Ptr () -> IO CInt +foreign import ccall "dynamic" dynamicApproximation :: FunPtr ApproximationCallback -> ApproximationCallback +callbackFunction :: FunPtr ApproximationCallback -> Ptr () -> Double -> Double +callbackFunction pointer userdata input = unsafePerformIO $ alloca $ \out -> withMathErrorWire $ \wire -> do + status <- dynamicApproximation pointer (coerce input) out userdata wire + if status==0 then coerce <$> peek out + else if status==11 then readMathError wire >>= throwIO . CallbackMathError + else readWireMessage wire >>= throwIO . CallbackFailure status +{-# NOINLINE callbackFunction #-} +foreign export ccall "hm_polynomial_chebyshev_approximation" approximation :: CPtrdiff -> FunPtr ApproximationCallback -> Ptr () -> Ptr (StablePtr V.Value) -> IO CInt +approximation :: CPtrdiff -> FunPtr ApproximationCallback -> Ptr () -> Ptr (StablePtr V.Value) -> IO CInt +approximation degree callback userdata out = polynomialBoundary $ do + result <- source (P.chebyshevApproximation (fromIntegral degree) (callbackFunction callback userdata)) + B.checked (Right ()) (const (V.publish (poly SDouble result) out)) diff --git a/src/HMath/FFI/RandomCodec.hs b/src/HMath/FFI/RandomCodec.hs new file mode 100644 index 0000000..10de9c9 --- /dev/null +++ b/src/HMath/FFI/RandomCodec.hs @@ -0,0 +1,16 @@ +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Lossless ownership of the original complete RNG continuation state. +module HMath.FFI.RandomCodec where +import Control.Exception (evaluate) +import Data.Typeable (cast) +import qualified HMath.Random as R +import qualified HMath.FFI.Value as V + +rng :: R.RNG -> V.Value +rng value = V.Opaque 240 (-1) 0 (evaluate value >> pure ()) value + +asRNG :: V.Value -> IO R.RNG +asRNG (V.Opaque 240 _ _ _ payload) = + maybe (V.invalid "invalid original RNG payload") pure (cast payload) +asRNG _ = V.invalid "expected original RNG state" diff --git a/src/HMath/FFI/Rotations.hs b/src/HMath/FFI/Rotations.hs new file mode 100644 index 0000000..987bd26 --- /dev/null +++ b/src/HMath/FFI/Rotations.hs @@ -0,0 +1,386 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_rotation_bindings.py. +module HMath.FFI.Rotations where +import Control.Exception (evaluate) +import Data.Typeable (cast) +import Foreign +import Foreign.C +import HMath.FFI.Boundary (boundary, checked) +import HMath.FFI.Coefficient (ScalarType (SDouble)) +import qualified HMath.FFI.Value as V +import qualified HMath.Matrix as M +import qualified HMath.Quaternion as Q +import qualified HMath.Rotation as R + +type Handle = StablePtr V.Value +getQuaternion :: V.Value -> IO Q.Quaternion +getQuaternion (V.Opaque 72 _ _ _ value) = maybe (V.invalid "Quaternion payload mismatch") pure (cast value) +getQuaternion _ = V.invalid "expected HMath.Quaternion.Quaternion" +getRotation :: V.Value -> IO R.SO3 +getRotation (V.Opaque 73 _ _ _ value) = maybe (V.invalid "SO3 payload mismatch") pure (cast value) +getRotation _ = V.invalid "expected HMath.Rotation.SO3" +getTransform :: V.Value -> IO R.SE3 +getTransform (V.Opaque 74 _ _ _ value) = maybe (V.invalid "SE3 payload mismatch") pure (cast value) +getTransform _ = V.invalid "expected HMath.Rotation.SE3" +getDualQuaternion :: V.Value -> IO R.DualQuaternion +getDualQuaternion (V.Opaque 75 _ _ _ value) = maybe (V.invalid "DualQuaternion payload mismatch") pure (cast value) +getDualQuaternion _ = V.invalid "expected HMath.Rotation.DualQuaternion" +getMatrix :: V.Value -> IO (M.Matrix Double) +getMatrix (V.Dense (V.SomeMatrix _ value)) = maybe (V.invalid "Matrix Double required") pure (cast value) +getMatrix _ = V.invalid "expected dense Matrix Double" +getVector :: V.Value -> IO [Double] +getVector value = V.asList value >>= mapM V.asScalar +getTwist :: V.Value -> IO ([Double],[Double]) +getTwist value = do + values <- V.asTuple 2 value + case values of [a,b] -> (,) <$> getVector a <*> getVector b; _ -> V.invalid "twist tuple arity" +scalar :: Double -> V.Value +scalar = V.Scalar SDouble +vector :: [Double] -> V.Value +vector = V.List . map scalar +quaternion :: Q.Quaternion -> V.Value +quaternion value = V.Opaque 72 0 4 (mapM_ evaluate (Q.components value)) value +rotation :: R.SO3 -> V.Value +rotation value = V.Opaque 73 0 4 (V.forceValue (quaternion (R.rotationQuaternion value))) value +transform :: R.SE3 -> V.Value +transform value = V.Opaque 74 0 7 (V.forceValue (rotation (R.rotationPart value)) >> V.forceValue (vector (R.translationPart value))) value +dualQuaternion :: R.DualQuaternion -> V.Value +dualQuaternion value = let (a,b)=R.dualParts value in V.Opaque 75 0 8 (V.forceValue (quaternion a) >> V.forceValue (quaternion b)) value +matrix :: M.Matrix Double -> V.Value +matrix = V.Dense . V.SomeMatrix SDouble +axisAngle :: ([Double],Double) -> V.Value +axisAngle (axis,angle) = V.Tuple [vector axis,scalar angle] +triple :: (Double,Double,Double) -> V.Value +triple (a,b,c) = V.Tuple [scalar a,scalar b,scalar c] +quaternionPair :: (Q.Quaternion,Q.Quaternion) -> V.Value +quaternionPair (a,b) = V.Tuple [quaternion a,quaternion b] +twist :: ([Double],[Double]) -> V.Value +twist (a,b) = V.Tuple [vector a,vector b] +foreign export ccall "hm_rotations_equal" equal :: Handle -> Handle -> Ptr Handle -> IO CInt +equal :: Handle -> Handle -> Ptr Handle -> IO CInt +equal first second out = boundary $ do + a <- deRefStablePtr first + b <- deRefStablePtr second + result <- case (V.valueInfo a,V.valueInfo b) of + ((72,_,_),(72,_,_)) -> (==) <$> getQuaternion a <*> getQuaternion b + ((73,_,_),(73,_,_)) -> (==) <$> getRotation a <*> getRotation b + ((74,_,_),(74,_,_)) -> (==) <$> getTransform a <*> getTransform b + ((75,_,_),(75,_,_)) -> (==) <$> getDualQuaternion a <*> getDualQuaternion b + _ -> V.invalid "rotation object types differ" + checked (Right (V.Boolean result)) (`V.publish` out) + +foreign export ccall "hm_quaternion_quaternion" ffiQuaternionQuaternion :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionQuaternion :: Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionQuaternion rawW rawX rawY rawZ out = boundary $ do + argW <- deRefStablePtr rawW >>= V.asScalar + argX <- deRefStablePtr rawX >>= V.asScalar + argY <- deRefStablePtr rawY >>= V.asScalar + argZ <- deRefStablePtr rawZ >>= V.asScalar + checked (Q.quaternion argW argX argY argZ) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_components" ffiQuaternionComponents :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionComponents :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionComponents rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Right (Q.components argValue)) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_quaternion_norm" ffiQuaternionNorm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNorm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNorm rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Right (Q.norm argValue)) (\value -> V.publish (scalar value) out) + +foreign export ccall "hm_quaternion_normalize" ffiQuaternionNormalize :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNormalize :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionNormalize rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.normalize argValue) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_inverse" ffiQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionInverse :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionInverse rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.inverse argValue) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_conjugate" ffiQuaternionConjugate :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionConjugate :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionConjugate rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Right (Q.conjugate argValue)) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_multiply" ffiQuaternionMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionMultiply :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionMultiply rawA rawB out = boundary $ do + argA <- deRefStablePtr rawA >>= getQuaternion + argB <- deRefStablePtr rawB >>= getQuaternion + checked (Q.multiply argA argB) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_add" ffiQuaternionAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionAdd :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionAdd rawA rawB out = boundary $ do + argA <- deRefStablePtr rawA >>= getQuaternion + argB <- deRefStablePtr rawB >>= getQuaternion + checked (Q.add argA argB) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_scale" ffiQuaternionScale :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionScale :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionScale rawFactor rawValue out = boundary $ do + argFactor <- deRefStablePtr rawFactor >>= V.asScalar + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.scale argFactor argValue) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_rotate_vector" ffiQuaternionRotateVector :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionRotateVector :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionRotateVector rawValue rawVector out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + argVector <- deRefStablePtr rawVector >>= getVector + checked (Q.rotateVector argValue argVector) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_quaternion_axis_angle" ffiQuaternionAxisAngle :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionAxisAngle :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionAxisAngle rawAxis rawAngle out = boundary $ do + argAxis <- deRefStablePtr rawAxis >>= getVector + argAngle <- deRefStablePtr rawAngle >>= V.asScalar + checked (Q.axisAngle argAxis argAngle) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_to_axis_angle" ffiQuaternionToAxisAngle :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToAxisAngle :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToAxisAngle rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.toAxisAngle argValue) (\value -> V.publish (axisAngle value) out) + +foreign export ccall "hm_quaternion_from_euler" ffiQuaternionFromEuler :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionFromEuler :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionFromEuler rawRoll rawPitch rawYaw out = boundary $ do + argRoll <- deRefStablePtr rawRoll >>= V.asScalar + argPitch <- deRefStablePtr rawPitch >>= V.asScalar + argYaw <- deRefStablePtr rawYaw >>= V.asScalar + checked (Q.fromEuler argRoll argPitch argYaw) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_to_euler" ffiQuaternionToEuler :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToEuler :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToEuler rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.toEuler argValue) (\value -> V.publish (triple value) out) + +foreign export ccall "hm_quaternion_to_matrix" ffiQuaternionToMatrix :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToMatrix :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionToMatrix rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.toMatrix argValue) (\value -> V.publish (matrix value) out) + +foreign export ccall "hm_quaternion_from_matrix" ffiQuaternionFromMatrix :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionFromMatrix :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionFromMatrix rawMatrix out = boundary $ do + argMatrix <- deRefStablePtr rawMatrix >>= getMatrix + checked (Q.fromMatrix argMatrix) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_nlerp" ffiQuaternionNlerp :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionNlerp :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionNlerp rawFraction rawA rawB out = boundary $ do + argFraction <- deRefStablePtr rawFraction >>= V.asScalar + argA <- deRefStablePtr rawA >>= getQuaternion + argB <- deRefStablePtr rawB >>= getQuaternion + checked (Q.nlerp argFraction argA argB) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_slerp" ffiQuaternionSlerp :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSlerp :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSlerp rawFraction rawA rawB out = boundary $ do + argFraction <- deRefStablePtr rawFraction >>= V.asScalar + argA <- deRefStablePtr rawA >>= getQuaternion + argB <- deRefStablePtr rawB >>= getQuaternion + checked (Q.slerp argFraction argA argB) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_squad" ffiQuaternionSquad :: Handle -> Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSquad :: Handle -> Handle -> Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSquad rawFraction rawQ0 rawQ1 rawQ2 rawQ3 out = boundary $ do + argFraction <- deRefStablePtr rawFraction >>= V.asScalar + argQ0 <- deRefStablePtr rawQ0 >>= getQuaternion + argQ1 <- deRefStablePtr rawQ1 >>= getQuaternion + argQ2 <- deRefStablePtr rawQ2 >>= getQuaternion + argQ3 <- deRefStablePtr rawQ3 >>= getQuaternion + checked (Q.squad argFraction argQ0 argQ1 argQ2 argQ3) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_exponential" ffiQuaternionExponential :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionExponential :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionExponential rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.exponential argValue) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_logarithm" ffiQuaternionLogarithm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionLogarithm :: Handle -> Ptr Handle -> IO CInt +ffiQuaternionLogarithm rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.logarithm argValue) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_quaternion_swing_twist" ffiQuaternionSwingTwist :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSwingTwist :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiQuaternionSwingTwist rawAxis rawValue out = boundary $ do + argAxis <- deRefStablePtr rawAxis >>= getVector + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (Q.swingTwist argAxis argValue) (\value -> V.publish (quaternionPair value) out) + +foreign export ccall "hm_rotation_so3" ffiRotationSo3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationSo3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationSo3 rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getQuaternion + checked (R.so3 argValue) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_rotation_quaternion" ffiRotationRotationQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationRotationQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationRotationQuaternion rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getRotation + checked (Right (R.rotationQuaternion argValue)) (\value -> V.publish (quaternion value) out) + +foreign export ccall "hm_rotation_identity_rotation" ffiRotationIdentityRotation :: Ptr Handle -> IO CInt +ffiRotationIdentityRotation :: Ptr Handle -> IO CInt +ffiRotationIdentityRotation out = boundary $ do + checked (Right (R.identityRotation)) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_compose_rotation" ffiRotationComposeRotation :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationComposeRotation :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationComposeRotation rawA rawB out = boundary $ do + argA <- deRefStablePtr rawA >>= getRotation + argB <- deRefStablePtr rawB >>= getRotation + checked (R.composeRotation argA argB) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_inverse_rotation" ffiRotationInverseRotation :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverseRotation :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverseRotation rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getRotation + checked (Right (R.inverseRotation argValue)) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_rotate" ffiRotationRotate :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationRotate :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationRotate rawValue rawVector out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getRotation + argVector <- deRefStablePtr rawVector >>= getVector + checked (R.rotate argValue argVector) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_rotation_exp_so3" ffiRotationExpSO3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationExpSO3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationExpSO3 rawOmega out = boundary $ do + argOmega <- deRefStablePtr rawOmega >>= getVector + checked (R.expSO3 argOmega) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_log_so3" ffiRotationLogSO3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationLogSO3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationLogSO3 rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getRotation + checked (R.logSO3 argValue) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_rotation_se3" ffiRotationSe3 :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationSe3 :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationSe3 rawRotation rawTranslation out = boundary $ do + argRotation <- deRefStablePtr rawRotation >>= getRotation + argTranslation <- deRefStablePtr rawTranslation >>= getVector + checked (R.se3 argRotation argTranslation) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_rotation_part" ffiRotationRotationPart :: Handle -> Ptr Handle -> IO CInt +ffiRotationRotationPart :: Handle -> Ptr Handle -> IO CInt +ffiRotationRotationPart rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (Right (R.rotationPart argValue)) (\value -> V.publish (rotation value) out) + +foreign export ccall "hm_rotation_translation_part" ffiRotationTranslationPart :: Handle -> Ptr Handle -> IO CInt +ffiRotationTranslationPart :: Handle -> Ptr Handle -> IO CInt +ffiRotationTranslationPart rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (Right (R.translationPart argValue)) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_rotation_identity_transform" ffiRotationIdentityTransform :: Ptr Handle -> IO CInt +ffiRotationIdentityTransform :: Ptr Handle -> IO CInt +ffiRotationIdentityTransform out = boundary $ do + checked (Right (R.identityTransform)) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_compose" ffiRotationCompose :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationCompose :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationCompose rawA rawB out = boundary $ do + argA <- deRefStablePtr rawA >>= getTransform + argB <- deRefStablePtr rawB >>= getTransform + checked (R.compose argA argB) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_inverse" ffiRotationInverse :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverse :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverse rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (R.inverse argValue) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_transform_point" ffiRotationTransformPoint :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationTransformPoint :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationTransformPoint rawValue rawPoint out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + argPoint <- deRefStablePtr rawPoint >>= getVector + checked (R.transformPoint argValue argPoint) (\value -> V.publish (vector value) out) + +foreign export ccall "hm_rotation_exp_se3" ffiRotationExpSE3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationExpSE3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationExpSE3 rawTwist out = boundary $ do + argTwist <- deRefStablePtr rawTwist >>= getTwist + checked (R.expSE3 argTwist) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_log_se3" ffiRotationLogSE3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationLogSE3 :: Handle -> Ptr Handle -> IO CInt +ffiRotationLogSE3 rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (R.logSE3 argValue) (\value -> V.publish (twist value) out) + +foreign export ccall "hm_rotation_to_homogeneous" ffiRotationToHomogeneous :: Handle -> Ptr Handle -> IO CInt +ffiRotationToHomogeneous :: Handle -> Ptr Handle -> IO CInt +ffiRotationToHomogeneous rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (R.toHomogeneous argValue) (\value -> V.publish (matrix value) out) + +foreign export ccall "hm_rotation_from_homogeneous" ffiRotationFromHomogeneous :: Handle -> Ptr Handle -> IO CInt +ffiRotationFromHomogeneous :: Handle -> Ptr Handle -> IO CInt +ffiRotationFromHomogeneous rawMatrix out = boundary $ do + argMatrix <- deRefStablePtr rawMatrix >>= getMatrix + checked (R.fromHomogeneous argMatrix) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_dual_quaternion" ffiRotationDualQuaternion :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationDualQuaternion :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationDualQuaternion rawReal rawDual out = boundary $ do + argReal <- deRefStablePtr rawReal >>= getQuaternion + argDual <- deRefStablePtr rawDual >>= getQuaternion + checked (R.dualQuaternion argReal argDual) (\value -> V.publish (dualQuaternion value) out) + +foreign export ccall "hm_rotation_dual_parts" ffiRotationDualParts :: Handle -> Ptr Handle -> IO CInt +ffiRotationDualParts :: Handle -> Ptr Handle -> IO CInt +ffiRotationDualParts rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getDualQuaternion + checked (Right (R.dualParts argValue)) (\value -> V.publish (quaternionPair value) out) + +foreign export ccall "hm_rotation_to_dual_quaternion" ffiRotationToDualQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationToDualQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationToDualQuaternion rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getTransform + checked (R.toDualQuaternion argValue) (\value -> V.publish (dualQuaternion value) out) + +foreign export ccall "hm_rotation_from_dual_quaternion" ffiRotationFromDualQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationFromDualQuaternion :: Handle -> Ptr Handle -> IO CInt +ffiRotationFromDualQuaternion rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getDualQuaternion + checked (R.fromDualQuaternion argValue) (\value -> V.publish (transform value) out) + +foreign export ccall "hm_rotation_multiply_dual" ffiRotationMultiplyDual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationMultiplyDual :: Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationMultiplyDual rawA rawB out = boundary $ do + argA <- deRefStablePtr rawA >>= getDualQuaternion + argB <- deRefStablePtr rawB >>= getDualQuaternion + checked (R.multiplyDual argA argB) (\value -> V.publish (dualQuaternion value) out) + +foreign export ccall "hm_rotation_inverse_dual" ffiRotationInverseDual :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverseDual :: Handle -> Ptr Handle -> IO CInt +ffiRotationInverseDual rawValue out = boundary $ do + argValue <- deRefStablePtr rawValue >>= getDualQuaternion + checked (R.inverseDual argValue) (\value -> V.publish (dualQuaternion value) out) + +foreign export ccall "hm_rotation_interpolate_dual" ffiRotationInterpolateDual :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationInterpolateDual :: Handle -> Handle -> Handle -> Ptr Handle -> IO CInt +ffiRotationInterpolateDual rawFraction rawA rawB out = boundary $ do + argFraction <- deRefStablePtr rawFraction >>= V.asScalar + argA <- deRefStablePtr rawA >>= getDualQuaternion + argB <- deRefStablePtr rawB >>= getDualQuaternion + checked (R.interpolateDual argFraction argA argB) (\value -> V.publish (dualQuaternion value) out) diff --git a/src/HMath/FFI/ScalarExtras.hs b/src/HMath/FFI/ScalarExtras.hs new file mode 100644 index 0000000..bda2e1f --- /dev/null +++ b/src/HMath/FFI/ScalarExtras.hs @@ -0,0 +1,196 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_scalar_extras.py; all mathematics is original. +module HMath.FFI.ScalarExtras where +import Control.Exception (evaluate,throwIO) +import Data.Complex (Complex) +import Data.Typeable (cast) +import Foreign +import Foreign.C +import HMath.Error (MathError) +import HMath.FFI.Boundary +import HMath.FFI.Coefficient (ScalarType(SComplexDouble,SComplexFloat)) +import HMath.FFI.MathError (CallbackFailure(..)) +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.GraphCodec as W +import qualified HMath.Complex as C +import qualified HMath.Trigonometry as T +import qualified HMath.NumberTheory as N +import qualified HMath.Special as S +import qualified HMath.Matrix as M +source :: Either MathError a -> IO a +source = either (throwIO . CallbackMathError) pure +elementary :: C.Elementary -> V.Value +elementary value = V.Opaque 352 (-1) 0 (evaluate value >> pure ()) value +complexFunction :: T.ComplexFunction -> V.Value +complexFunction value = V.Opaque 353 (-1) 0 (evaluate value >> pure ()) value +getElementary :: V.Value -> IO C.Elementary +getElementary = W.unboxed 352 +getComplexFunction :: V.Value -> IO T.ComplexFunction +getComplexFunction = W.unboxed 353 +complexDoubleValue :: Complex Double -> V.Value +complexDoubleValue = V.Scalar SComplexDouble +matrix :: M.Matrix (Complex Double) -> V.Value +matrix = V.Dense . V.SomeMatrix SComplexDouble +getMatrix :: V.Value -> IO (M.Matrix (Complex Double)) +getMatrix (V.Dense (V.SomeMatrix _ value)) = maybe (V.invalid "Complex Double matrix required") pure (cast value) +getMatrix _ = V.invalid "dense complex matrix required" +sfResult :: S.SFResult -> V.Value +sfResult value = V.Tuple [W.wire (S.sfValue value),W.wire (S.sfError value)] +getSFResult :: V.Value -> IO S.SFResult +getSFResult value = do + fields <- V.asTuple 2 value + case fields of [a,b] -> S.SFResult <$> W.unwire a <*> W.unwire b;_ -> V.invalid "SFResult field count differs" +trigonometric :: T.ComplexFunction -> V.Value -> IO V.Value +trigonometric operation value = case value of + V.Scalar SComplexDouble x -> source (T.complexFunction operation x) >>= pure . V.Scalar SComplexDouble + V.Scalar SComplexFloat x -> source (T.complexFunction operation x) >>= pure . V.Scalar SComplexFloat + _ -> V.invalid "complexFunction requires actual Complex Float or Complex Double" +foreign export ccall "hm_scalar_extras_apply" apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +apply operation inputs arity out = boundary $ do + values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr + result <- case (operation,values) of + (0,[]) -> do + pure (elementary C.Exp) + (1,[]) -> do + pure (elementary C.Log) + (2,[]) -> do + pure (elementary C.Sqrt) + (3,[]) -> do + pure (elementary C.Sin) + (4,[]) -> do + pure (elementary C.Cos) + (5,[]) -> do + pure (elementary C.Tan) + (6,[]) -> do + pure (elementary C.Sinh) + (7,[]) -> do + pure (elementary C.Cosh) + (8,[]) -> do + pure (elementary C.Tanh) + (9,[]) -> do + pure (elementary C.Asin) + (10,[]) -> do + pure (elementary C.Acos) + (11,[]) -> do + pure (elementary C.Atan) + (12,[]) -> do + pure (elementary C.Asinh) + (13,[]) -> do + pure (elementary C.Acosh) + (14,[]) -> do + pure (elementary C.Atanh) + (15,[]) -> do + pure (complexFunction T.CSin) + (16,[]) -> do + pure (complexFunction T.CCos) + (17,[]) -> do + pure (complexFunction T.CTan) + (18,[]) -> do + pure (complexFunction T.CAsin) + (19,[]) -> do + pure (complexFunction T.CAcos) + (20,[]) -> do + pure (complexFunction T.CAtan) + (21,[]) -> do + pure (complexFunction T.CSinh) + (22,[]) -> do + pure (complexFunction T.CCosh) + (23,[]) -> do + pure (complexFunction T.CTanh) + (24,[]) -> do + pure (complexFunction T.CAsinh) + (25,[]) -> do + pure (complexFunction T.CAcosh) + (26,[]) -> do + pure (complexFunction T.CAtanh) + (27,[]) -> do + pure (complexFunction T.CSec) + (28,[]) -> do + pure (complexFunction T.CCsc) + (29,[]) -> do + pure (complexFunction T.CCot) + (30,[]) -> do + pure (complexFunction T.CSech) + (31,[]) -> do + pure (complexFunction T.CCsch) + (32,[]) -> do + pure (complexFunction T.CCoth) + (33,[voperation,vvalue]) -> do + argOperation <- getElementary voperation + argValue <- V.asScalar vvalue + source (C.elementary argOperation argValue) >>= pure . complexDoubleValue + (34,[vrows,vcolumns,vvalues]) -> do + argRows <- W.unwire vrows + argColumns <- W.unwire vcolumns + argValues <- (\value -> V.asList value >>= mapM V.asScalar) vvalues + source (C.complexMatrix argRows argColumns argValues) >>= pure . matrix + (35,[va,vb]) -> do + argA <- getMatrix va + argB <- getMatrix vb + source (C.multiplyMatrices argA argB) >>= pure . matrix + (36,[vvalue]) -> do + argValue <- getMatrix vvalue + source (C.conjugateTranspose argValue) >>= pure . matrix + (37,[vvalues]) -> do + argValues <- (\value -> V.asList value >>= mapM V.asScalar) vvalues + source (C.complexFFT argValues) >>= pure . V.List . map complexDoubleValue + (38,[vvalues]) -> do + argValues <- (\value -> V.asList value >>= mapM V.asScalar) vvalues + source (C.complexIFFT argValues) >>= pure . V.List . map complexDoubleValue + (39,[voperation,vvalue]) -> do + argOperation <- getComplexFunction voperation + argValue <- pure vvalue + trigonometric argOperation argValue + (40,[vcongruences]) -> do + argCongruences <- W.unwire vcongruences + source (N.chineseRemainder argCongruences) >>= pure . W.wire + (41,[va,vb,vc]) -> do + argA <- W.unwire va + argB <- W.unwire vb + argC <- W.unwire vc + source (N.linearDiophantine argA argB argC) >>= pure . W.wire + (42,[vvalue]) -> do + argValue <- W.unwire vvalue + pure (N.perfectPower argValue) >>= pure . W.wire + (43,[vbudget,vvalue]) -> do + argBudget <- W.unwire vbudget + argValue <- W.unwire vvalue + source (N.primeFactorization argBudget argValue) >>= pure . W.wire + (44,[vvalue]) -> do + argValue <- W.unwire vvalue + source (N.partitions argValue) >>= pure . W.wire + (45,[vvalue,verror]) -> do + argValue <- W.unwire vvalue + argError <- W.unwire verror + pure (sfResult (S.SFResult argValue argError)) + (46,[vvalue]) -> do + argValue <- getSFResult vvalue + pure (W.wire (S.sfValue argValue)) + (47,[vvalue]) -> do + argValue <- getSFResult vvalue + pure (W.wire (S.sfError argValue)) + _ -> V.invalid "scalar adapter identifier or arity differs" + checked (Right result) (`V.publish` out) +foreign export ccall "hm_scalar_selector_name" selectorName :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +selectorName :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +selectorName input out = boundary $ do + value <- deRefStablePtr input + name <- case V.valueInfo value of + (352,_,_) -> show <$> getElementary value + (353,_,_) -> show <$> getComplexFunction value + _ -> V.invalid "expected complex selector" + checked (Right (V.Text name)) (`V.publish` out) +foreign export ccall "hm_scalar_selector_equal" selectorEqual :: StablePtr V.Value -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +selectorEqual :: StablePtr V.Value -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +selectorEqual left right out = boundary $ do + a <- deRefStablePtr left + b <- deRefStablePtr right + equal <- case (V.valueInfo a,V.valueInfo b) of + ((352,_,_),(352,_,_)) -> (==) <$> getElementary a <*> getElementary b + ((353,_,_),(353,_,_)) -> (==) <$> getComplexFunction a <*> getComplexFunction b + _ -> pure False + checked (Right (V.Boolean equal)) (`V.publish` out) diff --git a/src/HMath/FFI/ShapeAll.hs b/src/HMath/FFI/ShapeAll.hs new file mode 100644 index 0000000..dd9e599 --- /dev/null +++ b/src/HMath/FFI/ShapeAll.hs @@ -0,0 +1,38 @@ +{-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated calls to original shape APIs and typed representation helpers. +module HMath.FFI.ShapeAll where +import Foreign +import Foreign.C +import qualified HMath.API.Shape as S +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.FoundationCodec(source,foundationBoundary) +import HMath.FFI.ShapeCodec hiding(shape,coordinates) +import qualified HMath.FFI.ShapeCodec as Codec +apply :: Int -> [V.Value] -> IO V.Value +apply operation args=case(operation,args)of + (0,[shape]) -> asShape shape >>= pure . V.List . map V.Index . S.shapeDimensions + (1,[shape]) -> asShape shape >>= pure . V.Index . S.shapeElements + (2,[dimensions]) -> do {ds <- V.asList dimensions >>= mapM V.asIndex;Codec.shape <$> source(S.makeShape ds)} + (3,[shape]) -> do {s <- asShape shape;pure(V.Boolean(case s of S.ScalarShape -> True;_ -> False))} + (4,[shape]) -> do {s <- asShape shape;pure(case s of S.VectorShape n -> V.Index n;_ -> V.None)} + (5,[shape]) -> do {s <- asShape shape;pure(case s of S.MatrixShape r c -> V.Tuple[V.Index r,V.Index c];_ -> V.None)} + (6,[rows,columns,matrix]) -> do {r <- V.asScalar rows;c <- V.asScalar columns;staticMatrix r c matrix} + (7,[matrix]) -> dynamicMatrix matrix + (8,[left,right]) -> staticMultiply left right + (9,[matrix]) -> staticTranspose matrix + (10,[dimensions]) -> V.asList dimensions >>= mapM V.asScalar >>= reflectedShape + (11,[dimensions,tensor]) -> do {ds <- V.asList dimensions >>= mapM V.asScalar;staticTensor ds tensor} + (12,[tensor]) -> dynamicTensor tensor + (13,[prototype,count,values]) -> do {n <- V.asScalar count;xs <- V.asList values;coordinatesFrom prototype n xs} + (14,[coordinates]) -> coordinateValues coordinates + (15,[coordinates]) -> coordinatesToVector coordinates + _ -> V.invalid "invalid shape operation/arity" +foreign export ccall "hm_shape_apply" ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(V.publish value out)) diff --git a/src/HMath/FFI/ShapeCodec.hs b/src/HMath/FFI/ShapeCodec.hs new file mode 100644 index 0000000..631b59e --- /dev/null +++ b/src/HMath/FFI/ShapeCodec.hs @@ -0,0 +1,123 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE FlexibleContexts #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Reify real source KnownNat/KnownShape indices; never coerce dimensions. +module HMath.FFI.ShapeCodec where + +import Control.Exception(evaluate) +import Data.Proxy(Proxy(..)) +import Data.Typeable(Typeable,cast) +import Data.Type.Equality((:~:)(Refl)) +import GHC.TypeLits(Nat,KnownNat,SomeNat(..),someNatVal,sameNat) +import qualified HMath.API.Shape as S +import qualified HMath.Matrix as M +import qualified HMath.Error as E +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.TensorCodec as TC +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec +import HMath.FFI.AlgebraCodec(Wire(..),coefficientWire,wireCode,forceWire,writeWire,withMatrix,matrix,algebraElement) + +shape :: S.Shape -> V.Value +shape value=opaqueEq "HMath.API.Shape.Shape" (-1)value(evaluate(S.shapeElements value)>>pure())(V.unsupported "original abstract Shape has no public constructor fields") +asShape :: V.Value -> IO S.Shape +asShape=unbox "HMath.API.Shape.Shape" + +data SomeStaticMatrix where + SomeStaticMatrix :: (KnownNat m,KnownNat n,Typeable a) => Wire a -> Maybe(Dict(Num a)) -> (M.Matrix a -> V.Value) -> S.StaticMatrix m n a -> SomeStaticMatrix +static :: SomeStaticMatrix -> V.Value +static payload@(SomeStaticMatrix wire _ _ value)=opaque "HMath.API.Shape.StaticMatrix" (wireCode wire)payload(mapM_(forceWire wire)(M.toList(S.dynamicMatrix value)))(V.unsupported "original abstract StaticMatrix has no public constructor fields") +asStatic :: V.Value -> IO SomeStaticMatrix +asStatic=unbox "HMath.API.Shape.StaticMatrix" +staticFrom :: forall a. Typeable a => Wire a -> Maybe(Dict(Num a)) -> (M.Matrix a -> V.Value) -> Integer -> Integer -> M.Matrix a -> IO V.Value +staticFrom wire numeric publish rows columns input=case(someNatVal rows,someNatVal columns) of + (Just(SomeNat(_::Proxy m)),Just(SomeNat(_::Proxy n))) -> do + result <- source(S.staticMatrix input::Either E.MathError(S.StaticMatrix m n a)) + pure(static(SomeStaticMatrix wire numeric publish result)) + _ -> V.invalid "type-level matrix dimensions must be nonnegative naturals" +staticMatrix :: Integer -> Integer -> V.Value -> IO V.Value +staticMatrix rows columns value=case value of + V.Dense(V.SomeMatrix w input) -> staticFrom(coefficientWire w)(Just Dict)(V.Dense . V.SomeMatrix w)rows columns input + _ -> withMatrix value $ \wire input -> staticFrom wire Nothing(matrix wire)rows columns input +dynamicMatrix :: V.Value -> IO V.Value +dynamicMatrix input=do SomeStaticMatrix _ _ publish value <- asStatic input;pure(publish(S.dynamicMatrix value)) +staticTranspose :: V.Value -> IO V.Value +staticTranspose input=do SomeStaticMatrix wire numeric publish value <- asStatic input;pure(static(SomeStaticMatrix wire numeric publish(S.staticTranspose value))) +staticMultiply :: V.Value -> V.Value -> IO V.Value +staticMultiply leftValue rightValue=do + SomeStaticMatrix wire numeric publish(left::S.StaticMatrix m k a) <- asStatic leftValue + SomeStaticMatrix _ _ _(right::S.StaticMatrix l n b) <- asStatic rightValue + case sameNat(Proxy::Proxy k)(Proxy::Proxy l) of + Nothing -> V.invalid "staticMultiply requires matching nominal inner dimensions" + Just Refl -> case cast right of + Nothing -> V.invalid "staticMultiply element types differ" + Just other -> case numeric of + Nothing -> V.unsupported "original staticMultiply requires Num elements" + Just Dict -> do + result <- source(S.staticMultiply left(other::S.StaticMatrix k n a)) + pure(static(SomeStaticMatrix wire numeric publish result)) + +data ShapeWitness where + ShapeWitness :: S.KnownShape(ds::[Nat]) => Proxy ds -> ShapeWitness +shapeWitness :: [Integer] -> IO ShapeWitness +shapeWitness []=pure(ShapeWitness(Proxy::Proxy('[]::[Nat]))) +shapeWitness(n:ns)=case someNatVal n of + Nothing -> V.invalid "type-level tensor dimensions must be nonnegative naturals" + Just(SomeNat(_::Proxy n)) -> do + ShapeWitness(_::Proxy ds) <- shapeWitness ns + pure(ShapeWitness(Proxy::Proxy(n ': ds))) +reflectedShape :: [Integer] -> IO V.Value +reflectedShape dimensions=do ShapeWitness witness <- shapeWitness dimensions;pure(V.List(map(V.Scalar SInteger)(S.reflectedShape witness))) +data SomeStaticTensor where + SomeStaticTensor :: (S.KnownShape ds,Typeable a,Eq a,Show a) => TC.Element a -> S.StaticTensor ds a -> SomeStaticTensor +staticTensorValue :: SomeStaticTensor -> V.Value +staticTensorValue payload@(SomeStaticTensor kind value)=opaque "HMath.API.Shape.StaticTensor" (TC.elementCode kind)payload(V.forceValue(TC.fromTensor kind(S.dynamicTensor value)))(V.unsupported "original abstract StaticTensor has no public constructor fields") +staticTensor :: [Integer] -> V.Value -> IO V.Value +staticTensor dimensions input=do + ShapeWitness(_::Proxy ds) <- shapeWitness dimensions + TC.SomeTensor(kind::TC.Element a) tensor <- TC.asTensor input + result <- source(S.staticTensor tensor::Either E.MathError(S.StaticTensor ds a)) + pure(staticTensorValue(SomeStaticTensor kind result)) +dynamicTensor :: V.Value -> IO V.Value +dynamicTensor input=do SomeStaticTensor kind value <- unbox "HMath.API.Shape.StaticTensor" input;pure(TC.fromTensor kind(S.dynamicTensor value)) + +data SomeCoordinates where + SomeCoordinates :: (KnownNat n,Typeable a) => Wire a -> Maybe(ScalarType a) -> S.Coordinates n a -> SomeCoordinates +coordinatesValue :: SomeCoordinates -> V.Value +coordinatesValue payload@(SomeCoordinates wire _ value)=opaque "HMath.API.Shape.Coordinates" (wireCode wire)payload(mapM_(forceWire wire)(S.coordinateValues value))(V.unsupported "original abstract Coordinates has no public constructor fields") +coordinates :: forall a. Typeable a => Wire a -> Maybe(ScalarType a) -> Integer -> [a] -> IO V.Value +coordinates wire numeric count values=case someNatVal count of + Nothing -> V.invalid "coordinate type-level length must be a nonnegative natural" + Just(SomeNat(_::Proxy n)) -> do + result <- source(S.coordinates values::Either E.MathError(S.Coordinates n a)) + pure(coordinatesValue(SomeCoordinates wire numeric result)) +coordinatesFrom :: V.Value -> Integer -> [V.Value] -> IO V.Value +coordinatesFrom prototype count values=do + TC.SomeElement kind <- algebraElement prototype + let wire=Wire(pure . TC.scalar kind)(TC.asElement kind)(TC.forceElement kind)(TC.elementCode kind) + numeric=case kind of TC.Numeric witness -> Just witness;_ -> Nothing + xs <- mapM(TC.asElement kind)values + coordinates wire numeric count xs +coordinateValues :: V.Value -> IO V.Value +coordinateValues input=do + SomeCoordinates wire _ value <- unbox "HMath.API.Shape.Coordinates" input + V.List <$> mapM(writeWire wire)(S.coordinateValues value) +coordinatesToVector :: V.Value -> IO V.Value +coordinatesToVector input=do + SomeCoordinates wire numeric value <- unbox "HMath.API.Shape.Coordinates" input + vector <- source(S.coordinatesToVector value) + case numeric of + Just w -> withCoefficient w $ LC.encodeVector w vector + Nothing -> case wire of Wire write readValue force code -> pure(LC.encodeStructuralVector code write readValue force vector) +withCoefficient :: ScalarType a -> (Coefficient a => IO V.Value) -> IO V.Value +withCoefficient w action=case w of + SDouble -> action;SFloat -> action;SInteger -> action;SRational -> action;SComplexDouble -> action;SComplexFloat -> action + SInt8 -> action;SInt16 -> action;SInt32 -> action;SInt64 -> action;SWord8 -> action;SWord16 -> action;SWord32 -> action;SWord64 -> action;SInt -> action;SWord -> action + SDual child -> withCoefficient child action + SQuaternion _ -> action diff --git a/src/HMath/FFI/SpectralAll.hs b/src/HMath/FFI/SpectralAll.hs new file mode 100644 index 0000000..f6abc10 --- /dev/null +++ b/src/HMath/FFI/SpectralAll.hs @@ -0,0 +1,286 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated representation adapters; numerical functions are the originals. +module HMath.FFI.SpectralAll where +import Foreign +import Foreign.C +import qualified HMath.FFI.Boundary as B +import HMath.FFI.NumericalCodec +import qualified HMath.FFI.Value as V +import qualified HMath.Signal as S +import qualified HMath.Interpolation as I +import qualified HMath.Fourier as F +import HMath.FFI.NumericalAll () +import Data.Complex (Complex) +instance From S.Filter where from = unbox 360 +instance To S.Filter where + to value = pure (box 360 value [to (S.filterCoefficients value),to (S.filterState value)]) +instance From S.FilterFamily where from = unbox 361 +instance To S.FilterFamily where + to value = pure (box 361 value []) +instance From S.FilterBand where from = unbox 362 +instance To S.FilterBand where + to value = pure (box 362 value []) +instance From S.Window where from = unbox 363 +instance To S.Window where + to value = pure (box 363 value []) +instance From S.Peak where from = unbox 364 +instance To S.Peak where + to value = pure (box 364 value [to (S.peakIndex value),to (S.peakHeight value),to (S.peakProminence value),to (S.peakWidth value)]) +instance From S.Wavelet where from = unbox 365 +instance To S.Wavelet where + to value = pure (box 365 value []) +instance From S.WaveletTree where from = unbox 366 +instance To S.WaveletTree where + to value = pure (box 366 value [to (S.waveletApproximation value),to (S.waveletDetails value)]) +instance From S.MotherWavelet where from = unbox 367 +instance To S.MotherWavelet where + to value = pure (box 367 value []) +instance From S.WaveletPacket where from = unbox 368 +instance To S.WaveletPacket where + to value = pure (box 368 value [to (S.packetBands value)]) +instance From I.Extrapolation where from = unbox 369 +instance To I.Extrapolation where + to value = pure (box 369 value []) +instance From I.InterpolationMethod where from = unbox 370 +instance To I.InterpolationMethod where + to value = pure (box 370 value []) +instance From I.SplineBoundary where from = unbox 371 +instance To I.SplineBoundary where + to value = pure (box 371 value []) +instance From I.PiecewisePolynomial where from = unbox 372 +instance To I.PiecewisePolynomial where + to value = pure (box 372 value [to (I.piecewiseKnots value)]) +instance From I.BSpline where from = unbox 373 +instance To I.BSpline where + to value = pure (box 373 value []) +instance From I.RadialKernel where from = unbox 374 +instance To I.RadialKernel where + to value = pure (box 374 value []) +instance From I.RBF where from = unbox 375 +instance To I.RBF where + to value = pure (box 375 value []) +instance From I.Approximation where from = unbox 376 +instance To I.Approximation where + to value = pure (box 376 value [to (I.approximationCoefficients value),to (I.approximationError value),to (I.approximationIterations value)]) +instance From F.Direction where from = unbox 377 +instance To F.Direction where + to value = pure (box 377 value []) +instance From F.FFTAlgorithm where from = unbox 378 +instance To F.FFTAlgorithm where + to value = pure (box 378 value []) +instance From F.FFTPlan where from = unbox 379 +instance To F.FFTPlan where + to value = pure (box 379 value []) +instance From F.TransformType where from = unbox 380 +instance To F.TransformType where + to value = pure (box 380 value []) +instance From F.STFT where from = unbox 381 +instance To F.STFT where + to value = pure (box 381 value [to (F.stftFrames value)]) +foreign export ccall "hm_spectral_apply" dispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +dispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +dispatch operation input arity out = B.boundary $ do + values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr + result <- case operation of + 0 -> apply S.iir values + 1 -> apply S.fir values + 2 -> apply S.filterCoefficients values + 3 -> apply S.filterState values + 4 -> apply S.resetFilter values + 5 -> apply S.filterSignal values + 6 -> apply S.frequencyResponse values + 7 -> apply S.Butterworth values + 8 -> apply S.ChebyshevI values + 9 -> apply S.ChebyshevII values + 10 -> apply S.Elliptic values + 11 -> apply S.Bessel values + 12 -> apply S.Lowpass values + 13 -> apply S.Highpass values + 14 -> apply S.Bandpass values + 15 -> apply S.Bandstop values + 16 -> apply S.designIIR values + 17 -> apply S.notch values + 18 -> apply S.allPass values + 19 -> apply S.wiener values + 20 -> apply S.Hann values + 21 -> apply S.Hamming values + 22 -> apply S.Blackman values + 23 -> apply S.Bartlett values + 24 -> apply S.Kaiser values + 25 -> apply S.Gaussian values + 26 -> apply S.Tukey values + 27 -> apply S.FlatTop values + 28 -> apply S.DolphChebyshev values + 29 -> apply S.window values + 30 -> apply S.windowedSinc values + 31 -> apply S.Peak values + 32 -> apply S.peakIndex values + 33 -> apply S.peakHeight values + 34 -> apply S.peakProminence values + 35 -> apply S.peakWidth values + 36 -> apply S.peaks values + 37 -> apply S.kalman values + 38 -> apply S.extendedKalman values + 39 -> apply S.unscentedKalman values + 40 -> apply S.Haar values + 41 -> apply S.Daubechies2 values + 42 -> apply S.Daubechies4 values + 43 -> apply S.Biorthogonal53 values + 44 -> apply S.waveletApproximation values + 45 -> apply S.waveletDetails values + 46 -> apply S.dwt values + 47 -> apply S.idwt values + 48 -> apply S.Morlet values + 49 -> apply S.MexicanHat values + 50 -> apply S.GaussianDerivative values + 51 -> apply S.cwt values + 52 -> apply S.waveletPackets values + 53 -> apply S.inverseWaveletPackets values + 54 -> apply S.packetBands values + 55 -> apply S.waveletDenoise values + 56 -> apply I.Reject values + 57 -> apply I.Clamp values + 58 -> apply I.Extrapolate values + 59 -> apply I.Nearest values + 60 -> apply I.Linear values + 61 -> apply I.Lagrange values + 62 -> apply I.Newton values + 63 -> apply I.Barycentric values + 64 -> apply I.Natural values + 65 -> apply I.Clamped values + 66 -> apply I.Periodic values + 67 -> apply I.Gaussian values + 68 -> apply I.Multiquadric values + 69 -> apply I.InverseMultiquadric values + 70 -> apply I.ThinPlate values + 71 -> apply I.Cubic values + 72 -> apply I.Approximation values + 73 -> apply I.approximationCoefficients values + 74 -> apply I.approximationError values + 75 -> apply I.approximationIterations values + 76 -> apply I.interpolate values + 77 -> apply I.hermite values + 78 -> apply I.piecewisePolynomial values + 79 -> apply I.piecewiseKnots values + 80 -> apply I.evaluatePiecewise values + 81 -> apply I.differentiatePiecewise values + 82 -> apply I.integratePiecewise values + 83 -> apply I.cubicHermite values + 84 -> apply I.cubicSpline values + 85 -> apply I.pchip values + 86 -> apply I.akima values + 87 -> apply I.smoothingSpline values + 88 -> apply I.bSpline values + 89 -> apply I.evaluateBSpline values + 90 -> apply I.derivativeBSpline values + 91 -> apply I.insertKnot values + 92 -> apply I.rationalBezier values + 93 -> apply I.bezier values + 94 -> apply I.kochanekBartels values + 95 -> apply I.cardinalSpline values + 96 -> apply I.catmullRom values + 97 -> apply I.curveIntegral values + 98 -> apply I.arcLength values + 99 -> apply I.gridInterpolate values + 100 -> apply I.fitRBF values + 101 -> apply I.evaluateRBF values + 102 -> apply I.inverseDistance values + 103 -> apply I.shepard values + 104 -> apply I.kriging values + 105 -> apply I.polynomialFit values + 106 -> apply I.chebyshevApproximate values + 107 -> apply I.pade values + 108 -> apply I.rationalFit values + 109 -> apply I.remez values + 110 -> apply I.nonlinearFit values + 111 -> apply I.interpolationError values + 112 -> apply F.Forward values + 113 -> apply F.Inverse values + 114 -> apply F.Automatic values + 115 -> apply F.Direct values + 116 -> apply F.Radix2 values + 117 -> apply F.Radix4 values + 118 -> apply F.MixedRadix values + 119 -> apply F.SplitRadix values + 120 -> apply F.Bluestein values + 121 -> apply F.Rader values + 122 -> apply F.TypeI values + 123 -> apply F.TypeII values + 124 -> apply F.TypeIII values + 125 -> apply F.TypeIV values + 126 -> apply F.planFFT values + 127 -> apply F.executeFFT values + 128 -> apply F.fft values + 129 -> apply F.ifft values + 130 -> apply F.dft values + 131 -> apply F.realFFT values + 132 -> apply F.inverseRealFFT values + 133 -> apply F.fftBatch values + 134 -> apply F.fftND values + 135 -> apply F.dct values + 136 -> apply F.idct values + 137 -> apply F.dst values + 138 -> apply F.idst values + 139 -> apply F.stftFrames values + 140 -> apply F.stft values + 141 -> apply F.istft values + 142 -> apply F.magnitudeSpectrum values + 143 -> apply F.phaseSpectrum values + 144 -> apply F.powerSpectrum values + 145 -> apply F.crossSpectrum values + 146 -> apply F.spectrogram values + 147 -> apply F.analyticSignal values + 148 -> apply F.chirpZ values + 149 -> apply F.goertzel values + 150 -> apply F.fftConvolve values + 151 -> apply F.fftCorrelate values + 152 -> apply (F.fftShift :: [V.Value] -> [V.Value]) values + 153 -> apply (F.ifftShift :: [V.Value] -> [V.Value]) values + _ -> V.invalid "unknown numerical operation" + V.forceValue result + B.checked (Right ()) (\_ -> V.publish result out) + +instance From S.GaussianState where from = unbox 140 +instance To S.GaussianState where + to value = pure (box 140 value [to (S.stateMean value),to (S.stateCovariance value)]) + +foreign export ccall "hm_spectral_fft_in_place" rawFFT :: StablePtr V.Value -> Ptr (Complex Double) -> CPtrdiff -> IO CInt +rawFFT :: StablePtr V.Value -> Ptr (Complex Double) -> CPtrdiff -> IO CInt +rawFFT input pointer count = B.boundary $ do + plan <- deRefStablePtr input >>= from + outcome <- F.fftInPlace plan pointer (fromIntegral count) + B.checked outcome (const (pure ())) + +foreign export ccall "hm_spectral_describe" describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +describe input out = B.boundary $ do + value <- deRefStablePtr input + rendered <- case value of + V.Opaque 360 _ _ _ _ -> show <$> (from value :: IO S.Filter) + V.Opaque 361 _ _ _ _ -> show <$> (from value :: IO S.FilterFamily) + V.Opaque 362 _ _ _ _ -> show <$> (from value :: IO S.FilterBand) + V.Opaque 363 _ _ _ _ -> show <$> (from value :: IO S.Window) + V.Opaque 364 _ _ _ _ -> show <$> (from value :: IO S.Peak) + V.Opaque 365 _ _ _ _ -> show <$> (from value :: IO S.Wavelet) + V.Opaque 366 _ _ _ _ -> show <$> (from value :: IO S.WaveletTree) + V.Opaque 367 _ _ _ _ -> show <$> (from value :: IO S.MotherWavelet) + V.Opaque 368 _ _ _ _ -> show <$> (from value :: IO S.WaveletPacket) + V.Opaque 369 _ _ _ _ -> show <$> (from value :: IO I.Extrapolation) + V.Opaque 370 _ _ _ _ -> show <$> (from value :: IO I.InterpolationMethod) + V.Opaque 371 _ _ _ _ -> show <$> (from value :: IO I.SplineBoundary) + V.Opaque 372 _ _ _ _ -> show <$> (from value :: IO I.PiecewisePolynomial) + V.Opaque 373 _ _ _ _ -> show <$> (from value :: IO I.BSpline) + V.Opaque 374 _ _ _ _ -> show <$> (from value :: IO I.RadialKernel) + V.Opaque 375 _ _ _ _ -> show <$> (from value :: IO I.RBF) + V.Opaque 376 _ _ _ _ -> show <$> (from value :: IO I.Approximation) + V.Opaque 377 _ _ _ _ -> show <$> (from value :: IO F.Direction) + V.Opaque 378 _ _ _ _ -> show <$> (from value :: IO F.FFTAlgorithm) + V.Opaque 379 _ _ _ _ -> show <$> (from value :: IO F.FFTPlan) + V.Opaque 380 _ _ _ _ -> show <$> (from value :: IO F.TransformType) + V.Opaque 381 _ _ _ _ -> show <$> (from value :: IO F.STFT) + V.Opaque 140 _ _ _ _ -> show <$> (from value :: IO S.GaussianState) + _ -> V.invalid "expected a spectral-domain object" + B.checked (Right ()) (const (V.publish (V.Text rendered) out)) diff --git a/src/HMath/FFI/Stochastic.hs b/src/HMath/FFI/Stochastic.hs new file mode 100644 index 0000000..31d7f31 --- /dev/null +++ b/src/HMath/FFI/Stochastic.hs @@ -0,0 +1,864 @@ +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; original algorithms and complete immutable continuation states. +module HMath.FFI.Stochastic where +import Control.Exception (catch,evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import qualified HMath.Matrix as M +import HMath.FFI.Coefficient +import HMath.FFI.RandomCodec (rng,asRNG) +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.MathError +import qualified HMath.Random as R +import qualified HMath.Probability as P +import qualified HMath.Statistics.Advanced as S + +unbox :: forall a. Typeable a => Int -> X.Value -> IO a +unbox kind (X.Opaque actual _ _ _ payload) | kind==actual=maybe(X.invalid "stochastic object payload differs") pure(cast payload) +unbox _ _=X.invalid "stochastic object kind differs" +source :: Either E.MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +forceFields :: [IO X.Value] -> IO () +forceFields fields=sequence fields >>= mapM_ X.forceValue +checkedCallback :: X.Value -> X.Value -> (X.Value -> IO a) -> IO(Either E.MathError a) +checkedCallback function argument decodeResult=(LC.callbackValue function argument >>= decodeResult >>= pure . Right) `catch` relay + where + relay(CallbackMathError errorValue)=pure(Left errorValue) + relay other=throwIO(other::CallbackFailure) +stochasticBoundary :: IO CInt -> IO CInt +stochasticBoundary action=Boundary.boundary $ callbackBoundary (\e -> Boundary.checked(Left e)(const(pure()))) action + +encodeGenerator :: R.Generator -> IO X.Value +encodeGenerator value=pure(X.Opaque 241 (-1) 0 force value) + where + force=evaluate value >> pure() + +encodeRNG :: R.RNG -> IO X.Value +encodeRNG=pure . rng + +encodeAliasTable :: R.AliasTable -> IO X.Value +encodeAliasTable value=pure(X.Opaque 242 (-1) 0 force value) + where + force=evaluate value >> pure() + +encodeDistribution :: P.Distribution -> IO X.Value +encodeDistribution value=pure(X.Opaque 243 (-1) 0 force value) + where + force=case value of + P.Bernoulli field1 -> forceFields [pure(X.Scalar SDouble field1)] + P.Binomial field2 field3 -> forceFields [pure(X.Index field2),pure(X.Scalar SDouble field3)] + P.NegativeBinomial field4 field5 -> forceFields [pure(X.Scalar SDouble field4),pure(X.Scalar SDouble field5)] + P.Geometric field6 -> forceFields [pure(X.Scalar SDouble field6)] + P.Hypergeometric field7 field8 field9 -> forceFields [pure(X.Index field7),pure(X.Index field8),pure(X.Index field9)] + P.Poisson field10 -> forceFields [pure(X.Scalar SDouble field10)] + P.Categorical field11 -> forceFields [X.List <$> mapM (\item12 -> pure(X.Scalar SDouble item12)) field11] + P.DiscreteUniform field13 field14 -> forceFields [pure(X.Index field13),pure(X.Index field14)] + P.Uniform field15 field16 -> forceFields [pure(X.Scalar SDouble field15),pure(X.Scalar SDouble field16)] + P.Normal field17 field18 -> forceFields [pure(X.Scalar SDouble field17),pure(X.Scalar SDouble field18)] + P.LogNormal field19 field20 -> forceFields [pure(X.Scalar SDouble field19),pure(X.Scalar SDouble field20)] + P.Exponential field21 -> forceFields [pure(X.Scalar SDouble field21)] + P.Gamma field22 field23 -> forceFields [pure(X.Scalar SDouble field22),pure(X.Scalar SDouble field23)] + P.Beta field24 field25 -> forceFields [pure(X.Scalar SDouble field24),pure(X.Scalar SDouble field25)] + P.ChiSquare field26 -> forceFields [pure(X.Scalar SDouble field26)] + P.StudentT field27 -> forceFields [pure(X.Scalar SDouble field27)] + P.FisherF field28 field29 -> forceFields [pure(X.Scalar SDouble field28),pure(X.Scalar SDouble field29)] + P.Cauchy field30 field31 -> forceFields [pure(X.Scalar SDouble field30),pure(X.Scalar SDouble field31)] + P.Laplace field32 field33 -> forceFields [pure(X.Scalar SDouble field32),pure(X.Scalar SDouble field33)] + P.Logistic field34 field35 -> forceFields [pure(X.Scalar SDouble field34),pure(X.Scalar SDouble field35)] + P.Weibull field36 field37 -> forceFields [pure(X.Scalar SDouble field36),pure(X.Scalar SDouble field37)] + P.Pareto field38 field39 -> forceFields [pure(X.Scalar SDouble field38),pure(X.Scalar SDouble field39)] + P.Rayleigh field40 -> forceFields [pure(X.Scalar SDouble field40)] + P.Maxwell field41 -> forceFields [pure(X.Scalar SDouble field41)] + P.Gumbel field42 field43 -> forceFields [pure(X.Scalar SDouble field42),pure(X.Scalar SDouble field43)] + P.GeneralizedExtremeValue field44 field45 field46 -> forceFields [pure(X.Scalar SDouble field44),pure(X.Scalar SDouble field45),pure(X.Scalar SDouble field46)] + P.BetaBinomial field47 field48 field49 -> forceFields [pure(X.Index field47),pure(X.Scalar SDouble field48),pure(X.Scalar SDouble field49)] + P.Skellam field50 field51 -> forceFields [pure(X.Scalar SDouble field50),pure(X.Scalar SDouble field51)] + P.VonMises field52 field53 -> forceFields [pure(X.Scalar SDouble field52),pure(X.Scalar SDouble field53)] + P.Triangular field54 field55 field56 -> forceFields [pure(X.Scalar SDouble field54),pure(X.Scalar SDouble field55),pure(X.Scalar SDouble field56)] + P.TruncatedNormal field57 field58 field59 field60 -> forceFields [pure(X.Scalar SDouble field57),pure(X.Scalar SDouble field58),pure(X.Scalar SDouble field59),pure(X.Scalar SDouble field60)] + P.Mixture field61 -> forceFields [X.List <$> mapM (\item62 -> (\(part63,part64) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part63),encodeDistribution part64]) item62) field61] + P.Empirical field65 -> forceFields [X.List <$> mapM (\item66 -> pure(X.Scalar SDouble item66)) field65] + P.GaussianKDE field67 field68 -> forceFields [pure(X.Scalar SDouble field67),X.List <$> mapM (\item69 -> pure(X.Scalar SDouble item69)) field68] + +encodeMarkov :: P.Markov -> IO X.Value +encodeMarkov value=pure(X.Opaque 244 (-1) 0 force value) + where + force=evaluate value >> pure() + +encodeHMM :: P.HMM -> IO X.Value +encodeHMM value=pure(X.Opaque 245 (-1) 0 force value) + where + force=evaluate value >> pure() + +encodeStreaming :: S.Streaming -> IO X.Value +encodeStreaming value=pure(X.Opaque 246 (-1) 0 force value) + where + force=evaluate value >> pure() + +encodeTestResult :: S.TestResult -> IO X.Value +encodeTestResult value=pure(X.Opaque 247 (-1) 0 force value) + where + force=forceFields [pure(X.Scalar SDouble (S.testStatistic value)),pure(X.Scalar SDouble (S.pValue value)),X.List <$> mapM (\item70 -> pure(X.Scalar SDouble item70)) (S.degreesOfFreedom value)] + +apply :: Int -> [X.Value] -> IO X.Value +apply operation args=case(operation,args) of + (0,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + encodeRNG (R.cloneRNG a0Value :: (R.RNG)) + (1,[a0,a1]) -> do + a0Value <- (unbox 241 a0 :: IO (R.Generator)) + a1Value <- (X.asScalar a1 :: IO (Word64)) + encodeRNG (R.seedRNG a0Value a1Value :: (R.RNG)) + (2,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + (\(part71,part72) -> X.Tuple <$> sequence [pure(X.Scalar SWord64 part71),encodeRNG part72]) (R.nextWord64 a0Value :: ((Word64),(R.RNG))) + (3,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + (\(part73,part74) -> X.Tuple <$> sequence [encodeRNG part73,encodeRNG part74]) (R.splitRNG a0Value :: ((R.RNG),(R.RNG))) + (4,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + pure(X.Text (R.serializeRNG a0Value :: (String))) + (5,[a0]) -> do + a0Value <- (X.asText a0 :: IO (String)) + source (R.restoreRNG a0Value :: (Either (E.MathError) (R.RNG))) >>= \_result75 -> encodeRNG _result75 + (6,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + (\(part76,part77) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part76),encodeRNG part77]) (R.uniform a0Value :: ((Double),(R.RNG))) + (7,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + (\(part78,part79) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part78),encodeRNG part79]) (R.uniformOpen a0Value :: ((Double),(R.RNG))) + (8,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.uniformInt a0Value a1Value a2Value :: (Either (E.MathError) ((Int),(R.RNG)))) >>= \_result80 -> (\(part81,part82) -> X.Tuple <$> sequence [pure(X.Index part81),encodeRNG part82]) _result80 + (9,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure (\parameter83 -> unsafePerformIO $ do { callbackArgs <- sequence [encodeRNG parameter83]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a1 callbackInput (\reply -> (X.asTuple 2 reply >>= \tuple86 -> case tuple86 of { [part84,part85] -> (,) <$> (pure part84) <*> (asRNG part85); _ -> X.invalid "tuple arity differs" })) }) :: IO ((R.RNG) -> (Either (E.MathError) ((X.Value),(R.RNG))))) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.sampleN a0Value a1Value a2Value :: (Either (E.MathError) ([(X.Value)],(R.RNG)))) >>= \_result87 -> (\(part88,part89) -> X.Tuple <$> sequence [X.List <$> mapM (\item90 -> pure item90) part88,encodeRNG part89]) _result87 + (10,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + (\(part91,part92) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part91),encodeRNG part92]) (R.boxMuller a0Value :: ((Double),(R.RNG))) + (11,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + source (R.marsagliaNormal a0Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result93 -> (\(part94,part95) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part94),encodeRNG part95]) _result93 + (12,[a0]) -> do + a0Value <- (asRNG a0 :: IO (R.RNG)) + source (R.zigguratNormal a0Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result96 -> (\(part97,part98) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part97),encodeRNG part98]) _result96 + (13,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.normal a0Value a1Value a2Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result99 -> (\(part100,part101) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part100),encodeRNG part101]) _result99 + (14,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.exponential a0Value a1Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result102 -> (\(part103,part104) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part103),encodeRNG part104]) _result102 + (15,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.gamma a0Value a1Value a2Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result105 -> (\(part106,part107) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part106),encodeRNG part107]) _result105 + (16,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.beta a0Value a1Value a2Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result108 -> (\(part109,part110) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part109),encodeRNG part110]) _result108 + (17,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.poisson a0Value a1Value :: (Either (E.MathError) ((Int),(R.RNG)))) >>= \_result111 -> (\(part112,part113) -> X.Tuple <$> sequence [pure(X.Index part112),encodeRNG part113]) _result111 + (18,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.binomial a0Value a1Value a2Value :: (Either (E.MathError) ((Int),(R.RNG)))) >>= \_result114 -> (\(part115,part116) -> X.Tuple <$> sequence [pure(X.Index part115),encodeRNG part116]) _result114 + (19,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item117 -> X.asScalar item117) :: IO [(Double)]) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.weighted a0Value a1Value :: (Either (E.MathError) ((Int),(R.RNG)))) >>= \_result118 -> (\(part119,part120) -> X.Tuple <$> sequence [pure(X.Index part119),encodeRNG part120]) _result118 + (20,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item121 -> X.asScalar item121) :: IO [(Double)]) + source (R.aliasTable a0Value :: (Either (E.MathError) (R.AliasTable))) >>= \_result122 -> encodeAliasTable _result122 + (21,[a0,a1]) -> do + a0Value <- (unbox 242 a0 :: IO (R.AliasTable)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.aliasSample a0Value a1Value :: (Either (E.MathError) ((Int),(R.RNG)))) >>= \_result123 -> (\(part124,part125) -> X.Tuple <$> sequence [pure(X.Index part124),encodeRNG part125]) _result123 + (22,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item126 -> pure item126) :: IO [(X.Value)]) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.shuffle a0Value a1Value :: (Either (E.MathError) ([(X.Value)],(R.RNG)))) >>= \_result127 -> (\(part128,part129) -> X.Tuple <$> sequence [X.List <$> mapM (\item130 -> pure item130) part128,encodeRNG part129]) _result127 + (23,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item131 -> pure item131) :: IO [(X.Value)]) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.withReplacement a0Value a1Value a2Value :: (Either (E.MathError) ([(X.Value)],(R.RNG)))) >>= \_result132 -> (\(part133,part134) -> X.Tuple <$> sequence [X.List <$> mapM (\item135 -> pure item135) part133,encodeRNG part134]) _result132 + (24,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item136 -> pure item136) :: IO [(X.Value)]) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.withoutReplacement a0Value a1Value a2Value :: (Either (E.MathError) ([(X.Value)],(R.RNG)))) >>= \_result137 -> (\(part138,part139) -> X.Tuple <$> sequence [X.List <$> mapM (\item140 -> pure item140) part138,encodeRNG part139]) _result137 + (25,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item141 -> pure item141) :: IO [(X.Value)]) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.reservoir a0Value a1Value a2Value :: (Either (E.MathError) ([(X.Value)],(R.RNG)))) >>= \_result142 -> (\(part143,part144) -> X.Tuple <$> sequence [X.List <$> mapM (\item145 -> pure item145) part143,encodeRNG part144]) _result142 + (26,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.stratified a0Value a1Value :: (Either (E.MathError) ([(Double)],(R.RNG)))) >>= \_result146 -> (\(part147,part148) -> X.Tuple <$> sequence [X.List <$> mapM (\item149 -> pure(X.Scalar SDouble item149)) part147,encodeRNG part148]) _result146 + (27,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure (\parameter150 -> unsafePerformIO $ do { callbackArgs <- sequence [pure(X.Scalar SDouble parameter150)]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a1 callbackInput >>= \reply -> X.asScalar reply }) :: IO ((Double) -> (Double))) + a2Value <- (pure (\parameter151 -> unsafePerformIO $ do { callbackArgs <- sequence [encodeRNG parameter151]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a2 callbackInput (\reply -> (X.asTuple 2 reply >>= \tuple154 -> case tuple154 of { [part152,part153] -> (,) <$> (X.asScalar part152) <*> (asRNG part153); _ -> X.invalid "tuple arity differs" })) }) :: IO ((R.RNG) -> (Either (E.MathError) ((Double),(R.RNG))))) + a3Value <- (asRNG a3 :: IO (R.RNG)) + source (R.rejection a0Value a1Value a2Value a3Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result155 -> (\(part156,part157) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part156),encodeRNG part157]) _result155 + (28,[a0,a1]) -> do + a0Value <- (pure (\parameter158 -> unsafePerformIO $ do { callbackArgs <- sequence [pure(X.Scalar SDouble parameter158)]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a0 callbackInput (\reply -> X.asScalar reply) }) :: IO ((Double) -> (Either (E.MathError) (Double)))) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.inverseTransform a0Value a1Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result159 -> (\(part160,part161) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part160),encodeRNG part161]) _result159 + (29,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (pure (\parameter162 -> unsafePerformIO $ do { callbackArgs <- sequence [pure(X.Scalar SDouble parameter162)]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a2 callbackInput >>= \reply -> X.asScalar reply }) :: IO ((Double) -> (Double))) + a3Value <- (X.asScalar a3 :: IO (Double)) + a4Value <- (asRNG a4 :: IO (R.RNG)) + source (R.metropolisHastings a0Value a1Value a2Value a3Value a4Value :: (Either (E.MathError) ([(Double)],(R.RNG)))) >>= \_result163 -> (\(part164,part165) -> X.Tuple <$> sequence [X.List <$> mapM (\item166 -> pure(X.Scalar SDouble item166)) part164,encodeRNG part165]) _result163 + (30,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item167 -> pure (\parameter168 parameter169 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item170 -> pure(X.Scalar SDouble item170)) parameter168,encodeRNG parameter169]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback item167 callbackInput (\reply -> (X.asTuple 2 reply >>= \tuple173 -> case tuple173 of { [part171,part172] -> (,) <$> (X.asScalar part171) <*> (asRNG part172); _ -> X.invalid "tuple arity differs" })) })) :: IO [([(Double)] -> (R.RNG) -> (Either (E.MathError) ((Double),(R.RNG))))]) + a2Value <- (X.asList a2 >>= mapM (\item174 -> X.asScalar item174) :: IO [(Double)]) + a3Value <- (asRNG a3 :: IO (R.RNG)) + source (R.gibbs a0Value a1Value a2Value a3Value :: (Either (E.MathError) ([[(Double)]],(R.RNG)))) >>= \_result175 -> (\(part176,part177) -> X.Tuple <$> sequence [X.List <$> mapM (\item178 -> X.List <$> mapM (\item179 -> pure(X.Scalar SDouble item179)) item178) part176,encodeRNG part177]) _result175 + (31,[a0,a1,a2,a3,a4,a5,a6]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asScalar a2 :: IO (Double)) + a3Value <- (pure (\parameter180 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item181 -> pure(X.Scalar SDouble item181)) parameter180]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a3 callbackInput >>= \reply -> X.asScalar reply }) :: IO ([(Double)] -> (Double))) + a4Value <- (pure (\parameter182 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item183 -> pure(X.Scalar SDouble item183)) parameter182]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a4 callbackInput >>= \reply -> X.asList reply >>= mapM (\item184 -> X.asScalar item184) }) :: IO ([(Double)] -> [(Double)])) + a5Value <- (X.asList a5 >>= mapM (\item185 -> X.asScalar item185) :: IO [(Double)]) + a6Value <- (asRNG a6 :: IO (R.RNG)) + source (R.hamiltonianMonteCarlo a0Value a1Value a2Value a3Value a4Value a5Value a6Value :: (Either (E.MathError) ([[(Double)]],(R.RNG)))) >>= \_result186 -> (\(part187,part188) -> X.Tuple <$> sequence [X.List <$> mapM (\item189 -> X.List <$> mapM (\item190 -> pure(X.Scalar SDouble item190)) item189) part187,encodeRNG part188]) _result186 + (32,[a0,a1,a2]) -> do + a0Value <- (pure (\parameter191 -> unsafePerformIO $ do { callbackArgs <- sequence [pure(X.Scalar SDouble parameter191)]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a0 callbackInput >>= \reply -> X.asScalar reply }) :: IO ((Double) -> (Double))) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.monteCarlo a0Value a1Value a2Value :: (Either (E.MathError) (((Double),(Double)),(R.RNG)))) >>= \_result192 -> (\(part193,part194) -> X.Tuple <$> sequence [(\(part195,part196) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part195),pure(X.Scalar SDouble part196)]) part193,encodeRNG part194]) _result192 + (33,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (R.latinHypercube a0Value a1Value a2Value :: (Either (E.MathError) ([[(Double)]],(R.RNG)))) >>= \_result197 -> (\(part198,part199) -> X.Tuple <$> sequence [X.List <$> mapM (\item200 -> X.List <$> mapM (\item201 -> pure(X.Scalar SDouble item201)) item200) part198,encodeRNG part199]) _result197 + (34,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (R.randomQuality a0Value a1Value :: (Either (E.MathError) (((Double),(Double),(Double)),(R.RNG)))) >>= \_result202 -> (\(part203,part204) -> X.Tuple <$> sequence [(\(part205,part206,part207) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part205),pure(X.Scalar SDouble part206),pure(X.Scalar SDouble part207)]) part203,encodeRNG part204]) _result202 + (35,[]) -> do + (R.entropySeed :: (IO (Word64))) >>= \_result208 -> pure(X.Scalar SWord64 _result208) + (36,[]) -> do + encodeGenerator (R.PCG32 :: (R.Generator)) + (37,[]) -> do + encodeGenerator (R.Xoshiro256StarStar :: (R.Generator)) + (38,[]) -> do + encodeGenerator (R.Xoroshiro128Plus :: (R.Generator)) + (39,[]) -> do + encodeGenerator (R.MT19937 :: (R.Generator)) + (40,[]) -> do + encodeGenerator (R.Philox4x32 :: (R.Generator)) + (41,[]) -> do + encodeGenerator (R.Threefry2x64 :: (R.Generator)) + (42,[]) -> do + encodeGenerator (R.ChaCha20 :: (R.Generator)) + (43,[a0]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + source (P.validateDistribution a0Value :: (Either (E.MathError) ())) >>= \_result209 -> pure X.None + (44,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.logDensity a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result210 -> pure(X.Scalar SDouble _result210) + (45,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.density a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result211 -> pure(X.Scalar SDouble _result211) + (46,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.cdf a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result212 -> pure(X.Scalar SDouble _result212) + (47,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.survival a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result213 -> pure(X.Scalar SDouble _result213) + (48,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.quantile a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result214 -> pure(X.Scalar SDouble _result214) + (49,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (P.hazard a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result215 -> pure(X.Scalar SDouble _result215) + (50,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asList a1 >>= mapM (\item216 -> X.asScalar item216) :: IO [(Double)]) + source (P.logLikelihood a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result217 -> pure(X.Scalar SDouble _result217) + (51,[a0]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + source (P.moments a0Value :: (Either (E.MathError) ((Double),(Double)))) >>= \_result218 -> (\(part219,part220) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part219),pure(X.Scalar SDouble part220)]) _result218 + (52,[a0]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + source (P.entropy a0Value :: (Either (E.MathError) (Double))) >>= \_result221 -> pure(X.Scalar SDouble _result221) + (53,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (pure (\parameter222 -> unsafePerformIO $ do { callbackArgs <- sequence [pure(X.Scalar SDouble parameter222)]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a1 callbackInput >>= \reply -> X.asScalar reply }) :: IO ((Double) -> (Double))) + source (P.expectation a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result223 -> pure(X.Scalar SDouble _result223) + (54,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (asRNG a1 :: IO (R.RNG)) + source (P.sample a0Value a1Value :: (Either (E.MathError) ((Double),(R.RNG)))) >>= \_result224 -> (\(part225,part226) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part225),encodeRNG part226]) _result224 + (55,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item227 -> X.asScalar item227) :: IO [(Double)]) + source (P.fitNormal a0Value :: (Either (E.MathError) (P.Distribution))) >>= \_result228 -> encodeDistribution _result228 + (56,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item229 -> X.asScalar item229) :: IO [(Double)]) + source (P.fitExponential a0Value :: (Either (E.MathError) (P.Distribution))) >>= \_result230 -> encodeDistribution _result230 + (57,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item231 -> X.asScalar item231) :: IO [(Double)]) + source (P.fitBernoulli a0Value :: (Either (E.MathError) (P.Distribution))) >>= \_result232 -> encodeDistribution _result232 + (58,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item233 -> unbox 243 item233) :: IO [(P.Distribution)]) + a1Value <- (X.asList a1 >>= mapM (\item234 -> X.asScalar item234) :: IO [(Double)]) + source (P.fitMLEGrid a0Value a1Value :: (Either (E.MathError) (P.Distribution))) >>= \_result235 -> encodeDistribution _result235 + (59,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item236 -> unbox 243 item236) :: IO [(P.Distribution)]) + a1Value <- (X.asList a1 >>= mapM (\item237 -> X.asScalar item237) :: IO [(Double)]) + a2Value <- (pure (\parameter238 -> unsafePerformIO $ do { callbackArgs <- sequence [encodeDistribution parameter238]; let { callbackInput=X.Tuple callbackArgs }; LC.callbackValue a2 callbackInput >>= \reply -> X.asScalar reply }) :: IO ((P.Distribution) -> (Double))) + source (P.fitMAPGrid a0Value a1Value a2Value :: (Either (E.MathError) (P.Distribution))) >>= \_result239 -> encodeDistribution _result239 + (60,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asList a2 >>= mapM (\item240 -> X.asBoolean item240) :: IO [(Bool)]) + source (P.betaBernoulliUpdate a0Value a1Value a2Value :: (Either (E.MathError) ((Double),(Double)))) >>= \_result241 -> (\(part242,part243) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part242),pure(X.Scalar SDouble part243)]) _result241 + (61,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asList a1 >>= mapM (\item244 -> X.asScalar item244) :: IO [(Double)]) + source (P.goodnessOfFit a0Value a1Value :: (Either (E.MathError) (Double))) >>= \_result245 -> pure(X.Scalar SDouble _result245) + (62,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asList a1 >>= mapM (\item246 -> X.asScalar item246) :: IO [(Double)]) + source (P.gaussianKDE a0Value a1Value :: (Either (E.MathError) (P.Distribution))) >>= \_result247 -> encodeDistribution _result247 + (63,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item248 -> X.asScalar item248) :: IO [(Double)]) + a1Value <- (LC.asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (X.asList a2 >>= mapM (\item249 -> X.asScalar item249) :: IO [(Double)]) + source (P.multivariateNormalLogDensity a0Value a1Value a2Value :: (Either (E.MathError) (Double))) >>= \_result250 -> pure(X.Scalar SDouble _result250) + (64,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item251 -> X.asScalar item251) :: IO [(Double)]) + a1Value <- (LC.asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (P.sampleMultivariateNormal a0Value a1Value a2Value :: (Either (E.MathError) ([(Double)],(R.RNG)))) >>= \_result252 -> (\(part253,part254) -> X.Tuple <$> sequence [X.List <$> mapM (\item255 -> pure(X.Scalar SDouble item255)) part253,encodeRNG part254]) _result252 + (65,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (LC.asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (LC.asMatrix a2 :: IO (M.Matrix (Double))) + source (P.wishartLogDensity a0Value a1Value a2Value :: (Either (E.MathError) (Double))) >>= \_result256 -> pure(X.Scalar SDouble _result256) + (66,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (LC.asMatrix a1 :: IO (M.Matrix (Double))) + a2Value <- (asRNG a2 :: IO (R.RNG)) + source (P.sampleWishart a0Value a1Value a2Value :: (Either (E.MathError) ((M.Matrix (Double)),(R.RNG)))) >>= \_result257 -> (\(part258,part259) -> X.Tuple <$> sequence [pure(X.Dense(X.SomeMatrix SDouble part258)),encodeRNG part259]) _result257 + (67,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item260 -> X.asList item260 >>= mapM (\item261 -> X.asScalar item261)) :: IO [[(Double)]]) + source (P.markov a0Value :: (Either (E.MathError) (P.Markov))) >>= \_result262 -> encodeMarkov _result262 + (68,[a0,a1]) -> do + a0Value <- (unbox 244 a0 :: IO (P.Markov)) + a1Value <- (X.asList a1 >>= mapM (\item263 -> X.asScalar item263) :: IO [(Double)]) + source (P.transition a0Value a1Value :: (Either (E.MathError) [(Double)])) >>= \_result264 -> X.List <$> mapM (\item265 -> pure(X.Scalar SDouble item265)) _result264 + (69,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (unbox 244 a2 :: IO (P.Markov)) + source (P.stationary a0Value a1Value a2Value :: (Either (E.MathError) [(Double)])) >>= \_result266 -> X.List <$> mapM (\item267 -> pure(X.Scalar SDouble item267)) _result266 + (70,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item268 -> X.asScalar item268) :: IO [(Double)]) + a1Value <- (X.asList a1 >>= mapM (\item269 -> X.asList item269 >>= mapM (\item270 -> X.asScalar item270)) :: IO [[(Double)]]) + a2Value <- (X.asList a2 >>= mapM (\item271 -> X.asList item271 >>= mapM (\item272 -> X.asScalar item272)) :: IO [[(Double)]]) + source (P.hmm a0Value a1Value a2Value :: (Either (E.MathError) (P.HMM))) >>= \_result273 -> encodeHMM _result273 + (71,[a0,a1]) -> do + a0Value <- (unbox 245 a0 :: IO (P.HMM)) + a1Value <- (X.asList a1 >>= mapM (\item274 -> X.asIndex item274) :: IO [(Int)]) + source (P.forward a0Value a1Value :: (Either (E.MathError) ((Double),[[(Double)]],[(Double)]))) >>= \_result275 -> (\(part276,part277,part278) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part276),X.List <$> mapM (\item279 -> X.List <$> mapM (\item280 -> pure(X.Scalar SDouble item280)) item279) part277,X.List <$> mapM (\item281 -> pure(X.Scalar SDouble item281)) part278]) _result275 + (72,[a0,a1]) -> do + a0Value <- (unbox 245 a0 :: IO (P.HMM)) + a1Value <- (X.asList a1 >>= mapM (\item282 -> X.asIndex item282) :: IO [(Int)]) + source (P.backward a0Value a1Value :: (Either (E.MathError) [[(Double)]])) >>= \_result283 -> X.List <$> mapM (\item284 -> X.List <$> mapM (\item285 -> pure(X.Scalar SDouble item285)) item284) _result283 + (73,[a0,a1]) -> do + a0Value <- (unbox 245 a0 :: IO (P.HMM)) + a1Value <- (X.asList a1 >>= mapM (\item286 -> X.asIndex item286) :: IO [(Int)]) + source (P.posteriorStates a0Value a1Value :: (Either (E.MathError) [[(Double)]])) >>= \_result287 -> X.List <$> mapM (\item288 -> X.List <$> mapM (\item289 -> pure(X.Scalar SDouble item289)) item288) _result287 + (74,[a0,a1]) -> do + a0Value <- (unbox 245 a0 :: IO (P.HMM)) + a1Value <- (X.asList a1 >>= mapM (\item290 -> X.asIndex item290) :: IO [(Int)]) + source (P.viterbi a0Value a1Value :: (Either (E.MathError) ([(Int)],(Double)))) >>= \_result291 -> (\(part292,part293) -> X.Tuple <$> sequence [X.List <$> mapM (\item294 -> pure(X.Index item294)) part292,pure(X.Scalar SDouble part293)]) _result291 + (75,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (unbox 245 a2 :: IO (P.HMM)) + a3Value <- (X.asList a3 >>= mapM (\item295 -> X.asIndex item295) :: IO [(Int)]) + source (P.baumWelch a0Value a1Value a2Value a3Value :: (Either (E.MathError) (P.HMM))) >>= \_result296 -> encodeHMM _result296 + (76,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Bernoulli a0Value :: (P.Distribution)) + (77,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Binomial a0Value a1Value :: (P.Distribution)) + (78,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.NegativeBinomial a0Value a1Value :: (P.Distribution)) + (79,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Geometric a0Value :: (P.Distribution)) + (80,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + encodeDistribution (P.Hypergeometric a0Value a1Value a2Value :: (P.Distribution)) + (81,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Poisson a0Value :: (P.Distribution)) + (82,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item297 -> X.asScalar item297) :: IO [(Double)]) + encodeDistribution (P.Categorical a0Value :: (P.Distribution)) + (83,[a0,a1]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + encodeDistribution (P.DiscreteUniform a0Value a1Value :: (P.Distribution)) + (84,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Uniform a0Value a1Value :: (P.Distribution)) + (85,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Normal a0Value a1Value :: (P.Distribution)) + (86,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.LogNormal a0Value a1Value :: (P.Distribution)) + (87,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Exponential a0Value :: (P.Distribution)) + (88,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Gamma a0Value a1Value :: (P.Distribution)) + (89,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Beta a0Value a1Value :: (P.Distribution)) + (90,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.ChiSquare a0Value :: (P.Distribution)) + (91,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.StudentT a0Value :: (P.Distribution)) + (92,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.FisherF a0Value a1Value :: (P.Distribution)) + (93,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Cauchy a0Value a1Value :: (P.Distribution)) + (94,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Laplace a0Value a1Value :: (P.Distribution)) + (95,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Logistic a0Value a1Value :: (P.Distribution)) + (96,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Weibull a0Value a1Value :: (P.Distribution)) + (97,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Pareto a0Value a1Value :: (P.Distribution)) + (98,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Rayleigh a0Value :: (P.Distribution)) + (99,[a0]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + encodeDistribution (P.Maxwell a0Value :: (P.Distribution)) + (100,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Gumbel a0Value a1Value :: (P.Distribution)) + (101,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asScalar a2 :: IO (Double)) + encodeDistribution (P.GeneralizedExtremeValue a0Value a1Value a2Value :: (P.Distribution)) + (102,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asScalar a2 :: IO (Double)) + encodeDistribution (P.BetaBinomial a0Value a1Value a2Value :: (P.Distribution)) + (103,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.Skellam a0Value a1Value :: (P.Distribution)) + (104,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + encodeDistribution (P.VonMises a0Value a1Value :: (P.Distribution)) + (105,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asScalar a2 :: IO (Double)) + encodeDistribution (P.Triangular a0Value a1Value a2Value :: (P.Distribution)) + (106,[a0,a1,a2,a3]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asScalar a2 :: IO (Double)) + a3Value <- (X.asScalar a3 :: IO (Double)) + encodeDistribution (P.TruncatedNormal a0Value a1Value a2Value a3Value :: (P.Distribution)) + (107,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item298 -> (X.asTuple 2 item298 >>= \tuple301 -> case tuple301 of { [part299,part300] -> (,) <$> (X.asScalar part299) <*> (unbox 243 part300); _ -> X.invalid "tuple arity differs" })) :: IO [((Double),(P.Distribution))]) + encodeDistribution (P.Mixture a0Value :: (P.Distribution)) + (108,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item302 -> X.asScalar item302) :: IO [(Double)]) + encodeDistribution (P.Empirical a0Value :: (P.Distribution)) + (109,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asList a1 >>= mapM (\item303 -> X.asScalar item303) :: IO [(Double)]) + encodeDistribution (P.GaussianKDE a0Value a1Value :: (P.Distribution)) + (110,[a0,a1]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (X.asList a1 >>= mapM (\item304 -> X.asList item304 >>= mapM (\item305 -> X.asScalar item305)) :: IO [[(Double)]]) + source (S.covarianceMatrix a0Value a1Value :: (Either (E.MathError) [[(Double)]])) >>= \_result306 -> X.List <$> mapM (\item307 -> X.List <$> mapM (\item308 -> pure(X.Scalar SDouble item308)) item307) _result306 + (111,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item309 -> X.asList item309 >>= mapM (\item310 -> X.asScalar item310)) :: IO [[(Double)]]) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + source (S.partialCorrelation a0Value a1Value a2Value :: (Either (E.MathError) (Double))) >>= \_result311 -> pure(X.Scalar SDouble _result311) + (112,[]) -> do + encodeStreaming (S.emptyStreaming :: (S.Streaming)) + (113,[a0,a1]) -> do + a0Value <- (unbox 246 a0 :: IO (S.Streaming)) + a1Value <- (X.asScalar a1 :: IO (Double)) + source (S.updateStreaming a0Value a1Value :: (Either (E.MathError) (S.Streaming))) >>= \_result312 -> encodeStreaming _result312 + (114,[a0,a1]) -> do + a0Value <- (unbox 246 a0 :: IO (S.Streaming)) + a1Value <- (unbox 246 a1 :: IO (S.Streaming)) + source (S.combineStreaming a0Value a1Value :: (Either (E.MathError) (S.Streaming))) >>= \_result313 -> encodeStreaming _result313 + (115,[a0,a1]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (unbox 246 a1 :: IO (S.Streaming)) + source (S.streamingResult a0Value a1Value :: (Either (E.MathError) ((Integer),(Double),(Double)))) >>= \_result314 -> (\(part315,part316,part317) -> X.Tuple <$> sequence [pure(X.Scalar SInteger part315),pure(X.Scalar SDouble part316),pure(X.Scalar SDouble part317)]) _result314 + (116,[a0,a1,a2]) -> do + a0Value <- (X.asList a0 >>= mapM (\item318 -> X.asList item318 >>= mapM (\item319 -> X.asScalar item319)) :: IO [[(Double)]]) + a1Value <- (X.asList a1 >>= mapM (\item320 -> X.asList item320 >>= mapM (\item321 -> X.asScalar item321)) :: IO [[(Double)]]) + a2Value <- (X.asList a2 >>= mapM (\item322 -> X.asScalar item322) :: IO [(Double)]) + source (S.histogramND a0Value a1Value a2Value :: (Either (E.MathError) [(Double)])) >>= \_result323 -> X.List <$> mapM (\item324 -> pure(X.Scalar SDouble item324)) _result323 + (117,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item325 -> X.asList item325 >>= mapM (\item326 -> X.asScalar item326)) :: IO [[(Double)]]) + source (S.mutualInformation a0Value :: (Either (E.MathError) (Double))) >>= \_result327 -> pure(X.Scalar SDouble _result327) + (118,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure (\parameter328 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item329 -> pure(X.Scalar SDouble item329)) parameter328]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a1 callbackInput (\reply -> X.asScalar reply) }) :: IO ([(Double)] -> (Either (E.MathError) (Double)))) + a2Value <- (X.asList a2 >>= mapM (\item330 -> X.asScalar item330) :: IO [(Double)]) + a3Value <- (asRNG a3 :: IO (R.RNG)) + source (S.bootstrap a0Value a1Value a2Value a3Value :: (Either (E.MathError) ([(Double)],(R.RNG)))) >>= \_result331 -> (\(part332,part333) -> X.Tuple <$> sequence [X.List <$> mapM (\item334 -> pure(X.Scalar SDouble item334)) part332,encodeRNG part333]) _result331 + (119,[a0,a1]) -> do + a0Value <- (pure (\parameter335 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item336 -> pure(X.Scalar SDouble item336)) parameter335]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a0 callbackInput (\reply -> X.asScalar reply) }) :: IO ([(Double)] -> (Either (E.MathError) (Double)))) + a1Value <- (X.asList a1 >>= mapM (\item337 -> X.asScalar item337) :: IO [(Double)]) + source (S.jackknife a0Value a1Value :: (Either (E.MathError) ((Double),(Double)))) >>= \_result338 -> (\(part339,part340) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part339),pure(X.Scalar SDouble part340)]) _result338 + (120,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asList a1 >>= mapM (\item341 -> X.asScalar item341) :: IO [(Double)]) + source (S.oneSampleT a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result342 -> encodeTestResult _result342 + (121,[a0,a1,a2]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (X.asList a1 >>= mapM (\item343 -> X.asScalar item343) :: IO [(Double)]) + a2Value <- (X.asList a2 >>= mapM (\item344 -> X.asScalar item344) :: IO [(Double)]) + source (S.twoSampleT a0Value a1Value a2Value :: (Either (E.MathError) (S.TestResult))) >>= \_result345 -> encodeTestResult _result345 + (122,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item346 -> X.asScalar item346) :: IO [(Double)]) + a1Value <- (X.asList a1 >>= mapM (\item347 -> X.asScalar item347) :: IO [(Double)]) + source (S.pairedT a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result348 -> encodeTestResult _result348 + (123,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asList a2 >>= mapM (\item349 -> X.asScalar item349) :: IO [(Double)]) + source (S.zTest a0Value a1Value a2Value :: (Either (E.MathError) (S.TestResult))) >>= \_result350 -> encodeTestResult _result350 + (124,[a0,a1,a2]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asList a1 >>= mapM (\item351 -> X.asScalar item351) :: IO [(Double)]) + a2Value <- (X.asList a2 >>= mapM (\item352 -> X.asScalar item352) :: IO [(Double)]) + source (S.chiSquareTest a0Value a1Value a2Value :: (Either (E.MathError) (S.TestResult))) >>= \_result353 -> encodeTestResult _result353 + (125,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item354 -> X.asScalar item354) :: IO [(Double)]) + a1Value <- (X.asList a1 >>= mapM (\item355 -> X.asScalar item355) :: IO [(Double)]) + source (S.varianceFTest a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result356 -> encodeTestResult _result356 + (126,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item357 -> X.asList item357 >>= mapM (\item358 -> X.asScalar item358)) :: IO [[(Double)]]) + source (S.anova a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result359 -> encodeTestResult _result359 + (127,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item360 -> X.asList item360 >>= mapM (\item361 -> X.asScalar item361)) :: IO [[(Double)]]) + source (S.welchAnova a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result362 -> encodeTestResult _result362 + (128,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item363 -> X.asList item363 >>= mapM (\item364 -> X.asScalar item364)) :: IO [[(Double)]]) + source (S.kruskalWallis a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result365 -> encodeTestResult _result365 + (129,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item366 -> X.asScalar item366) :: IO [(Double)]) + a1Value <- (X.asList a1 >>= mapM (\item367 -> X.asScalar item367) :: IO [(Double)]) + source (S.mannWhitney a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result368 -> encodeTestResult _result368 + (130,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item369 -> X.asScalar item369) :: IO [(Double)]) + source (S.wilcoxon a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result370 -> encodeTestResult _result370 + (131,[a0,a1]) -> do + a0Value <- (unbox 243 a0 :: IO (P.Distribution)) + a1Value <- (X.asList a1 >>= mapM (\item371 -> X.asScalar item371) :: IO [(Double)]) + source (S.kolmogorovSmirnov a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result372 -> encodeTestResult _result372 + (132,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item373 -> X.asScalar item373) :: IO [(Double)]) + source (S.shapiroWilk a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result374 -> encodeTestResult _result374 + (133,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item375 -> X.asScalar item375) :: IO [(Double)]) + source (S.andersonDarling a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result376 -> encodeTestResult _result376 + (134,[a0,a1]) -> do + a0Value <- (X.asBoolean a0 :: IO (Bool)) + a1Value <- (X.asList a1 >>= mapM (\item377 -> X.asList item377 >>= mapM (\item378 -> X.asScalar item378)) :: IO [[(Double)]]) + source (S.levene a0Value a1Value :: (Either (E.MathError) (S.TestResult))) >>= \_result379 -> encodeTestResult _result379 + (135,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item380 -> X.asList item380 >>= mapM (\item381 -> X.asScalar item381)) :: IO [[(Double)]]) + source (S.bartlett a0Value :: (Either (E.MathError) (S.TestResult))) >>= \_result382 -> encodeTestResult _result382 + (136,[a0,a1,a2,a3]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (X.asIndex a1 :: IO (Int)) + a2Value <- (X.asIndex a2 :: IO (Int)) + a3Value <- (X.asIndex a3 :: IO (Int)) + source (S.fisherExact a0Value a1Value a2Value a3Value :: (Either (E.MathError) (S.TestResult))) >>= \_result383 -> encodeTestResult _result383 + (137,[a0,a1,a2,a3,a4]) -> do + a0Value <- (X.asIndex a0 :: IO (Int)) + a1Value <- (pure (\parameter384 parameter385 -> unsafePerformIO $ do { callbackArgs <- sequence [X.List <$> mapM (\item386 -> pure(X.Scalar SDouble item386)) parameter384,X.List <$> mapM (\item387 -> pure(X.Scalar SDouble item387)) parameter385]; let { callbackInput=X.Tuple callbackArgs }; checkedCallback a1 callbackInput (\reply -> X.asScalar reply) }) :: IO ([(Double)] -> [(Double)] -> (Either (E.MathError) (Double)))) + a2Value <- (X.asList a2 >>= mapM (\item388 -> X.asScalar item388) :: IO [(Double)]) + a3Value <- (X.asList a3 >>= mapM (\item389 -> X.asScalar item389) :: IO [(Double)]) + a4Value <- (asRNG a4 :: IO (R.RNG)) + source (S.permutationTest a0Value a1Value a2Value a3Value a4Value :: (Either (E.MathError) ((S.TestResult),(R.RNG)))) >>= \_result390 -> (\(part391,part392) -> X.Tuple <$> sequence [encodeTestResult part391,encodeRNG part392]) _result390 + (138,[a0]) -> do + a0Value <- (X.asList a0 >>= mapM (\item393 -> X.asList item393 >>= mapM (\item394 -> X.asScalar item394)) :: IO [[(Double)]]) + source (S.etaSquared a0Value :: (Either (E.MathError) (Double))) >>= \_result395 -> pure(X.Scalar SDouble _result395) + (139,[a0,a1]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asList a1 >>= mapM (\item396 -> X.asScalar item396) :: IO [(Double)]) + source (S.grubbs a0Value a1Value :: (Either (E.MathError) ((Int),(Double),(Bool)))) >>= \_result397 -> (\(part398,part399,part400) -> X.Tuple <$> sequence [pure(X.Index part398),pure(X.Scalar SDouble part399),pure(X.Boolean part400)]) _result397 + (140,[a0,a1]) -> do + a0Value <- (X.asList a0 >>= mapM (\item401 -> X.asBoolean item401) :: IO [(Bool)]) + a1Value <- (X.asList a1 >>= mapM (\item402 -> X.asScalar item402) :: IO [(Double)]) + source (S.masked a0Value a1Value :: (Either (E.MathError) [(Double)])) >>= \_result403 -> X.List <$> mapM (\item404 -> pure(X.Scalar SDouble item404)) _result403 + (141,[a0]) -> do + a0Value <- (unbox 247 a0 :: IO (S.TestResult)) + pure(X.Scalar SDouble (S.testStatistic a0Value :: (Double))) + (142,[a0]) -> do + a0Value <- (unbox 247 a0 :: IO (S.TestResult)) + pure(X.Scalar SDouble (S.pValue a0Value :: (Double))) + (143,[a0]) -> do + a0Value <- (unbox 247 a0 :: IO (S.TestResult)) + X.List <$> mapM (\item405 -> pure(X.Scalar SDouble item405)) (S.degreesOfFreedom a0Value :: [(Double)]) + (144,[a0,a1,a2]) -> do + a0Value <- (X.asScalar a0 :: IO (Double)) + a1Value <- (X.asScalar a1 :: IO (Double)) + a2Value <- (X.asList a2 >>= mapM (\item406 -> X.asScalar item406) :: IO [(Double)]) + encodeTestResult (S.TestResult a0Value a1Value a2Value :: (S.TestResult)) + (-1,[value]) -> case X.valueInfo value of + (241,_,_) -> do + object <- (unbox 241 value :: IO R.Generator) + case object of + R.PCG32 -> do + values <- sequence [] + pure(X.Tuple[X.Text "PCG32",X.Tuple values]) + R.Xoshiro256StarStar -> do + values <- sequence [] + pure(X.Tuple[X.Text "Xoshiro256StarStar",X.Tuple values]) + R.Xoroshiro128Plus -> do + values <- sequence [] + pure(X.Tuple[X.Text "Xoroshiro128Plus",X.Tuple values]) + R.MT19937 -> do + values <- sequence [] + pure(X.Tuple[X.Text "MT19937",X.Tuple values]) + R.Philox4x32 -> do + values <- sequence [] + pure(X.Tuple[X.Text "Philox4x32",X.Tuple values]) + R.Threefry2x64 -> do + values <- sequence [] + pure(X.Tuple[X.Text "Threefry2x64",X.Tuple values]) + R.ChaCha20 -> do + values <- sequence [] + pure(X.Tuple[X.Text "ChaCha20",X.Tuple values]) + (240,_,_) -> do + X.unsupported "original abstract type has no public constructor fields" + (242,_,_) -> do + X.unsupported "original abstract type has no public constructor fields" + (243,_,_) -> do + object <- (unbox 243 value :: IO P.Distribution) + case object of + P.Bernoulli field407 -> do + values <- sequence [pure(X.Scalar SDouble field407)] + pure(X.Tuple[X.Text "Bernoulli",X.Tuple values]) + P.Binomial field408 field409 -> do + values <- sequence [pure(X.Index field408),pure(X.Scalar SDouble field409)] + pure(X.Tuple[X.Text "Binomial",X.Tuple values]) + P.NegativeBinomial field410 field411 -> do + values <- sequence [pure(X.Scalar SDouble field410),pure(X.Scalar SDouble field411)] + pure(X.Tuple[X.Text "NegativeBinomial",X.Tuple values]) + P.Geometric field412 -> do + values <- sequence [pure(X.Scalar SDouble field412)] + pure(X.Tuple[X.Text "Geometric",X.Tuple values]) + P.Hypergeometric field413 field414 field415 -> do + values <- sequence [pure(X.Index field413),pure(X.Index field414),pure(X.Index field415)] + pure(X.Tuple[X.Text "Hypergeometric",X.Tuple values]) + P.Poisson field416 -> do + values <- sequence [pure(X.Scalar SDouble field416)] + pure(X.Tuple[X.Text "Poisson",X.Tuple values]) + P.Categorical field417 -> do + values <- sequence [X.List <$> mapM (\item418 -> pure(X.Scalar SDouble item418)) field417] + pure(X.Tuple[X.Text "Categorical",X.Tuple values]) + P.DiscreteUniform field419 field420 -> do + values <- sequence [pure(X.Index field419),pure(X.Index field420)] + pure(X.Tuple[X.Text "DiscreteUniform",X.Tuple values]) + P.Uniform field421 field422 -> do + values <- sequence [pure(X.Scalar SDouble field421),pure(X.Scalar SDouble field422)] + pure(X.Tuple[X.Text "Uniform",X.Tuple values]) + P.Normal field423 field424 -> do + values <- sequence [pure(X.Scalar SDouble field423),pure(X.Scalar SDouble field424)] + pure(X.Tuple[X.Text "Normal",X.Tuple values]) + P.LogNormal field425 field426 -> do + values <- sequence [pure(X.Scalar SDouble field425),pure(X.Scalar SDouble field426)] + pure(X.Tuple[X.Text "LogNormal",X.Tuple values]) + P.Exponential field427 -> do + values <- sequence [pure(X.Scalar SDouble field427)] + pure(X.Tuple[X.Text "Exponential",X.Tuple values]) + P.Gamma field428 field429 -> do + values <- sequence [pure(X.Scalar SDouble field428),pure(X.Scalar SDouble field429)] + pure(X.Tuple[X.Text "Gamma",X.Tuple values]) + P.Beta field430 field431 -> do + values <- sequence [pure(X.Scalar SDouble field430),pure(X.Scalar SDouble field431)] + pure(X.Tuple[X.Text "Beta",X.Tuple values]) + P.ChiSquare field432 -> do + values <- sequence [pure(X.Scalar SDouble field432)] + pure(X.Tuple[X.Text "ChiSquare",X.Tuple values]) + P.StudentT field433 -> do + values <- sequence [pure(X.Scalar SDouble field433)] + pure(X.Tuple[X.Text "StudentT",X.Tuple values]) + P.FisherF field434 field435 -> do + values <- sequence [pure(X.Scalar SDouble field434),pure(X.Scalar SDouble field435)] + pure(X.Tuple[X.Text "FisherF",X.Tuple values]) + P.Cauchy field436 field437 -> do + values <- sequence [pure(X.Scalar SDouble field436),pure(X.Scalar SDouble field437)] + pure(X.Tuple[X.Text "Cauchy",X.Tuple values]) + P.Laplace field438 field439 -> do + values <- sequence [pure(X.Scalar SDouble field438),pure(X.Scalar SDouble field439)] + pure(X.Tuple[X.Text "Laplace",X.Tuple values]) + P.Logistic field440 field441 -> do + values <- sequence [pure(X.Scalar SDouble field440),pure(X.Scalar SDouble field441)] + pure(X.Tuple[X.Text "Logistic",X.Tuple values]) + P.Weibull field442 field443 -> do + values <- sequence [pure(X.Scalar SDouble field442),pure(X.Scalar SDouble field443)] + pure(X.Tuple[X.Text "Weibull",X.Tuple values]) + P.Pareto field444 field445 -> do + values <- sequence [pure(X.Scalar SDouble field444),pure(X.Scalar SDouble field445)] + pure(X.Tuple[X.Text "Pareto",X.Tuple values]) + P.Rayleigh field446 -> do + values <- sequence [pure(X.Scalar SDouble field446)] + pure(X.Tuple[X.Text "Rayleigh",X.Tuple values]) + P.Maxwell field447 -> do + values <- sequence [pure(X.Scalar SDouble field447)] + pure(X.Tuple[X.Text "Maxwell",X.Tuple values]) + P.Gumbel field448 field449 -> do + values <- sequence [pure(X.Scalar SDouble field448),pure(X.Scalar SDouble field449)] + pure(X.Tuple[X.Text "Gumbel",X.Tuple values]) + P.GeneralizedExtremeValue field450 field451 field452 -> do + values <- sequence [pure(X.Scalar SDouble field450),pure(X.Scalar SDouble field451),pure(X.Scalar SDouble field452)] + pure(X.Tuple[X.Text "GeneralizedExtremeValue",X.Tuple values]) + P.BetaBinomial field453 field454 field455 -> do + values <- sequence [pure(X.Index field453),pure(X.Scalar SDouble field454),pure(X.Scalar SDouble field455)] + pure(X.Tuple[X.Text "BetaBinomial",X.Tuple values]) + P.Skellam field456 field457 -> do + values <- sequence [pure(X.Scalar SDouble field456),pure(X.Scalar SDouble field457)] + pure(X.Tuple[X.Text "Skellam",X.Tuple values]) + P.VonMises field458 field459 -> do + values <- sequence [pure(X.Scalar SDouble field458),pure(X.Scalar SDouble field459)] + pure(X.Tuple[X.Text "VonMises",X.Tuple values]) + P.Triangular field460 field461 field462 -> do + values <- sequence [pure(X.Scalar SDouble field460),pure(X.Scalar SDouble field461),pure(X.Scalar SDouble field462)] + pure(X.Tuple[X.Text "Triangular",X.Tuple values]) + P.TruncatedNormal field463 field464 field465 field466 -> do + values <- sequence [pure(X.Scalar SDouble field463),pure(X.Scalar SDouble field464),pure(X.Scalar SDouble field465),pure(X.Scalar SDouble field466)] + pure(X.Tuple[X.Text "TruncatedNormal",X.Tuple values]) + P.Mixture field467 -> do + values <- sequence [X.List <$> mapM (\item468 -> (\(part469,part470) -> X.Tuple <$> sequence [pure(X.Scalar SDouble part469),encodeDistribution part470]) item468) field467] + pure(X.Tuple[X.Text "Mixture",X.Tuple values]) + P.Empirical field471 -> do + values <- sequence [X.List <$> mapM (\item472 -> pure(X.Scalar SDouble item472)) field471] + pure(X.Tuple[X.Text "Empirical",X.Tuple values]) + P.GaussianKDE field473 field474 -> do + values <- sequence [pure(X.Scalar SDouble field473),X.List <$> mapM (\item475 -> pure(X.Scalar SDouble item475)) field474] + pure(X.Tuple[X.Text "GaussianKDE",X.Tuple values]) + (244,_,_) -> do + X.unsupported "original abstract type has no public constructor fields" + (245,_,_) -> do + X.unsupported "original abstract type has no public constructor fields" + (246,_,_) -> do + X.unsupported "original abstract type has no public constructor fields" + (247,_,_) -> do + object <- (unbox 247 value :: IO S.TestResult) + case object of + S.TestResult field476 field477 field478 -> do + values <- sequence [pure(X.Scalar SDouble field476),pure(X.Scalar SDouble field477),X.List <$> mapM (\item479 -> pure(X.Scalar SDouble item479)) field478] + pure(X.Tuple[X.Text "TestResult",X.Tuple values]) + _ -> X.invalid "expected stochastic object" + (-2,[left,right]) -> case(X.valueInfo left,X.valueInfo right) of + ((241,_,_),(241,_,_)) -> do + a <- (unbox 241 left :: IO R.Generator); b <- unbox 241 right + pure(X.Boolean(a==b)) + ((240,_,_),(240,_,_)) -> do + a <- (asRNG left :: IO R.RNG); b <- asRNG right + pure(X.Boolean(a==b)) + ((242,_,_),(242,_,_)) -> do + a <- (unbox 242 left :: IO R.AliasTable); b <- unbox 242 right + pure(X.Boolean(a==b)) + ((243,_,_),(243,_,_)) -> do + a <- (unbox 243 left :: IO P.Distribution); b <- unbox 243 right + pure(X.Boolean(a==b)) + ((244,_,_),(244,_,_)) -> do + a <- (unbox 244 left :: IO P.Markov); b <- unbox 244 right + pure(X.Boolean(a==b)) + ((245,_,_),(245,_,_)) -> do + a <- (unbox 245 left :: IO P.HMM); b <- unbox 245 right + pure(X.Boolean(a==b)) + ((246,_,_),(246,_,_)) -> do + a <- (unbox 246 left :: IO S.Streaming); b <- unbox 246 right + pure(X.Boolean(a==b)) + ((247,_,_),(247,_,_)) -> do + a <- (unbox 247 left :: IO S.TestResult); b <- unbox 247 right + pure(X.Boolean(a==b)) + _ -> X.invalid "stochastic equality requires matching types" + _ -> X.invalid "invalid stochastic operation/arity" +foreign export ccall "hm_stochastic_apply" ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation pointers count out=stochasticBoundary $ do + values <- peekArray(fromIntegral count) pointers >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(X.publish value out)) diff --git a/src/HMath/FFI/TensorAll.hs b/src/HMath/FFI/TensorAll.hs new file mode 100644 index 0000000..0342386 --- /dev/null +++ b/src/HMath/FFI/TensorAll.hs @@ -0,0 +1,216 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE GADTs #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Direct original Tensor and mutable tensor calls with explicit element witnesses. +module HMath.FFI.TensorAll where + +import Control.Exception (bracket,throwIO) +import Data.Typeable (Typeable,cast) +import Data.Proxy (Proxy(..)) +import Foreign hiding (shift) +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Tensor as T +import qualified HMath.Tensor.Mutable as M +import HMath.Error (MathError) +import qualified HMath.FFI.Boundary as B +import HMath.FFI.Coefficient (ScalarType(SDouble,SInt)) +import HMath.FFI.GraphCodec (Wire(..)) +import HMath.FFI.MathError (CallbackFailure(..),withMathErrorWire,readCallbackFailure) +import HMath.FFI.TensorCodec +import qualified HMath.FFI.Value as V + +source :: Either MathError a -> (a -> IO V.Value) -> IO V.Value +source (Left err) _ = throwIO (CallbackMathError err) +source (Right value) encode = encode value +plain :: Wire a => a -> IO V.Value +plain = pure . wire +checked :: Wire a => Either MathError a -> IO V.Value +checked value = source value plain +output :: (Typeable a,Eq a,Show a) => Element a -> Either MathError (T.Tensor a) -> IO V.Value +output witness value = source value (pure . fromTensor witness) +outputs :: (Typeable a,Eq a,Show a) => Element a -> Either MathError [T.Tensor a] -> IO V.Value +outputs witness value = source value (pure . V.List . map (fromTensor witness)) +ints :: V.Value -> IO [Int] +ints value = V.asList value >>= mapM V.asIndex +values :: Element a -> V.Value -> IO [a] +values witness value = V.asList value >>= mapM (asElement witness) +structural :: (forall a. T.Tensor a -> Either MathError (T.Tensor a)) -> V.Value -> IO V.Value +structural function input = do SomeTensor witness tensor<-asTensor input; output witness (function tensor) +numericBinary :: (forall a. Num a => T.Tensor a -> T.Tensor a -> Either MathError (T.Tensor a)) -> V.Value -> V.Value -> IO V.Value +numericBinary function left right = do SomeTensor witness a<-asTensor left; b<-asTensorType right; withNum witness (output witness (function a b)) +ordinal :: (forall a. Ord a => T.Tensor a -> Either MathError (T.Tensor a)) -> V.Value -> IO V.Value +ordinal function input = do SomeTensor witness tensor<-asTensor input; withOrd witness (output witness (function tensor)) +logicalTensor :: V.Value -> IO (T.Tensor Bool) +logicalTensor = asTensorType +intTensor :: T.Tensor Int -> V.Value +intTensor = fromTensor (Numeric SInt) +boolTensor :: T.Tensor Bool -> V.Value +boolTensor = fromTensor Logical + +-- Function pointers/userdata are borrowed until all deferred graph owners die. +data Function = Function Int (FunPtr ()) (Ptr ()) +asFunction :: Int -> V.Value -> IO Function +asFunction expected (V.Opaque 273 _ _ _ payload) = case cast payload of + Just result@(Function actual _ _) | actual==expected -> pure result + _ -> V.invalid "tensor callback role differs" +asFunction _ _ = V.invalid "expected a tensor callback" +foreign import ccall safe "hm_tensor_invoke_callback" + invokeCallback :: FunPtr () -> Ptr () -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> Ptr () -> IO CInt +foreign import ccall safe "hm_tensor_invoke_buffer" + invokeBuffer :: FunPtr () -> Ptr () -> Ptr () -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> Ptr () -> IO CInt +{-# NOINLINE callback #-} +callback :: Function -> V.Value -> (V.Value -> IO a) -> a +callback (Function _ callbackPointer userdata) input decode = unsafePerformIO $ + bracket (newStablePtr input) freeStablePtr $ \pointer -> + alloca $ \out -> withMathErrorWire $ \errorWire -> do + status<-invokeCallback callbackPointer userdata pointer out errorWire + if status/=0 then readCallbackFailure status errorWire >>= throwIO + else do stable<-peek out; bracket (pure stable) freeStablePtr (\result -> deRefStablePtr result >>= decode) +scalar1 :: Element a -> Element b -> Function -> a -> b +scalar1 input outputType cb a = callback cb (V.Tuple [scalar input a]) (asElement outputType) +scalar2 :: Element a -> Element b -> Element c -> Function -> a -> b -> c +scalar2 left right outputType cb a b = callback cb (V.Tuple [scalar left a,scalar right b]) (asElement outputType) +foreign export ccall "hm_tensor_callback" createCallback :: CInt -> FunPtr () -> Ptr () -> Ptr (StablePtr V.Value) -> IO CInt +createCallback :: CInt -> FunPtr () -> Ptr () -> Ptr (StablePtr V.Value) -> IO CInt +createCallback role pointer userdata out = B.boundary $ B.checked (Right ()) $ \_ -> + V.publish (V.Opaque 273 (-1) (fromIntegral role) (pure ()) (Function (fromIntegral role) pointer userdata)) out +foreign export ccall "hm_tensor_clone" clone :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +clone :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt +clone input out = B.boundary $ deRefStablePtr input >>= \value -> B.checked (Right ()) (\_ -> V.publish value out) +foreign export ccall "hm_tensor_apply" apply :: CString -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +apply :: CString -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +apply namePointer inputs count out = B.boundary $ do + name<-peekCString namePointer + arguments<-peekArray (fromIntegral count) inputs >>= mapM deRefStablePtr + result<-dispatch name arguments + B.checked (Right ()) (\_ -> V.publish result out) + +dispatch :: String -> [V.Value] -> IO V.Value +dispatch name arguments = case (name,arguments) of + ("RowMajor",[]) -> plain (0::Int) + ("ColumnMajor",[]) -> plain (1::Int) + ("Strided",[]) -> plain (2::Int) + ("CPU",[]) -> plain (0::Int) + ("tensor",[kind,shape,xs]) -> do SomeElement witness<-element kind; dims<-ints shape; coefficients<-values witness xs; output witness (T.tensor dims coefficients) + ("tensorColumnMajor",[kind,shape,xs]) -> do SomeElement witness<-element kind; dims<-ints shape; coefficients<-values witness xs; output witness (T.tensorColumnMajor dims coefficients) + ("tensorFull",[shape,fill]) -> do SomeElement witness<-element fill; dims<-ints shape; value<-asElement witness fill; output witness (T.tensorFull dims value) + ("tensorZeros",[kind,shape]) -> do SomeElement witness<-element kind; dims<-ints shape; withNum witness (output witness (T.tensorZeros dims)) + ("tensorOnes",[kind,shape]) -> do SomeElement witness<-element kind; dims<-ints shape; withNum witness (output witness (T.tensorOnes dims)) + ("tensorArange",[start,end,step]) -> do SomeElement witness<-element start; a<-asElement witness start; b<-asElement witness end; c<-asElement witness step; withRealFloat witness (output witness (T.tensorArange a b c)) + ("tensorLinspace",[start,end,count]) -> do SomeElement witness<-element start; a<-asElement witness start; b<-asElement witness end; n<-V.asIndex count; withFractional witness (output witness (T.tensorLinspace a b n)) + ("tensorLogspace",[base,start,end,count]) -> do SomeElement witness<-element base; a<-asElement witness base; b<-asElement witness start; c<-asElement witness end; n<-V.asIndex count; withFloating witness (output witness (T.tensorLogspace a b c n)) + ("tensorRandom",[seed,shape]) -> do state<-unwire seed; dims<-ints shape; source (T.tensorRandom state dims) (\(tensor,next) -> pure (V.Tuple [fromTensor (Numeric SDouble) tensor,wire next])) + ("tensorValues",[input]) -> do SomeTensor witness tensor<-asTensor input; pure (V.List (map (scalar witness) (T.tensorValues tensor))) + ("tensorShape",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.tensorShape tensor) + ("tensorStrides",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.tensorStrides tensor) + ("tensorOffset",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.tensorOffset tensor) + ("tensorDType",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.tensorDType tensor) + ("tensorDevice",[input]) -> do SomeTensor _ tensor<-asTensor input; case T.tensorDevice tensor of T.CPU -> plain (0::Int) + ("tensorLayout",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (case T.tensorLayout tensor of {T.RowMajor->0::Int;T.ColumnMajor->1;T.Strided->2}) + ("numel",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.numel tensor) + ("isContiguous",[input]) -> do SomeTensor _ tensor<-asTensor input; plain (T.isContiguous tensor) + ("shapeSize",[shape]) -> ints shape >>= checked . T.shapeSize + ("inferBroadcast",[left,right]) -> do a<-ints left;b<-ints right;checked(T.inferBroadcast a b) + ("contiguous",[input]) -> structural T.contiguous input + ("indexTensor",[input,index]) -> do SomeTensor witness tensor<-asTensor input; ix<-ints index;source (T.indexTensor tensor ix) (pure . scalar witness) + ("sliceTensor",[axis,start,count,step,input]) -> do a<-V.asIndex axis;b<-V.asIndex start;c<-V.asIndex count;d<-V.asIndex step;structural (T.sliceTensor a b c d) input + ("fancyIndex",[axis,indices,input]) -> do a<-V.asIndex axis;ix<-ints indices;structural (T.fancyIndex a ix) input + ("gather",[axis,indices,input]) -> do a<-V.asIndex axis;ix<-ints indices;structural (T.gather a ix) input + ("booleanIndex",[mask,input]) -> do booleans<-logicalTensor mask;structural (T.booleanIndex booleans) input + ("scatter",[axis,indices,updates,target]) -> do a<-V.asIndex axis;ix<-ints indices;SomeTensor witness tensor<-asTensor updates;other<-asTensorType target;output witness(T.scatter a ix tensor other) + ("scatterAdd",[axis,indices,updates,target]) -> do a<-V.asIndex axis;ix<-ints indices;SomeTensor witness tensor<-asTensor updates;other<-asTensorType target;withNum witness(output witness(T.scatterAdd a ix tensor other)) + ("reshapeTensor",[shape,input]) -> do dims<-ints shape;structural (T.reshapeTensor dims) input + ("flattenTensor",[input]) -> structural T.flattenTensor input + ("squeeze",[input]) -> structural T.squeeze input + ("unsqueeze",[axis,input]) -> V.asIndex axis >>= \a -> structural (T.unsqueeze a) input + ("expand",[shape,input]) -> ints shape >>= \dims -> structural (T.expand dims) input + ("permute",[axes,input]) -> ints axes >>= \dims -> structural (T.permute dims) input + ("transposeTensor",[input]) -> structural T.transposeTensor input + ("moveAxis",[from,to,input]) -> do a<-V.asIndex from;b<-V.asIndex to;structural(T.moveAxis a b)input + ("swapAxes",[from,to,input]) -> do a<-V.asIndex from;b<-V.asIndex to;structural(T.swapAxes a b)input + ("broadcastTo",[shape,input]) -> ints shape >>= \dims -> structural(T.broadcastTo dims)input + ("repeatTensor",[axis,count,input]) -> do a<-V.asIndex axis;b<-V.asIndex count;structural(T.repeatTensor a b)input + ("tile",[counts,input]) -> ints counts >>= \dims -> structural(T.tile dims)input + ("concatenate",[kind,axis,inputs]) -> do SomeElement witness<-element kind;a<-V.asIndex axis;ts<-V.asList inputs >>= mapM asTensorType;output witness(T.concatenate a ts) + ("stack",[kind,axis,inputs]) -> do SomeElement witness<-element kind;a<-V.asIndex axis;ts<-V.asList inputs >>= mapM asTensorType;output witness(T.stack a ts) + ("splitTensor",[axis,segments,input]) -> do a<-V.asIndex axis;sizes<-ints segments;SomeTensor witness tensor<-asTensor input;outputs witness(T.splitTensor a sizes tensor) + ("chunkTensor",[axis,count,input]) -> do a<-V.asIndex axis;n<-V.asIndex count;SomeTensor witness tensor<-asTensor input;outputs witness(T.chunkTensor a n tensor) + ("padTensor",[padding,fill,input]) -> do pads<-unwire padding;SomeTensor witness tensor<-asTensor input;value<-asElement witness fill;output witness(T.padTensor pads value tensor) + ("roll",[axis,shift,input]) -> do a<-V.asIndex axis;b<-V.asIndex shift;structural(T.roll a b)input + ("flipTensor",[axis,input]) -> V.asIndex axis >>= \a -> structural(T.flipTensor a)input + ("rotate",[first,second,turns,input]) -> do a<-V.asIndex first;b<-V.asIndex second;c<-V.asIndex turns;structural(T.rotate a b c)input + ("sortTensor",[input]) -> ordinal T.sortTensor input + ("unique",[input]) -> ordinal T.unique input + ("argsort",[input]) -> do SomeTensor witness tensor<-asTensor input;withOrd witness(source(T.argsort tensor)(pure.intTensor)) + ("topk",[count,input]) -> do n<-V.asIndex count;SomeTensor witness tensor<-asTensor input;withOrd witness(source(T.topk n tensor)(\(a,b)->pure(V.Tuple[fromTensor witness a,intTensor b]))) + ("nonzero",[input]) -> do SomeTensor witness tensor<-asTensor input;withNum witness(source(T.nonzero tensor)(pure.intTensor)) + ("whereTensor",[mask,left,right]) -> do booleans<-logicalTensor mask;SomeTensor witness a<-asTensor left;b<-asTensorType right;output witness(T.whereTensor booleans a b) + ("maskedFill",[mask,fill,input]) -> do booleans<-logicalTensor mask;SomeTensor witness tensor<-asTensor input;value<-asElement witness fill;output witness(T.maskedFill booleans value tensor) + ("maskedSelect",[mask,input]) -> do booleans<-logicalTensor mask;structural(T.maskedSelect booleans)input + ("mapTensor",[kind,cb,input]) -> do SomeElement outKind<-element kind;handler<-asFunction 0 cb;SomeTensor inKind tensor<-asTensor input;pure(fromTensor outKind(T.mapTensor(scalar1 inKind outKind handler)tensor)) + ("zipTensor",[kind,cb,left,right]) -> do SomeElement outKind<-element kind;handler<-asFunction 0 cb;SomeTensor aKind a<-asTensor left;SomeTensor bKind b<-asTensor right;output outKind(T.zipTensor(scalar2 aKind bKind outKind handler)a b) + ("tensorAdd",[a,b]) -> numericBinary T.tensorAdd a b + ("tensorSubtract",[a,b]) -> numericBinary T.tensorSubtract a b + ("tensorMultiply",[a,b]) -> numericBinary T.tensorMultiply a b + ("tensorDivide",[a,b]) -> do SomeTensor witness x<-asTensor a;y<-asTensorType b;withFractional witness(output witness(T.tensorDivide x y)) + ("tensorEqual",[a,b]) -> do SomeTensor _ x<-asTensor a;y<-asTensorType b;source(T.tensorEqual x y)(pure.boolTensor) + ("tensorLess",[a,b]) -> do SomeTensor witness x<-asTensor a;y<-asTensorType b;withOrd witness(source(T.tensorLess x y)(pure.boolTensor)) + ("tensorAnd",[a,b]) -> do x<-logicalTensor a;y<-logicalTensor b;source(T.tensorAnd x y)(pure.boolTensor) + ("tensorOr",[a,b]) -> do x<-logicalTensor a;y<-logicalTensor b;source(T.tensorOr x y)(pure.boolTensor) + ("tensorNot",[input]) -> logicalTensor input >>= pure . boolTensor . T.tensorNot + ("promoteTensor",[kind,input]) -> do SomeElement target<-element kind;SomeTensor origin tensor<-asTensor input;withReal origin(withFractional target(pure(fromTensor target(T.promoteTensor tensor)))) + ("sumAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withNum witness(output witness(T.sumAxes dims k tensor)) + ("productAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withNum witness(output witness(T.productAxes dims k tensor)) + ("meanAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withFractional witness(output witness(T.meanAxes dims k tensor)) + ("varianceAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withFractional witness(output witness(T.varianceAxes dims k tensor)) + ("normAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withRealFloat witness(output witness(T.normAxes dims k tensor)) + ("minAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withOrd witness(output witness(T.minAxes dims k tensor)) + ("maxAxes",[axes,keep,input]) -> do dims<-ints axes;k<-V.asBoolean keep;SomeTensor witness tensor<-asTensor input;withOrd witness(output witness(T.maxAxes dims k tensor)) + ("argmin",[input]) -> do SomeTensor witness tensor<-asTensor input;withOrd witness(checked(T.argmin tensor)) + ("argmax",[input]) -> do SomeTensor witness tensor<-asTensor input;withOrd witness(checked(T.argmax tensor)) + ("cumulativeSum",[axis,input]) -> do a<-V.asIndex axis;SomeTensor witness tensor<-asTensor input;withNum witness(output witness(T.cumulativeSum a tensor)) + ("cumulativeProduct",[axis,input]) -> do a<-V.asIndex axis;SomeTensor witness tensor<-asTensor input;withNum witness(output witness(T.cumulativeProduct a tensor)) + ("tensordot",[leftAxes,rightAxes,left,right]) -> do a<-ints leftAxes;b<-ints rightAxes;SomeTensor witness x<-asTensor left;y<-asTensorType right;withNum witness(output witness(T.tensordot a b x y)) + ("einsum",[kind,labels,outputLabels,inputs]) -> do SomeElement witness<-element kind;names<-unwire labels;out<-V.asText outputLabels;ts<-V.asList inputs >>= mapM asTensorType;withNum witness(output witness(T.einsum names out ts)) + ("batchedMatmul",[a,b]) -> numericBinary T.batchedMatmul a b + ("tensorKronecker",[a,b]) -> numericBinary T.tensorKronecker a b + ("serializeTensor",[input]) -> do SomeTensor _ tensor<-asTensor input;plain(T.serializeTensor tensor) + ("deserializeTensor",[kind,text]) -> do SomeElement witness<-element kind;input<-V.asText text;withRead witness(output witness(T.deserializeTensor input)) + ("inputGraph",[input]) -> do SomeTensor witness tensor<-asTensor input;pure(fromGraph witness(T.inputGraph tensor)) + ("mapGraph",[kind,cb,input]) -> do SomeElement outKind<-element kind;handler<-asFunction 0 cb;SomeGraph inKind graph<-asGraph input;pure(fromGraph outKind(T.mapGraph(scalar1 inKind outKind handler)graph)) + ("zipGraph",[kind,cb,left,right]) -> do SomeElement outKind<-element kind;handler<-asFunction 0 cb;SomeGraph aKind a<-asGraph left;SomeGraph bKind b<-asGraph right;source(T.zipGraph(scalar2 aKind bKind outKind handler)a b)(pure.fromGraph outKind) + ("evaluateGraph",[input]) -> do SomeGraph witness graph<-asGraph input;output witness(T.evaluateGraph graph) + ("newMutable",[shape,fill]) -> do SomeElement witness<-element fill;dims<-ints shape;value<-asElement witness fill;withStorable witness(M.newMutable dims value >>= \result -> source result(pure.fromMutable witness)) + ("thawTensor",[input]) -> do SomeTensor witness tensor<-asTensor input;withStorable witness(M.thawTensor tensor >>= \result -> source result(pure.fromMutable witness)) + ("freezeTensor",[input]) -> do SomeMutable witness tensor<-asMutable input;M.freezeTensor tensor >>= output witness + ("mutableShape",[input]) -> do SomeMutable _ tensor<-asMutable input;plain(M.mutableShape tensor) + ("readMutable",[input,index]) -> do SomeMutable witness tensor<-asMutable input;ix<-ints index;M.readMutable tensor ix >>= \result -> source result(pure.scalar witness) + ("writeMutable",[input,index,fill]) -> do SomeMutable witness tensor<-asMutable input;ix<-ints index;value<-asElement witness fill;M.writeMutable tensor ix value >>= checked + ("modifyMutable",[input,index,cb]) -> do SomeMutable witness tensor<-asMutable input;ix<-ints index;handler<-asFunction 0 cb;M.modifyMutable tensor ix(scalar1 witness witness handler) >>= checked + ("sliceMutable",[axis,start,count,step,input]) -> do a<-V.asIndex axis;b<-V.asIndex start;c<-V.asIndex count;d<-V.asIndex step;SomeMutable witness tensor<-asMutable input;source(M.sliceMutable a b c d tensor)(pure.fromMutable witness) + ("transposeMutable",[input]) -> do SomeMutable witness tensor<-asMutable input;pure(fromMutable witness(M.transposeMutable tensor)) + ("mutableAlignment",[kind]) -> do SomeElement (witness::Element a)<-element kind;withStorable witness(plain(M.mutableAlignment(Proxy::Proxy a))) + ("withMutableBuffer",[input,cb]) -> do + SomeMutable witness tensor<-asMutable input + Function _ callbackPointer userdata<-asFunction 1 cb + M.withMutableBuffer tensor $ \pointer shape strides -> do + let metadata=V.Tuple[prototype witness,wire shape,wire strides,wire(sizeOfPtr pointer),wire(alignmentPtr pointer)] + bracket(newStablePtr metadata)freeStablePtr $ \stable -> alloca $ \out -> withMathErrorWire $ \errorWire -> do + status<-invokeBuffer callbackPointer userdata(castPtr pointer)stable out errorWire + if status/=0 then readCallbackFailure status errorWire >>= throwIO + else do result<-peek out;bracket(pure result)freeStablePtr deRefStablePtr + ("__prototype",[input]) -> do SomeTensor witness _<-asTensor input;pure(prototype witness) + ("__full_typed",[kind,shape,fill]) -> do SomeElement witness<-element kind;dims<-ints shape;value<-asElement witness fill;output witness(T.tensorFull dims value) + ("__graph_prototype",[input]) -> do SomeGraph witness _<-asGraph input;pure(prototype witness) + ("__mutable_prototype",[input]) -> do SomeMutable witness _<-asMutable input;pure(prototype witness) + ("__equal",[left,right]) -> do SomeTensor _ a<-asTensor left;b<-asTensorType right;plain(a==b) + _ -> V.invalid "invalid Tensor operation or argument count" + +-- The pointer is used only to select the source Storable type, never read. +sizeOfPtr :: forall a. Storable a => Ptr a -> Int +sizeOfPtr _ = sizeOf(undefined::a) +alignmentPtr :: forall a. Storable a => Ptr a -> Int +alignmentPtr _ = alignment(undefined::a) diff --git a/src/HMath/FFI/TensorCodec.hs b/src/HMath/FFI/TensorCodec.hs new file mode 100644 index 0000000..3d8d836 --- /dev/null +++ b/src/HMath/FFI/TensorCodec.hs @@ -0,0 +1,187 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ConstraintKinds #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Exact element witnesses and ownership of original Tensor/MutableTensor values. +module HMath.FFI.TensorCodec where + +import Control.Exception (evaluate) +import Data.Proxy (Proxy(..)) +import Data.Typeable (Typeable,cast) +import Foreign.Storable (Storable) +import HMath.FFI.Coefficient +import qualified HMath.FFI.Value as V +import qualified HMath.Tensor as T +import qualified HMath.Tensor.Mutable as M + +-- Every witness retains the original Haskell element type. Bool/String are +-- permitted for structural and callback APIs without inventing Num instances. +data Element a where + Numeric :: Coefficient a => ScalarType a -> Element a + Logical :: Element Bool + Characters :: Element String + Structural :: (Typeable a,Eq a,Show a) => StructuralCodec a -> Element a + +-- Providers retain their actual source type, without requiring or inventing a +-- Num instance. Optional dictionaries expose only instances the source has. +data StructuralCodec a = StructuralCodec + { structuralCode :: Int + , structuralEncode :: a -> V.Value + , structuralDecode :: V.Value -> IO a + , structuralForce :: a -> IO () + , structuralOrdering :: Maybe (Dict (Ord a)) + , structuralRead :: Maybe (Dict (Read a)) + , structuralStorable :: Maybe (Dict (Storable a)) + } + +data SomeElement where + SomeElement :: (Typeable a,Eq a,Show a) => Element a -> SomeElement +data SomeTensor where + SomeTensor :: (Typeable a,Eq a,Show a) => Element a -> T.Tensor a -> SomeTensor +data SomeGraph where + SomeGraph :: (Typeable a,Eq a,Show a) => Element a -> T.TensorGraph a -> SomeGraph +data SomeMutable where + SomeMutable :: (Typeable a,Eq a,Show a,Storable a) => Element a -> M.MutableTensor a -> SomeMutable + +element :: V.Value -> IO SomeElement +element (V.Scalar witness _) = pure (SomeElement (Numeric witness)) +element (V.Boolean _) = pure (SomeElement Logical) +element (V.Text _) = pure (SomeElement Characters) +element (V.Opaque 294 _ _ _ payload) = maybe (V.invalid "invalid structural tensor type token") pure (cast payload) +element _ = V.invalid "expected a typed scalar, Boolean or String prototype" + +elementCode :: Element a -> Int +elementCode (Numeric witness) = scalarTypeCode witness +elementCode Logical = 16 +elementCode Characters = 17 +elementCode (Structural codec) = structuralCode codec +prototype :: Element a -> V.Value +prototype (Numeric witness) = V.Scalar witness 0 +prototype Logical = V.Boolean False +prototype Characters = V.Text "" +prototype witness@(Structural codec) = V.Opaque 294 (structuralCode codec) 0 (pure ()) (SomeElement witness) +asElement :: Element a -> V.Value -> IO a +asElement (Numeric _) = V.asScalar +asElement Logical = V.asBoolean +asElement Characters = V.asText +asElement (Structural codec) = structuralDecode codec +scalar :: Element a -> a -> V.Value +scalar (Numeric witness) value = V.Scalar witness value +scalar Logical value = V.Boolean value +scalar Characters value = V.Text value +scalar (Structural codec) value = structuralEncode codec value +forceElement :: Element a -> a -> IO () +forceElement (Numeric _) value = forceCoefficient value +forceElement Logical value = evaluate value >> pure () +forceElement Characters value = mapM_ evaluate value +forceElement (Structural codec) value = structuralForce codec value + +fromTensor :: (Typeable a,Eq a,Show a) => Element a -> T.Tensor a -> V.Value +fromTensor kind value = case kind of + Numeric SDouble -> V.Opaque 161 0 (T.numel value) (mapM_ (forceElement kind) (T.tensorValues value)) value + _ -> V.Opaque 270 (elementCode kind) (T.numel value) (mapM_ (forceElement kind) (T.tensorValues value)) (SomeTensor kind value) +asTensor :: V.Value -> IO SomeTensor +asTensor (V.Opaque 161 _ _ _ payload) = maybe (V.invalid "invalid Tensor Double payload") (pure . SomeTensor (Numeric SDouble)) (cast payload) +asTensor (V.Opaque 270 _ _ _ payload) = maybe (V.invalid "invalid typed Tensor payload") pure (cast payload) +asTensor _ = V.invalid "expected original immutable Tensor" +asTensorType :: forall a. Typeable a => V.Value -> IO (T.Tensor a) +asTensorType value = do + SomeTensor _ tensor <- asTensor value + maybe (V.invalid "tensor element types differ") pure (cast tensor) +fromGraph :: (Typeable a,Eq a,Show a) => Element a -> T.TensorGraph a -> V.Value +fromGraph kind value = V.Opaque 271 (elementCode kind) 0 (evaluate value >> pure ()) (SomeGraph kind value) +asGraph :: V.Value -> IO SomeGraph +asGraph (V.Opaque 271 _ _ _ payload) = maybe (V.invalid "invalid TensorGraph payload") pure (cast payload) +asGraph _ = V.invalid "expected original TensorGraph" +asGraphType :: forall a. Typeable a => V.Value -> IO (T.TensorGraph a) +asGraphType value = do + SomeGraph _ graph <- asGraph value + maybe (V.invalid "graph element types differ") pure (cast graph) +fromMutable :: (Typeable a,Eq a,Show a,Storable a) => Element a -> M.MutableTensor a -> V.Value +fromMutable kind value = V.Opaque 272 (elementCode kind) (product (M.mutableShape value)) (evaluate value >> pure ()) (SomeMutable kind value) +asMutable :: V.Value -> IO SomeMutable +asMutable (V.Opaque 272 _ _ _ payload) = maybe (V.invalid "invalid MutableTensor payload") pure (cast payload) +asMutable _ = V.invalid "expected original MutableTensor" + +withNum :: Element a -> (Num a => IO b) -> IO b +withNum (Numeric _) action = action +withNum _ _ = V.unsupported "element type has no original Num instance" +withFractional :: forall a b. Element a -> (Fractional a => IO b) -> IO b +withFractional (Numeric _) action = case fractionalDict (Proxy::Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "element type has no original Fractional instance" +withFractional _ _ = V.unsupported "element type has no original Fractional instance" +withFloating :: forall a b. Element a -> (Floating a => IO b) -> IO b +withFloating (Numeric _) action = case floatingDict (Proxy::Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "element type has no original Floating instance" +withFloating _ _ = V.unsupported "element type has no original Floating instance" +withReal :: forall a b. Element a -> (Real a => IO b) -> IO b +withReal (Numeric _) action = case realDict (Proxy::Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "element type has no original Real instance" +withReal _ _ = V.unsupported "element type has no original Real instance" +withRealFloat :: forall a b. Element a -> (RealFloat a => IO b) -> IO b +withRealFloat (Numeric _) action = case realFloatDict (Proxy::Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "element type has no original RealFloat instance" +withRealFloat _ _ = V.unsupported "element type has no original RealFloat instance" +withOrd :: forall a b. Element a -> (Ord a => IO b) -> IO b +withOrd (Numeric _) action = case orderingDict (Proxy::Proxy a) of + Just Dict -> action + Nothing -> V.unsupported "element type has no original Ord instance" +withOrd Logical action = action +withOrd Characters action = action +withOrd (Structural codec) action = maybe (V.unsupported "structural element has no exposed original Ord instance") (\Dict -> action) (structuralOrdering codec) + +readDictionary :: Element a -> Maybe (Dict (Read a)) +readDictionary (Numeric witness) = case witness of + SDouble -> Just Dict + SFloat -> Just Dict + SInteger -> Just Dict + SRational -> Just Dict + SComplexDouble -> Just Dict + SComplexFloat -> Just Dict + SInt8 -> Just Dict + SInt16 -> Just Dict + SInt32 -> Just Dict + SInt64 -> Just Dict + SWord8 -> Just Dict + SWord16 -> Just Dict + SWord32 -> Just Dict + SWord64 -> Just Dict + SInt -> Just Dict + SWord -> Just Dict + SDual _ -> Nothing + SQuaternion _ -> Nothing +readDictionary Logical = Just Dict +readDictionary Characters = Just Dict +readDictionary (Structural codec) = structuralRead codec +storableDictionary :: Element a -> Maybe (Dict (Storable a)) +storableDictionary (Numeric witness) = case witness of + SDouble -> Just Dict + SFloat -> Just Dict + SComplexDouble -> Just Dict + SComplexFloat -> Just Dict + SInt8 -> Just Dict + SInt16 -> Just Dict + SInt32 -> Just Dict + SInt64 -> Just Dict + SWord8 -> Just Dict + SWord16 -> Just Dict + SWord32 -> Just Dict + SWord64 -> Just Dict + SInt -> Just Dict + SWord -> Just Dict + SInteger -> Nothing + SRational -> Nothing + SDual _ -> Nothing + SQuaternion _ -> Nothing +storableDictionary Logical = Just Dict +storableDictionary Characters = Nothing +storableDictionary (Structural codec) = structuralStorable codec +withRead :: Element a -> (Read a => IO b) -> IO b +withRead witness action = maybe (V.unsupported "element type has no original Read instance") (\Dict -> action) (readDictionary witness) +withStorable :: Element a -> (Storable a => IO b) -> IO b +withStorable witness action = maybe (V.unsupported "element type has no original Storable instance") (\Dict -> action) (storableDictionary witness) diff --git a/src/HMath/FFI/TimeSeries.hs b/src/HMath/FFI/TimeSeries.hs new file mode 100644 index 0000000..fe0bf63 --- /dev/null +++ b/src/HMath/FFI/TimeSeries.hs @@ -0,0 +1,466 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated representation adapters; all mathematics remains in original modules. +module HMath.FFI.TimeSeries where +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.FFI.Value +import HMath.FFI.GraphCodec (Wire(..),boxed,unboxed) +import qualified HMath.TimeSeries as T +import qualified HMath.Signal as S +import qualified HMath.Optimization.Common as O +instance Wire O.OptimizeOptions where + wire = boxed 20 + unwire = unboxed 20 +instance Wire T.Series where + wire = boxed 120 + unwire = unboxed 120 +instance Wire T.Alignment where + wire = boxed 121 + unwire = unboxed 121 +instance Wire T.Fill where + wire = boxed 122 + unwire = unboxed 122 +instance Wire T.Resampling where + wire = boxed 123 + unwire = unboxed 123 +instance Wire T.Rolling where + wire = boxed 124 + unwire = unboxed 124 +instance Wire T.DTWResult where + wire = boxed 125 + unwire = unboxed 125 +instance Wire T.Deterministic where + wire = boxed 126 + unwire = unboxed 126 +instance Wire T.ForecastMetric where + wire = boxed 127 + unwire = unboxed 127 +instance Wire T.Stationarity where + wire = boxed 128 + unwire = unboxed 128 +instance Wire T.ARIMAModel where + wire = boxed 129 + unwire = unboxed 129 +instance Wire T.ARModel where + wire = boxed 130 + unwire = unboxed 130 +instance Wire T.Decomposition where + wire = boxed 131 + unwire = unboxed 131 +instance Wire T.SARIMAOrder where + wire = boxed 132 + unwire = unboxed 132 +instance Wire T.STLConfig where + wire = boxed 133 + unwire = unboxed 133 +instance Wire T.Smoothing where + wire = boxed 134 + unwire = unboxed 134 +instance Wire T.VARModel where + wire = boxed 135 + unwire = unboxed 135 +instance Wire S.GaussianState where + wire = boxed 140 + unwire = unboxed 140 +foreign export ccall "hm_timeseries_describe" describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +describe input out = boundary $ do + value <- deRefStablePtr input + text <- case value of + Opaque 120 _ _ _ _ -> show <$> (unwire value :: IO T.Series) + Opaque 121 _ _ _ _ -> show <$> (unwire value :: IO T.Alignment) + Opaque 122 _ _ _ _ -> show <$> (unwire value :: IO T.Fill) + Opaque 123 _ _ _ _ -> show <$> (unwire value :: IO T.Resampling) + Opaque 124 _ _ _ _ -> show <$> (unwire value :: IO T.Rolling) + Opaque 125 _ _ _ _ -> show <$> (unwire value :: IO T.DTWResult) + Opaque 126 _ _ _ _ -> show <$> (unwire value :: IO T.Deterministic) + Opaque 127 _ _ _ _ -> show <$> (unwire value :: IO T.ForecastMetric) + Opaque 128 _ _ _ _ -> show <$> (unwire value :: IO T.Stationarity) + Opaque 129 _ _ _ _ -> show <$> (unwire value :: IO T.ARIMAModel) + Opaque 130 _ _ _ _ -> show <$> (unwire value :: IO T.ARModel) + Opaque 131 _ _ _ _ -> show <$> (unwire value :: IO T.Decomposition) + Opaque 132 _ _ _ _ -> show <$> (unwire value :: IO T.SARIMAOrder) + Opaque 133 _ _ _ _ -> show <$> (unwire value :: IO T.STLConfig) + Opaque 134 _ _ _ _ -> show <$> (unwire value :: IO T.Smoothing) + Opaque 135 _ _ _ _ -> show <$> (unwire value :: IO T.VARModel) + Opaque 140 _ _ _ _ -> show <$> (unwire value :: IO S.GaussianState) + _ -> invalid "expected a time-series domain object" + publish (Text text) out + pure 0 +foreign export ccall "hm_timeseries_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +apply operation input arity out = boundary $ do + values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr + case (operation,values) of + (0,[]) -> do + checked (Right (T.BackwardFill)) (\result_value -> publish (wire result_value) out) + (1,[]) -> do + checked (Right (T.BinLast)) (\result_value -> publish (wire result_value) out) + (2,[]) -> do + checked (Right (T.BinMean)) (\result_value -> publish (wire result_value) out) + (3,[]) -> do + checked (Right (T.ForwardFill)) (\result_value -> publish (wire result_value) out) + (4,[]) -> do + checked (Right (T.Inner)) (\result_value -> publish (wire result_value) out) + (5,[]) -> do + checked (Right (T.LeftAligned)) (\result_value -> publish (wire result_value) out) + (6,[]) -> do + checked (Right (T.LinearFill)) (\result_value -> publish (wire result_value) out) + (7,[]) -> do + checked (Right (T.LinearSamples)) (\result_value -> publish (wire result_value) out) + (8,[]) -> do + checked (Right (T.MovingMaximum)) (\result_value -> publish (wire result_value) out) + (9,[]) -> do + checked (Right (T.MovingMean)) (\result_value -> publish (wire result_value) out) + (10,[]) -> do + checked (Right (T.MovingMinimum)) (\result_value -> publish (wire result_value) out) + (11,[]) -> do + checked (Right (T.MovingSD)) (\result_value -> publish (wire result_value) out) + (12,[]) -> do + checked (Right (T.MovingVariance)) (\result_value -> publish (wire result_value) out) + (13,[]) -> do + checked (Right (T.Outer)) (\result_value -> publish (wire result_value) out) + (14,[vvalue,vvalue2,vvalue3]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + value3 <- unwire vvalue3 + checked (T.align value value2 value3) (\result_value -> publish (wire result_value) out) + (15,[vlags,vxs]) -> do + lags <- unwire vlags + xs <- unwire vxs + checked (T.autocorrelation lags xs) (\result_value -> publish (wire result_value) out) + (16,[vlag,vxs,vys]) -> do + lag <- unwire vlag + xs <- unwire vxs + ys <- unwire vys + checked (T.crossCorrelation lag xs ys) (\result_value -> publish (wire result_value) out) + (17,[vxs]) -> do + xs <- unwire vxs + checked (T.cumulativeReturns xs) (\result_value -> publish (wire result_value) out) + (18,[vorder,vlag,vxs]) -> do + order <- unwire vorder + lag <- unwire vlag + xs <- unwire vxs + checked (T.difference order lag xs) (\result_value -> publish (wire result_value) out) + (19,[vcovariance]) -> do + covariance <- unwire vcovariance + checked (T.durbinLevinson covariance) (\result_value -> publish (wire result_value) out) + (20,[valpha,vxs]) -> do + alpha <- unwire valpha + xs <- unwire vxs + checked (T.exponentialAverage alpha xs) (\result_value -> publish (wire result_value) out) + (21,[vvalue,vvalue2]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + checked (T.fillMissing value value2) (\result_value -> publish (wire result_value) out) + (22,[vvalue,vvalue2]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + checked (T.isRegular value value2) (\result_value -> publish (wire result_value) out) + (23,[vxs]) -> do + xs <- unwire vxs + checked (T.logarithmicReturns xs) (\result_value -> publish (wire result_value) out) + (24,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.observations value)) (\result_value -> publish (wire result_value) out) + (25,[vorder,vxs]) -> do + order <- unwire vorder + xs <- unwire vxs + checked (T.partialAutocorrelation order xs) (\result_value -> publish (wire result_value) out) + (26,[vstart,vstep,vxs]) -> do + start <- unwire vstart + step <- unwire vstep + xs <- unwire vxs + checked (T.regularSeries start step xs) (\result_value -> publish (wire result_value) out) + (27,[vvalue,vvalue2,vvalue3,vvalue4,vvalue5]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + value5 <- unwire vvalue5 + checked (T.resample value value2 value3 value4 value5) (\result_value -> publish (wire result_value) out) + (28,[vmethod,vwidth,vxs]) -> do + method <- unwire vmethod + width <- unwire vwidth + xs <- unwire vxs + checked (T.rolling method width xs) (\result_value -> publish (wire result_value) out) + (29,[vxs]) -> do + xs <- unwire vxs + checked (T.series xs) (\result_value -> publish (wire result_value) out) + (30,[vvalue]) -> do + value <- unwire vvalue + checked (T.seriesValues value) (\result_value -> publish (wire result_value) out) + (31,[vws,vxs]) -> do + ws <- unwire vws + xs <- unwire vxs + checked (T.weightedAverage ws xs) (\result_value -> publish (wire result_value) out) + (32,[vorder,vxs]) -> do + order <- unwire vorder + xs <- unwire vxs + checked (T.yuleWalker order xs) (\result_value -> publish (wire result_value) out) + (33,[vdistance,vpath]) -> do + distance <- unwire vdistance + path <- unwire vpath + checked (Right (T.DTWResult distance path)) (\result_value -> publish (wire result_value) out) + (34,[]) -> do + checked (Right (T.Level)) (\result_value -> publish (wire result_value) out) + (35,[]) -> do + checked (Right (T.LinearTrend)) (\result_value -> publish (wire result_value) out) + (36,[]) -> do + checked (Right (T.MAE)) (\result_value -> publish (wire result_value) out) + (37,[]) -> do + checked (Right (T.MAPE)) (\result_value -> publish (wire result_value) out) + (38,[vperiod,vtraining]) -> do + period <- unwire vperiod + training <- unwire vtraining + checked (Right (T.MASE period training)) (\result_value -> publish (wire result_value) out) + (39,[]) -> do + checked (Right (T.MSE)) (\result_value -> publish (wire result_value) out) + (40,[]) -> do + checked (Right (T.RMSE)) (\result_value -> publish (wire result_value) out) + (41,[]) -> do + checked (Right (T.SMAPE)) (\result_value -> publish (wire result_value) out) + (42,[vstatistic,vcritical_values,vobservations,vnull_hypothesis]) -> do + statistic <- unwire vstatistic + critical_values <- unwire vcritical_values + observations <- unwire vobservations + null_hypothesis <- unwire vnull_hypothesis + checked (Right (T.Stationarity statistic critical_values observations null_hypothesis)) (\result_value -> publish (wire result_value) out) + (43,[vthreshold,vxs]) -> do + threshold <- unwire vthreshold + xs <- unwire vxs + checked (T.anomalies threshold xs) (\result_value -> publish (wire result_value) out) + (44,[vdeterministic,vlags,vxs]) -> do + deterministic <- unwire vdeterministic + lags <- unwire vlags + xs <- unwire vxs + checked (T.augmentedDickeyFuller deterministic lags xs) (\result_value -> publish (wire result_value) out) + (45,[vpenalty,vmin_segment,vxs]) -> do + penalty <- unwire vpenalty + min_segment <- unwire vmin_segment + xs <- unwire vxs + checked (T.changePoints penalty min_segment xs) (\result_value -> publish (wire result_value) out) + (46,[vmean,vsd,vdrift,vthreshold,vxs]) -> do + mean <- unwire vmean + sd <- unwire vsd + drift <- unwire vdrift + threshold <- unwire vthreshold + xs <- unwire vxs + checked (T.cusum mean sd drift threshold xs) (\result_value -> publish (wire result_value) out) + (47,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.dtwDistance value)) (\result_value -> publish (wire result_value) out) + (48,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.dtwPath value)) (\result_value -> publish (wire result_value) out) + (49,[vradius,vxs,vys]) -> do + radius <- unwire vradius + xs <- unwire vxs + ys <- unwire vys + checked (T.dynamicTimeWarping radius xs ys) (\result_value -> publish (wire result_value) out) + (50,[vmetric,vactual,vpredicted]) -> do + metric <- unwire vmetric + actual <- unwire vactual + predicted <- unwire vpredicted + checked (T.forecastError metric actual predicted) (\result_value -> publish (wire result_value) out) + (51,[vdeterministic,vlags,vxs]) -> do + deterministic <- unwire vdeterministic + lags <- unwire vlags + xs <- unwire vxs + checked (T.kpss deterministic lags xs) (\result_value -> publish (wire result_value) out) + (52,[vsample_rate,vxs]) -> do + sample_rate <- unwire vsample_rate + xs <- unwire vxs + checked (T.spectrum sample_rate xs) (\result_value -> publish (wire result_value) out) + (53,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stationarityCriticalValues value)) (\result_value -> publish (wire result_value) out) + (54,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stationarityNull value)) (\result_value -> publish (wire result_value) out) + (55,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stationarityObservations value)) (\result_value -> publish (wire result_value) out) + (56,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stationarityStatistic value)) (\result_value -> publish (wire result_value) out) + (57,[vtrend,vseasonal,vremainder]) -> do + trend <- unwire vtrend + seasonal <- unwire vseasonal + remainder <- unwire vremainder + checked (Right (T.Decomposition trend seasonal remainder)) (\result_value -> publish (wire result_value) out) + (58,[valpha,vbeta]) -> do + alpha <- unwire valpha + beta <- unwire vbeta + checked (Right (T.Holt alpha beta)) (\result_value -> publish (wire result_value) out) + (59,[vperiod,valpha,vbeta,vgamma]) -> do + period <- unwire vperiod + alpha <- unwire valpha + beta <- unwire vbeta + gamma <- unwire vgamma + checked (Right (T.HoltWinters period alpha beta gamma)) (\result_value -> publish (wire result_value) out) + (60,[var,vdifference,vma,vseasonal_ar,vseasonal_difference,vseasonal_ma,vperiod]) -> do + ar <- unwire var + difference <- unwire vdifference + ma <- unwire vma + seasonal_ar <- unwire vseasonal_ar + seasonal_difference <- unwire vseasonal_difference + seasonal_ma <- unwire vseasonal_ma + period <- unwire vperiod + checked (Right (T.SARIMAOrder ar difference ma seasonal_ar seasonal_difference seasonal_ma period)) (\result_value -> publish (wire result_value) out) + (61,[vperiod,vseasonal_window,vtrend_window,vlow_pass_window,vinner_iterations,vrobust_iterations]) -> do + period <- unwire vperiod + seasonal_window <- unwire vseasonal_window + trend_window <- unwire vtrend_window + low_pass_window <- unwire vlow_pass_window + inner_iterations <- unwire vinner_iterations + robust_iterations <- unwire vrobust_iterations + checked (Right (T.STLConfig period seasonal_window trend_window low_pass_window inner_iterations robust_iterations)) (\result_value -> publish (wire result_value) out) + (62,[valpha]) -> do + alpha <- unwire valpha + checked (Right (T.Simple alpha)) (\result_value -> publish (wire result_value) out) + (63,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.arCoefficients value)) (\result_value -> publish (wire result_value) out) + (64,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.arOrder value)) (\result_value -> publish (wire result_value) out) + (65,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.arimaInnovationVariance value)) (\result_value -> publish (wire result_value) out) + (66,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.arimaParameters value)) (\result_value -> publish (wire result_value) out) + (67,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.arimaResiduals value)) (\result_value -> publish (wire result_value) out) + (68,[vperiod,vxs]) -> do + period <- unwire vperiod + xs <- unwire vxs + checked (T.decompose period xs) (\result_value -> publish (wire result_value) out) + (69,[vperiod]) -> do + period <- unwire vperiod + checked (Right (T.defaultSTLConfig period)) (\result_value -> publish (wire result_value) out) + (70,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.differenceOrder value)) (\result_value -> publish (wire result_value) out) + (71,[vorder,vxs]) -> do + order <- unwire vorder + xs <- unwire vxs + checked (T.fitAR order xs) (\result_value -> publish (wire result_value) out) + (72,[vvalue,vvalue2,vvalue3,vvalue4,vvalue5]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + value5 <- unwire vvalue5 + checked (T.fitARIMA value value2 value3 value4 value5) (\result_value -> publish (wire result_value) out) + (73,[vvalue,vvalue2,vvalue3,vvalue4]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + value3 <- unwire vvalue3 + value4 <- unwire vvalue4 + checked (T.fitARMA value value2 value3 value4) (\result_value -> publish (wire result_value) out) + (74,[vvalue,vvalue2,vvalue3]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + value3 <- unwire vvalue3 + checked (T.fitMA value value2 value3) (\result_value -> publish (wire result_value) out) + (75,[voptions,vorder,vxs]) -> do + options <- unwire voptions + order <- unwire vorder + xs <- unwire vxs + checked (T.fitSARIMA options order xs) (\result_value -> publish (wire result_value) out) + (76,[vorder,vxs]) -> do + order <- unwire vorder + xs <- unwire vxs + checked (T.fitVAR order xs) (\result_value -> publish (wire result_value) out) + (77,[vvalue,vvalue2]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + checked (T.forecastAR value value2) (\result_value -> publish (wire result_value) out) + (78,[vvalue,vvalue2]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + checked (T.forecastARIMA value value2) (\result_value -> publish (wire result_value) out) + (79,[vvalue,vvalue2]) -> do + value <- unwire vvalue + value2 <- unwire vvalue2 + checked (T.forecastVAR value value2) (\result_value -> publish (wire result_value) out) + (80,[vtransition,vobservation,vq,vr,vinitial,vmeasured]) -> do + transition <- unwire vtransition + observation <- unwire vobservation + q <- unwire vq + r <- unwire vr + initial <- unwire vinitial + measured <- unwire vmeasured + checked (T.kalmanSeries transition observation q r initial measured) (\result_value -> publish (wire result_value) out) + (81,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.maOrder value)) (\result_value -> publish (wire result_value) out) + (82,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.remainderComponent value)) (\result_value -> publish (wire result_value) out) + (83,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.seasonalAROrder value)) (\result_value -> publish (wire result_value) out) + (84,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.seasonalComponent value)) (\result_value -> publish (wire result_value) out) + (85,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.seasonalDifferenceOrder value)) (\result_value -> publish (wire result_value) out) + (86,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.seasonalMAOrder value)) (\result_value -> publish (wire result_value) out) + (87,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.seasonalPeriod value)) (\result_value -> publish (wire result_value) out) + (88,[vmethod,vhorizon,vxs]) -> do + method <- unwire vmethod + horizon <- unwire vhorizon + xs <- unwire vxs + checked (T.smoothForecast method horizon xs) (\result_value -> publish (wire result_value) out) + (89,[vconfig,vxs]) -> do + config <- unwire vconfig + xs <- unwire vxs + checked (T.stl config xs) (\result_value -> publish (wire result_value) out) + (90,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlInnerIterations value)) (\result_value -> publish (wire result_value) out) + (91,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlLowPassWindow value)) (\result_value -> publish (wire result_value) out) + (92,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlPeriod value)) (\result_value -> publish (wire result_value) out) + (93,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlRobustIterations value)) (\result_value -> publish (wire result_value) out) + (94,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlSeasonalWindow value)) (\result_value -> publish (wire result_value) out) + (95,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.stlTrendWindow value)) (\result_value -> publish (wire result_value) out) + (96,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.trendComponent value)) (\result_value -> publish (wire result_value) out) + (97,[vvalue]) -> do + value <- unwire vvalue + checked (Right (T.varCoefficients value)) (\result_value -> publish (wire result_value) out) + (98,[vmean,vcovariance]) -> do + mean <- unwire vmean + covariance <- unwire vcovariance + checked (S.gaussianState mean covariance) (\result_value -> publish (wire result_value) out) + (99,[vvalue]) -> do + value <- unwire vvalue + checked (Right (S.stateMean value)) (\result_value -> publish (wire result_value) out) + (100,[vvalue]) -> do + value <- unwire vvalue + checked (Right (S.stateCovariance value)) (\result_value -> publish (wire result_value) out) + _ -> invalid "time-series operation identifier or arity differs" diff --git a/src/HMath/FFI/Units.hs b/src/HMath/FFI/Units.hs new file mode 100644 index 0000000..6146e43 --- /dev/null +++ b/src/HMath/FFI/Units.hs @@ -0,0 +1,243 @@ +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_units_bindings.py. No numerical reimplementation. +module HMath.FFI.Units where +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Units as U +import HMath.Error (MathError) +import HMath.FFI.Coefficient +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError + +dimension :: U.Dimension -> V.Value +dimension x=V.Opaque 68 (-1) 9 (mapM_ forceCoefficient (U.dimensionExponents x)) x +unit :: U.Unit -> V.Value +unit x=V.Opaque 69 (-1) 0 (V.forceValue(V.Text(U.unitName x)) >> V.forceValue(dimension(U.unitDimension x)) >> forceCoefficient(U.unitScale x) >> forceCoefficient(U.unitOffset x)) x +quantity :: U.Quantity -> V.Value +quantity x=V.Opaque 70 (-1) 0 (V.forceValue(dimension(U.quantityDimension x)) >> forceCoefficient(U.siValue x) >> evaluate x >> pure ()) x +siPrefix :: U.SIPrefix -> V.Value +siPrefix x=V.Opaque 71 (-1) 0 (V.forceValue(V.Text(U.prefixName x)) >> V.forceValue(V.Text(U.prefixSymbol x)) >> evaluate(U.prefixExponent x) >> pure ()) x +asObject :: Typeable a => Int -> V.Value -> IO a +asObject kind (V.Opaque actual _ _ _ payload) | kind==actual=maybe (V.invalid "Units object payload/type mismatch") pure (cast payload) +asObject _ _=V.invalid "Units object kind mismatch" +source :: Either MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +unitsBoundary :: IO CInt -> IO CInt +unitsBoundary action=B.boundary $ callbackBoundary (\e -> B.checked (Left e) (const(pure ()))) action +apply :: Int -> [V.Value] -> IO V.Value +apply opcode args=case (opcode,args) of + (0,[a0]) -> do + a0Value <- (\v -> V.asList v >>= mapM V.asScalar) a0 + (dimension) <$> source (U.dimension a0Value) + (1,[a0]) -> do + a0Value <- asObject 68 a0 + pure ((V.List . map (V.Scalar SInteger)) (U.dimensionExponents a0Value)) + (2,[]) -> do + pure ((dimension) (U.dimensionless )) + (3,[]) -> do + pure ((dimension) (U.lengthDimension )) + (4,[]) -> do + pure ((dimension) (U.massDimension )) + (5,[]) -> do + pure ((dimension) (U.timeDimension )) + (6,[]) -> do + pure ((dimension) (U.temperatureDimension )) + (7,[]) -> do + pure ((dimension) (U.angleDimension )) + (8,[]) -> do + pure ((dimension) (U.dataDimension )) + (9,[a0,a1,a2,a3]) -> do + a0Value <- V.asText a0 + a1Value <- asObject 68 a1 + a2Value <- V.asScalar a2 + a3Value <- V.asScalar a3 + (unit) <$> source (U.unit a0Value a1Value a2Value a3Value) + (10,[a0]) -> do + a0Value <- asObject 69 a0 + pure ((V.Text) (U.unitName a0Value)) + (11,[a0]) -> do + a0Value <- asObject 69 a0 + pure ((dimension) (U.unitDimension a0Value)) + (12,[a0]) -> do + a0Value <- asObject 69 a0 + pure ((V.Scalar SRational) (U.unitScale a0Value)) + (13,[a0]) -> do + a0Value <- asObject 69 a0 + pure ((V.Scalar SRational) (U.unitOffset a0Value)) + (14,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- asObject 69 a1 + (unit) <$> source (U.unitProduct a0Value a1Value) + (15,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- asObject 69 a1 + (unit) <$> source (U.unitQuotient a0Value a1Value) + (16,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- V.asScalar a1 + (unit) <$> source (U.unitPower a0Value a1Value) + (17,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- V.asScalar a1 + pure ((quantity) (U.quantity a0Value a1Value)) + (18,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- V.asScalar a1 + (quantity) <$> source (U.temperatureDifference a0Value a1Value) + (19,[a0]) -> do + a0Value <- asObject 70 a0 + pure ((dimension) (U.quantityDimension a0Value)) + (20,[a0]) -> do + a0Value <- asObject 70 a0 + pure ((V.Scalar SRational) (U.siValue a0Value)) + (21,[a0,a1]) -> do + a0Value <- asObject 69 a0 + a1Value <- asObject 70 a1 + (V.Scalar SRational) <$> source (U.inUnit a0Value a1Value) + (22,[a0,a1,a2]) -> do + a0Value <- asObject 69 a0 + a1Value <- asObject 69 a1 + a2Value <- V.asScalar a2 + (V.Scalar SRational) <$> source (U.convert a0Value a1Value a2Value) + (23,[a0,a1]) -> do + a0Value <- asObject 70 a0 + a1Value <- asObject 70 a1 + (quantity) <$> source (U.addQuantity a0Value a1Value) + (24,[a0,a1]) -> do + a0Value <- asObject 70 a0 + a1Value <- asObject 70 a1 + (quantity) <$> source (U.subtractQuantity a0Value a1Value) + (25,[a0,a1]) -> do + a0Value <- asObject 70 a0 + a1Value <- asObject 70 a1 + (quantity) <$> source (U.multiplyQuantity a0Value a1Value) + (26,[a0,a1]) -> do + a0Value <- asObject 70 a0 + a1Value <- asObject 70 a1 + (quantity) <$> source (U.divideQuantity a0Value a1Value) + (27,[a0,a1,a2]) -> do + a0Value <- V.asText a0 + a1Value <- V.asText a1 + a2Value <- V.asIndex a2 + pure ((siPrefix) (U.SIPrefix a0Value a1Value a2Value)) + (28,[]) -> do + pure ((V.List . map siPrefix) (U.siPrefixes )) + (29,[a0,a1]) -> do + a0Value <- asObject 71 a0 + a1Value <- asObject 69 a1 + (unit) <$> source (U.prefixed a0Value a1Value) + (30,[]) -> do + pure ((unit) (U.metre )) + (31,[]) -> do + pure ((unit) (U.kilometre )) + (32,[]) -> do + pure ((unit) (U.centimetre )) + (33,[]) -> do + pure ((unit) (U.millimetre )) + (34,[]) -> do + pure ((unit) (U.inch )) + (35,[]) -> do + pure ((unit) (U.foot )) + (36,[]) -> do + pure ((unit) (U.yard )) + (37,[]) -> do + pure ((unit) (U.mile )) + (38,[]) -> do + pure ((unit) (U.nauticalMile )) + (39,[]) -> do + pure ((unit) (U.squareMetre )) + (40,[]) -> do + pure ((unit) (U.hectare )) + (41,[]) -> do + pure ((unit) (U.cubicMetre )) + (42,[]) -> do + pure ((unit) (U.litre )) + (43,[]) -> do + pure ((unit) (U.millilitre )) + (44,[]) -> do + pure ((unit) (U.kilogram )) + (45,[]) -> do + pure ((unit) (U.gram )) + (46,[]) -> do + pure ((unit) (U.tonne )) + (47,[]) -> do + pure ((unit) (U.pound )) + (48,[]) -> do + pure ((unit) (U.second )) + (49,[]) -> do + pure ((unit) (U.minute )) + (50,[]) -> do + pure ((unit) (U.hour )) + (51,[]) -> do + pure ((unit) (U.day )) + (52,[]) -> do + pure ((unit) (U.metresPerSecond )) + (53,[]) -> do + pure ((unit) (U.kilometresPerHour )) + (54,[]) -> do + pure ((unit) (U.milesPerHour )) + (55,[]) -> do + pure ((unit) (U.metresPerSecondSquared )) + (56,[]) -> do + pure ((unit) (U.newton )) + (57,[]) -> do + pure ((unit) (U.joule )) + (58,[]) -> do + pure ((unit) (U.watt )) + (59,[]) -> do + pure ((unit) (U.pascal )) + (60,[]) -> do + pure ((unit) (U.bar )) + (61,[]) -> do + pure ((unit) (U.atmosphere )) + (62,[]) -> do + pure ((unit) (U.kelvin )) + (63,[]) -> do + pure ((unit) (U.celsius )) + (64,[]) -> do + pure ((unit) (U.fahrenheit )) + (65,[]) -> do + pure ((unit) (U.hertz )) + (66,[]) -> do + pure ((unit) (U.bit )) + (67,[]) -> do + pure ((unit) (U.byte )) + (68,[]) -> do + pure ((unit) (U.kibibyte )) + (69,[]) -> do + pure ((unit) (U.mebibyte )) + (70,[]) -> do + pure ((unit) (U.gigabyte )) + (71,[]) -> do + pure ((unit) (U.radian )) + (72,[]) -> do + pure ((unit) (U.degree )) + (73,[]) -> do + pure ((unit) (U.gradian )) + (74,[a0]) -> do + a0Value <- asObject 71 a0 + pure ((V.Text) (U.prefixName a0Value)) + (75,[a0]) -> do + a0Value <- asObject 71 a0 + pure ((V.Text) (U.prefixSymbol a0Value)) + (76,[a0]) -> do + a0Value <- asObject 71 a0 + pure ((V.Index) (U.prefixExponent a0Value)) + (100,[a,b]) -> case (V.valueInfo a,V.valueInfo b) of + ((68,_,_),(68,_,_)) -> do x <- asObject 68 a; y <- asObject 68 b; pure(V.Boolean((x::U.Dimension)==y)) + ((69,_,_),(69,_,_)) -> do x <- asObject 69 a; y <- asObject 69 b; pure(V.Boolean((x::U.Unit)==y)) + ((70,_,_),(70,_,_)) -> do x <- asObject 70 a; y <- asObject 70 b; pure(V.Boolean((x::U.Quantity)==y)) + ((71,_,_),(71,_,_)) -> do x <- asObject 71 a; y <- asObject 71 b; pure(V.Boolean((x::U.SIPrefix)==y)) + _ -> V.invalid "Units equality requires matching types" + _ -> V.invalid "invalid Units operation/arity" +foreign export ccall "hm_units_apply" ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply opcode pointers count out=unitsBoundary $ do + args <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + value <- apply (fromIntegral opcode) args + B.checked (Right ()) (const (V.publish value out)) diff --git a/src/HMath/FFI/Value.hs b/src/HMath/FFI/Value.hs new file mode 100644 index 0000000..04c1382 --- /dev/null +++ b/src/HMath/FFI/Value.hs @@ -0,0 +1,223 @@ +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- | Shared lossless value/ownership representation, not a mathematical engine. +module HMath.FFI.Value where +import Control.Exception (bracketOnError, evaluate, throwIO) +import Data.Coerce (coerce) +import Data.Char (chr, ord) +import Data.Complex (Complex ((:+)), imagPart, realPart) +import Data.Ratio ((%), numerator, denominator) +import Data.Proxy (Proxy (..)) +import Data.Typeable (Typeable, cast) +import Foreign +import Foreign.C +import HMath.FFI.Coefficient +import HMath.FFI.Boundary +import HMath.FFI.MathError (CallbackFailure (..)) +import qualified HMath.Matrix as M + +data SomeMatrix where + SomeMatrix :: Coefficient a => ScalarType a -> M.Matrix a -> SomeMatrix + StructuralMatrix :: Typeable a => Int -> (a -> IO Value) -> (Value -> IO a) -> (a -> IO ()) -> M.Matrix a -> SomeMatrix + +booleanMatrix :: M.Matrix Bool -> Value +booleanMatrix = Dense . StructuralMatrix 16 (pure . Boolean) asBoolean (\x -> evaluate x >> pure ()) +stringMatrix :: M.Matrix String -> Value +stringMatrix = Dense . StructuralMatrix 17 (pure . Text) asText (mapM_ evaluate) + +-- Structural matrices do not pretend to have a Num instance. This accessor +-- exposes the original Matrix type while callers retain their own constraints. +asMatrix :: forall a. Typeable a => Value -> IO (M.Matrix a) +asMatrix (Dense (SomeMatrix _ matrix)) = maybe (invalid "Matrix element types differ") pure (cast matrix) +asMatrix (Dense (StructuralMatrix _ _ _ _ matrix)) = maybe (invalid "Matrix element types differ") pure (cast matrix) +asMatrix _ = invalid "expected Matrix value" + + +data Value where + None :: Value + Scalar :: Coefficient a => ScalarType a -> a -> Value + Index :: Int -> Value + Boolean :: Bool -> Value + List :: [Value] -> Value + Tuple :: [Value] -> Value + Dense :: SomeMatrix -> Value + Text :: String -> Value + Opaque :: Typeable a => Int -> Int -> Int -> IO () -> a -> Value + +valueInfo :: Value -> (Int,Int,Int) +valueInfo value = case value of + None -> (0,-1,0) + Scalar witness _ -> (1,scalarTypeCode witness,0) + Index _ -> (2,-1,0) + Boolean _ -> (3,-1,0) + List values -> (4,-1,length values) + Tuple values -> (5,-1,length values) + Dense (SomeMatrix witness matrix) -> (9,scalarTypeCode witness,length (M.toList matrix)) + Dense (StructuralMatrix dtype _ _ _ matrix) -> (9,dtype,length (M.toList matrix)) + Text text -> (10,-1,length text) + Opaque kind dtype count _ _ -> (kind,dtype,count) + +forceValue :: Value -> IO () +forceValue value = case value of + None -> pure () + Scalar _ x -> forceCoefficient x + Index x -> evaluate x >> pure () + Boolean x -> evaluate x >> pure () + List xs -> mapM_ forceValue xs + Tuple xs -> mapM_ forceValue xs + Dense (SomeMatrix _ matrix) -> mapM_ forceCoefficient (M.toList matrix) + Dense (StructuralMatrix _ _ _ force matrix) -> mapM_ force (M.toList matrix) + Text text -> mapM_ evaluate text + Opaque _ _ count force _ -> evaluate count >> force + +publish :: Value -> Ptr (StablePtr Value) -> IO () +publish value out = forceValue value >> bracketOnError (newStablePtr value) freeStablePtr (poke out) +invalid :: String -> IO a +invalid = throwIO . CallbackFailure 1 +unsupported :: String -> IO a +unsupported = throwIO . CallbackFailure 10 +asScalar :: forall a. Coefficient a => Value -> IO a +asScalar (Scalar _ value) = maybe (invalid "coefficient types differ") pure (cast value) +asScalar _ = invalid "expected a scalar coefficient" +asIndex :: Value -> IO Int +asIndex (Index n) = pure n +asIndex (Scalar (_ :: ScalarType a) value) = case integralDict (Proxy :: Proxy a) of + Just Dict -> let n = toInteger value in + if n >= toInteger (minBound :: Int) && n <= toInteger (maxBound :: Int) + then pure (fromInteger n) + else throwIO (CallbackFailure 3 "integral scalar is outside the Haskell Int representation") + Nothing -> invalid "expected an integral Haskell Int representation" +asIndex _ = invalid "expected a Haskell Int" +asList :: Value -> IO [Value] +asList (List xs) = pure xs +asList _ = invalid "expected a list value" +asTuple :: Int -> Value -> IO [Value] +asTuple count (Tuple xs) | length xs == count = pure xs +asTuple _ _ = invalid "tuple arity differs" + +asBoolean :: Value -> IO Bool +asBoolean (Boolean value) = pure value +asBoolean _ = invalid "expected Boolean value" +asText :: Value -> IO String +asText (Text value) = pure value +asText _ = invalid "expected String value" +foreign export ccall "hm_value_text" textValue :: Ptr Word32 -> CSize -> Ptr (StablePtr Value) -> IO CInt +textValue :: Ptr Word32 -> CSize -> Ptr (StablePtr Value) -> IO CInt +textValue input count out = boundary $ do + points <- peekArray (fromIntegral count) input + checked (Right ()) $ \_ -> publish (Text (map (chr . fromIntegral) points)) out +foreign export ccall "hm_value_get_text" getText :: StablePtr Value -> Ptr Word32 -> IO CInt +getText :: StablePtr Value -> Ptr Word32 -> IO CInt +getText pointer out = boundary $ do + value <- deRefStablePtr pointer >>= asText + checked (Right ()) $ \_ -> pokeArray out (map (fromIntegral . ord) value) + +foreign export ccall "hm_value_free" freeValue :: StablePtr Value -> IO () +freeValue :: StablePtr Value -> IO () +freeValue = freeStablePtr +foreign export ccall "hm_value_info" info :: StablePtr Value -> Ptr CInt -> Ptr CInt -> Ptr CSize -> IO CInt +info :: StablePtr Value -> Ptr CInt -> Ptr CInt -> Ptr CSize -> IO CInt +info pointer kind dtype count = boundary $ do + value <- deRefStablePtr pointer + let (k,t,n)=valueInfo value + _ <- evaluate k >> evaluate t >> evaluate n + checked (Right ()) $ \_ -> poke kind (fromIntegral k) >> poke dtype (fromIntegral t) >> poke count (fromIntegral n) +foreign export ccall "hm_value_sequence" sequenceValue :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +sequenceValue :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt +sequenceValue tuple pointers count out = boundary $ do + values <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + checked (Right ()) $ \_ -> publish (if tuple==0 then List values else Tuple values) out +foreign export ccall "hm_value_item" item :: StablePtr Value -> CSize -> Ptr (StablePtr Value) -> IO CInt +item :: StablePtr Value -> CSize -> Ptr (StablePtr Value) -> IO CInt +item pointer index out = boundary $ do + value <- deRefStablePtr pointer + let xs = case value of List values -> values; Tuple values -> values; _ -> error "value item kind mismatch" + checked (Right ()) $ \_ -> publish (xs !! fromIntegral index) out +foreign export ccall "hm_value_none" noneValue :: Ptr (StablePtr Value) -> IO CInt +noneValue :: Ptr (StablePtr Value) -> IO CInt +noneValue out = boundary $ checked (Right ()) $ \_ -> publish None out +foreign export ccall "hm_value_boolean" booleanValue :: CInt -> Ptr (StablePtr Value) -> IO CInt +booleanValue :: CInt -> Ptr (StablePtr Value) -> IO CInt +booleanValue value out = boundary $ checked (Right ()) $ \_ -> publish (Boolean (value/=0)) out +foreign export ccall "hm_value_index" indexValue :: CPtrdiff -> Ptr (StablePtr Value) -> IO CInt +indexValue :: CPtrdiff -> Ptr (StablePtr Value) -> IO CInt +indexValue value out = boundary $ checked (Right ()) $ \_ -> publish (Index (fromIntegral value)) out +foreign export ccall "hm_value_get_index" getIndex :: StablePtr Value -> Ptr CPtrdiff -> IO CInt +getIndex :: StablePtr Value -> Ptr CPtrdiff -> IO CInt +getIndex pointer out = boundary $ do + value <- deRefStablePtr pointer >>= asIndex + checked (Right ()) $ \_ -> poke out (fromIntegral value) +foreign export ccall "hm_value_get_boolean" getBoolean :: StablePtr Value -> Ptr CInt -> IO CInt +getBoolean :: StablePtr Value -> Ptr CInt -> IO CInt +getBoolean pointer out = boundary $ do + value <- deRefStablePtr pointer + case value of + Boolean result -> checked (Right ()) $ \_ -> poke out (if result then 1 else 0) + _ -> invalid "expected Boolean value" +boundedInteger :: forall a. (Coefficient a, Integral a, Bounded a) => ScalarType a -> Integer -> IO Value +boundedInteger witness value + | value < toInteger (minBound :: a) || value > toInteger (maxBound :: a) = + throwIO (CallbackFailure 3 "coefficient exceeds its bounded integral representation") + | otherwise = pure (Scalar witness (fromInteger value)) + +foreign export ccall "hm_value_exact" exact :: CInt -> CString -> CString -> Ptr (StablePtr Value) -> IO CInt +exact :: CInt -> CString -> CString -> Ptr (StablePtr Value) -> IO CInt +exact dtype numeratorPointer denominatorPointer out = boundary $ do + n <- readInteger numeratorPointer + if dtype==3 then do + d <- readInteger denominatorPointer + if d==0 then invalid "zero Rational denominator" else checked (Right ()) $ \_ -> publish (Scalar SRational (n % d)) out + else case dtype of + 2 -> checked (Right ()) $ \_ -> publish (Scalar SInteger n) out + 6 -> boundedInteger SInt8 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 7 -> boundedInteger SInt16 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 8 -> boundedInteger SInt32 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 9 -> boundedInteger SInt64 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 10 -> boundedInteger SWord8 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 11 -> boundedInteger SWord16 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 12 -> boundedInteger SWord32 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 13 -> boundedInteger SWord64 n >>= \value -> checked (Right ()) $ \_ -> publish value out + 14 -> boundedInteger SInt n >>= \value -> checked (Right ()) $ \_ -> publish value out + 15 -> boundedInteger SWord n >>= \value -> checked (Right ()) $ \_ -> publish value out + _ -> invalid "exact scalar type not implemented" +foreign export ccall "hm_value_get_exact" getExact :: StablePtr Value -> Ptr CString -> Ptr CString -> IO CInt +getExact :: StablePtr Value -> Ptr CString -> Ptr CString -> IO CInt +getExact pointer numeratorOut denominatorOut = boundary $ do + value <- deRefStablePtr pointer + case value of + Scalar SInteger n -> checked (Right ()) $ \_ -> writeStrings [show n,"1"] $ \xs -> poke numeratorOut (xs!!0) >> poke denominatorOut (xs!!1) + Scalar SRational n -> checked (Right ()) $ \_ -> writeStrings [show (numerator n),show (denominator n)] $ \xs -> poke numeratorOut (xs!!0) >> poke denominatorOut (xs!!1) + Scalar (_ :: ScalarType a) n -> case integralDict (Proxy :: Proxy a) of + Just Dict -> checked (Right ()) $ \_ -> writeStrings [show (toInteger n),"1"] $ \xs -> poke numeratorOut (xs!!0) >> poke denominatorOut (xs!!1) + Nothing -> invalid "expected integral/Rational scalar" + _ -> invalid "expected integral/Rational scalar" + +foreign export ccall "hm_value_real_f32" real32 :: CFloat -> CFloat -> CInt -> Ptr (StablePtr Value) -> IO CInt +real32 :: CFloat -> CFloat -> CInt -> Ptr (StablePtr Value) -> IO CInt +real32 real imaginary complex out = boundary $ checked (Right ()) $ \_ -> + if complex==0 then publish (Scalar SFloat (coerce real :: Float)) out + else publish (Scalar SComplexFloat ((coerce real :: Float) :+ coerce imaginary)) out +foreign export ccall "hm_value_get_real_f32" getReal32 :: StablePtr Value -> Ptr CFloat -> Ptr CFloat -> IO CInt +getReal32 :: StablePtr Value -> Ptr CFloat -> Ptr CFloat -> IO CInt +getReal32 pointer realOut imaginaryOut = boundary $ do + value <- deRefStablePtr pointer + case value of + Scalar SFloat real -> checked (Right ()) $ \_ -> poke realOut (coerce real) >> poke imaginaryOut 0 + Scalar SComplexFloat z -> checked (Right ()) $ \_ -> poke realOut (coerce (realPart z)) >> poke imaginaryOut (coerce (imagPart z)) + _ -> invalid "coefficient type differs from typed accessor" + +foreign export ccall "hm_value_real_f64" real64 :: CDouble -> CDouble -> CInt -> Ptr (StablePtr Value) -> IO CInt +real64 :: CDouble -> CDouble -> CInt -> Ptr (StablePtr Value) -> IO CInt +real64 real imaginary complex out = boundary $ checked (Right ()) $ \_ -> + if complex==0 then publish (Scalar SDouble (coerce real :: Double)) out + else publish (Scalar SComplexDouble ((coerce real :: Double) :+ coerce imaginary)) out +foreign export ccall "hm_value_get_real_f64" getReal64 :: StablePtr Value -> Ptr CDouble -> Ptr CDouble -> IO CInt +getReal64 :: StablePtr Value -> Ptr CDouble -> Ptr CDouble -> IO CInt +getReal64 pointer realOut imaginaryOut = boundary $ do + value <- deRefStablePtr pointer + case value of + Scalar SDouble real -> checked (Right ()) $ \_ -> poke realOut (coerce real) >> poke imaginaryOut 0 + Scalar SComplexDouble z -> checked (Right ()) $ \_ -> poke realOut (coerce (realPart z)) >> poke imaginaryOut (coerce (imagPart z)) + _ -> invalid "coefficient type differs from typed accessor" diff --git a/test/abi-symbols.txt b/test/abi-symbols.txt index 4208e10..f01ea6b 100644 --- a/test/abi-symbols.txt +++ b/test/abi-symbols.txt @@ -43,3 +43,7 @@ hmath_tensor_reshape hmath_tensor_retain hmath_tensor_sum hmath_vector_copy +hmath_initialize_optimizer +hmath_optimizer_state_retain +hmath_optimizer_state_release +hmath_optimizer_step diff --git a/test/native/autodiff_bindings.py b/test/native/autodiff_bindings.py new file mode 100644 index 0000000..b1caff5 --- /dev/null +++ b/test/native/autodiff_bindings.py @@ -0,0 +1,379 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Graph ownership, derivative identities, tensor rules and native error contracts.""" + +import gc +import math +import os +import sys +import unittest +import weakref +from concurrent.futures import ThreadPoolExecutor +from fractions import Fraction +from pathlib import Path + +if os.environ.get("HMATH_LIBRARY"): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import autodiff as ad + + +class AutodiffBindings(unittest.TestCase): + def test_reverse_and_higher_order(self): + objective = lambda xs: xs[0] ** 2 + xs[0] * xs[1] + self.assertEqual(ad.value_and_gradient(objective, [3, 4]), (21, [10, 3])) + self.assertEqual(ad.gradient(objective, [3, 4]), [10, 3]) + self.assertEqual(ad.hessian(objective, [3, 4]), [[2, 1], [1, 0]]) + self.assertEqual(ad.hvp(objective, [3, 4], [2, -1]), [3, 2]) + self.assertLess(ad.gradient_check(1e-05, objective, [3, 4]), 1e-08) + self.assertEqual( + ad.complex_gradient(lambda x: x[0] ** 2 + x[1] ** 2, 3 + 4j), 3 + 4j + ) + vector = lambda x: [x[0] * x[1], x[0] + x[1]] + self.assertEqual(ad.jacobian(vector, [2, 3]), [[3, 2], [1, 1]]) + self.assertEqual(ad.jvp(vector, [2, 3], [1, 2]), [7, 3]) + self.assertEqual(ad.vjp(vector, [2, 3], [1, 2]), [5, 4]) + self.assertEqual(ad.jacobian(lambda _: [], [2, 3]), []) + self.assertEqual(ad.jacobian(lambda _: [1, 2], []), [[], []]) + self.assertEqual(ad.hessian(lambda _: 5, []), []) + + def test_reusable_graph_and_handle_lifetime(self): + x = ad.variable(0) + expression = x * x + 1 + graph = ad.compile_graph(1, expression) + x.close() + expression.close() + try: + self.assertEqual(graph.evaluate([3]), 10) + self.assertEqual(graph.evaluate([4]), 17) + with self.assertRaises(hmath.HMathError) as error: + hmath.shutdown() + self.assertEqual(error.exception.status, 9) + with self.assertRaises(hmath.HMathError) as error: + graph.evaluate([]) + self.assertEqual(str(error.exception), "VectorLengthMismatch 1 0") + finally: + graph.close() + with self.assertRaises(ValueError): + graph.evaluate([1]) + graph.close() + + def test_forward_native_dual(self): + self.assertEqual(ad.forward(lambda x: x * x * x, 3), (27, 27)) + self.assertEqual( + ad.forward_jvp(lambda x: [x[0] * x[1]], [2, 3], [1, 2]), ([6], [7]) + ) + called = [] + with self.assertRaises(hmath.HMathError) as error: + ad.forward_jvp(lambda x: called.append(x) or x, [2, 3], [1]) + self.assertEqual(called, []) + self.assertEqual(str(error.exception), "VectorLengthMismatch 2 1") + with ad.Dual(1, 2) as dual: + self.assertEqual(ad.primal(dual), 1) + self.assertEqual(ad.tangent(dual), 2) + with ad.Dual(math.inf, math.nan) as dual: + self.assertEqual(dual.primal, math.inf) + self.assertTrue(math.isnan(dual.tangent)) + + def test_explicit_gradient_state(self): + with ( + ad.zero_gradients(2) as initial, + ad.accumulate_gradients(initial, [3, 4]) as updated, + ): + self.assertEqual(initial.accumulated_gradient, [0, 0]) + self.assertEqual(updated.accumulated_gradient, [3, 4]) + with ad.gradient_hook(lambda xs: [-x for x in xs], updated) as changed: + self.assertEqual(changed.accumulated_gradient, [-3, -4]) + with ad.reset_gradients(updated) as reset: + self.assertEqual(reset.accumulated_gradient, [0, 0]) + with self.assertRaises(hmath.HMathError) as error: + ad.gradient_hook(lambda _: [1], updated) + self.assertEqual(str(error.exception), "VectorLengthMismatch 2 1") + self.assertEqual(ad.clip_gradient(2, [3, 4]), [1.2000000000000002, 1.6]) + with ad.GradientState([math.nan]) as state: + self.assertTrue(math.isnan(state.accumulated_gradient[0])) + with ad.reset_gradients(state) as reset: + self.assertEqual(reset.accumulated_gradient, [0]) + with self.assertRaises(hmath.HMathError) as error: + ad.zero_gradients(-1) + self.assertEqual( + str(error.exception), 'InvalidArgument "negative gradient size"' + ) + + def test_tensor_rules(self): + + def objective(values): + with ad.ad_tensor([2, 2], values) as tensor: + self.assertEqual(ad.ad_shape(tensor), (2, 2)) + cells = ad.ad_values(tensor) + try: + with ( + ad.ad_tensor([2, 2], cells) as copied, + ad.ad_matmul(tensor, copied) as squared, + ): + return ad.ad_sum(squared) + finally: + for cell in cells: + cell.close() + + self.assertEqual(ad.gradient(objective, [1, 2, 3, 4]), [7, 11, 9, 13]) + + def broadcast(values): + with ( + ad.ad_tensor([1], values) as tensor, + ad.ad_broadcast([2, 3], tensor) as expanded, + ): + return ad.ad_sum(expanded) + + self.assertEqual(ad.gradient(broadcast, [2]), [6]) + + def contract(values): + with ( + ad.ad_tensor([2], values) as tensor, + ad.ad_contract([0], [0], tensor, tensor) as product, + ): + return ad.ad_sum(product) + + self.assertEqual(ad.gradient(contract, [2, 3]), [4, 6]) + self.assertEqual( + ad.gradient( + lambda xs: ad.ad_sum( + ad.ad_multiply(ad.ad_tensor([2], xs), ad.ad_tensor([2], xs)) + ), + [2, 3], + ), + [4, 6], + ) + + def test_detach_and_symbolic_derivative(self): + self.assertEqual(ad.gradient(lambda x: x[0] + ad.detach(x[0] * x[0]), [3]), [1]) + self.assertEqual(ad.gradient(lambda x: ad.stop_gradient(x[0]), [3]), [0]) + with ( + ad.variable(0) as x, + ad.differentiate(0, x**3) as derivative, + ad.compile_graph(1, derivative) as graph, + ): + self.assertEqual(graph.evaluate([2]), 12) + + def test_symbolic_optimizer_step(self): + with ad.variable(0) as x: + points = ad.differentiable_step(0.1, lambda xs: xs[0] ** 2, [x]) + try: + self.assertEqual(ad.gradient(points[0], [3]), [0.8]) + next_points = ad.differentiable_step(0.1, lambda xs: xs[0] ** 2, points) + try: + self.assertAlmostEqual(ad.gradient(next_points[0], [3])[0], 0.64) + finally: + for point in next_points: + point.close() + finally: + for point in points: + point.close() + + def test_original_validation_conditions(self): + with self.assertRaises(hmath.HMathError) as error: + ad.compile_graph(0, ad.constant(float("nan"))) + self.assertEqual(str(error.exception), "NonFiniteResult") + with self.assertRaises(hmath.HMathError) as error: + ad.compile_graph(0, ad.variable(-1)) + self.assertEqual(str(error.exception), 'InvalidArgument "graph input index"') + with self.assertRaises(hmath.HMathError) as error: + ad.gradient_check(0, lambda x: x[0], [1]) + self.assertEqual(str(error.exception), "InvalidTolerance") + with self.assertRaises(hmath.HMathError) as error: + ad.jvp(lambda x: x, [1], [1, 2]) + self.assertEqual(str(error.exception), "VectorLengthMismatch 1 2") + + def test_nested_forward(self): + with ad.Dual(3, 1) as seed: + value, derivative = ad.forward(lambda x: x * x * x, seed) + with value, derivative: + self.assertEqual((value.primal, value.tangent), (27, 27)) + self.assertEqual((derivative.primal, derivative.tangent), (27, 18)) + with ad.Dual(ad.Dual(3, 1), ad.Dual(1, 0)) as seed: + self.assertEqual(seed.depth, 2) + with seed * seed * seed as result, result.tangent as first: + self.assertEqual(first.tangent, 18) + with ( + ad.Dual(1, 0) as left, + ad.Dual(ad.Dual(1, 0), ad.Dual(0, 0)) as right, + self.assertRaises(TypeError), + ): + _ = left + right + + def test_forward_scalar_specializations(self): + self.assertEqual( + ad.forward(lambda x: x + 1, 16777216, dtype="float32"), (16777216, 1) + ) + self.assertEqual(ad.forward(lambda x: x + 1, 16777216), (16777217, 1)) + large = 10**5000 + self.assertEqual( + ad.forward(lambda x: x * x, large, dtype="integer"), + (large * large, 2 * large), + ) + self.assertEqual( + ad.forward(lambda x: 1 / x, Fraction(2, 3), dtype="rational"), + (Fraction(3, 2), Fraction(-9, 4)), + ) + for dtype in ["float32", "integer", "rational"]: + with ad.Dual(3, 1, dtype=dtype) as seed: + value, derivative = ad.forward(lambda x: x * x * x, seed) + with value, derivative: + self.assertEqual((value.primal, value.tangent), (27, 27)) + self.assertEqual((derivative.primal, derivative.tangent), (27, 18)) + self.assertEqual(value.dtype, dtype) + with self.assertRaises(hmath.HMathError) as error: + ad.forward(lambda x: 1 / x, 3, dtype="integer") + self.assertIn("no Fractional instance", str(error.exception)) + with self.assertRaises(hmath.HMathError) as error: + ad.forward(ad.exp, Fraction(1, 2), dtype="rational") + self.assertIn("no Floating instance", str(error.exception)) + + def test_all_coefficient_leaves_and_original_class_dictionaries(self): + from hmath import numeric_types as numeric + + for dtype in [ + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "intp", + "uintp", + ]: + with self.subTest(dtype=dtype): + self.assertEqual(ad.forward(lambda x: x * x, 3, dtype=dtype), (9, 6)) + with self.assertRaises(hmath.HMathError) as error: + ad.forward(lambda x: 1 / x, 3, dtype=dtype) + self.assertIn("no Fractional instance", str(error.exception)) + self.assertEqual(ad.forward(lambda x: x * x, 120, dtype="int8"), (64, -16)) + for dtype in ["complex64", "complex128"]: + with ad.Dual(1 + 2j, 1, dtype=dtype) as value: + result = value * value + with result: + self.assertEqual((result.primal, result.tangent), (-3 + 4j, 2 + 4j)) + with self.assertRaises(hmath.HMathError) as error: + _ = value < 0 + self.assertIn("no Ord instance", str(error.exception)) + with ( + numeric.number(1.0000001, "float32") as primal_value, + numeric.number(1, "float32") as tangent_value, + numeric.dual(primal_value, tangent_value, boxed=True) as leaf, + ad.Dual(leaf, 1) as value, + ad.Dual(value, value) as nested, + nested.element_type as prototype, + ): + self.assertEqual(value.dtype, "numeric.dual") + self.assertEqual(nested.depth, 2) + self.assertEqual(prototype.info[:2], (1, 20)) + with self.assertRaises(hmath.HMathError) as error: + _ = value < 0 + self.assertIn("no Ord instance", str(error.exception)) + output, derivative = ad.forward(lambda x: x * x * x, nested) + with output, derivative, output.primal as first, first.primal as scalar: + self.assertEqual(scalar.info[:2], (1, 20)) + with scalar.primal as real: + self.assertEqual(real.value, 1.0000003576278687) + with ( + numeric.number(1, "float32") as one, + numeric.quaternion(one, one, one, one, boxed=True) as leaf, + ad.Dual(leaf, 1) as value, + ): + self.assertEqual(value.dtype, "numeric.quaternion") + with self.assertRaises(hmath.HMathError) as error: + ad.exp(value) + self.assertIn("no Floating instance", str(error.exception)) + with self.assertRaises((OverflowError, hmath.HMathError)): + ad.Dual(128, 1, dtype="int8") + + def test_forward_comparisons(self): + self.assertEqual(ad.forward(lambda x: -x if x < 0 else x * x, -2), (2, -1)) + with ad.Dual(1, 1) as left, ad.Dual(1, 2) as right: + self.assertFalse(left == right) + self.assertTrue(left <= right) + self.assertTrue(left >= right) + self.assertFalse(left < right) + self.assertEqual(ad.forward(lambda x: x + 1 if x == 0 else x * x, 0), (0, 0)) + + def test_custom_rules_and_laziness(self): + cube = lambda xs: ad.custom_operation( + lambda values: (values[0] ** 3, [3 * values[0] ** 2]), xs + ) + self.assertEqual(ad.value_and_gradient(cube, [2]), (8, [12])) + with self.assertRaises(hmath.HMathError) as error: + ad.hessian(cube, [2]) + self.assertEqual( + str(error.exception), + 'InvalidArgument "custom rules support first order; provide a symbolic operation for higher orders"', + ) + with ( + ad.variable(0) as x, + ad.custom_operation(lambda values: (values[0], []), [x]) as expression, + ): + with ad.compile_graph(1, expression) as graph: + self.assertEqual(graph.evaluate([2]), 2) + with self.assertRaises(hmath.HMathError) as error: + ad.gradient(expression, [2]) + self.assertEqual(str(error.exception), "VectorLengthMismatch 1 0") + derivative_calls = [] + + def derivative(value): + derivative_calls.append(value) + raise ValueError("custom derivative failed") + + with ( + ad.variable(0) as x, + ad.custom_unary(lambda value: value * value, derivative, x) as expression, + ): + with ad.compile_graph(1, expression) as graph: + self.assertEqual(graph.evaluate([3]), 9) + self.assertEqual(derivative_calls, []) + with self.assertRaisesRegex(ValueError, "custom derivative failed"): + ad.gradient(expression, [3]) + self.assertEqual(derivative_calls, [3]) + + def test_checkpoint_callback_lifetime(self): + x = ad.variable(0) + expression = ad.checkpoint( + lambda inputs: ad.custom_unary( + lambda value: value * value, lambda value: 2 * value, inputs[0] + ), + [x], + ) + owner = weakref.ref(expression._keepers[-1]) + graph = ad.compile_graph(1, expression) + expression.close() + x.close() + gc.collect() + self.assertIsNotNone(owner()) + self.assertEqual(graph.evaluate([3]), 9) + self.assertEqual(graph.evaluate([4]), 16) + graph.close() + gc.collect() + self.assertIsNone(owner()) + self.assertEqual( + ad.gradient(lambda xs: ad.checkpoint(lambda ys: ys[0] * ys[0], xs), [3]), + [6], + ) + + def invalid_builder(_): + raise ValueError("checkpoint builder failed") + + with self.assertRaisesRegex(ValueError, "checkpoint builder failed"): + ad.gradient(lambda xs: ad.checkpoint(invalid_builder, xs), [2]) + + def test_shared_graph_threads(self): + with ( + ad.compile_graph(2, ad.variable(0) * ad.variable(1)) as graph, + ThreadPoolExecutor(max_workers=4) as executor, + ): + self.assertEqual( + list(executor.map(lambda n: graph.evaluate([n, n + 1]), range(16))), + [n * (n + 1) for n in range(16)], + ) + + +if __name__ == "__main__": + unittest.main(argv=[__file__]) diff --git a/test/native/autodiff_checked_contracts.c b/test/native/autodiff_checked_contracts.c new file mode 100644 index 0000000..66fed39 --- /dev/null +++ b/test/native/autodiff_checked_contracts.c @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_autodiff.h" +#include "hmath_error.h" +#include +#include +static const char payload[] = "full\0payload\xED\xA0\x80"; +static hmath_status checked_rule(const double *values, size_t count, void *userdata, + double *value, double *partials, size_t capacity, + size_t *written, hmath_callback_error *error) { + (void)values; + (void)count; + (void)userdata; + (void)value; + (void)partials; + (void)capacity; + (void)written; + memset(error, 0, sizeof(*error)); + error->kind = HMATH_MATH_NON_CONVERGENCE; + error->details[0] = 123; + error->message = payload; + error->message_length = sizeof(payload) - 1; + return HMATH_MATH_ERROR; +} +int main(void) { + assert(hmath_init() == HMATH_INIT_OK); + hmath_ad_expr *input = NULL, *output = NULL; + assert(hmath_ad_variable(NULL, 0, &input) == HMATH_OK); + const hmath_ad_expr *arguments[] = {input}; + assert(hmath_ad_custom_operation_checked(NULL, checked_rule, NULL, arguments, 1, &output) == HMATH_OK); + hmath_ad_release(input); + double point = 2, result[] = {37, 53}; + assert(hmath_ad_value_and_gradient(NULL, output, &point, 1, result, 2) == HMATH_MATH_ERROR); + assert(result[0] == 37 && result[1] == 53); + hmath_math_error error; + assert(hmath_last_math_error(&error) == 1); + assert(error.kind == HMATH_MATH_NON_CONVERGENCE && error.details[0] == 123); + assert(error.message_length == sizeof(payload) - 1); + assert(memcmp(error.message, payload, sizeof(payload) - 1) == 0); + hmath_callback_error forwarded; + assert(hmath_callback_capture_error(HMATH_MATH_ERROR, &forwarded) == 1); + assert(forwarded.kind == error.kind && forwarded.message_length == error.message_length); + hmath_ad_release(output); + /* A bounded original Num instance keeps its wraparound through AD. */ + hmath_value *base = NULL, *unit = NULL, *coefficient = NULL; + hmath_ad_dual *base_handle = NULL, *unit_handle = NULL, *dual = NULL; + hmath_ad_handle *squared = NULL; + assert(hmath_value_integral(NULL, HMATH_COEFFICIENT_INT8, "120", &base) == HMATH_OK); + assert(hmath_value_integral(NULL, HMATH_COEFFICIENT_INT8, "1", &unit) == HMATH_OK); + assert(hmath_ad_value_export(NULL, base, &base_handle) == HMATH_OK); + assert(hmath_ad_value_export(NULL, unit, &unit_handle) == HMATH_OK); + assert(hmath_ad_dual_nested(NULL, base_handle, unit_handle, &dual) == HMATH_OK); + assert(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, dual, dual, &squared) == HMATH_OK); + hmath_ad_dual *primal = NULL, *tangent = NULL; + assert(hmath_ad_dual_parts(squared, &primal, &tangent) == HMATH_OK); + assert(hmath_ad_value_import(NULL, primal, &coefficient) == HMATH_OK); + char *numerator = NULL, *denominator = NULL; + assert(hmath_value_get_exact(coefficient, &numerator, &denominator) == HMATH_OK); + assert(strcmp(numerator, "64") == 0 && strcmp(denominator, "1") == 0); + hmath_value_string_free(numerator); + hmath_value_string_free(denominator); + hmath_value_release(base); + hmath_value_release(unit); + hmath_value_release(coefficient); + hmath_ad_release(base_handle); + hmath_ad_release(unit_handle); + hmath_ad_release(dual); + hmath_ad_release(squared); + hmath_ad_release(primal); + hmath_ad_release(tangent); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/autodiff_checked_contracts.cpp b/test/native/autodiff_checked_contracts.cpp new file mode 100644 index 0000000..83f2dbf --- /dev/null +++ b/test/native/autodiff_checked_contracts.cpp @@ -0,0 +1,3 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Exercise the identical public C contract from C++17. */ +#include "autodiff_checked_contracts.c" diff --git a/test/native/autodiff_contracts.c b/test/native/autodiff_contracts.c new file mode 100644 index 0000000..ed89848 --- /dev/null +++ b/test/native/autodiff_contracts.c @@ -0,0 +1,167 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_autodiff.h" +#include +#include +#include +#include +#define CHECK(c) \ + do { \ + if (!(c)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #c, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static hmath_status cube_rule(const double *values, size_t count, void *userdata, double *value, + double *partials, size_t capacity, size_t *partial_count, + const char **error_message) { + (void)userdata; + (void)error_message; + CHECK(count == 1 && capacity == 1); + *value = values[0] * values[0] * values[0]; + partials[0] = 3 * values[0] * values[0]; + *partial_count = 1; + return HMATH_OK; +} +static hmath_status square_builder(const hmath_ad_expr *const *values, size_t count, void *userdata, + hmath_ad_expr **out, const char **error_message) { + (void)userdata; + (void)error_message; + CHECK(count == 1); + return hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, values[0], values[0], out); +} +static hmath_status domain_rule(const double *values, size_t count, void *userdata, double *value, + double *partials, size_t capacity, size_t *partial_count, + const char **error_message) { + (void)values; + (void)count; + (void)userdata; + (void)value; + (void)partials; + (void)capacity; + (void)partial_count; + *error_message = "DomainError \"custom domain\""; + return HMATH_MATH_ERROR; +} +int main(void) { + CHECK(hmath_init() == HMATH_INIT_OK); + hmath_ad_expr *x = NULL, *squared = NULL, *invalid = NULL; + hmath_ad_graph *graph = NULL; + CHECK(hmath_ad_variable(NULL, 0, &x) == HMATH_OK); + CHECK(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, x, x, &squared) == HMATH_OK); + CHECK(hmath_ad_compile_graph(NULL, 1, squared, &graph) == HMATH_OK); + double input = 3, output = 99, gradient[] = {99, 99}; + CHECK(hmath_ad_evaluate_graph(NULL, graph, &input, 1, &output, 0) == HMATH_BOUNDS_ERROR); + CHECK(output == 99); + CHECK(hmath_ad_value_and_gradient(NULL, squared, &input, 1, gradient, 1) == HMATH_BOUNDS_ERROR); + CHECK(gradient[0] == 99 && gradient[1] == 99); + CHECK(hmath_ad_value_and_gradient(NULL, squared, &input, 1, gradient, 2) == HMATH_OK); + CHECK(gradient[0] == 9 && gradient[1] == 6); + CHECK(hmath_ad_variable(NULL, -1, &invalid) == HMATH_OK); + hmath_ad_graph *failure = NULL; + CHECK(hmath_ad_compile_graph(NULL, 0, invalid, &failure) == HMATH_MATH_ERROR); + CHECK(failure == NULL && + strcmp(hmath_last_error_message(), "InvalidArgument \"graph input index\"") == 0); + hmath_ad_release(invalid); + CHECK(hmath_ad_constant(NULL, NAN, &invalid) == HMATH_OK); + CHECK(hmath_ad_compile_graph(NULL, 0, invalid, &failure) == HMATH_MATH_ERROR); + CHECK(failure == NULL && strcmp(hmath_last_error_message(), "NonFiniteResult") == 0); + hmath_ad_release(invalid); + CHECK(hmath_ad_gradient(NULL, graph, &input, 1, gradient, 2) == HMATH_INVALID_ARGUMENT); + hmath_ad_dual *dual = NULL, *dual_square = NULL; + CHECK(hmath_ad_dual_create(NULL, 3, 1, &dual) == HMATH_OK); + CHECK(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, dual, dual, &dual_square) == HMATH_OK); + CHECK(hmath_ad_values_copy(dual_square, gradient, 2) == HMATH_OK); + CHECK(gradient[0] == 9 && gradient[1] == 6); + CHECK(hmath_last_error_code() == HMATH_OK); + hmath_ad_release(dual); + hmath_ad_release(dual_square); + hmath_ad_tensor *empty = NULL; + ptrdiff_t shape[] = {0}; + size_t count, rank; + CHECK(hmath_ad_tensor_create(NULL, shape, 1, NULL, 0, &empty) == HMATH_OK); + CHECK(hmath_ad_metadata(empty, &count, &rank) == HMATH_OK && count == 0 && rank == 1); + CHECK(hmath_ad_tensor_values(empty, NULL, 0) == HMATH_OK); + hmath_ad_release(empty); + hmath_ad_dual *seed_a = NULL, *seed_b = NULL, *nested = NULL, *nested_square = NULL, + *nested_cube = NULL, *primal_part = NULL, *tangent_part = NULL; + CHECK(hmath_ad_dual_create(NULL, 3, 1, &seed_a) == HMATH_OK); + CHECK(hmath_ad_dual_create(NULL, 1, 0, &seed_b) == HMATH_OK); + CHECK(hmath_ad_dual_nested(NULL, seed_a, seed_b, &nested) == HMATH_OK); + size_t depth; + CHECK(hmath_ad_dual_depth(nested, &depth) == HMATH_OK && depth == 2); + CHECK(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, nested, nested, &nested_square) == HMATH_OK); + CHECK(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, nested_square, nested, &nested_cube) == + HMATH_OK); + CHECK(hmath_ad_dual_parts(nested_cube, &primal_part, &tangent_part) == HMATH_OK); + CHECK(hmath_ad_values_copy(tangent_part, gradient, 2) == HMATH_OK && gradient[0] == 27 && + gradient[1] == 18); + hmath_ad_release(seed_a); + hmath_ad_release(seed_b); + hmath_ad_release(nested); + hmath_ad_release(nested_square); + hmath_ad_release(nested_cube); + hmath_ad_release(primal_part); + hmath_ad_release(tangent_part); + hmath_ad_dual *small = NULL, *one = NULL, *sum = NULL, *large = NULL, *square = NULL, + *ep = NULL, *et = NULL, *ratio = NULL, *reciprocal = NULL; + CHECK(hmath_ad_dual_create_f32(NULL, 16777216, 1, &small) == HMATH_OK); + CHECK(hmath_ad_dual_create_f32(NULL, 1, 0, &one) == HMATH_OK); + CHECK(hmath_ad_binary(NULL, HMATH_AD_ADD, small, one, &sum) == HMATH_OK); + CHECK(hmath_ad_values_copy(sum, gradient, 2) == HMATH_OK && gradient[0] == 16777216 && + gradient[1] == 1); + hmath_ad_release(small); + hmath_ad_release(one); + hmath_ad_release(sum); + CHECK(hmath_ad_dual_create_integer(NULL, "9007199254740993", "1", &large) == HMATH_OK); + CHECK(hmath_ad_binary(NULL, HMATH_AD_MULTIPLY, large, large, &square) == HMATH_OK); + CHECK(hmath_ad_dual_parts(square, &ep, &et) == HMATH_OK); + char *numerator = NULL, *denominator = NULL; + CHECK(hmath_ad_scalar_text(ep, &numerator, &denominator) == HMATH_OK); + CHECK(strcmp(numerator, "81129638414606699710187514626049") == 0 && + strcmp(denominator, "1") == 0); + hmath_ad_string_free(numerator); + hmath_ad_string_free(denominator); + hmath_ad_release(ep); + hmath_ad_release(et); + hmath_ad_release(large); + hmath_ad_release(square); + CHECK(hmath_ad_dual_create_rational(NULL, "2", "3", "1", "1", &ratio) == HMATH_OK); + CHECK(hmath_ad_unary(NULL, HMATH_AD_RECIPROCAL, ratio, &reciprocal) == HMATH_OK); + CHECK(hmath_ad_dual_parts(reciprocal, &ep, &et) == HMATH_OK); + CHECK(hmath_ad_scalar_text(et, &numerator, &denominator) == HMATH_OK); + CHECK(strcmp(numerator, "-9") == 0 && strcmp(denominator, "4") == 0); + hmath_ad_string_free(numerator); + hmath_ad_string_free(denominator); + hmath_ad_release(ep); + hmath_ad_release(et); + hmath_ad_release(ratio); + hmath_ad_release(reciprocal); + const hmath_ad_expr *custom_inputs[] = {x}; + hmath_ad_expr *custom = NULL, *checkpoint = NULL; + CHECK(hmath_ad_custom_operation(NULL, cube_rule, NULL, custom_inputs, 1, &custom) == HMATH_OK); + CHECK(hmath_ad_value_and_gradient(NULL, custom, &input, 1, gradient, 2) == HMATH_OK); + CHECK(gradient[0] == 27 && gradient[1] == 27); + hmath_ad_release(custom); + CHECK(hmath_ad_checkpoint(NULL, square_builder, NULL, custom_inputs, 1, &checkpoint) == + HMATH_OK); + CHECK(hmath_ad_value_and_gradient(NULL, checkpoint, &input, 1, gradient, 2) == HMATH_OK); + CHECK(gradient[0] == 9 && gradient[1] == 6); + hmath_ad_release(checkpoint); + CHECK(hmath_ad_custom_operation(NULL, domain_rule, NULL, custom_inputs, 1, &custom) == + HMATH_OK); + gradient[0] = 99; + gradient[1] = 99; + CHECK(hmath_ad_value_and_gradient(NULL, custom, &input, 1, gradient, 2) == HMATH_MATH_ERROR); + CHECK(strcmp(hmath_last_error_message(), "DomainError \"custom domain\"") == 0); + CHECK(gradient[0] == 99 && gradient[1] == 99); + hmath_ad_release(custom); + hmath_ad_release(x); + hmath_ad_release(squared); + CHECK(hmath_ad_evaluate_graph(NULL, graph, &input, 1, &output, 1) == HMATH_OK && output == 9); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_ad_release(graph); + hmath_ad_release(NULL); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/buffer_contracts.c b/test/native/buffer_contracts.c new file mode 100644 index 0000000..939f807 --- /dev/null +++ b/test/native/buffer_contracts.c @@ -0,0 +1,98 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_buffer.h" +#include "hmath_error.h" +#include +#include +#include +#include +typedef struct state {hmath_value *retained;hmath_value *io;int calls;} state; +static hmath_status region(const hmath_value *arguments,void *userdata,hmath_value **out,hmath_math_error *error) { + (void)error;state *s=(state *)userdata; + hmath_value *index=NULL,*value=NULL,*unit=NULL; + hmath_status status=hmath_value_item(NULL,arguments,0,&s->retained); + if(!status)status=hmath_value_index(NULL,1,&index); + if(!status)status=hmath_value_integer(NULL,"1234567890123456789012345678901234567890",&value); + if(!status)status=hmath_buffer_write_st_buffer(NULL,s->retained,index,value,&unit); + if(!status)status=hmath_buffer_freeze_st_buffer(NULL,s->retained,out); + hmath_value_release(index);hmath_value_release(value);hmath_value_release(unit); + ++s->calls;return status; +} +static hmath_status pointer(const hmath_value *arguments,void *userdata,hmath_value **out,hmath_math_error *error) { + (void)error;state *s=(state *)userdata; + hmath_value *index=NULL,*value=NULL,*unit=NULL,*unchanged=(hmath_value *)(uintptr_t)1; + hmath_status status=hmath_value_item(NULL,arguments,0,&s->retained); + if(!status)status=hmath_value_index(NULL,0,&index); + if(!status)status=hmath_value_f32(NULL,3.5f,&value); + if(!status) { + assert(hmath_buffer_read_io_buffer(NULL,s->io,index,&unchanged)==HMATH_BUSY); + assert(unchanged==(hmath_value *)(uintptr_t)1); + status=hmath_buffer_pointer_write(NULL,s->retained,index,value,&unit); + } + if(!status)status=hmath_buffer_pointer_read(NULL,s->retained,index,out); + hmath_value_release(index);hmath_value_release(value);hmath_value_release(unit); + ++s->calls;return status; +} +static hmath_status failure(const hmath_value *arguments,void *userdata,hmath_value **out,hmath_math_error *error) { + (void)arguments;(void)userdata;(void)out; + memset(error,0,sizeof *error);error->kind=HMATH_MATH_DOMAIN_ERROR; + error->message="borrow callback failed";error->message_length=strlen(error->message); + return HMATH_MATH_ERROR; +} +int main(void) { + assert(hmath_init()==HMATH_OK); + hmath_value *one=NULL,*two=NULL,*xs=NULL,*boxed=NULL,*callback=NULL,*result=NULL,*child=NULL,*index=NULL; + assert(hmath_value_integer(NULL,"1",&one)==HMATH_OK); + assert(hmath_value_integer(NULL,"2",&two)==HMATH_OK); + const hmath_value *items[]={one,two}; + assert(hmath_value_list(NULL,items,2,&xs)==HMATH_OK); + assert(hmath_buffer_lazy_boxed(NULL,xs,&boxed)==HMATH_OK); + state s={NULL,NULL,0}; + assert(hmath_linear_callback(NULL,region,&s,&callback)==HMATH_OK); + assert(hmath_buffer_run_st_buffer(NULL,boxed,callback,&result)==HMATH_OK && s.calls==1); + hmath_value_release(callback); + assert(hmath_buffer_boxed_values(NULL,result,&child)==HMATH_OK); + hmath_value_release(result);assert(hmath_value_index(NULL,1,&index)==HMATH_OK); + assert(hmath_value_item(NULL,child,1,&result)==HMATH_OK);hmath_value_release(child); + char *numerator=NULL,*denominator=NULL; + assert(hmath_value_get_exact(result,&numerator,&denominator)==HMATH_OK); + assert(strcmp(numerator,"1234567890123456789012345678901234567890")==0); + hmath_value_string_free(numerator);hmath_value_string_free(denominator);hmath_value_release(result); + hmath_value *unchanged=(hmath_value *)(uintptr_t)1; + assert(hmath_buffer_read_st_buffer(NULL,s.retained,index,&unchanged)==HMATH_INVALID_ARGUMENT); + assert(unchanged==(hmath_value *)(uintptr_t)1); + assert(hmath_buffer_st_active(NULL,s.retained,&result)==HMATH_OK); + int alive=1;assert(hmath_value_get_boolean(result,&alive)==HMATH_OK && !alive); + hmath_value_release(result);hmath_value_release(s.retained);s.retained=NULL; + hmath_value *initial=NULL,*count=NULL; + assert(hmath_value_f32(NULL,-0.0f,&initial)==HMATH_OK); + assert(hmath_value_index(NULL,2,&count)==HMATH_OK); + assert(hmath_buffer_new_io_buffer(NULL,count,initial,&s.io)==HMATH_OK); + assert(hmath_linear_callback(NULL,pointer,&s,&callback)==HMATH_OK); + assert(hmath_buffer_with_io_buffer(NULL,s.io,callback,&result)==HMATH_OK && s.calls==2); + float real=0,imaginary=0;assert(hmath_value_get_f32(result,&real,&imaginary)==HMATH_OK && real==3.5f); + hmath_value_release(result);hmath_value_release(callback); + assert(hmath_buffer_pointer_read(NULL,s.retained,index,&unchanged)==HMATH_INVALID_ARGUMENT); + assert(hmath_buffer_pointer_address(NULL,s.retained,&unchanged)==HMATH_INVALID_ARGUMENT); + assert(unchanged==(hmath_value *)(uintptr_t)1);hmath_value_release(s.retained); + assert(hmath_linear_callback(NULL,failure,NULL,&callback)==HMATH_OK); + assert(hmath_buffer_with_io_buffer(NULL,s.io,callback,&unchanged)==HMATH_MATH_ERROR); + assert(unchanged==(hmath_value *)(uintptr_t)1); + hmath_math_error error;assert(hmath_last_math_error(&error) && error.kind==HMATH_MATH_DOMAIN_ERROR); + assert(error.message_length==22 && memcmp(error.message,"borrow callback failed",22)==0); + hmath_value_release(callback); + assert(hmath_buffer_read_io_buffer(NULL,s.io,index,&result)==HMATH_OK); + hmath_value_release(result); + assert(hmath_buffer_freeze_io_buffer(NULL,s.io,&result)==HMATH_OK); + hmath_value *none=NULL,*copy=NULL; + assert(hmath_value_none(NULL,&none)==HMATH_OK); + assert(hmath_buffer_thaw_io_buffer(NULL,none,result,©)==HMATH_OK); + hmath_value_release(result);hmath_value_release(s.io);hmath_value_release(none); + assert(hmath_buffer_read_io_buffer(NULL,copy,index,&result)==HMATH_OK); + hmath_value_release(copy);hmath_value_release(result); + assert(hmath_runtime_shutdown()==HMATH_BUSY); + hmath_value_release(initial);hmath_value_release(count);hmath_value_release(index); + hmath_value_release(one);hmath_value_release(two);hmath_value_release(xs);hmath_value_release(boxed); + assert(hmath_runtime_shutdown()==HMATH_OK); + puts("Buffer C exact/scoped ST, original pointer borrows, callback errors, reentry and owned copying contracts passed."); + return 0; +} diff --git a/test/native/buffer_contracts.cpp b/test/native/buffer_contracts.cpp new file mode 100644 index 0000000..edd3786 --- /dev/null +++ b/test/native/buffer_contracts.cpp @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: MPL-2.0 +// Compile the same public contract as an actual C++17 consumer. +#include "buffer_contracts.c" diff --git a/test/native/callback_errors.py b/test/native/callback_errors.py new file mode 100644 index 0000000..a272f3c --- /dev/null +++ b/test/native/callback_errors.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Structured callback failures remain lossless across AD and tensor boundaries.""" + +import gc +import os +import sys +import unittest +from pathlib import Path + +if os.environ.get("HMATH_LIBRARY"): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import _tensor_core as tensor +from _hmath_native import autodiff as ad +from _hmath_native._expression_error import ErrorKind, ExprError, SourcePos +from _hmath_native._interchange_error import InterchangeError, InterchangeErrorKind +from _hmath_native._math_error import _ARITY, MathError, MathErrorKind + + +def fail(error): + raise error + + +class CallbackErrors(unittest.TestCase): + def test_all_original_math_error_constructors(self): + for kind in MathErrorKind: + details = tuple(range(-_ARITY[kind], 0)) + message = "full\0payload\ud800한글" + "x" * 6000 + original = MathError(kind, details, message if kind in (17, 18, 19) else "") + with ( + self.subTest(kind=kind), + ad.variable(0) as x, + ad.custom_operation( + lambda _, original=original: fail(original), [x] + ) as expr, + ): + with self.assertRaises(hmath.HMathError) as caught: + ad.value_and_gradient(expr, [2]) + actual = caught.exception.math_error + self.assertEqual(caught.exception.status, 11) + self.assertEqual( + (actual.kind, actual.details, actual.message), + (original.kind, original.details, original.message), + ) + + def test_domain_errors_cross_rule_unary_checkpoint_and_tensor(self): + payload = "domain\0한글\udfff" + "z" * 4096 + originals = [ + ExprError(ErrorKind.SYNTAX_ERROR, SourcePos(-7, 22, 103), payload), + InterchangeError(InterchangeErrorKind.IO_ERROR, payload), + ] + for original in originals: + for route in ("rule", "unary", "checkpoint", "tensor"): + with self.subTest(error=type(original).__name__, route=route): + with self.assertRaises(hmath.HMathError) as caught: + if route == "tensor": + with tensor.tensor([1], [2]) as base: + tensor.map_tensor( + lambda _, original=original: fail(original), base + ) + else: + with ad.variable(0) as x: + if route == "rule": + expr = ad.custom_operation( + lambda _, original=original: fail(original), [x] + ) + elif route == "unary": + expr = ad.custom_unary( + lambda _, original=original: fail(original), + lambda _: 0, + x, + ) + else: + expr = ad.checkpoint( + lambda _, original=original: fail(original), [x] + ) + with expr: + ad.value_and_gradient(expr, [2]) + if isinstance(original, ExprError): + self.assertEqual(caught.exception.status, 12) + self.assertEqual(caught.exception.expression_error, original) + else: + self.assertEqual(caught.exception.status, 13) + self.assertEqual(caught.exception.interchange_error, original) + + def test_malformed_math_error_details_never_narrow(self): + original = MathError(MathErrorKind.SINGULAR_MATRIX, [1]) + original.details = (1 << 200,) + with ( + ad.variable(0) as x, + ad.custom_operation( + lambda _, original=original: fail(original), [x] + ) as expr, + self.assertRaises(OverflowError), + ): + ad.gradient(expr, [2]) + with self.assertRaises(OverflowError): + MathError(MathErrorKind.NON_CONVERGENCE, [1 << 200], "budget") + + def test_unexpected_base_exception_and_checkpoint_cleanup(self): + original = KeyboardInterrupt("original identity") + for route in ("rule", "checkpoint"): + with self.subTest(route=route): + with ad.variable(0) as x: + expr = ( + ad.custom_operation( + lambda _, original=original: fail(original), [x] + ) + if route == "rule" + else ad.checkpoint( + lambda _, original=original: fail(original), [x] + ) + ) + with expr: + with self.assertRaises(KeyboardInterrupt) as caught: + ad.gradient(expr, [2]) + self.assertIs(caught.exception, original) + original.__traceback__ = None + gc.collect() + + +if __name__ == "__main__": + unittest.main(argv=[__file__]) diff --git a/test/native/deeplearning_bindings.py b/test/native/deeplearning_bindings.py new file mode 100644 index 0000000..520688b --- /dev/null +++ b/test/native/deeplearning_bindings.py @@ -0,0 +1,191 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Neural cross-domain ownership, immutable states and public interface contracts.""" + +import gc +import math +import os +import sys +import unittest +from pathlib import Path + +if os.environ.get("HMATH_LIBRARY"): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from hmath import autodiff as ad +from hmath import deeplearning_core as core +from hmath import deeplearning_layers as layers +from hmath import deeplearning_metrics as metrics +from hmath import deeplearning_precision as precision +from hmath import random, tensor + + +def close(value): + if isinstance(value, (list, tuple)): + for item in value: + close(item) + elif hasattr(value, "close"): + value.close() + + +class NeuralBindings(unittest.TestCase): + def test_fixed_double_and_public_namespaces(self): + self.assertEqual(core.activation(core.Sigmoid, 0), 0.5) + with ( + tensor.tensor([1, 2], [1, 2]) as x, + tensor.tensor([1, 2], [3, 4]) as w, + layers.dense(x, w, [1]) as output, + ): + self.assertIsInstance(output, tensor.TensorDouble) + self.assertEqual(output.values, [12]) + with ( + tensor.tensor([1, 2], [1, 2], dtype="float32") as x, + tensor.tensor([1, 2], [3, 4]) as w, + self.assertRaises(hmath.HMathError), + ): + layers.dense(x, w, [1]) + + def test_explicit_full_rng_continuation(self): + with ( + random.pcg32() as generator, + random.seed_rng(generator, 42) as rng, + tensor.tensor([1, 2, 3], list(range(6))) as x, + ): + original = rng.serialize() + first = layers.spatial_dropout(layers.Training.TRAINING, 0.5, rng, x) + second = layers.spatial_dropout(layers.Training.TRAINING, 0.5, rng, x) + try: + self.assertEqual(first[0].values, second[0].values) + self.assertEqual(first[1].values, second[1].values) + self.assertEqual(first[2].serialize(), second[2].serialize()) + self.assertNotEqual(first[2].serialize(), original) + self.assertEqual(rng.serialize(), original) + self.assertTrue( + all( + len(set(first[1].values[start : start + 3])) == 1 + for start in (0, 3) + ) + ) + finally: + close(first) + close(second) + inference = layers.dropout(layers.Inference, 0.9, rng, x) + try: + self.assertEqual(inference[0].values, x.values) + self.assertEqual(inference[2].serialize(), original) + finally: + close(inference) + + def test_batch_norm_records_original_state_unchanged(self): + state = layers.BatchNormState([0], [1], 0) + with tensor.tensor([2, 1], [1, 3]) as x: + output, updated = layers.batch_norm( + layers.Training.TRAINING, 0.1, 1e-5, [1], [0], state, x + ) + try: + self.assertEqual(updated.batches_seen, 1) + self.assertEqual(updated.running_mean, [0.2]) + self.assertEqual(updated.running_variance, [1.1]) + self.assertEqual(state, layers.BatchNormState([0], [1], 0)) + self.assertEqual(layers.running_mean(updated), updated.running_mean) + self.assertEqual( + layers.running_variance(updated), updated.running_variance + ) + self.assertEqual(layers.batches_seen(updated), 1) + finally: + output.close() + + def test_cache_independent_original_objects_and_capacity(self): + cache = layers.empty_cache(2, 1, 1) + with ( + tensor.tensor([2, 1], [1, 2]) as keys, + tensor.tensor([2, 1], [3, 4]) as values, + ): + updated = layers.append_cache(cache, keys, values) + empty = layers.cache_values(cache) + try: + self.assertEqual(empty[0].shape, [0, 1]) + self.assertEqual(empty[1].values, []) + finally: + close(empty) + with self.assertRaises(hmath.HMathError): + layers.append_cache(updated, keys, values) + cache.close() + extracted = layers.cache_values(updated) + updated.close() + try: + self.assertEqual(extracted[0].values, [1, 2]) + self.assertEqual(extracted[1].values, [3, 4]) + finally: + close(extracted) + + def test_quantized_fields_and_loss_scaler_transitions(self): + with ( + tensor.tensor([2, 2], [-2, -1, 1, 2]) as x, + precision.quantize(precision.Symmetric, 0, x) as quantized, + ): + self.assertEqual(quantized.values, precision.quantized_values(quantized)) + self.assertEqual(quantized.scales, precision.quantization_scales(quantized)) + self.assertEqual( + quantized.zero_points, precision.quantization_zero_points(quantized) + ) + self.assertEqual(quantized.zero_points, [0, 0]) + with precision.dequantize(quantized) as restored: + self.assertEqual(restored.shape, [2, 2]) + initial = precision.initial_loss_scaler(128, 2) + one = precision.update_loss_scaler(True, initial) + two = precision.update_loss_scaler(True, one) + failed = precision.update_loss_scaler(False, two) + self.assertEqual(initial, precision.LossScaler(128, 2, 0)) + self.assertEqual(one, precision.LossScaler(128, 2, 1)) + self.assertEqual(two, precision.LossScaler(256, 2, 0)) + self.assertEqual(failed, precision.LossScaler(128, 2, 0)) + self.assertEqual(precision.unscale_gradients(initial, [math.inf]), (False, [])) + + def test_original_graph_and_callback_owner_interchange(self): + def objective(xs): + with ad.custom_unary( + lambda value: value * value, lambda value: 2 * value, xs[0] + ) as square: + return core.activation_expr(core.Sigmoid, square) + + value, gradient = ad.value_and_gradient(objective, [2]) + expected = core.activation(core.Sigmoid, 4) + self.assertEqual(value, expected) + self.assertEqual(gradient, [4 * expected * (1 - expected)]) + with ad.variable(0) as x, core.activation_expr(core.ReLU, x) as activated: + self.assertEqual(ad.value_and_gradient(activated, [0]), (0, [0])) + + def test_attention_fully_masked_and_classification_diagnostics(self): + with ( + tensor.tensor([1, 2], [1, 2]) as query, + tensor.tensor([1, 2], [3, 4]) as key, + tensor.tensor([1, 1], [9]) as value, + ): + output, weights = layers.scaled_dot_product_attention( + query, key, value, [[False]], None + ) + try: + self.assertEqual(output.values, [0]) + self.assertEqual(weights.values, [0]) + finally: + close((output, weights)) + result = metrics.classification_metrics(3, [0, 1, 1, 2], [0, 2, 1, 2]) + self.assertEqual(result.accuracy, 0.75) + self.assertEqual(result.precision, [1, 1, 0.5]) + self.assertEqual(result.recall, [1, 0.5, 1]) + self.assertEqual(result.f1, [1, 2 / 3, 2 / 3]) + self.assertEqual(metrics.accuracy(result), 0.75) + self.assertEqual(metrics.precision_by_class(result), result.precision) + + def test_original_errors_and_final_cleanup(self): + with self.assertRaises(hmath.HMathError) as error: + core.activation(core.ELU(0), 1) + self.assertEqual( + error.exception.math_error.message, "positive ELU alpha required" + ) + self.assertEqual(core.activation(core.Sigmoid, 1000), 1) + gc.collect() + + +if __name__ == "__main__": + unittest.main(argv=[__file__]) diff --git a/test/native/deeplearning_contracts.c b/test/native/deeplearning_contracts.c new file mode 100644 index 0000000..78211ed --- /dev/null +++ b/test/native/deeplearning_contracts.c @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_deeplearning.h" +#include +#include +#include + +int main(void) { + assert(hmath_init() == HMATH_INIT_OK); + hmath_value *kind = NULL, *zero = NULL, *result = NULL; + assert(hmath_neural_core_sigmoid_create(NULL, &kind) == HMATH_OK); + assert(hmath_value_f64(NULL, 0, &zero) == HMATH_OK); + assert(hmath_neural_core_activation(NULL, kind, zero, &result) == HMATH_OK); + double real, imaginary; + assert(hmath_value_get_f64(result, &real, &imaginary) == HMATH_OK && real == 0.5); + hmath_value_release(result); + hmath_ad_expr *input = NULL, *expression = NULL; + hmath_value *wrapped = NULL, *output = NULL; + assert(hmath_ad_variable(NULL, 0, &input) == HMATH_OK); + assert(hmath_ad_value_import(NULL, input, &wrapped) == HMATH_OK); + assert(hmath_neural_core_activation_expr(NULL, kind, wrapped, &output) == HMATH_OK); + assert(hmath_ad_value_export(NULL, output, &expression) == HMATH_OK); + hmath_value_release(output); + hmath_value_release(wrapped); + hmath_ad_release(input); + double point = 0, evaluated[2] = {0, 0}; + assert(hmath_ad_value_and_gradient(NULL, expression, &point, 1, evaluated, 2) == HMATH_OK); + assert(evaluated[0] == 0.5 && evaluated[1] == 0.25); + hmath_ad_release(expression); + hmath_value *elu = NULL; + assert(hmath_neural_core_elu_create(NULL, zero, &elu) == HMATH_OK); + hmath_value *sentinel = (hmath_value *)(uintptr_t)0x1234; + assert(hmath_neural_core_activation(NULL, elu, zero, &sentinel) == HMATH_MATH_ERROR); + assert(sentinel == (hmath_value *)(uintptr_t)0x1234); + hmath_math_error error; + assert(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_DOMAIN_ERROR); + const char message[] = "positive ELU alpha required"; + assert(error.message_length == strlen(message) && memcmp(error.message, message, strlen(message)) == 0); + hmath_value_release(elu); + hmath_value_release(kind); + hmath_value_release(zero); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/deeplearning_contracts.cpp b/test/native/deeplearning_contracts.cpp new file mode 100644 index 0000000..653cef7 --- /dev/null +++ b/test/native/deeplearning_contracts.cpp @@ -0,0 +1,3 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Exercise the identical public C contract from C++17. */ +#include "deeplearning_contracts.c" diff --git a/test/native/dlpack_numpy.py b/test/native/dlpack_numpy.py index 0c9e6a1..eeed28a 100644 --- a/test/native/dlpack_numpy.py +++ b/test/native/dlpack_numpy.py @@ -55,17 +55,22 @@ def __init__(self, tensor, versioned): def __dlpack_device__(self): return (1, 0) - def __dlpack__(self, stream=None, **_kwargs): + def __dlpack__(self, stream=None, *, max_version=None, **_kwargs): if stream is not None: raise BufferError("CPU export has no stream") + # DLPack consumers negotiate versioned capsules explicitly. Older + # supported NumPy versions request the legacy capsule by omitting this. + self.exported_versioned = ( + self.versioned and max_version is not None and max_version >= (1, 0) + ) managed = pointer() export = ( library.hmath_dlpack_export_versioned - if self.versioned + if self.exported_versioned else library.hmath_dlpack_export ) hmath._check(export(self.tensor._live(), C.byref(managed))) - name = b"dltensor_versioned" if self.versioned else b"dltensor" + name = b"dltensor_versioned" if self.exported_versioned else b"dltensor" # This test consumes every capsule immediately with np.from_dlpack. # Production capsule wrappers also need an unconsumed-capsule destructor. return capsule_new(managed, name, None) @@ -73,17 +78,18 @@ def __dlpack__(self, stream=None, **_kwargs): for versioned in (False, True): tensor = hmath.Tensor([1, 2, 3, 4], (2, 2)) - array = np.from_dlpack(Producer(tensor, versioned)) + producer = Producer(tensor, versioned) + array = np.from_dlpack(producer) tensor.close() del tensor gc.collect() assert array.shape == (2, 2) assert np.array_equal(array, [[1, 2], [3, 4]]) - if versioned: + if producer.exported_versioned: assert not array.flags.writeable del array gc.collect() print( - "NumPy DLPack strided import, legacy copy export and readonly versioned export passed" + "NumPy DLPack strided import, legacy exports and negotiated versioned export passed" ) diff --git a/test/native/execution_blas_spy.c b/test/native/execution_blas_spy.c new file mode 100644 index 0000000..9e81b1c --- /dev/null +++ b/test/native/execution_blas_spy.c @@ -0,0 +1,73 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* A deterministic BLAS protocol spy, not a production numerical backend. */ +#include +#include +#ifdef ILP64 +#define INTEGER int64_t +#else +#define INTEGER int32_t +#endif +static unsigned calls32, calls64; +static const void *last_a, *last_b, *last_c; +static int64_t last_ldc; +static float last_alpha32; +const char *openblas_get_config(void) { +#ifdef ILP64 + return "OpenBLAS test USE64BITINT"; +#else + return "OpenBLAS test LP64"; +#endif +} +void cblas_daxpy(void) {} +void cblas_ddot(void) {} +void cblas_dnrm2(void) {} +void cblas_dgemv(void) {} +void cblas_zgemm(void) {} +#ifndef NO_SGEMM +void cblas_sgemm(int order, int ta, int tb, INTEGER m, INTEGER n, INTEGER k, float alpha, + const float *a, INTEGER lda, const float *b, INTEGER ldb, float beta, float *c, + INTEGER ldc) { + (void)order; + (void)ta; + (void)tb; + ++calls32; + last_a = a; + last_b = b; + last_c = c; + last_ldc = ldc; + last_alpha32 = alpha; + for (INTEGER i = 0; i < m; ++i) + for (INTEGER j = 0; j < n; ++j) { + float value = 0; + for (INTEGER z = 0; z < k; ++z) + value += a[i * lda + z] * b[z * ldb + j]; + c[i * ldc + j] = alpha * value + beta * c[i * ldc + j]; + } +} +#endif +void cblas_dgemm(int order, int ta, int tb, INTEGER m, INTEGER n, INTEGER k, double alpha, + const double *a, INTEGER lda, const double *b, INTEGER ldb, double beta, double *c, + INTEGER ldc) { + (void)order; + (void)ta; + (void)tb; + ++calls64; + last_a = a; + last_b = b; + last_c = c; + last_ldc = ldc; + for (INTEGER i = 0; i < m; ++i) + for (INTEGER j = 0; j < n; ++j) { + double value = 0; + for (INTEGER z = 0; z < k; ++z) + value += a[i * lda + z] * b[z * ldb + j]; + c[i * ldc + j] = alpha * value + beta * c[i * ldc + j]; + } +} +unsigned hm_spy_calls32(void) { return calls32; } +unsigned hm_spy_calls64(void) { return calls64; } +uintptr_t hm_spy_pointer(unsigned which) { + return (uintptr_t)(which == 0 ? last_a : which == 1 ? last_b : last_c); +} +int64_t hm_spy_ldc(void) { return last_ldc; } +float hm_spy_alpha32(void) { return last_alpha32; } diff --git a/test/native/execution_smoke.c b/test/native/execution_smoke.c new file mode 100644 index 0000000..e7b6cb3 --- /dev/null +++ b/test/native/execution_smoke.c @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_execution.h" +#include + +int main(void) { + double a[] = {1, 2, 3, 4}, b[] = {1, 0, 0, 1}, c[] = {0, 0, 0, 0}; + hmath_execution *execution = NULL; + hmath_execution_view av = {a, 4, 2, 2, 2}, bv = {b, 4, 2, 2, 2}; + hmath_execution_output cv = {c, 4, 2, 2, 2}; + if (hmath_init() != 0 || hmath_execution_create(NULL, &execution) != HMATH_OK || + hmath_execution_gemm_f64(execution, NULL, 1, &av, &bv, 0, &cv) != HMATH_OK) { + fprintf(stderr, "%s\n", hmath_last_error_message()); + return 1; + } + if (c[0] != 1 || c[1] != 2 || c[2] != 3 || c[3] != 4) + return 1; + hmath_execution_release(execution); + return hmath_runtime_shutdown() == HMATH_OK ? 0 : 1; +} diff --git a/test/native/expanded_bindings.py b/test/native/expanded_bindings.py new file mode 100644 index 0000000..6f0f2ea --- /dev/null +++ b/test/native/expanded_bindings.py @@ -0,0 +1,102 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Native numeric transport and optimizer lifetime regression checks.""" + +import math +import os +import sys +import unittest +from concurrent.futures import ThreadPoolExecutor +from fractions import Fraction +from pathlib import Path + +if os.environ.get("HMATH_LIBRARY"): + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from hmath import basic, constants, optimization, scalar, statistics, trigonometry + + +class ExpandedBindings(unittest.TestCase): + def test_original_numerical_contracts(self): + self.assertEqual(scalar.prefix_sum([1, 2, 3]), [0, 1, 3, 6]) + self.assertEqual(scalar.prefix_sum([]), [0]) + self.assertEqual(scalar.cumulative_sum([]), []) + self.assertEqual(scalar.integer_fraction(-1.5), (-1, -0.5)) + self.assertEqual(scalar.quotient_remainder(-7, 3), (-2, -1)) + self.assertEqual(scalar.euclidean_division(-7, 3), (-3, 2)) + self.assertEqual(scalar.bernoulli(4), Fraction(-1, 30)) + self.assertEqual(statistics.variance([1, 3]), 1) + self.assertTrue(math.isnan(constants.nan())) + self.assertTrue(math.isinf(scalar.add(float("inf"), 1))) + self.assertEqual(basic.clamp(2, 1, 0), 2) # original unchecked reversed bounds + with self.assertRaises(hmath.HMathError) as error: + scalar.clamp_checked(2, 1, 0) + self.assertEqual(error.exception.status, 11) + self.assertEqual(str(error.exception), 'DomainError "reversed clamp bounds"') + with self.assertRaises(hmath.HMathError) as error: + statistics.mean([]) + self.assertEqual(error.exception.status, 6) + with self.assertRaises(OverflowError): + scalar.round_digits(1 << 100, 1.0) + with self.assertRaises(ValueError): + scalar.add(1, 2, dtype="invalid") + + def test_exact_integer_transport(self): + self.assertEqual(basic.factorial(2000), math.factorial(2000)) + value = 10**6000 + 12345 + self.assertEqual(scalar.positive_modulo(-value, value + 17), 17) + + def test_precision_and_signed_zero(self): + self.assertEqual(scalar.add(16777216, 1, dtype="float32"), 16777216) + self.assertEqual(scalar.add(16777216, 1), 16777217) + self.assertEqual(math.copysign(1, scalar.integer_fraction(-0.0)[1]), -1) + self.assertAlmostEqual( + trigonometry.complex_sin(1 + 2j).real, math.sin(1) * math.cosh(2) + ) + + def test_thread_local_errors(self): + def work(index): + for _ in range(25): + if index % 2: + self.assertEqual(scalar.hypot(3, 4), 5) + else: + with self.assertRaises(hmath.HMathError) as error: + scalar.divide(1, 0) + self.assertEqual( + str(error.exception), 'DomainError "division by zero"' + ) + + with ThreadPoolExecutor(max_workers=4) as pool: + list(pool.map(work, range(8))) + + def test_optimizer_state_is_immutable(self): + with optimization.initialize_optimizer(2) as state: + for method in optimization.GradientMethod: + left, left_state = optimization.optimizer_step( + method, 0.1, state, [1, 2], [2, -3] + ) + right, right_state = optimization.optimizer_step( + method, 0.1, state, [1, 2], [2, -3] + ) + try: + self.assertEqual(left, right) + with self.assertRaises(hmath.HMathError) as error: + hmath.shutdown() + self.assertEqual(error.exception.status, 9) + finally: + left_state.close() + right_state.close() + with self.assertRaises(hmath.HMathError) as error: + optimization.optimizer_step( + optimization.GradientMethod.ADAM, 0, state, [1, 2], [2, 3] + ) + self.assertEqual( + str(error.exception), 'InvalidArgument "optimizer rate or state shape"' + ) + with self.assertRaises(ValueError): + optimization.optimizer_step( + optimization.GradientMethod.ADAM, 0.1, state, [1, 2], [2, 3] + ) + + +if __name__ == "__main__": + unittest.main(argv=[__file__]) diff --git a/test/native/expression_bindings.py b/test/native/expression_bindings.py new file mode 100644 index 0000000..0190a0e --- /dev/null +++ b/test/native/expression_bindings.py @@ -0,0 +1,355 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Positioned AST, exact arithmetic, symbolic conditions and error contracts.""" + +import dataclasses +import gc +import unittest +from fractions import Fraction + +import hmath +from _hmath_native import expression as e +from _hmath_native import symbolic as s +from _hmath_native._expression_error import last_expression_error +from _hmath_native._math_error import last_math_error + + +def close(value): + if isinstance(value, (list, tuple)): + for item in value: + close(item) + elif dataclasses.is_dataclass(value): + for field in dataclasses.fields(value): + close(getattr(value, field.name)) + elif hasattr(value, "close"): + value.close() + + +class ExpressionContracts(unittest.TestCase): + def setUp(self): + self.limits = e.default_limits() + self.registry = e.default_registry() + self.options = s.default_symbolic_options() + + def tearDown(self): + close(self.options) + close(self.registry) + + def test_original_defaults_and_all_limit_selectors(self): + self.assertEqual(self.limits, e.Limits()) + for name in [ + "maximum_steps", + "maximum_depth", + "maximum_nodes", + "maximum_input_chars", + "maximum_integer_bits", + "maximum_cache_entries", + ]: + self.assertEqual(getattr(e, name)(self.limits), getattr(self.limits, name)) + self.assertEqual(e.unknown_position(), e.SourcePos(0, 0, 0)) + + def test_source_positions_full_ast_and_original_equality(self): + position = e.SourcePos(-3, 9, 12) + with ( + e.Literal(Fraction(2, 3)) as node, + e.Expr(position, node) as located, + e.literal(Fraction(2, 3)) as generated, + ): + self.assertEqual(located.position, position) + self.assertEqual(located, generated) + with located.node as retrieved: + self.assertEqual(retrieved.fields, (0, Fraction(2, 3))) + self.assertEqual(retrieved, node) + self.assertEqual(e.source_offset(position), -3) + self.assertEqual(e.source_line(position), 9) + self.assertEqual(e.source_column(position), 12) + with ( + e.parse_expression(self.limits, "x +\n 2*y") as parsed, + parsed.node as root, + ): + fields = root.fields + try: + self.assertEqual(fields[:2], (4, e.Add)) + self.assertEqual(fields[2].position, e.SourcePos(0, 1, 1)) + self.assertEqual(fields[3].position, e.SourcePos(5, 2, 2)) + finally: + close(fields) + + def test_exact_and_float_tags_and_unreferenced_bindings(self): + with e.parse_expression(self.limits, "let a = x+1 in a*a") as expression: + exact = e.evaluate_expression( + self.limits, + e.ExactRational, + self.registry, + {"x": e.ExactValue(Fraction(2, 3))}, + expression, + ) + self.assertEqual(exact, e.ExactValue(Fraction(25, 9))) + approximate = e.evaluate_expression( + self.limits, + e.Float64, + self.registry, + {"x": e.FloatValue(2)}, + expression, + ) + self.assertEqual(approximate, e.FloatValue(9)) + self.assertEqual( + e.evaluate_text( + self.limits, + e.ExactRational, + self.registry, + {"unused": e.FloatValue(float("nan"))}, + "1", + ), + e.ExactValue(Fraction(1)), + ) + self.assertEqual( + e.evaluate_text( + self.limits, + e.ExactRational, + self.registry, + [("x", e.ExactValue(1)), ("x", e.ExactValue(2))], + "x", + ), + e.ExactValue(Fraction(2)), + ) + + def test_closed_registry_aliases_and_compiled_revalidation(self): + with ( + e.empty_registry() as empty, + e.register_function("squared_root", e.Sqrt, empty) as registry, + ): + self.assertEqual(e.allowed_functions(registry), ["squared_root"]) + with ( + e.parse_expression(self.limits, "squared_root(4)") as expression, + e.compile_expression(self.limits, expression) as compiled, + ): + self.assertEqual( + e.evaluate_compiled( + self.limits, e.ExactRational, registry, {}, compiled + ), + e.ExactValue(Fraction(2)), + ) + with self.assertRaises(hmath.HMathError) as caught: + e.evaluate_compiled( + self.limits, e.ExactRational, empty, {}, compiled + ) + self.assertEqual(caught.exception.expression_error.kind, e.UnknownName) + + def test_immutable_cache_and_serialization(self): + with e.empty_expression_cache() as empty: + compiled, populated = e.cached_expression(self.limits, "x*x+x*x", empty) + try: + self.assertEqual(e.cache_size(empty), 0) + self.assertEqual(e.cache_size(populated), 1) + self.assertEqual(e.compiled_node_count(compiled), 3) + again, next_cache = e.cached_expression( + self.limits, "x*x+x*x", populated + ) + close((again, next_cache)) + finally: + close((compiled, populated)) + with e.parse_expression(self.limits, "let x = 2//3 in x^2") as original: + text = e.serialize_expression(self.limits, original) + with e.deserialize_expression(self.limits, text) as restored: + self.assertEqual(original, restored) + self.assertEqual( + e.expression_hash(self.limits, original), + e.expression_hash(self.limits, restored), + ) + self.assertEqual(restored.position, e.unknown_position()) + + def test_all_ten_original_error_kinds_and_query_lifetime(self): + + def parse(source, **limits): + return e.parse_expression( + dataclasses.replace(self.limits, **limits), source + ) + + cases = [ + (e.SyntaxError, lambda: parse(")")), + ( + e.UnknownName, + lambda: e.evaluate_text( + self.limits, e.ExactRational, self.registry, {}, "missing" + ), + ), + ( + e.TypeMismatch, + lambda: e.evaluate_text( + self.limits, e.ExactRational, self.registry, {}, "sin(1)" + ), + ), + ( + e.DomainFailure, + lambda: e.evaluate_text( + self.limits, e.ExactRational, self.registry, {}, "1/0" + ), + ), + ( + e.NonFinite, + lambda: e.evaluate_text( + self.limits, + e.Float64, + self.registry, + {"x": e.FloatValue(float("inf"))}, + "x", + ), + ), + (e.StepLimit, lambda: parse("1", maximum_steps=1)), + (e.DepthLimit, lambda: parse("1", maximum_depth=1)), + (e.MemoryLimit, lambda: parse("12", maximum_input_chars=1)), + ( + e.InvalidLimits, + lambda: e.validate_limits( + dataclasses.replace(self.limits, maximum_steps=0) + ), + ), + (e.Unsupported, lambda: self.integrate_unsupported()), + ] + for expected, call in cases: + with self.subTest(kind=expected): + with self.assertRaises(hmath.HMathError) as caught: + call() + error = caught.exception + self.assertEqual(error.status, 12) + self.assertEqual(error.expression_error.kind, expected) + self.assertIsNone(error.math_error) + self.assertIsNone(last_math_error(hmath._lib)) + self.assertEqual( + last_expression_error(hmath._lib), error.expression_error + ) + e.validate_limits(self.limits) + self.assertIsNone(last_expression_error(hmath._lib)) + + def integrate_unsupported(self): + with e.parse_expression(self.limits, "exp(x^2)") as expression: + return s.integrate_basic(self.options, "x", expression) + + def test_long_unicode_error_and_lossless_error_record_fields(self): + name = "λ" * 3000 + with self.assertRaises(hmath.HMathError) as caught: + e.evaluate_text(self.limits, e.ExactRational, self.registry, {}, name) + self.assertEqual( + caught.exception.expression_error.message, "unknown variable: " + name + ) + payload = "λ\x00𝄞\ud800\udfff" * 3000 + original = e.ExprError(e.Unsupported, e.SourcePos(-4, 2, 3), payload) + self.assertEqual(e.error_kind(original), e.Unsupported) + self.assertEqual(e.error_position(original), original.position) + self.assertEqual(e.error_message(original), payload) + + def test_assumptions_preserve_domain_conditions(self): + with ( + e.parse_expression(self.limits, "x/x") as expression, + s.assumptions([("x", [s.NonZero])]) as assumptions, + ): + without = s.simplify(self.options, expression) + with_assumptions = s.simplify( + s.SymbolicOptions(self.limits, assumptions), expression + ) + try: + self.assertEqual(e.pretty_expression(without), "(x/x)") + self.assertEqual(e.pretty_expression(with_assumptions), "1") + self.assertFalse( + s.proves(self.options.assumptions, s.NonZero, expression) + ) + finally: + close((without, with_assumptions)) + with self.assertRaises(hmath.HMathError) as caught: + s.assumptions([("x", [s.Positive, s.NonPositive])]) + self.assertEqual(caught.exception.expression_error.kind, e.DomainFailure) + + def test_guarded_eigenvalues_preserve_explicit_conditions(self): + with ( + e.variable("a") as a, + e.literal(0) as zero, + e.literal(1) as one, + s.symbolic_matrix(self.options, [[zero, one], [a, zero]]) as matrix, + ): + guarded = s.symbolic_eigenvalues(self.options, matrix) + try: + self.assertEqual(len(guarded.value), 2) + self.assertEqual(len(guarded.conditions), 1) + self.assertEqual(guarded.conditions[0][1], s.NonNegative) + copied = s.required_conditions(guarded) + close(copied) + roots = s.guarded_value(guarded) + self.assertEqual(len(roots), 2) + close(roots) + finally: + close(guarded) + + def test_patterns_repeated_wildcards_and_capture_avoiding_substitution(self): + with ( + s.Any("a") as any_a, + s.BinaryPattern(e.Add, any_a, any_a) as pattern, + e.parse_expression(self.limits, "x+x") as equal, + e.parse_expression(self.limits, "x+y") as unequal, + ): + match = s.match_pattern(self.limits, pattern, equal) + self.assertEqual(match[0][0], "a") + close(match) + self.assertIsNone(s.match_pattern(self.limits, pattern, unequal)) + with ( + e.parse_expression(self.limits, "let y = 2 in x+y") as expression, + e.variable("y") as y, + s.substitute(self.limits, [("x", y)], expression) as substituted, + ): + self.assertEqual(e.free_variables(substituted), ["y"]) + self.assertEqual( + e.evaluate_expression( + self.limits, + e.ExactRational, + self.registry, + {"y": e.ExactValue(3)}, + substituted, + ), + e.ExactValue(5), + ) + + def test_formal_series_polynomial_and_linear_solution_interop(self): + with e.parse_expression(self.limits, "x^2-1") as expression: + with s.to_polynomial(self.options, "x", expression) as polynomial: + self.assertEqual(polynomial.dtype, "rational") + self.assertEqual( + polynomial.coefficients, [Fraction(-1), Fraction(0), Fraction(1)] + ) + with ( + s.from_polynomial("x", polynomial) as restored, + s.simplify(self.options, restored) as simplified, + ): + self.assertEqual( + e.evaluate_expression( + self.limits, + e.ExactRational, + self.registry, + {"x": e.ExactValue(3)}, + simplified, + ), + e.ExactValue(8), + ) + with ( + s.formal_power_series( + self.options, [Fraction(1), Fraction(2)] + ) as series, + s.reciprocal_formal_series(self.options, series) as reciprocal, + ): + self.assertEqual(reciprocal.coefficients, [Fraction(1), Fraction(-2)]) + with e.variable("x") as x, e.literal(2) as two: + solution = s.solve_linear_equations(self.options, ["x", "y"], [(x, two)]) + try: + self.assertEqual(solution.name, "ParametricSolution") + self.assertEqual(solution.arguments[1], ["y"]) + self.assertEqual(solution.arguments[0][0][0], "x") + finally: + close(solution) + + def test_zz_runtime_shutdown_releases_all_owners(self): + close(self.options) + close(self.registry) + gc.collect() + hmath.shutdown() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/expression_contracts.c b/test/native/expression_contracts.c new file mode 100644 index 0000000..82b120d --- /dev/null +++ b/test/native/expression_contracts.c @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Compile and run in both C99 and C++17. */ +#include "hmath_error.h" +#include "hmath_expression.h" +#include +#include +#include +#include +static hmath_value *text(const char *ascii) { + size_t count = strlen(ascii); + uint32_t *points = (uint32_t *)malloc((count ? count : 1) * sizeof *points); + assert(points); + for (size_t i = 0; i < count; ++i) + points[i] = (unsigned char)ascii[i]; + hmath_value *value = NULL; + assert(hmath_value_text(NULL, points, count, &value) == HMATH_OK); + free(points); + return value; +} +static hmath_value *index(ptrdiff_t n) { + hmath_value *value = NULL; + assert(hmath_value_index(NULL, n, &value) == HMATH_OK); + return value; +} +int main(void) { + assert(hmath_init() == HMATH_INIT_OK); + hmath_value *limits = NULL, *registry = NULL, *precision = NULL, *bindings = NULL; + assert(hmath_expression_default_limits(NULL, &limits) == HMATH_OK); + assert(hmath_expression_default_registry(NULL, ®istry) == HMATH_OK); + assert(hmath_expression_exact_rational_create(NULL, &precision) == HMATH_OK); + assert(hmath_value_list(NULL, NULL, 0, &bindings) == HMATH_OK); + hmath_value *source = text("1//3 + 2//3"), *expr = NULL, *result = NULL, *item = NULL; + assert(hmath_expression_parse_expression(NULL, limits, source, &expr) == HMATH_OK); + assert(hmath_expression_evaluate_expression(NULL, limits, precision, registry, bindings, expr, + &result) == HMATH_OK); + assert(hmath_value_item(NULL, result, 1, &item) == HMATH_OK); + char *n = NULL, *d = NULL; + assert(hmath_value_get_exact(item, &n, &d) == HMATH_OK); + assert(strcmp(n, "1") == 0 && strcmp(d, "1") == 0); + hmath_value_string_free(n); + hmath_value_string_free(d); + hmath_value_release(item); + hmath_value_release(result); + + hmath_value *cache = NULL, *cached = NULL; + assert(hmath_expression_empty_expression_cache(NULL, &cache) == HMATH_OK); + assert(hmath_expression_cached_expression(NULL, limits, source, cache, &cached) == HMATH_OK); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(cached); + hmath_value_release(cache); + hmath_value *bad = text(")"); + result = (hmath_value *)(uintptr_t)0x1234; + assert(hmath_expression_parse_expression(NULL, limits, bad, &result) == HMATH_EXPRESSION_ERROR); + assert(result == (hmath_value *)(uintptr_t)0x1234); + hmath_expression_error error; + hmath_math_error math_error; + assert(hmath_last_expression_error(&error) == 1); + assert(error.kind == HMATH_EXPRESSION_SYNTAX_ERROR); + assert(error.source_offset == 0 && error.source_line == 1 && error.source_column == 1); + assert(hmath_last_math_error(&math_error) == 0); + int kind, dtype; + size_t count; + assert(hmath_value_info(limits, &kind, &dtype, &count) == HMATH_OK); + assert(hmath_last_expression_error(&error) == 1); /* query did not clear */ + assert(hmath_expression_validate_limits(NULL, limits, &result) == HMATH_OK); + hmath_value_release(result); + assert(hmath_last_expression_error(&error) == 0); + + /* A pure source ExprError value also retains all characters and positions. */ + const uint32_t points[] = {'a', 0, 0xd800, 0x1d11e}; + hmath_value *message = NULL, *offset = index(-3), *line = index(2), *column = index(9), + *position = NULL, *error_kind = NULL, *record = NULL; + assert(hmath_value_text(NULL, points, 4, &message) == HMATH_OK); + assert(hmath_expression_source_pos_create(NULL, offset, line, column, &position) == HMATH_OK); + assert(hmath_expression_unsupported_create(NULL, &error_kind) == HMATH_OK); + assert(hmath_expression_expr_error_create(NULL, error_kind, position, message, &record) == + HMATH_OK); + assert(hmath_expression_error_message(NULL, record, &result) == HMATH_OK); + uint32_t copied[4]; + assert(hmath_value_info(result, &kind, &dtype, &count) == HMATH_OK && count == 4); + assert(hmath_value_get_text(result, copied, 4) == HMATH_OK); + assert(memcmp(copied, points, sizeof points) == 0); + hmath_value_release(result); + hmath_value_release(record); + hmath_value_release(error_kind); + hmath_value_release(position); + hmath_value_release(column); + hmath_value_release(line); + hmath_value_release(offset); + hmath_value_release(message); + + hmath_value *options = NULL, *variable = text("x"), *quadratic = text("x^2+x"), + *function = NULL, *derivative = NULL; + assert(hmath_symbolic_default_symbolic_options(NULL, &options) == HMATH_OK); + assert(hmath_expression_parse_expression(NULL, limits, quadratic, &function) == HMATH_OK); + assert(hmath_symbolic_differentiate(NULL, options, variable, function, &derivative) == + HMATH_OK); + assert(hmath_expression_expression_node(NULL, derivative, &item) == HMATH_OK); + assert(hmath_value_info(item, &kind, &dtype, &count) == HMATH_OK && kind == 81); + hmath_value_release(item); + hmath_value_release(derivative); + hmath_value_release(function); + hmath_value_release(quadratic); + hmath_value_release(variable); + hmath_value_release(options); + hmath_value_release(bad); + hmath_value_release(expr); + hmath_value_release(source); + hmath_value_release(bindings); + hmath_value_release(precision); + hmath_value_release(registry); + hmath_value_release(limits); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/foundation_bindings.py b/test/native/foundation_bindings.py new file mode 100644 index 0000000..089dd52 --- /dev/null +++ b/test/native/foundation_bindings.py @@ -0,0 +1,268 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Source budgets, exact instances, nominal shapes and retained callback owners.""" + +import gc +import struct +import sys +import weakref +from fractions import Fraction as Q +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import algebra as a +from _hmath_native import algebra_api as p +from _hmath_native import algorithm_values as algorithms +from _hmath_native import combinatorics_values as combinatorics +from _hmath_native import convergence_values as c +from _hmath_native import data_structures as d +from _hmath_native import discrete_values as discrete +from _hmath_native import matrix_advanced, vector +from _hmath_native import shape_values as s +from _hmath_native._expression_error import ErrorKind, ExprError, SourcePos +from _hmath_native._interchange_error import InterchangeError, InterchangeErrorKind +from _hmath_native._linear_base import _callback +from _hmath_native._math_error import MathError, MathErrorKind + +big = 10**6000 + 7 +with d.fenwick([big, 2]) as original, d.fenwick_add(0, 3, original) as changed: + assert d.fenwick_prefix(2, original) == big + 2 + assert d.fenwick_prefix(2, changed) == big + 5 +assert algorithms.run_length_encode(["x\0α\ud800", "x\0α\ud800", "🙂"]) == [ + ("x\0α\ud800", 2), + ("🙂", 1), +] +assert combinatorics.finite_differences([big, big + 1, big + 4]) == [ + [big, big + 1, big + 4], + [1, 3], + [2], +] +for operation in [ + lambda: combinatorics.subsets(1, [1, 2]), + lambda: discrete.bit_set(-1, 0), +]: + try: + operation() + except hmath.HMathError: + pass + else: + raise AssertionError("original budget/dimension check was discarded") + +with c.optional_type(0) as optional: + with d.Heap([None, None], prototype=optional) as heap: + first, next_heap = d.heap_pop(heap) + assert first is None + second, empty = d.heap_pop(next_heap) + assert second is None and d.heap_pop(empty) is None + next_heap.close() + empty.close() + assert d.next_greater([None, None], prototype=optional) == [None, None] + with discrete.MultiSet([None, None], prototype=optional) as multi: + assert discrete.multiset_entries(multi) == [(None, 2)] + with ( + c.optional_type(optional) as nested, + c.just(None) as just_none, + d.heap_from_list([just_none, None], prototype=nested) as heap, + ): + value, next_heap = d.heap_pop(heap) + assert value is None + value, end = d.heap_pop(next_heap) + assert isinstance(value, c.Just) and value.parts == ("Just", None) + value.close() + next_heap.close() + end.close() +with c.right(None) as choice, c.result_maybe(choice) as present: + assert present.parts == ("Just", None) +with c.from_maybe_error("error", None) as choice: + assert choice.parts == ("Left", "error") + +with p.Exact(Q(big, 7)) as x, p.Exact(Q(2, 5)) as y, p.plus(x, y) as z: + assert z.value == Q(big, 7) + Q(2, 5) + with p.horner([x, y], y) as h: + assert h.value == Q(big, 7) * Q(2, 5) + Q(2, 5) + with p.matrix_construct(1, 2, [x, y]) as matrix: + assert matrix.dtype == "exact" + values = matrix.to_list() + assert [v.value for v in values] == [Q(big, 7), Q(2, 5)] + for value in values: + value.close() + with ( + s.coordinates(2, [x, y], dtype=x) as coordinates, + s.coordinates_to_vector(coordinates) as v, + ): + values = vector.vector_values(v) + assert [value.value for value in values] == [Q(big, 7), Q(2, 5)] + for value in values: + value.close() + with ( + p.tensor_construct([2], [x, y]) as tensor, + s.static_tensor([2], tensor) as static, + s.dynamic_tensor(static) as dynamic, + ): + values = p.tensor_elements(dynamic) + assert [v.value for v in values] == [Q(big, 7), Q(2, 5)] + for value in values: + value.close() + with x.element_type as element, vector.vector([x, y], dtype=element) as v: + assert vector.vector_dimension(v) == 2 +assert struct.pack("f", p.plus(16777216.0, 1.0, dtype="float32")) == struct.pack( + "f", 16777216.0 +) +assert p.plus(16777216.0, 1.0, dtype="float64") == 16777217.0 +for operation in [ + lambda: a.plus(1.0, 2.0), + lambda: p.invert(1), + lambda: p.machine_epsilon(dtype="rational"), +]: + try: + operation() + except hmath.HMathError as error: + assert error.status == 10 + else: + raise AssertionError("adapter invented an original typeclass instance") +with a.modular(7, 3) as left, a.modular(5, 3) as right: + try: + a.add_modular(left, right) + except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.DOMAIN_ERROR + else: + raise AssertionError("different runtime rings were silently combined") +assert s.reflected_shape([2**100, 0]) == [2**100, 0] +with ( + p.matrix_construct(2, 2, [1, 2, 3, 4]) as matrix, + s.static_matrix(2, 2, matrix) as static, + s.static_transpose(static) as transpose, + s.static_multiply(static, transpose) as product, + s.dynamic_matrix(product) as dynamic, +): + assert dynamic.to_list() == [5, 11, 11, 25] +with ( + s.coordinates(2, ["α\0", "🙂\ud800"], dtype="string") as coordinates, + s.coordinates_to_vector(coordinates) as v, + vector.vector_slice(1, 1, v) as suffix, +): + assert vector.vector_values(suffix) == ["🙂\ud800"] + +with c.IterationOptions(8, 0.0, 0.0) as options: + calls = [] + + def step(state): + calls.append(state) + return (state[0] + 1, state[1] + 2) + + with c.iterate_until( + options, + step, + lambda state: float(3 - state[0]), + lambda old, new: old == new, + (0, 5), + ) as result: + assert result.estimate == (3, 11) and len(calls) == 3 + message = "callback\0α🙂\ud800" + failures = [ + MathError(MathErrorKind.NON_CONVERGENCE, (7,), message), + ExprError(ErrorKind.TYPE_MISMATCH, SourcePos(19, 3, 5), message), + InterchangeError(InterchangeErrorKind.INVALID_DATA, message), + ] + for failure in failures: + + def failing(_state, failure=failure): + raise failure + + try: + c.iterate_until(options, failing, lambda _x: 1.0, lambda _a, _b: False, 0) + except hmath.HMathError as error: + payload = ( + error.math_error or error.expression_error or error.interchange_error + ) + assert vars(payload) == vars(failure) + else: + raise AssertionError("callback domain error payload was replaced") + + class BrokenMessage(Exception): + def __str__(self): + raise RuntimeError("broken formatter") + + unexpected = BrokenMessage() + + def unexpected_step(_state): + raise unexpected + + try: + c.iterate_until( + options, unexpected_step, lambda _x: 1.0, lambda _a, _b: False, 0 + ) + except BrokenMessage as error: + assert error is unexpected + else: + raise AssertionError("unexpected callback exception was swallowed") + + # A caught recursive callback error must not replace an unrelated later + # source failure, and must not poison a successful outer invocation. + active = False + shared = None + + def reentrant_step(state): + global active + if active: + raise unexpected + active = True + try: + try: + c.iterate_until( + options, shared, lambda _x: 1.0, lambda _a, _b: False, 0 + ) + except BrokenMessage: + pass + finally: + active = False + return state + 1 + + shared = _callback(reentrant_step, ["a"], "integer") + with ( + shared, + c.iterate_until( + options, shared, lambda x: float(2 - x), lambda _a, _b: False, 0 + ) as result, + ): + assert result.estimate == 2 + + +class Userdata: + pass + + +references = [] + + +def return_function(_state): + userdata = Userdata() + references.append(weakref.ref(userdata)) + + def operation(row, column): + assert userdata is not None + return float(row + column) + + return _callback(operation, ["a"], "float64") + + +with c.IterationOptions(1, 0.0, 0.0) as options: + report = c.iterate_until( + options, + return_function, + lambda state: 1.0 if state is None else 0.0, + lambda _a, _b: False, + None, + ) +function = report.estimate +report.close() +gc.collect() +assert references[0]() is not None +with matrix_advanced.generate_matrix(1, 2, function) as matrix: + assert matrix.to_list() == [0.0, 1.0] +function.close() +gc.collect() +assert references[0]() is None +print( + "Foundation exact/typedOrd/nestedMaybe/sourcebudgets/nominaltypes/Float32/cross-domain-errors/reentrant-callback/lifetime contracts passed" +) diff --git a/test/native/foundation_contracts.c b/test/native/foundation_contracts.c new file mode 100644 index 0000000..058d4aa --- /dev/null +++ b/test/native/foundation_contracts.c @@ -0,0 +1,205 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_algebra.h" +#include "hmath_expression_error.h" +#include "hmath_interchange_error.h" +#include "hmath_matrix_value.h" +#include "hmath_shape.h" +#include +#include +#include +#include + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #condition, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static void integer_is(const hmath_value *value, const char *expected) { + char *numerator = NULL, *denominator = NULL; + CHECK(hmath_value_get_exact(value, &numerator, &denominator) == HMATH_OK); + CHECK(strcmp(numerator, expected) == 0 && strcmp(denominator, "1") == 0); + hmath_value_string_free(numerator); + hmath_value_string_free(denominator); +} +static hmath_status residual(const hmath_value *input, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)userdata; + (void)error; + int kind = -1, dtype = -1; + size_t count = 0; + CHECK(hmath_value_info(input, &kind, &dtype, &count) == HMATH_OK && kind == 5 && count == 1); + return hmath_value_f64(NULL, 1.0, out); +} +static hmath_status stagnant(const hmath_value *input, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)input; + (void)userdata; + (void)error; + return hmath_value_boolean(NULL, 0, out); +} +static hmath_status failed_step(const hmath_value *input, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)input; + (void)out; + int status = *(int *)userdata; + static const char message[] = "failed\0\xce\xb1"; + memset(error, 0, sizeof *error); + error->message = message; + error->message_length = sizeof message - 1; + if (status == HMATH_MATH_ERROR) { + error->kind = HMATH_MATH_NON_CONVERGENCE; + error->details[0] = 17; + } else if (status == HMATH_EXPRESSION_ERROR) { + error->kind = HMATH_EXPRESSION_TYPE_MISMATCH; + error->details[0] = 19; + error->details[1] = 3; + error->details[2] = 5; + } else + error->kind = HMATH_INTERCHANGE_INVALID_DATA; + return (hmath_status)status; +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *one = NULL, *two = NULL, *zero = NULL, *index_zero = NULL, *index_two = NULL, + *list = NULL, *original = NULL, *changed = NULL, *sum = NULL; + CHECK(hmath_value_integer(NULL, "1", &one) == HMATH_OK); + CHECK(hmath_value_integer(NULL, "2", &two) == HMATH_OK); + CHECK(hmath_value_integer(NULL, "0", &zero) == HMATH_OK); + CHECK(hmath_value_index(NULL, 0, &index_zero) == HMATH_OK); + CHECK(hmath_value_index(NULL, 2, &index_two) == HMATH_OK); + const hmath_value *entries[] = {one, two}; + CHECK(hmath_value_list(NULL, entries, 2, &list) == HMATH_OK); + CHECK(hmath_foundation_datastructure_fenwick(NULL, list, &original) == HMATH_OK); + CHECK(hmath_foundation_datastructure_fenwick_add(NULL, index_zero, two, original, &changed) == + HMATH_OK); + CHECK(hmath_foundation_datastructure_fenwick_prefix(NULL, index_two, original, &sum) == + HMATH_OK); + integer_is(sum, "3"); + hmath_value_release(sum); + CHECK(hmath_foundation_datastructure_fenwick_prefix(NULL, index_two, changed, &sum) == + HMATH_OK); + integer_is(sum, "5"); + hmath_value_release(sum); + hmath_value_release(original); + hmath_value_release(changed); + + /* A source Field instance is not invented for Integer. */ + hmath_value *sentinel = one; + CHECK(hmath_algebra_api_invert(NULL, one, one, &sentinel) == HMATH_UNSUPPORTED && + sentinel == one); + hmath_value *rational = NULL, *exact = NULL, *combined = NULL, *fraction = NULL; + CHECK(hmath_value_rational(NULL, "1", "3", &rational) == HMATH_OK); + CHECK(hmath_algebra_api_new_exact(NULL, rational, &exact) == HMATH_OK); + CHECK(hmath_algebra_api_plus(NULL, exact, exact, exact, &combined) == HMATH_OK); + CHECK(hmath_algebra_api_get_exact(NULL, combined, &fraction) == HMATH_OK); + char *n = NULL, *d = NULL; + CHECK(hmath_value_get_exact(fraction, &n, &d) == HMATH_OK && strcmp(n, "2") == 0 && + strcmp(d, "3") == 0); + hmath_value_string_free(n); + hmath_value_string_free(d); + hmath_value_release(fraction); + hmath_value_release(combined); + hmath_value_release(exact); + hmath_value_release(rational); + + /* Real nominal dimensions survive transpose and dynamic conversion. */ + hmath_value *matrix_values = NULL, *matrix = NULL, *static_matrix = NULL, *transpose = NULL, + *dynamic = NULL, *values = NULL; + const hmath_value *four[] = {one, two, two, one}; + CHECK(hmath_value_list(NULL, four, 4, &matrix_values) == HMATH_OK); + CHECK(hmath_algebra_api_matrix_construct(NULL, zero, index_two, index_two, matrix_values, + &matrix) == HMATH_OK); + CHECK(hmath_shape_static_matrix(NULL, two, two, matrix, &static_matrix) == HMATH_OK); + CHECK(hmath_shape_static_transpose(NULL, static_matrix, &transpose) == HMATH_OK); + CHECK(hmath_shape_dynamic_matrix(NULL, transpose, &dynamic) == HMATH_OK); + CHECK(hmath_matrix_value_to_list(NULL, dynamic, &values) == HMATH_OK); + hmath_value *entry = NULL; + CHECK(hmath_value_item(NULL, values, 1, &entry) == HMATH_OK); + integer_is(entry, "2"); + hmath_value_release(entry); + sentinel = one; + CHECK(hmath_shape_static_matrix(NULL, one, two, matrix, &sentinel) == HMATH_MATH_ERROR && + sentinel == one); + hmath_math_error math; + CHECK(hmath_last_math_error(&math) == 1 && math.kind == HMATH_MATH_SHAPE_MISMATCH && + math.details[0] == 1 && math.details[1] == 2 && math.details[2] == 2 && + math.details[3] == 2); + hmath_value_release(values); + hmath_value_release(dynamic); + hmath_value_release(transpose); + hmath_value_release(static_matrix); + hmath_value_release(matrix); + hmath_value_release(matrix_values); + + /* An explicit actual Ord(Maybe Integer) dictionary permits all-Nothing + * collections, without inventing an ordering on arbitrary foreign handles. */ + hmath_value *optional = NULL, *none = NULL, *missing = NULL, *heap = NULL, *popped = NULL; + CHECK(hmath_foundation_optional_type(NULL, zero, &optional) == HMATH_OK); + CHECK(hmath_value_none(NULL, &none) == HMATH_OK); + const hmath_value *missing_items[] = {none, none}; + CHECK(hmath_value_list(NULL, missing_items, 2, &missing) == HMATH_OK); + CHECK(hmath_foundation_heap_from_list_typed(NULL, optional, missing, &heap) == HMATH_OK); + CHECK(hmath_foundation_datastructure_heap_pop(NULL, heap, &popped) == HMATH_OK); + CHECK(hmath_value_item(NULL, popped, 0, &entry) == HMATH_OK); + int kind = -1, dtype = -1; + size_t count = 0; + CHECK(hmath_value_info(entry, &kind, &dtype, &count) == HMATH_OK && kind == 0); + hmath_value_release(entry); + hmath_value_release(popped); + hmath_value_release(heap); + hmath_value_release(missing); + hmath_value_release(none); + hmath_value_release(optional); + + /* Checked MathError callbacks become source Left; foreign Expr/Interchange + * errors abort while retaining their complete positioned/domain payload. */ + hmath_value *limit = NULL, *tolerance = NULL, *options = NULL, *step = NULL, *measure = NULL, + *equal = NULL; + CHECK(hmath_value_index(NULL, 1, &limit) == HMATH_OK); + CHECK(hmath_value_f64(NULL, 0.0, &tolerance) == HMATH_OK); + CHECK(hmath_foundation_convergence_new_iteration_options(NULL, limit, tolerance, tolerance, + &options) == HMATH_OK); + CHECK(hmath_linear_callback(NULL, residual, NULL, &measure) == HMATH_OK); + CHECK(hmath_linear_callback(NULL, stagnant, NULL, &equal) == HMATH_OK); + for (int status = HMATH_MATH_ERROR; status <= HMATH_INTERCHANGE_ERROR; ++status) { + CHECK(hmath_linear_callback(NULL, failed_step, &status, &step) == HMATH_OK); + sentinel = one; + CHECK(hmath_foundation_convergence_iterate_until(NULL, options, step, measure, equal, zero, + &sentinel) == (hmath_status)status && + sentinel == one); + if (status == HMATH_MATH_ERROR) + CHECK(hmath_last_math_error(&math) == 1 && math.kind == HMATH_MATH_NON_CONVERGENCE && + math.details[0] == 17 && math.message_length == 9 && + memcmp(math.message, "failed\0\xce\xb1", 9) == 0); + else if (status == HMATH_EXPRESSION_ERROR) { + hmath_expression_error expression; + CHECK(hmath_last_expression_error(&expression) == 1 && + expression.kind == HMATH_EXPRESSION_TYPE_MISMATCH && + expression.source_offset == 19 && expression.source_line == 3 && + expression.source_column == 5 && expression.message_length == 9); + } else { + hmath_interchange_error interchange; + CHECK(hmath_last_interchange_error(&interchange) == 1 && + interchange.kind == HMATH_INTERCHANGE_INVALID_DATA && + interchange.message_length == 9); + } + hmath_value_release(step); + } + hmath_value_release(options); + hmath_value_release(limit); + hmath_value_release(tolerance); + hmath_value_release(measure); + hmath_value_release(equal); + hmath_value_release(one); + hmath_value_release(two); + hmath_value_release(zero); + hmath_value_release(index_zero); + hmath_value_release(index_two); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(list); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/foundation_contracts.cpp b/test/native/foundation_contracts.cpp new file mode 100644 index 0000000..b8e909e --- /dev/null +++ b/test/native/foundation_contracts.cpp @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: MPL-2.0 +// Compile the independent public C client as C++17 too. +#include "foundation_contracts.c" diff --git a/test/native/geometry.c b/test/native/geometry.c new file mode 100644 index 0000000..85fdbe4 --- /dev/null +++ b/test/native/geometry.c @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_geometry.h" +#include "hmath_error.h" +#include +#include +#include +static void presence(hmath_value *value, int expected) { + hmath_value *flag = NULL, *inner = NULL; + assert(hmath_value_item(NULL, value, 0, &flag) == HMATH_OK); + int present = -1; + assert(hmath_value_get_boolean(flag, &present) == HMATH_OK && present == expected); + assert(hmath_value_item(NULL, value, 1, &inner) == HMATH_OK); + int kind = -1, dtype = 0; + size_t count = 0; + assert(hmath_value_info(inner, &kind, &dtype, &count) == HMATH_OK && kind == 0); + hmath_value_release(flag); + hmath_value_release(inner); +} +int main(void) { + hmath_value *zero = NULL, *one = NULL, *negative = NULL, *point = NULL, *normal = NULL; + hmath_value *plane = NULL, *shifted = NULL, *result = NULL, *circle = NULL, *fields = NULL; + hmath_value *unchanged = (hmath_value *)(uintptr_t)1; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_f64(NULL, 0, &zero) == HMATH_OK); + assert(hmath_value_f64(NULL, 1, &one) == HMATH_OK); + assert(hmath_value_f64(NULL, -1, &negative) == HMATH_OK); + assert(hmath_geometry_p3(NULL, zero, zero, one, &normal) == HMATH_OK); + assert(hmath_geometry_plane(NULL, normal, zero, &plane) == HMATH_OK); + assert(hmath_geometry_plane(NULL, normal, one, &shifted) == HMATH_OK); + assert(hmath_geometry_plane_intersection(NULL, plane, shifted, &result) == HMATH_OK); + presence(result, 0); + hmath_value_release(result); + assert(hmath_geometry_plane_intersection(NULL, plane, plane, &result) == HMATH_OK); + presence(result, 1); + hmath_value_release(result); + assert(hmath_geometry_p2(NULL, zero, zero, &point) == HMATH_OK); + assert(hmath_geometry_circle(NULL, point, negative, &circle) == HMATH_OK); + assert(hmath_geometry_parts(NULL, circle, &result) == HMATH_OK); + hmath_value_release(circle); + assert(hmath_value_item(NULL, result, 1, &fields) == HMATH_OK); + hmath_value_release(result); + assert(hmath_value_item(NULL, fields, 0, &result) == HMATH_OK); + int kind = 0, dtype = 0; + size_t count = 0; + assert(hmath_value_info(result, &kind, &dtype, &count) == HMATH_OK && kind == 169); + hmath_value_release(result); + hmath_value_release(fields); + assert(hmath_geometry_plane_intersection(NULL, point, plane, &unchanged) == HMATH_INVALID_ARGUMENT); + assert(unchanged == (hmath_value *)(uintptr_t)1); + assert(hmath_geometry_parts(NULL, NULL, &unchanged) == HMATH_INVALID_ARGUMENT); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(point); + hmath_value_release(plane); + hmath_value_release(shifted); + hmath_value_release(normal); + hmath_value_release(zero); + hmath_value_release(one); + hmath_value_release(negative); + assert(hmath_runtime_shutdown() == HMATH_OK); + puts("Geometry C nested Maybe, raw constructors, typed child lifetime and output contracts passed."); + return 0; +} diff --git a/test/native/header_c99.c b/test/native/header_c99.c index a955fd3..7f2709b 100644 --- a/test/native/header_c99.c +++ b/test/native/header_c99.c @@ -1,6 +1,41 @@ /* SPDX-License-Identifier: MPL-2.0 */ #include "hmath.h" +#include "hmath_algebra.h" +#include "hmath_autodiff.h" +#include "hmath_buffer.h" +#include "hmath_bytes.h" +#include "hmath_callback.h" +#include "hmath_deeplearning.h" #include "hmath_dlpack.h" +#include "hmath_error.h" +#include "hmath_execution.h" +#include "hmath_expression.h" +#include "hmath_expression_error.h" +#include "hmath_foundation.h" +#include "hmath_geometry.h" +#include "hmath_graph.h" +#include "hmath_image.h" +#include "hmath_interchange.h" +#include "hmath_interchange_error.h" +#include "hmath_linear.h" +#include "hmath_machinelearning.h" +#include "hmath_matrix.h" +#include "hmath_matrix_value.h" +#include "hmath_numeric.h" +#include "hmath_numeric_types.h" +#include "hmath_numerical.h" +#include "hmath_optimization.h" +#include "hmath_optimization_all.h" +#include "hmath_polynomial.h" +#include "hmath_rotations.h" +#include "hmath_scalar_extras.h" +#include "hmath_shape.h" +#include "hmath_spectral.h" +#include "hmath_stochastic.h" +#include "hmath_tensor_bindings.h" +#include "hmath_timeseries.h" +#include "hmath_units.h" +#include "hmath_value.h" int main(void) { double result; return hmath_init() || hmath_abi_version() != HMATH_ABI_VERSION || diff --git a/test/native/image.c b/test/native/image.c new file mode 100644 index 0000000..5c8b925 --- /dev/null +++ b/test/native/image.c @@ -0,0 +1,70 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_image.h" +#include "hmath_error.h" +#include +#include +#include +static hmath_status add_one(const hmath_value *arguments, void *userdata, hmath_value **out) { + (void)userdata; + hmath_value *first = NULL; + double real = 0, imaginary = 0; + hmath_status status = hmath_value_item(NULL, arguments, 0, &first); + if (!status) status = hmath_value_get_f64(first, &real, &imaginary); + hmath_value_release(first); + return status ? status : hmath_value_f64(NULL, real + 1, out); +} +static hmath_status source_error(const hmath_value *arguments, void *userdata, hmath_value **out) { + (void)arguments; + hmath_value *power = NULL; + hmath_status status = hmath_value_f64(NULL, -1, &power); + if (!status) status = hmath_image_gamma(NULL, power, (hmath_value *)userdata, out); + hmath_value_release(power); + return status; +} +int main(void) { + hmath_value *two = NULL, *one = NULL, *quarter = NULL, *shape = NULL, *values = NULL; + hmath_value *image = NULL, *mapped = NULL, *tensor = NULL, *child = NULL; + hmath_value *unchanged = (hmath_value *)(uintptr_t)1; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_index(NULL, 2, &two) == HMATH_OK); + assert(hmath_value_index(NULL, 1, &one) == HMATH_OK); + assert(hmath_value_f64(NULL, 0.25, &quarter) == HMATH_OK); + const hmath_value *axes[] = {two, two}; + const hmath_value *pixels[] = {quarter, quarter, quarter, quarter}; + assert(hmath_value_list(NULL, axes, 2, &shape) == HMATH_OK); + assert(hmath_value_list(NULL, pixels, 4, &values) == HMATH_OK); + assert(hmath_image_image(NULL, shape, one, values, &image) == HMATH_OK); + assert(hmath_image_map_image(NULL, add_one, NULL, image, &mapped) == HMATH_OK); + assert(hmath_image_image_values(NULL, mapped, &child) == HMATH_OK); + hmath_value_release(mapped); + mapped = NULL; + assert(hmath_value_item(NULL, child, 0, &mapped) == HMATH_OK); + double real = 0, imaginary = 0; + assert(hmath_value_get_f64(mapped, &real, &imaginary) == HMATH_OK && real == 1.25); + hmath_value_release(mapped); + hmath_value_release(child); + assert(hmath_image_map_image(NULL, source_error, image, image, &unchanged) == HMATH_MATH_ERROR); + assert(unchanged == (hmath_value *)(uintptr_t)1); + hmath_math_error error; + assert(hmath_last_math_error(&error) && error.kind == HMATH_MATH_INVALID_ARGUMENT); + assert(hmath_image_to_tensor(NULL, image, &tensor) == HMATH_OK); + hmath_value_release(image); + assert(hmath_image_tensor_shape(NULL, tensor, &child) == HMATH_OK); + assert(hmath_value_item(NULL, child, 0, &mapped) == HMATH_OK); + ptrdiff_t axis = 0; + assert(hmath_value_get_index(mapped, &axis) == HMATH_OK && axis == 2); + hmath_value_release(mapped); + hmath_value_release(child); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(tensor); + assert(hmath_image_image(NULL, NULL, one, values, &unchanged) == HMATH_INVALID_ARGUMENT); + assert(unchanged == (hmath_value *)(uintptr_t)1); + hmath_value_release(values); + hmath_value_release(shape); + hmath_value_release(quarter); + hmath_value_release(one); + hmath_value_release(two); + assert(hmath_runtime_shutdown() == HMATH_OK); + puts("Image C callback, MathError, Tensor lifetime and output contracts passed."); + return 0; +} diff --git a/test/native/interchange_bindings.py b/test/native/interchange_bindings.py new file mode 100644 index 0000000..69c366e --- /dev/null +++ b/test/native/interchange_bindings.py @@ -0,0 +1,309 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent formats, exact typed scalars, streams, scoped IO and callbacks.""" + +import gc +import io +import struct +import sys +import tempfile +import weakref +import zipfile +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import _value as wire +from _hmath_native import interchange as i +from _hmath_native import matrix_advanced +from _hmath_native._expression_error import ErrorKind, ExprError, SourcePos +from _hmath_native._interchange_error import InterchangeError, InterchangeErrorKind +from _hmath_native._linear_base import _callback +from _hmath_native._math_error import MathError, MathErrorKind + +DTYPES = [ + ("bool", "?", [True, False, False, True]), + ("int8", "b", [-128, -1, 0, 127]), + ("uint8", "B", [0, 1, 128, 255]), + ("int16", "h", [-32768, -1, 0, 32767]), + ("uint16", "H", [0, 1, 32768, 65535]), + ("int32", "i", [-(2**31), -1, 0, 2**31 - 1]), + ("uint32", "I", [0, 1, 2**31, 2**32 - 1]), + ("int64", "q", [-(2**63), -(2**53) - 1, 2**53 + 1, 2**63 - 1]), + ("uint64", "Q", [0, 1, 2**53 + 1, 2**64 - 1]), + ("float32", "f", [0.0, 1 / 3, -0.0, 1.0]), + ("float64", "d", [0.0, 1 / 3, -0.0, 1.0]), + ("complex64", "ff", [1 + 2j, 3 - 4j, 0j, 1j]), + ("complex128", "dd", [1 + 2j, 3 - 4j, 0j, 1j]), +] +with ( + tempfile.TemporaryDirectory(prefix="hmath-interchange-contract-") as directory, + i.default_limits() as limits, + i.little_endian() as little, + i.big_endian() as big, + i.c_order() as corder, + i.f_order() as forder, +): + root = Path(directory) + for dtype, format_code, values in DTYPES: + for endian, prefix in [(little, "<"), (big, ">")]: + flat = ( + [part for value in values for part in (value.real, value.imag)] + if format_code in ("ff", "dd") + else values + ) + expected = struct.pack(prefix + format_code * 4, *flat) + with ( + i.from_values(limits, endian, [2, 2], values, dtype=dtype) as array, + i.raw_encode(limits, endian, corder, array) as raw, + i.encode_binary(limits, array) as encoded, + i.decode_binary(limits, encoded) as decoded, + ): + assert bytes(raw) == expected and decoded == array + with i.to_matrix(decoded) as matrix: + assert matrix.shape == (2, 2) + with i.from_matrix(limits, endian, matrix) as roundtrip: + assert roundtrip == array + with ( + i.to_tensor(decoded) as tensor, + i.from_tensor(limits, endian, tensor) as roundtrip, + ): + assert roundtrip == array + with i.encode_npy(limits, forder, array) as npy: + assert bytes(npy).startswith(b"\x93NUMPY") + with ( + i.decode_npy(limits, npy) as npy_array, + i.raw_encode(limits, endian, corder, npy_array) as back, + ): + assert bytes(back) == expected + # NaN payloads and negative zero are compared as raw bytes, + # not merely by Python's numerical equality. + path = root / ( + dtype + prefix.replace("<", "l").replace(">", "b") + ".raw" + ) + path.write_bytes(expected) + with ( + i.element_type(dtype=dtype) as element, + i.raw_spec(element, endian, corder, [2, 2]) as spec, + ): + escaped = [] + + def mapped( + mapping, escaped=escaped, dtype=dtype, expected=expected + ): + escaped.append(wire.decode(mapping.clone())) + return ( + mapping.shape, + mapping.at([1, 0], dtype=dtype, boxed=True), + mapping.read_bytes(0, len(expected)), + ) + + shape, scalar, copied = i.with_mapped_array( + limits, spec, path, mapped + ) + assert shape == [2, 2] and bytes(copied) == expected + with ( + i.put_element(endian, scalar, dtype=dtype) as put, + i.put_bytes(put) as element_bytes, + ): + width = len(expected) // 4 + assert bytes(element_bytes) == expected[2 * width : 3 * width] + if isinstance(scalar, wire.Value): + scalar.close() + copied.close() + assert escaped[0].shape == [2, 2] # original safe metadata query + for read in [ + lambda escaped=escaped: escaped[0].read_bytes(0, 1), + lambda escaped=escaped, dtype=dtype: escaped[0].at( + [0, 0], dtype=dtype + ), + ]: + try: + read() + except hmath.HMathError as error: + assert error.interchange_error == InterchangeError( + InterchangeErrorKind.INVALID_DATA, "mapping is closed" + ) + else: + raise AssertionError("retired mapping permitted a read") + escaped[0].close() + # Raw and binary retain noncanonical IEEE payloads and signed zeros. + special = bytes.fromhex("010000000000f87f0000000000000080") + with ( + i.f64() as dtype, + i.raw_decode(limits, dtype, little, corder, [2], special) as array, + i.encode_binary(limits, array) as encoded, + i.decode_binary(limits, encoded) as decoded, + i.raw_encode(limits, little, corder, decoded) as raw, + ): + assert bytes(raw) == special + with i.Bytes(b"a\0b") as owner: + view = owner.view() + gc.collect() + assert view.readonly and view.tobytes() == b"a\0b" + del view + gc.collect() + + with ( + i.from_values(limits, little, [2, 2], [1.0, 2.0, 3.0, 4.0]) as array, + i.raw_encode(limits, little, corder, array) as raw, + i.f64() as dtype, + i.raw_spec(dtype, little, corder, [2, 2]) as spec, + ): + data_path = root / "source.raw" + data_path.write_bytes(bytes(raw)) + binary_path = root / "array.hmath" + i.write_array_file( + limits, + lambda budget, value: i.encode_binary(budget, value), + binary_path, + array, + ) + with i.read_array_file( + limits, lambda data: i.decode_binary(limits, data), binary_path + ) as restored: + assert restored == array + seen = [] + with i.open_handle(data_path, "rb") as handle: + i.read_raw_chunks( + limits, + spec, + 2, + handle, + lambda value: seen.append(i.to_values(value)) or True, + ) + assert handle.tell() == len(bytes(raw)) + assert seen == [[1.0, 2.0], [3.0, 4.0]] + with i.open_handle(data_path, "rb") as handle: + stopped = [] + i.read_raw_chunks( + limits, + spec, + 2, + handle, + lambda value: stopped.append(i.to_values(value)) or False, + ) + assert handle.tell() == 16 and stopped == [[1.0, 2.0]] + output = root / "produced.raw" + chunks = [bytes(raw)[:16], bytes(raw)[16:]] + calls = [] + + def produce(maximum): + calls.append(maximum) + return chunks.pop(0) if chunks else None + + with i.open_handle(output, "wb") as handle: + i.write_raw_chunks(limits, spec, 2, handle, produce) + assert calls == [16, 16, 0] and output.read_bytes() == bytes(raw) + # Checked consumer Left stops after its already-read first chunk. + message = "callback\0α🙂\ud800" + domain_errors = [ + MathError(MathErrorKind.NON_CONVERGENCE, (7,), message), + ExprError(ErrorKind.TYPE_MISMATCH, SourcePos(19, 3, 5), message), + InterchangeError(InterchangeErrorKind.INVALID_DATA, message), + ] + for failure in domain_errors: + + def bad(_value, failure=failure): + raise failure + + with i.open_handle(data_path, "rb") as handle: + try: + i.read_raw_chunks(limits, spec, 2, handle, bad) + except hmath.HMathError as error: + payload = ( + error.math_error + or error.expression_error + or error.interchange_error + ) + assert vars(payload) == vars(failure) and handle.tell() == 16 + else: + raise AssertionError("callback error fields were discarded") + + class BadMessage(Exception): + def __str__(self): + raise RuntimeError("formatter failure") + + unexpected = BadMessage() + + def bad_mapping(_mapping): + raise unexpected + + try: + i.with_mapped_array(limits, spec, data_path, bad_mapping) + except BadMessage as error: + assert error is unexpected + else: + raise AssertionError("unexpected mapping callback failure was swallowed") + # Binary encoder validation precedes opening/truncating an output file. + keep = root / "keep.hmath" + keep.write_bytes(b"keep") + + def rejected(_budget, _array): + raise InterchangeError(InterchangeErrorKind.UNSUPPORTED, "encoder rejected") + + try: + i.write_array_file(limits, rejected, keep, array) + except hmath.HMathError as error: + assert error.interchange_error.kind == InterchangeErrorKind.UNSUPPORTED + else: + raise AssertionError("encoder rejection was swallowed") + assert keep.read_bytes() == b"keep" + with ( + i.encode_npz(limits, False, [("array", array)]) as archive, + zipfile.ZipFile(io.BytesIO(bytes(archive))) as zipped, + ): + assert zipped.namelist() == ["array.npy"] and zipped.read( + "array.npy" + ).startswith(b"\x93NUMPY") + + # A generic mapping result can contain a freshly-created callback. + # Its userdata survives mapping retirement and is released with the owner. + class Userdata: + pass + + references = [] + + def return_callback(_mapping): + userdata = Userdata() + references.append(weakref.ref(userdata)) + + def operation(row, column): + assert userdata is not None + return float(row + column) + + return _callback(operation, ["a"], "float64") + + function = i.with_mapped_array(limits, spec, data_path, return_callback) + gc.collect() + assert references[0]() is not None + with matrix_advanced.generate_matrix(1, 2, function) as matrix: + assert matrix.to_list() == [0.0, 1.0] + function.close() + gc.collect() + assert references[0]() is None + for decode, data, kind in [ + ( + lambda data: i.decode_binary(limits, data), + b"bad", + InterchangeErrorKind.INVALID_DATA, + ), + ( + lambda data: i.decode_npy(limits, data), + b"bad", + InterchangeErrorKind.INVALID_DATA, + ), + ( + lambda data: i.decode_text(limits, data), + b"bad", + InterchangeErrorKind.UNSUPPORTED, + ), + ]: + try: + decode(data) + except hmath.HMathError as error: + assert error.status == 13 and error.interchange_error.kind == kind + else: + raise AssertionError("malformed input unexpectedly succeeded") +print( + "Interchange13Element/endian/IEEEbits/MatrixTensor/NPYZIP/Bytesviews/streamorder/mmap-retirement/callback11-12-13/lifetime contracts passed" +) diff --git a/test/native/interchange_contracts.c b/test/native/interchange_contracts.c new file mode 100644 index 0000000..e1a1869 --- /dev/null +++ b/test/native/interchange_contracts.c @@ -0,0 +1,282 @@ +#define _POSIX_C_SOURCE 200809L +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_error.h" +#include "hmath_expression_error.h" +#include "hmath_interchange.h" +#include +#include +#include +#include +#include + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #condition, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static hmath_value *index_value(ptrdiff_t number) { + hmath_value *out = NULL; + CHECK(hmath_value_index(NULL, number, &out) == HMATH_OK); + return out; +} +static void exact_is(const hmath_value *value, const char *expected) { + char *n = NULL, *d = NULL; + CHECK(hmath_value_get_exact(value, &n, &d) == HMATH_OK && strcmp(n, expected) == 0 && + strcmp(d, "1") == 0); + hmath_value_string_free(n); + hmath_value_string_free(d); +} +static void big_bytes(unsigned char *out, uint64_t bits, size_t width) { + for (size_t i = 0; i < width; ++i) + out[width - 1 - i] = (unsigned char)(bits >> (8 * i)); +} +static hmath_value *text_value(const char *text) { + size_t length = strlen(text); + uint32_t *chars = (uint32_t *)malloc((length ? length : 1) * sizeof *chars); + CHECK(chars != NULL); + for (size_t n = 0; n < length; ++n) + chars[n] = (unsigned char)text[n]; + hmath_value *value = NULL; + CHECK(hmath_value_text(NULL, chars, length, &value) == HMATH_OK); + free(chars); + return value; +} +struct mapped_state { + hmath_value *prototype, *indices, *zero, *size, *escaped; + int failure; +}; +static hmath_status mapping_callback(const hmath_value *arguments, void *userdata, + hmath_value **out, hmath_math_error *error) { + struct mapped_state *state = (struct mapped_state *)userdata; + hmath_value *mapping = NULL, *scalar = NULL, *bytes = NULL; + CHECK(hmath_value_item(NULL, arguments, 0, &mapping) == HMATH_OK); + hmath_value_release(state->escaped); + state->escaped = mapping; + if (state->failure) { + static const char message[] = "callback\0\xce\xb1"; + memset(error, 0, sizeof *error); + error->message = message; + error->message_length = sizeof message - 1; + if (state->failure == HMATH_MATH_ERROR) { + error->kind = HMATH_MATH_NON_CONVERGENCE; + error->details[0] = 17; + } else if (state->failure == HMATH_EXPRESSION_ERROR) { + error->kind = HMATH_EXPRESSION_TYPE_MISMATCH; + error->details[0] = 19; + error->details[1] = 3; + error->details[2] = 5; + } else + error->kind = HMATH_INTERCHANGE_INVALID_DATA; + return (hmath_status)state->failure; + } + CHECK(hmath_interchange_value_mapped_value(NULL, state->prototype, mapping, state->indices, + &scalar) == HMATH_OK); + CHECK(hmath_interchange_value_mapped_read_bytes(NULL, mapping, state->zero, state->size, + &bytes) == HMATH_OK); + const hmath_value *fields[] = {scalar, bytes}; + hmath_status status = hmath_value_tuple(NULL, fields, 2, out); + hmath_value_release(scalar); + hmath_value_release(bytes); + return status; +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *limits = NULL, *big = NULL, *little = NULL, *order = NULL, *one = index_value(1), + *two = index_value(2), *shape = NULL; + CHECK(hmath_interchange_value_default_limits(NULL, &limits) == HMATH_OK); + CHECK(hmath_interchange_value_big_endian(NULL, &big) == HMATH_OK); + CHECK(hmath_interchange_value_little_endian(NULL, &little) == HMATH_OK); + CHECK(hmath_interchange_value_c_order(NULL, &order) == HMATH_OK); + const hmath_value *dimensions[] = {one, two}; + CHECK(hmath_value_list(NULL, dimensions, 2, &shape) == HMATH_OK); + struct scalar_case { + int dtype; + const char *decimal; + uint64_t bits; + size_t width; + }; + const struct scalar_case cases[] = { + {16, NULL, 1, 1}, + {HMATH_COEFFICIENT_INT8, "-2", 254, 1}, + {HMATH_COEFFICIENT_UINT8, "254", 254, 1}, + {HMATH_COEFFICIENT_INT16, "-4660", 60876, 2}, + {HMATH_COEFFICIENT_UINT16, "43981", 43981, 2}, + {HMATH_COEFFICIENT_INT32, "-19088743", UINT32_C(0xfedcba99), 4}, + {HMATH_COEFFICIENT_UINT32, "2309737967", UINT32_C(0x89abcdef), 4}, + {HMATH_COEFFICIENT_INT64, "-9007199254740993", UINT64_C(0xffdfffffffffffff), 8}, + {HMATH_COEFFICIENT_UINT64, "18446744073709551615", UINT64_MAX, 8}, + {HMATH_COEFFICIENT_FLOAT32, NULL, UINT32_C(0x80000000), 4}, + {HMATH_COEFFICIENT_FLOAT64, NULL, UINT64_C(0x7ff8000000000001), 8}, + {HMATH_COEFFICIENT_COMPLEX64, NULL, 0, 8}, + {HMATH_COEFFICIENT_COMPLEX128, NULL, 0, 16}}; + for (size_t which = 0; which < sizeof cases / sizeof *cases; ++which) { + const struct scalar_case *entry = &cases[which]; + hmath_value *scalar = NULL, *program = NULL, *data = NULL, *parser = NULL, *decoded = NULL, + *values = NULL, *array = NULL, *matrix = NULL, *raw = NULL; + unsigned char expected[16] = {0}; + if (entry->decimal) + CHECK(hmath_value_integral(NULL, (hmath_coefficient_type)entry->dtype, entry->decimal, + &scalar) == HMATH_OK); + else if (entry->dtype == 16) + CHECK(hmath_value_boolean(NULL, 1, &scalar) == HMATH_OK); + else if (entry->dtype == HMATH_COEFFICIENT_FLOAT32) { + uint32_t bits = (uint32_t)entry->bits; + float value; + memcpy(&value, &bits, 4); + CHECK(hmath_value_f32(NULL, value, &scalar) == HMATH_OK); + } else if (entry->dtype == HMATH_COEFFICIENT_FLOAT64) { + double value; + memcpy(&value, &entry->bits, 8); + CHECK(hmath_value_f64(NULL, value, &scalar) == HMATH_OK); + } else if (entry->dtype == HMATH_COEFFICIENT_COMPLEX64) + CHECK(hmath_value_complex_f32(NULL, 1.5f, -2.25f, &scalar) == HMATH_OK); + else + CHECK(hmath_value_complex_f64(NULL, 1.5, -2.25, &scalar) == HMATH_OK); + if (entry->dtype == HMATH_COEFFICIENT_COMPLEX64) { + big_bytes(expected, UINT32_C(0x3fc00000), 4); + big_bytes(expected + 4, UINT32_C(0xc0100000), 4); + } else if (entry->dtype == HMATH_COEFFICIENT_COMPLEX128) { + big_bytes(expected, UINT64_C(0x3ff8000000000000), 8); + big_bytes(expected + 8, UINT64_C(0xc002000000000000), 8); + } else + big_bytes(expected, entry->bits, entry->width); + CHECK(hmath_interchange_value_put_element(NULL, scalar, big, scalar, &program) == HMATH_OK); + CHECK(hmath_interchange_value_put_bytes(NULL, program, &data) == HMATH_OK); + const unsigned char *bytes = NULL; + size_t count = 0; + CHECK(hmath_bytes_data(data, &bytes, &count) == HMATH_OK && count == entry->width && + memcmp(bytes, expected, count) == 0); + CHECK(hmath_interchange_value_get_element(NULL, scalar, big, &parser) == HMATH_OK); + CHECK(hmath_interchange_value_run_decoder(NULL, parser, data, &decoded) == HMATH_OK); + int kind = -1, dtype = -1; + size_t length = 0; + CHECK(hmath_value_info(decoded, &kind, &dtype, &length) == HMATH_OK && + (entry->dtype == 16 ? kind == 3 : (kind == 1 && dtype == entry->dtype))); + if (entry->decimal) + exact_is(decoded, entry->decimal); + const hmath_value *items[] = {scalar, scalar}; + CHECK(hmath_value_list(NULL, items, 2, &values) == HMATH_OK); + CHECK(hmath_interchange_value_from_values(NULL, scalar, limits, big, shape, values, + &array) == HMATH_OK); + CHECK(hmath_interchange_value_raw_encode(NULL, limits, big, order, array, &raw) == + HMATH_OK); + CHECK(hmath_bytes_data(raw, &bytes, &count) == HMATH_OK && count == 2 * entry->width && + memcmp(bytes, expected, entry->width) == 0 && + memcmp(bytes + entry->width, expected, entry->width) == 0); + CHECK(hmath_interchange_value_to_matrix(NULL, scalar, array, &matrix) == HMATH_OK); + CHECK(hmath_value_info(matrix, &kind, &dtype, &length) == HMATH_OK && kind == 9 && + dtype == entry->dtype && length == 2); + unsigned char extra[17]; + memcpy(extra, expected, entry->width); + extra[entry->width] = 0; + hmath_value *tail = NULL, *sentinel = scalar; + CHECK(hmath_bytes_copy(NULL, extra, entry->width + 1, &tail) == HMATH_OK); + CHECK(hmath_interchange_value_run_decoder(NULL, parser, tail, &sentinel) == + HMATH_INTERCHANGE_ERROR && + sentinel == scalar); + hmath_interchange_error failure; + CHECK(hmath_last_interchange_error(&failure) == 1 && + failure.kind == HMATH_INTERCHANGE_INVALID_DATA); + hmath_value_release(tail); + hmath_value_release(matrix); + hmath_value_release(raw); + hmath_value_release(array); + hmath_value_release(values); + hmath_value_release(decoded); + hmath_value_release(parser); + hmath_value_release(data); + hmath_value_release(program); + hmath_value_release(scalar); + } + char path[] = "/tmp/hmath-interchange-c-XXXXXX"; + int descriptor = mkstemp(path); + CHECK(descriptor >= 0); + const unsigned char raw_words[] = {255, 255, 255, 255, 255, 255, 255, 255, + 1, 0, 0, 0, 0, 0, 32, 0}; + CHECK(write(descriptor, raw_words, sizeof raw_words) == (ssize_t)sizeof raw_words); + CHECK(close(descriptor) == 0); + hmath_value *prototype = NULL, *native_path = text_value(path), *specification = NULL, + *data_type = NULL, *flat_shape = NULL, *indices = NULL, *callback = NULL, + *result = NULL; + CHECK(hmath_value_integral(NULL, HMATH_COEFFICIENT_UINT64, "0", &prototype) == HMATH_OK); + CHECK(hmath_interchange_value_element_type(NULL, prototype, &data_type) == HMATH_OK); + const hmath_value *flat_dimensions[] = {two}, *index_items[] = {one}; + CHECK(hmath_value_list(NULL, flat_dimensions, 1, &flat_shape) == HMATH_OK); + CHECK(hmath_value_list(NULL, index_items, 1, &indices) == HMATH_OK); + CHECK(hmath_interchange_value_raw_spec(NULL, data_type, little, order, flat_shape, + &specification) == HMATH_OK); + struct mapped_state state = {prototype, indices, index_value(0), index_value(16), NULL, 0}; + CHECK(hmath_linear_callback(NULL, mapping_callback, &state, &callback) == HMATH_OK); + CHECK(hmath_interchange_value_with_mapped_array(NULL, limits, specification, native_path, + callback, &result) == HMATH_OK); + hmath_value *number = NULL, *copied = NULL; + CHECK(hmath_value_item(NULL, result, 0, &number) == HMATH_OK); + exact_is(number, "9007199254740993"); + CHECK(hmath_value_item(NULL, result, 1, &copied) == HMATH_OK); + const unsigned char *bytes = NULL; + size_t size = 0; + CHECK(hmath_bytes_data(copied, &bytes, &size) == HMATH_OK && size == 16 && + memcmp(bytes, raw_words, 16) == 0); + hmath_value *sentinel = one; + CHECK(hmath_interchange_value_mapped_read_bytes(NULL, state.escaped, state.zero, state.size, + &sentinel) == HMATH_INTERCHANGE_ERROR && + sentinel == one); + hmath_interchange_error interchange; + CHECK(hmath_last_interchange_error(&interchange) == 1 && + interchange.kind == HMATH_INTERCHANGE_INVALID_DATA && interchange.message_length == 17 && + memcmp(interchange.message, "mapping is closed", 17) == 0); + hmath_value_release(number); + hmath_value_release(copied); + hmath_value_release(result); + for (int status = HMATH_MATH_ERROR; status <= HMATH_INTERCHANGE_ERROR; ++status) { + state.failure = status; + sentinel = one; + CHECK(hmath_interchange_value_with_mapped_array(NULL, limits, specification, native_path, + callback, + &sentinel) == (hmath_status)status && + sentinel == one); + if (status == HMATH_MATH_ERROR) { + hmath_math_error failure; + CHECK(hmath_last_math_error(&failure) == 1 && + failure.kind == HMATH_MATH_NON_CONVERGENCE && failure.details[0] == 17 && + failure.message_length == 11); + } else if (status == HMATH_EXPRESSION_ERROR) { + hmath_expression_error failure; + CHECK(hmath_last_expression_error(&failure) == 1 && + failure.kind == HMATH_EXPRESSION_TYPE_MISMATCH && failure.source_offset == 19 && + failure.source_line == 3 && failure.source_column == 5 && + failure.message_length == 11); + } else + CHECK(hmath_last_interchange_error(&interchange) == 1 && + interchange.kind == HMATH_INTERCHANGE_INVALID_DATA && + interchange.message_length == 11); + hmath_value *expired = one; + CHECK(hmath_interchange_value_mapped_read_bytes(NULL, state.escaped, state.zero, state.size, + &expired) == HMATH_INTERCHANGE_ERROR && + expired == one); + } + CHECK(unlink(path) == 0); + hmath_value_release(state.escaped); + hmath_value_release(state.zero); + hmath_value_release(state.size); + hmath_value_release(callback); + hmath_value_release(indices); + hmath_value_release(specification); + hmath_value_release(flat_shape); + hmath_value_release(data_type); + hmath_value_release(prototype); + hmath_value_release(native_path); + hmath_value_release(limits); + hmath_value_release(big); + hmath_value_release(little); + hmath_value_release(order); + hmath_value_release(one); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(shape); + hmath_value_release(two); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/interchange_contracts.cpp b/test/native/interchange_contracts.cpp new file mode 100644 index 0000000..768dbf1 --- /dev/null +++ b/test/native/interchange_contracts.cpp @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: MPL-2.0 +// Compile the independent public C client as C++17 too. +#include "interchange_contracts.c" diff --git a/test/native/kernel_storage.c b/test/native/kernel_storage.c new file mode 100644 index 0000000..fc553f0 --- /dev/null +++ b/test/native/kernel_storage.c @@ -0,0 +1,127 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Link with cbits/native.c and this deterministic boundary spy, without GHC. + * These checks verify input borrowing and result ownership, not numerics. */ +#include "native_internal.h" +#include +#include +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static unsigned calls, freed; +static int failure; +static const double *seen_a, *seen_b; +static double *seen_output; +static double observed[4]; +static hmath_context *cancel_after_kernel; +hmath_status hm_enter(hmath_context *context) { + if (hm_cancelled(context)) + return hm_error(HMATH_CANCELLED, "cancelled"); + ++calls; + return HMATH_OK; +} +void hm_leave(void) { + CHECK(calls > 0); + --calls; +} +int hm_haskell_kernel(int op, const double *a, const double *b, size_t n, size_t rows, size_t inner, + size_t columns, double *out) { + seen_a = a; + seen_b = b; + seen_output = out; + for (size_t i = 0; i < n && i < 4; ++i) + observed[i] = a[i]; + if (cancel_after_kernel) + hmath_context_cancel(cancel_after_kernel); + if (failure) + return failure; + if (op == 1 || op == 2) { + *out = 0; + for (size_t i = 0; i < n; ++i) + *out += op == 1 ? a[i] : a[i] * b[i]; + } else if (op == 3) { + for (size_t i = 0; i < n; ++i) + out[i] = a[i] + b[i]; + } else if (op == 4) { + for (size_t i = 0; i < rows; ++i) + for (size_t j = 0; j < columns; ++j) { + double value = 0; + for (size_t k = 0; k < inner; ++k) + value += a[i * inner + k] * b[k * columns + j]; + out[i * columns + j] = value; + } + } else + CHECK(0); + return 0; +} +static void released(void *user, const double *data) { + CHECK(user == &freed); + CHECK(data != NULL); + ++freed; +} +int main(void) { + double plain[] = {1, 2, 3, 4}, strided[] = {1, 99, 2, 99, 3, 99, 4}; + size_t shape[] = {2, 2}, strides[] = {4, 2}; + hmath_tensor *a = NULL, *b = NULL, *sparse = NULL, *result = NULL; + CHECK(hmath_tensor_borrow(plain, 4, shape, NULL, 2, released, &freed, &a) == HMATH_OK); + CHECK(hmath_tensor_borrow(plain, 4, shape, NULL, 2, released, &freed, &b) == HMATH_OK); + CHECK(hmath_tensor_borrow(strided, 7, shape, strides, 2, NULL, NULL, &sparse) == HMATH_OK); + double value = 0; + CHECK(hmath_tensor_sum(NULL, a, &value) == HMATH_OK && value == 10); + CHECK(seen_a == plain && seen_b == NULL && calls == 0 && freed == 0); + CHECK(hmath_tensor_dot(NULL, a, b, &value) == HMATH_OK && value == 30); + CHECK(seen_a == plain && seen_b == plain && calls == 0); + CHECK(hmath_tensor_sum(NULL, sparse, &value) == HMATH_OK && value == 10); + CHECK(seen_a != strided && observed[0] == 1 && observed[1] == 2 && observed[2] == 3 && + observed[3] == 4); + CHECK(hmath_tensor_add(NULL, a, b, &result) == HMATH_OK); + const double *data = NULL; + size_t count = 0; + CHECK(hmath_tensor_data(result, &data, &count) == HMATH_OK && count == 4); + CHECK(data == seen_output && data[0] == 2 && data[3] == 8); + CHECK(seen_a == plain && seen_b == plain && (uintptr_t)data % 64 == 0); + hmath_tensor_release(result); + result = NULL; + CHECK(hmath_tensor_matmul(NULL, sparse, b, &result) == HMATH_OK); + CHECK(seen_a != strided && seen_b == plain); + CHECK(hmath_tensor_data(result, &data, &count) == HMATH_OK && data == seen_output); + CHECK(data[0] == 7 && data[1] == 10 && data[2] == 15 && data[3] == 22); + hmath_tensor_release(result); + result = NULL; + failure = HMATH_OVERFLOW; + CHECK(hmath_tensor_add(NULL, a, b, &result) == HMATH_OVERFLOW && result == NULL && calls == 0); + failure = 0; + CHECK(hmath_context_create(&cancel_after_kernel) == HMATH_OK); + CHECK(hmath_tensor_matmul(cancel_after_kernel, a, b, &result) == HMATH_CANCELLED && + result == NULL && calls == 0); + hmath_context_release(cancel_after_kernel); + cancel_after_kernel = NULL; + /* Empty borrowed storage may be NULL; synchronous kernels do not read it. */ + hmath_tensor *empty = NULL; + size_t empty_shape[] = {0}; + CHECK(hmath_tensor_borrow(NULL, 0, empty_shape, NULL, 1, NULL, NULL, &empty) == HMATH_OK); + CHECK(hmath_tensor_sum(NULL, empty, &value) == HMATH_OK && value == 0 && seen_a == NULL); + CHECK(hmath_tensor_add(NULL, empty, empty, &result) == HMATH_OK); + CHECK(hmath_tensor_data(result, &data, &count) == HMATH_OK && count == 0 && + data == seen_output); + hmath_tensor_release(result); + hmath_tensor_release(empty); + hmath_tensor *view = NULL; + size_t flat[] = {4}; + CHECK(hmath_tensor_reshape(a, flat, 1, &view) == HMATH_OK); + hmath_tensor_release(a); + CHECK(freed == 0); + hmath_tensor_release(view); + CHECK(freed == 1); + hmath_tensor_release(b); + CHECK(freed == 2); + hmath_tensor_release(sparse); + CHECK(calls == 0); + return 0; +} diff --git a/test/native/linear_bindings.py b/test/native/linear_bindings.py new file mode 100644 index 0000000..4a6f26e --- /dev/null +++ b/test/native/linear_bindings.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exact/complex contracts, typed callbacks and direct original Backend policy.""" + +import sys +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import backend as b +from _hmath_native import matrix as m +from _hmath_native import matrix_advanced as a +from _hmath_native import sparse as s +from _hmath_native import vector as v +from _hmath_native._math_error import MathError, MathErrorKind + +with v.Vector([10**6000 + 1, 2], dtype="integer") as x: + assert v.vector_dot(x, x) == (10**6000 + 1) ** 2 + 4 +with s.sparse( + 2, 2, [(0, 0, Fraction(1, 3)), (0, 0, Fraction(1, 7)), (1, 1, 2)], dtype="rational" +) as sparse: + assert s.sparse_entries(sparse) == [(0, 0, Fraction(10, 21)), (1, 1, 2)] + dense = s.sparse_to_dense(sparse) +assert dense.dtype == "rational" and dense.to_list() == [Fraction(10, 21), 0, 0, 2] +dense.close() +with s.sparse( + 2, 2, [(0, 0, complex(1, 2)), (1, 1, complex(3, -1))], dtype="complex64" +) as sparse: + result = s.spmm(sparse, sparse) +assert s.sparse_entries(result) == [(0, 0, complex(-3, 4)), (1, 1, complex(8, -6))] +result.close() +with v.FixedVector(2, [1, 2], dtype="integer") as fixed: + assert v.fixed_values(fixed) == [1, 2] +try: + v.FixedVector(2, [1], dtype="integer") +except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.INVALID_ARGUMENT +else: + raise AssertionError("KnownNat length mismatch changed") +calls = [] +with a.generate_matrix( + 2, 3, lambda row, col: (calls.append((row, col)), row + col)[1], dtype="integer" +) as matrix: + assert matrix.to_list() == [0, 1, 2, 1, 2, 3] +assert calls == [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)] +with ( + m.from_list_checked(1, 1, [16777216], dtype="float32") as left, + m.from_list_checked(1, 1, [1], dtype="integer") as right, +): + output = a.zip_matrix_with(lambda x, y: x + y, left, right, dtype="float32") +assert output.dtype == "float32" and output.to_list() == [16777216] +output.close() +message = "linear\0α🙂\ud800" + + +def original_error(*_): + raise MathError(MathErrorKind.NON_CONVERGENCE, (7,), message) + + +try: + a.generate_matrix(1, 1, original_error) +except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.NON_CONVERGENCE + assert error.math_error.details == (7,) and error.math_error.message == message +else: + raise AssertionError("pure callback original error swallowed") + + +class BrokenMessage(Exception): + def __str__(self): + raise ValueError("formatter failed") + + +sentinel = BrokenMessage() + + +def unexpected(*_): + raise sentinel + + +try: + a.generate_matrix(1, 1, unexpected) +except BrokenMessage as error: + assert error is sentinel +else: + raise AssertionError("callback exception was swallowed") +with ( + b.pure_backend() as backend, + b.no_transpose() as no_transpose, + m.from_list_checked(1, 1, [1.0]) as finite, + m.from_list_checked(1, 1, [float("nan")]) as nonfinite, +): + try: + b.gemm(backend, no_transpose, no_transpose, 1.0, finite, finite, 0.0, nonfinite) + except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.NON_FINITE_VECTOR_ENTRY + else: + raise AssertionError("original Backend must validate C even when beta is zero") + lu = b.backend_lu(backend, finite) + qr = b.backend_qr(backend, finite) +assert m.determinant_lu(lu) == 1 and m.qr_rank(qr) == 1 +lu.close() +qr.close() +# A sparse format's public constructor fields remain accessible and exact. +with s.csr( + 2, 2, [0, 1, 2], [0, 1], [Fraction(1, 3), Fraction(2, 7)], dtype="rational" +) as fmt: + assert fmt.parts == ( + "CSR", + (2, 2, [0, 1, 2], [0, 1], [Fraction(1, 3), Fraction(2, 7)]), + ) + sparse = s.from_format(fmt) +assert s.sparse_entries(sparse) == [(0, 0, Fraction(1, 3)), (1, 1, Fraction(2, 7))] +sparse.close() +print("Linear exact/complex/FixedVector/callback/Backend/LU-QR/format contracts passed") diff --git a/test/native/linear_contracts.c b/test/native/linear_contracts.c new file mode 100644 index 0000000..2395bc1 --- /dev/null +++ b/test/native/linear_contracts.c @@ -0,0 +1,83 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_linear.h" +#include "hmath_matrix_value.h" +#include +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static hmath_status callback(const hmath_value *input, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)error; + hmath_value *row = NULL, *column = NULL; + ptrdiff_t r = -1, c = -1; + CHECK(hmath_value_item(NULL, input, 0, &row) == HMATH_OK); + CHECK(hmath_value_item(NULL, input, 1, &column) == HMATH_OK); + CHECK(hmath_value_get_index(row, &r) == HMATH_OK && + hmath_value_get_index(column, &c) == HMATH_OK); + hmath_value_release(row); + hmath_value_release(column); + ++*(int *)userdata; + return hmath_value_f32(NULL, (float)(r + c), out); +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *prototype = NULL, *rows = NULL, *columns = NULL, *function = NULL, *matrix = NULL, + *type = NULL; + CHECK(hmath_value_f32(NULL, 0, &prototype) == HMATH_OK); + CHECK(hmath_value_index(NULL, 2, &rows) == HMATH_OK); + CHECK(hmath_value_index(NULL, 3, &columns) == HMATH_OK); + int calls = 0; + CHECK(hmath_linear_callback(NULL, callback, &calls, &function) == HMATH_OK); + CHECK(hmath_linear_matrix_advanced_generate_matrix(NULL, prototype, rows, columns, function, + &matrix) == HMATH_OK && + calls == 6); + hmath_value_release(function); + int kind = -1, dtype = -1; + size_t count = 99; + CHECK(hmath_value_info(matrix, &kind, &dtype, &count) == HMATH_OK && kind == 9 && dtype == 1 && + count == 6); + hmath_dense_matrix *dense = NULL; + CHECK(hmath_dense_from_value(NULL, matrix, &dense) == HMATH_OK && + hmath_dense_precision(dense) == 32); + hmath_value_release(matrix); + float values[] = {99, 99, 99, 99, 99, 99, 99}; + CHECK(hmath_dense_values_f32(NULL, dense, values, 6) == HMATH_OK && values[0] == 0 && + values[1] == 1 && values[5] == 3 && values[6] == 99); + hmath_dense_release(dense); + /* Original KnownNat mismatch is checked, not a changed dynamic-vector API. */ + hmath_value *element = NULL, *list = NULL, *fixed = NULL; + CHECK(hmath_value_f32(NULL, 1, &element) == HMATH_OK); + const hmath_value *items[] = {element}; + CHECK(hmath_value_list(NULL, items, 1, &list) == HMATH_OK); + CHECK(hmath_linear_vector_fixed_vector(NULL, prototype, rows, list, &fixed) == + HMATH_MATH_ERROR && + fixed == NULL); + hmath_math_error math; + CHECK(hmath_last_math_error(&math) == 1 && math.kind == HMATH_MATH_INVALID_ARGUMENT); + hmath_value_release(list); + hmath_value_release(element); + /* An immutable backend/record handle pins the runtime independently. */ + hmath_value *backend = NULL, *info = NULL; + CHECK(hmath_linear_backend_pure_backend(NULL, &backend) == HMATH_OK); + CHECK(hmath_linear_backend_backend_info(NULL, backend, &info) == HMATH_OK); + hmath_value_release(backend); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + CHECK(hmath_linear_object_type(NULL, info, &type) == HMATH_OK); + CHECK(hmath_value_info(type, &kind, &dtype, &count) == HMATH_OK && kind == 10 && count == 25); + uint32_t text[25]; + CHECK(hmath_value_get_text(type, text, 25) == HMATH_OK && text[0] == 'H' && text[24] == 'o'); + hmath_value_release(type); + hmath_value_release(info); + hmath_value_release(rows); + hmath_value_release(columns); + hmath_value_release(prototype); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/machinelearning.c b/test/native/machinelearning.c new file mode 100644 index 0000000..bf82282 --- /dev/null +++ b/test/native/machinelearning.c @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_machinelearning.h" +#include "hmath_error.h" +#include +#include +#include +#include +static hmath_status score(const hmath_value *arguments, void *userdata, + hmath_value **out, hmath_math_error *error) { + (void)userdata; + (void)error; + hmath_value *parameter = NULL, *fold = NULL, *indices = NULL; + double real = 0, imaginary = 0; + hmath_status status = hmath_value_item(NULL, arguments, 0, ¶meter); + if (!status) status = hmath_value_get_f64(parameter, &real, &imaginary); + if (!status) status = hmath_value_item(NULL, arguments, 1, &fold); + if (!status) status = hmath_ml_validation_indices(NULL, fold, &indices); + int kind = 0, dtype = 0; + size_t count = 0; + if (!status) status = hmath_value_info(indices, &kind, &dtype, &count); + hmath_value_release(parameter); + hmath_value_release(fold); + hmath_value_release(indices); + return status ? status : hmath_value_f64(NULL, real + (double)count, out); +} +static hmath_status domain(const hmath_value *arguments, void *userdata, + hmath_value **out, hmath_math_error *error) { + (void)arguments; + (void)userdata; + (void)out; + memset(error, 0, sizeof *error); + error->kind = HMATH_MATH_DOMAIN_ERROR; + error->message = "validation failed"; + error->message_length = strlen(error->message); + return HMATH_MATH_ERROR; +} +int main(void) { + hmath_value *one = NULL, *two = NULL, *zero_index = NULL, *one_index = NULL; + hmath_value *training = NULL, *validation = NULL, *fold = NULL, *folds = NULL; + hmath_value *candidates = NULL, *callback = NULL, *result = NULL, *child = NULL; + hmath_value *unchanged = (hmath_value *)(uintptr_t)1; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_f64(NULL, 1, &one) == HMATH_OK); + assert(hmath_value_f64(NULL, 2, &two) == HMATH_OK); + assert(hmath_value_index(NULL, 0, &zero_index) == HMATH_OK); + assert(hmath_value_index(NULL, 1, &one_index) == HMATH_OK); + const hmath_value *training_values[] = {zero_index}, *validation_values[] = {one_index}; + assert(hmath_value_list(NULL, training_values, 1, &training) == HMATH_OK); + assert(hmath_value_list(NULL, validation_values, 1, &validation) == HMATH_OK); + assert(hmath_ml_fold(NULL, training, validation, &fold) == HMATH_OK); + const hmath_value *fold_values[] = {fold}, *parameters[] = {two, one}; + assert(hmath_value_list(NULL, fold_values, 1, &folds) == HMATH_OK); + assert(hmath_value_list(NULL, parameters, 2, &candidates) == HMATH_OK); + assert(hmath_linear_callback(NULL, score, NULL, &callback) == HMATH_OK); + assert(hmath_ml_grid_search(NULL, candidates, folds, callback, &result) == HMATH_OK); + assert(hmath_value_item(NULL, result, 0, &child) == HMATH_OK); + double real = 0, imaginary = 0; + assert(hmath_value_get_f64(child, &real, &imaginary) == HMATH_OK && real == 1); + hmath_value_release(child); + hmath_value_release(result); + hmath_value_release(callback); + assert(hmath_linear_callback(NULL, domain, NULL, &callback) == HMATH_OK); + assert(hmath_ml_grid_search(NULL, candidates, folds, callback, &unchanged) == HMATH_MATH_ERROR); + assert(unchanged == (hmath_value *)(uintptr_t)1); + hmath_math_error error; + assert(hmath_last_math_error(&error) && error.kind == HMATH_MATH_DOMAIN_ERROR); + assert(error.message_length == 17 && memcmp(error.message, "validation failed", 17) == 0); + hmath_value_release(callback); + hmath_value *large = NULL, *small = NULL, *labels = NULL, *encoder = NULL, *codes = NULL; + assert(hmath_value_integer(NULL, "100000000000000000000000000000000000000000000000003", &large) == HMATH_OK); + assert(hmath_value_integer(NULL, "1", &small) == HMATH_OK); + const hmath_value *label_values[] = {large, small, large}; + assert(hmath_value_list(NULL, label_values, 3, &labels) == HMATH_OK); + assert(hmath_ml_fit_encoder(NULL, labels, NULL, &encoder) == HMATH_OK); + assert(hmath_ml_label_encode(NULL, encoder, labels, &codes) == HMATH_OK); + assert(hmath_ml_label_decode(NULL, encoder, codes, &result) == HMATH_OK); + hmath_value_release(encoder); + assert(hmath_value_item(NULL, result, 0, &child) == HMATH_OK); + char *numerator = NULL, *denominator = NULL; + assert(hmath_value_get_exact(child, &numerator, &denominator) == HMATH_OK); + assert(strcmp(numerator, "100000000000000000000000000000000000000000000000003") == 0); + hmath_value_string_free(numerator); + hmath_value_string_free(denominator); + hmath_value_release(child); + hmath_value_release(result); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(codes); + hmath_value_release(labels); + hmath_value_release(large); + hmath_value_release(small); + hmath_value_release(fold); + hmath_value_release(folds); + hmath_value_release(candidates); + hmath_value_release(training); + hmath_value_release(validation); + hmath_value_release(zero_index); + hmath_value_release(one_index); + hmath_value_release(one); + hmath_value_release(two); + assert(hmath_runtime_shutdown() == HMATH_OK); + puts("ML C checked callbacks, exact label dictionaries, independent ownership and output contracts passed."); + return 0; +} diff --git a/test/native/matrix_contracts.c b/test/native/matrix_contracts.c new file mode 100644 index 0000000..df3a42d --- /dev/null +++ b/test/native/matrix_contracts.c @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_matrix.h" +#include +#include +#include +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +int main(void) { + CHECK(hmath_init() == 0); + double data[] = {4, 2, 1, 3}; + hmath_dense_matrix *matrix = NULL, *none = NULL, *transposed = NULL; + CHECK(hmath_dense_from_list_checked_f64(NULL, 2, 2, data, 4, &matrix) == HMATH_OK); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + CHECK(hmath_dense_precision(matrix) == 64); + CHECK(hmath_dense_from_list_f64(NULL, 2, 3, data, 4, &none) == HMATH_OK && none == NULL); + CHECK(hmath_last_error_code() == HMATH_OK); + CHECK(hmath_dense_from_list_checked_f64(NULL, 2, 3, data, 4, &none) == HMATH_MATH_ERROR && + none == NULL); + CHECK(strcmp(hmath_last_error_message(), "ElementCountMismatch 6 4") == 0); + ptrdiff_t rows = -1, columns = -1; + CHECK(hmath_dense_shape(NULL, matrix, &rows, &columns) == HMATH_OK && rows == 2 && + columns == 2); + CHECK(hmath_last_error_code() == HMATH_OK); + double value = 99; + int found = 99; + CHECK(hmath_dense_at_f64(NULL, matrix, 2, 0, &value, &found) == HMATH_OK && found == 0 && + value == 99); + CHECK(hmath_dense_at_checked_f64(NULL, matrix, 2, 0, &value) == HMATH_MATH_ERROR && + value == 99); + double out[] = {99, 99, 99, 99, 99}; + CHECK(hmath_dense_values_f64(NULL, matrix, out, 3) == HMATH_BOUNDS_ERROR && out[0] == 99 && + out[4] == 99); + CHECK(hmath_dense_values_f64(NULL, matrix, out, 4) == HMATH_OK && out[0] == 4 && out[3] == 3 && + out[4] == 99); + hmath_dense_lu *lu = NULL; + CHECK(hmath_dense_lu_lu_decompose_f64(NULL, matrix, &lu) == HMATH_OK); + hmath_dense_release(matrix); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + CHECK(hmath_dense_lu_determinant_lu_f64(NULL, lu, &value) == HMATH_OK && + fabs(value - 10) < 1e-12); + hmath_dense_indices *permutation = NULL; + CHECK(hmath_dense_lu_lu_permutation_f64(NULL, lu, &permutation) == HMATH_OK); + ptrdiff_t indices[] = {-1, -1, -1}; + CHECK(hmath_dense_indices_copy(NULL, permutation, indices, 1) == HMATH_BOUNDS_ERROR && + indices[0] == -1); + CHECK(hmath_dense_indices_copy(NULL, permutation, indices, 2) == HMATH_OK && indices[0] == 0 && + indices[1] == 1 && indices[2] == -1); + hmath_dense_release(permutation); + hmath_dense_release(lu); + CHECK(hmath_dense_from_list_checked_f64(NULL, 0, PTRDIFF_MAX, NULL, 0, &matrix) == HMATH_OK); + CHECK(hmath_dense_transpose_matrix_f64(NULL, matrix, &transposed) == HMATH_OK); + CHECK(hmath_dense_shape(NULL, transposed, &rows, &columns) == HMATH_OK && rows == PTRDIFF_MAX && + columns == 0); + hmath_dense_release(matrix); + hmath_dense_release(transposed); + float f[] = {16777216, 1}; + CHECK(hmath_dense_from_list_checked_f32(NULL, 1, 2, f, 2, &matrix) == HMATH_OK); + CHECK(hmath_dense_precision(matrix) == 32); + CHECK(hmath_dense_lu_determinant_f64(NULL, matrix, &value) == HMATH_INVALID_ARGUMENT); + hmath_dense_release(matrix); + hmath_dense_release(NULL); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/numeric_contracts.c b/test/native/numeric_contracts.c new file mode 100644 index 0000000..690acdc --- /dev/null +++ b/test/native/numeric_contracts.c @@ -0,0 +1,85 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_numeric.h" +#include "hmath_optimization.h" +#include +#include +#include +#include + +#define CHECK(test) \ + do { \ + if (!(test)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #test, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) + +int main(void) { + double output = 123.0; + CHECK(hmath_scalar_hypot_f64(NULL, 3, 4, &output) == HMATH_RUNTIME_ERROR); + CHECK(output == 123.0); + CHECK(hmath_init() == HMATH_INIT_OK); + CHECK(hmath_scalar_divide_f64(NULL, 1, 0, &output) == HMATH_MATH_ERROR); + CHECK(output == 123.0); + CHECK(strcmp(hmath_last_error_message(), "DomainError \"division by zero\"") == 0); + CHECK(hmath_constants_infinity_f64(NULL, &output) == HMATH_OK && isinf(output)); + CHECK(hmath_scalar_add_f64(NULL, INFINITY, 1, &output) == HMATH_OK && isinf(output)); + CHECK(hmath_scalar_hypot_f64(NULL, 3, 4, NULL) == HMATH_INVALID_ARGUMENT); + + float single = 123.0f; + CHECK(hmath_scalar_add_f32(NULL, 16777216.0f, 1.0f, &single) == HMATH_OK); + CHECK(single == 16777216.0f); + CHECK(hmath_scalar_add_f64(NULL, 16777216.0, 1.0, &output) == HMATH_OK); + CHECK(output == 16777217.0); + + double values[] = {1, 2, 3}, prefix[] = {99, 99, 99, 99, 99}; + CHECK(hmath_scalar_prefix_sum_f64(NULL, values, 3, prefix, 3) == HMATH_BOUNDS_ERROR); + CHECK(prefix[0] == 99 && prefix[3] == 99 && prefix[4] == 99); + CHECK(hmath_scalar_prefix_sum_f64(NULL, values, 3, prefix, 4) == HMATH_OK); + CHECK(prefix[0] == 0 && prefix[1] == 1 && prefix[2] == 3 && prefix[3] == 6 && prefix[4] == 99); + CHECK(hmath_scalar_prefix_sum_f64(NULL, NULL, 0, NULL, 0) == HMATH_BOUNDS_ERROR); + CHECK(hmath_scalar_prefix_sum_f64(NULL, NULL, 0, prefix, 1) == HMATH_OK && prefix[0] == 0); + + char *integer = NULL; + CHECK(hmath_basic_factorial(NULL, "100", &integer) == HMATH_OK); + CHECK(strlen(integer) == 158 && strncmp(integer, "933262154439", 12) == 0); + hmath_numeric_string_free(integer); + integer = NULL; + CHECK(hmath_basic_factorial(NULL, "-1", &integer) == HMATH_HASKELL_EXCEPTION); + CHECK(integer == NULL); + CHECK(hmath_basic_factorial(NULL, "1oops", &integer) == HMATH_INVALID_ARGUMENT); + CHECK(integer == NULL); + + hmath_context *context = NULL; + CHECK(hmath_context_create(&context) == HMATH_OK); + hmath_context_cancel(context); + output = 99; + CHECK(hmath_scalar_hypot_f64(context, 3, 4, &output) == HMATH_CANCELLED && output == 99); + hmath_context_release(context); + + hmath_optimizer_state *state = NULL, *next = NULL; + CHECK(hmath_initialize_optimizer(NULL, -1, &state) == HMATH_MATH_ERROR); + CHECK(state == NULL); + CHECK(hmath_initialize_optimizer(NULL, 1, &state) == HMATH_OK); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + double parameter = 1, gradient = 2, updated = 99; + CHECK(hmath_optimizer_step(NULL, HMATH_ADAM, 0.1, state, ¶meter, 1, &gradient, 0, &updated, + 1, &next) == HMATH_MATH_ERROR); + CHECK(updated == 99 && next == NULL); + CHECK(hmath_optimizer_step(NULL, HMATH_ADAM, 0.1, state, ¶meter, 1, &gradient, 1, &updated, + 0, &next) == HMATH_BOUNDS_ERROR); + CHECK(updated == 99 && next == NULL); + CHECK(hmath_optimizer_step(NULL, HMATH_ADAM, 0.1, state, ¶meter, 1, &gradient, 1, &updated, + 1, &next) == HMATH_OK); + CHECK(fabs(updated - 0.9) < 1e-8); + hmath_optimizer_state_retain(state); + hmath_optimizer_state_release(state); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_optimizer_state_release(state); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_optimizer_state_release(next); + hmath_optimizer_state_release(NULL); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/numeric_contracts.cpp b/test/native/numeric_contracts.cpp new file mode 100644 index 0000000..336b7bb --- /dev/null +++ b/test/native/numeric_contracts.cpp @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: MPL-2.0 +// The same public contract must compile and run through the C++ ABI. +#include "numeric_contracts.c" diff --git a/test/native/numeric_objects_contracts.c b/test/native/numeric_objects_contracts.c new file mode 100644 index 0000000..aaaea2f --- /dev/null +++ b/test/native/numeric_objects_contracts.c @@ -0,0 +1,272 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_autodiff.h" +#include "hmath_error.h" +#include "hmath_numeric_objects.h" +#include "hmath_numeric_types.h" +#include +#include +#include +#include +#include + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #condition, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +typedef hmath_status (*unary_value)(hmath_context *, const hmath_value *, const hmath_value *, + hmath_value **); +typedef hmath_status (*binary_value)(hmath_context *, const hmath_value *, const hmath_value *, + const hmath_value *, hmath_value **); +static double scalar(const hmath_value *value) { + double real = 0, imaginary = 1; + CHECK(hmath_value_get_f64(value, &real, &imaginary) == HMATH_OK && imaginary == 0); + return real; +} +static hmath_value *item(const hmath_value *value, ptrdiff_t index) { + hmath_value *out = NULL; + CHECK(hmath_value_item(NULL, value, index, &out) == HMATH_OK); + return out; +} +static void metadata(const hmath_value *value, int expected_kind, int expected_dtype, + size_t expected_length) { + int kind = -1, dtype = -1; + size_t count = 99; + CHECK(hmath_value_info(value, &kind, &dtype, &count) == HMATH_OK && kind == expected_kind && + dtype == expected_dtype && count == expected_length); +} +static void dual_parts(const hmath_value *value, double expected_primal, double expected_tangent) { + hmath_value *a = NULL, *b = NULL; + CHECK(hmath_numeric_types_primal(NULL, value, &a) == HMATH_OK); + CHECK(hmath_numeric_types_tangent(NULL, value, &b) == HMATH_OK); + CHECK(scalar(a) == expected_primal && scalar(b) == expected_tangent); + hmath_value_release(a); + hmath_value_release(b); +} +static void exact_is(const hmath_value *value, const char *expected) { + char *n = NULL, *d = NULL; + CHECK(hmath_value_get_exact(value, &n, &d) == HMATH_OK && strcmp(n, expected) == 0 && + strcmp(d, "1") == 0); + hmath_value_string_free(n); + hmath_value_string_free(d); +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *x = NULL, *y = NULL, *half = NULL, *empty = NULL, *list = NULL, *result = NULL; + CHECK(hmath_value_f64(NULL, 2, &x) == HMATH_OK); + CHECK(hmath_value_f64(NULL, 3, &y) == HMATH_OK); + CHECK(hmath_value_f64(NULL, 0.5, &half) == HMATH_OK); + CHECK(hmath_value_list(NULL, NULL, 0, &empty) == HMATH_OK); + const hmath_value *values[] = {x, y}; + CHECK(hmath_value_list(NULL, values, 2, &list) == HMATH_OK); + CHECK(hmath_basic_clamp_value(NULL, x, x, y, half, &result) == HMATH_OK && scalar(result) == 2); + hmath_value_release(result); + CHECK(hmath_basic_lerp_value(NULL, x, x, y, half, &result) == HMATH_OK && + scalar(result) == 2.5); + hmath_value_release(result); + const binary_value binaries[] = {hmath_scalar_add_value, hmath_scalar_subtract_scalar_value, + hmath_scalar_multiply_value, hmath_scalar_minimum_scalar_value, + hmath_scalar_maximum_scalar_value}; + const double expected_binary[] = {5, -1, 6, 2, 3}; + for (size_t i = 0; i < sizeof binaries / sizeof *binaries; ++i) { + CHECK(binaries[i](NULL, x, x, y, &result) == HMATH_OK && + scalar(result) == expected_binary[i]); + hmath_value_release(result); + } + const unary_value unary[] = {hmath_scalar_absolute_value, hmath_scalar_sign_value}; + for (size_t i = 0; i < sizeof unary / sizeof *unary; ++i) { + CHECK(unary[i](NULL, x, x, &result) == HMATH_OK && scalar(result) == (i ? 1 : 2)); + hmath_value_release(result); + } + const unary_value scans[] = {hmath_scalar_cumulative_sum_value, + hmath_scalar_cumulative_product_value, + hmath_scalar_prefix_sum_value}; + const double expected_scan[] = {5, 6, 5}; + for (size_t i = 0; i < sizeof scans / sizeof *scans; ++i) { + CHECK(scans[i](NULL, x, list, &result) == HMATH_OK); + hmath_value *last = item(result, i == 2 ? 2 : 1); + CHECK(scalar(last) == expected_scan[i]); + hmath_value_release(last); + hmath_value_release(result); + } + const unary_value statistics[] = {hmath_statistics_mean_value, hmath_statistics_variance_value, + hmath_statistics_standard_deviation_value, + hmath_statistics_median_value}; + const double expected_stats[] = {2.5, 0.25, 0.5, 2.5}; + for (size_t i = 0; i < sizeof statistics / sizeof *statistics; ++i) { + CHECK(statistics[i](NULL, x, list, &result) == HMATH_OK && + scalar(result) == expected_stats[i]); + hmath_value_release(result); + hmath_value *sentinel = x; + CHECK(statistics[i](NULL, x, empty, &sentinel) == HMATH_HASKELL_EXCEPTION && sentinel == x); + } + CHECK(hmath_linear_dot_value(NULL, x, list, list, &result) == HMATH_OK && scalar(result) == 13); + hmath_value_release(result); + CHECK(hmath_linear_dot_checked_value(NULL, x, list, list, &result) == HMATH_OK && + scalar(result) == 13); + hmath_value_release(result); + CHECK(hmath_linear_magnitude_value(NULL, x, list, &result) == HMATH_OK && + scalar(result) == sqrt(13)); + hmath_value_release(result); + CHECK(hmath_linear_normalize_value(NULL, x, list, &result) == HMATH_OK); + hmath_value *first = item(result, 0); + CHECK(scalar(first) == 2 / sqrt(13)); + hmath_value_release(first); + hmath_value_release(result); + const binary_value linear[] = {hmath_linear_add_value, hmath_linear_add_checked_value, + hmath_linear_subtract_checked_value}; + for (size_t i = 0; i < sizeof linear / sizeof *linear; ++i) { + CHECK(linear[i](NULL, x, list, list, &result) == HMATH_OK); + first = item(result, 0); + CHECK(scalar(first) == (i == 2 ? 0 : 4)); + hmath_value_release(first); + hmath_value_release(result); + } + CHECK(hmath_linear_scale_value(NULL, x, x, list, &result) == HMATH_OK); + first = item(result, 1); + CHECK(scalar(first) == 6); + hmath_value_release(first); + hmath_value_release(result); + hmath_value *sentinel = x; + CHECK(hmath_linear_dot_checked_value(NULL, x, list, empty, &sentinel) == HMATH_MATH_ERROR && + sentinel == x); + hmath_math_error error; + CHECK(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_VECTOR_LENGTH_MISMATCH && + error.details[0] == 2 && error.details[1] == 0); + CHECK(hmath_linear_dot_value(NULL, x, list, empty, &sentinel) == HMATH_HASKELL_EXCEPTION && + sentinel == x && strstr(hmath_last_error_message(), "dot: dimension mismatch") != NULL); + hmath_value *bounded = NULL, *unit = NULL; + CHECK(hmath_value_integral(NULL, HMATH_COEFFICIENT_INT8, "127", &bounded) == HMATH_OK); + CHECK(hmath_value_integral(NULL, HMATH_COEFFICIENT_INT8, "1", &unit) == HMATH_OK); + const binary_value bounded_functions[] = { + hmath_scalar_saturating_add_value, hmath_scalar_saturating_subtract_value, + hmath_scalar_saturating_multiply_value, hmath_scalar_checked_add_value, + hmath_scalar_checked_subtract_value, hmath_scalar_checked_multiply_value}; + const char *expected_bounded[] = {"127", "126", "127", NULL, "126", "127"}; + for (size_t i = 0; i < sizeof bounded_functions / sizeof *bounded_functions; ++i) { + sentinel = x; + hmath_status status = bounded_functions[i](NULL, bounded, bounded, unit, &sentinel); + if (expected_bounded[i]) { + CHECK(status == HMATH_OK); + exact_is(sentinel, expected_bounded[i]); + hmath_value_release(sentinel); + } else { + CHECK(status == HMATH_MATH_ERROR && sentinel == x); + CHECK(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_DOMAIN_ERROR); + } + } + CHECK(hmath_scalar_positive_modulo_value(NULL, bounded, bounded, unit, &result) == HMATH_OK); + exact_is(result, "0"); + hmath_value_release(result); + hmath_value_release(bounded); + hmath_value_release(unit); + + /* Both Numeric.Dual components and nested witnesses survive, including an + * empty-list zero selected solely by an explicit original prototype. */ + hmath_value *dual = NULL, *other = NULL, *tangent = NULL, *nested = NULL, *nested_sum = NULL; + CHECK(hmath_value_f64(NULL, 1, &tangent) == HMATH_OK); + CHECK(hmath_numeric_types_dual(NULL, x, tangent, &dual) == HMATH_OK); + CHECK(hmath_numeric_types_dual(NULL, y, x, &other) == HMATH_OK); + CHECK(hmath_scalar_multiply_value(NULL, dual, dual, other, &result) == HMATH_OK); + dual_parts(result, 6, 7); + hmath_value_release(result); + CHECK(hmath_numeric_types_dual(NULL, dual, other, &nested) == HMATH_OK); + CHECK(hmath_scalar_add_value(NULL, nested, nested, nested, &nested_sum) == HMATH_OK); + hmath_value *primal = NULL; + CHECK(hmath_numeric_types_primal(NULL, nested_sum, &primal) == HMATH_OK); + dual_parts(primal, 4, 2); + hmath_value_release(primal); + hmath_value_release(nested_sum); + CHECK(hmath_linear_dot_value(NULL, nested, empty, empty, &result) == HMATH_OK); + CHECK(hmath_numeric_types_primal(NULL, result, &primal) == HMATH_OK); + dual_parts(primal, 0, 0); + hmath_value_release(primal); + hmath_value_release(result); + sentinel = x; + CHECK(hmath_scalar_minimum_scalar_value(NULL, dual, dual, other, &sentinel) == + HMATH_UNSUPPORTED && + sentinel == x); + CHECK(hmath_statistics_median_value(NULL, dual, list, &sentinel) == HMATH_UNSUPPORTED && + sentinel == x); + CHECK(hmath_scalar_positive_modulo_value(NULL, dual, dual, other, &sentinel) == + HMATH_UNSUPPORTED && + sentinel == x); + hmath_value *quaternion = NULL; + CHECK(hmath_numeric_types_quaternion(NULL, x, y, tangent, half, &quaternion) == HMATH_OK); + CHECK(hmath_scalar_multiply_value(NULL, quaternion, quaternion, quaternion, &result) == + HMATH_OK); + metadata(result, 1, 21, 0); + hmath_value_release(result); + sentinel = x; + CHECK(hmath_basic_lerp_value(NULL, quaternion, quaternion, quaternion, quaternion, &sentinel) == + HMATH_UNSUPPORTED && + sentinel == x); + + /* Original AD.Dual is a separate type; its original Ord compares primals + * only, retaining the selected operand's full tangent. */ + hmath_ad_dual *ad_left = NULL, *ad_right = NULL; + hmath_value *ad_value = NULL, *ad_other = NULL; + CHECK(hmath_ad_dual_create(NULL, 2, 7, &ad_left) == HMATH_OK); + CHECK(hmath_ad_dual_create(NULL, 3, 11, &ad_right) == HMATH_OK); + CHECK(hmath_ad_value_import(NULL, ad_left, &ad_value) == HMATH_OK); + CHECK(hmath_ad_value_import(NULL, ad_right, &ad_other) == HMATH_OK); + CHECK(hmath_scalar_minimum_scalar_value(NULL, ad_value, ad_value, ad_other, &result) == + HMATH_OK); + hmath_ad_handle *converted = NULL; + CHECK(hmath_ad_value_export(NULL, result, &converted) == HMATH_OK); + double parts[2]; + CHECK(hmath_ad_values_copy(converted, parts, 2) == HMATH_OK && parts[0] == 2 && parts[1] == 7); + hmath_ad_release(converted); + hmath_value_release(result); + sentinel = x; + CHECK(hmath_scalar_add_value(NULL, dual, dual, ad_value, &sentinel) == HMATH_INVALID_ARGUMENT && + sentinel == x); + + /* Symbolic results remain original graph nodes; Eq-dependent normalization + * is unavailable rather than receiving an invented expression equality. */ + hmath_ad_expr *expression = NULL; + hmath_value *expression_value = NULL; + CHECK(hmath_ad_variable(NULL, 0, &expression) == HMATH_OK); + CHECK(hmath_ad_value_import(NULL, expression, &expression_value) == HMATH_OK); + CHECK(hmath_scalar_multiply_value(NULL, expression_value, expression_value, expression_value, + &result) == HMATH_OK); + metadata(result, 287, 0, 0); + CHECK(hmath_ad_value_export(NULL, result, &converted) == HMATH_OK); + hmath_ad_graph *graph = NULL; + CHECK(hmath_ad_compile_graph(NULL, 1, converted, &graph) == HMATH_OK); + double input = 1.25, output = 0; + CHECK(hmath_ad_evaluate_graph(NULL, graph, &input, 1, &output, 1) == HMATH_OK && + output == 1.5625); + hmath_ad_release(graph); + hmath_ad_release(converted); + hmath_value_release(result); + sentinel = x; + CHECK(hmath_linear_normalize_value(NULL, expression_value, empty, &sentinel) == + HMATH_UNSUPPORTED && + sentinel == x); + CHECK(hmath_scalar_minimum_scalar_value(NULL, expression_value, expression_value, + expression_value, &sentinel) == HMATH_UNSUPPORTED && + sentinel == x); + hmath_value_release(expression_value); + hmath_ad_release(expression); + hmath_value_release(ad_value); + hmath_value_release(ad_other); + hmath_ad_release(ad_left); + hmath_ad_release(ad_right); + hmath_value_release(quaternion); + hmath_value_release(nested); + hmath_value_release(dual); + hmath_value_release(other); + hmath_value_release(tangent); + hmath_value_release(x); + hmath_value_release(y); + hmath_value_release(half); + hmath_value_release(empty); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(list); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/numeric_objects_contracts.cpp b/test/native/numeric_objects_contracts.cpp new file mode 100644 index 0000000..d3ba328 --- /dev/null +++ b/test/native/numeric_objects_contracts.cpp @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: MPL-2.0 +// Compile the same independent public C client as C++17. +#include "numeric_objects_contracts.c" diff --git a/test/native/numeric_types.c b/test/native/numeric_types.c new file mode 100644 index 0000000..507310e --- /dev/null +++ b/test/native/numeric_types.c @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_numeric_types.h" +#include "hmath_error.h" +#include +#include +#include +#include + +static hmath_status square(const hmath_numeric_value *input, void *userdata, + hmath_numeric_value **out) { + (void)userdata; + return hmath_numeric_types_binary(NULL, 2, input, input, out); +} +static hmath_status source_error(const hmath_numeric_value *input, void *userdata, + hmath_numeric_value **out) { + (void)input; + (void)userdata; + return hmath_numeric_types_interval(NULL, 2, 1, out); +} +static hmath_status identity(const hmath_numeric_value *input, void *userdata, + hmath_numeric_value **out) { + (void)userdata; + hmath_numeric_types_retain((hmath_numeric_value *)input); + *out = (hmath_numeric_value *)input; + return HMATH_OK; +} +int main(void) { + hmath_numeric_value *value = NULL, *rounded = NULL, *child = NULL, *result = NULL; + hmath_numeric_value *unchanged = (hmath_numeric_value *)(uintptr_t)1; + double real = 0, imaginary = 0; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_f64(NULL, -2, &value) == HMATH_OK); + assert(hmath_numeric_types_derivative(NULL, square, NULL, value, &result) == HMATH_OK); + assert(hmath_value_get_f64(result, &real, &imaginary) == HMATH_OK && real == -4); + hmath_numeric_types_release(result); + result = NULL; + assert(hmath_numeric_types_derivative(NULL, identity, NULL, value, &result) == HMATH_OK); + assert(hmath_value_get_f64(result, &real, &imaginary) == HMATH_OK && real == 1); + hmath_numeric_types_release(result); + result = NULL; + assert(hmath_numeric_types_derivative(NULL, source_error, NULL, value, &unchanged) == HMATH_MATH_ERROR); + assert(unchanged == (hmath_numeric_value *)(uintptr_t)1); + hmath_math_error error; + assert(hmath_last_math_error(&error)); + assert(error.kind == HMATH_MATH_DOMAIN_ERROR); + assert(error.message_length > 0); + const int flags[] = {HMATH_INEXACT, HMATH_INVALID_OPERATION, HMATH_INEXACT}; + assert(hmath_numeric_types_rounded(NULL, value, flags, 3, &rounded) == HMATH_OK); + assert(hmath_numeric_types_rounded_value(NULL, rounded, &child) == HMATH_OK); + hmath_numeric_types_release(rounded); + hmath_numeric_types_release(value); + rounded = value = NULL; + assert(hmath_value_get_f64(child, &real, &imaginary) == HMATH_OK && real == -2); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_numeric_types_release(child); + child = NULL; + assert(hmath_numeric_types_float16(NULL, HMATH_NEAREST_EVEN, 1.1, &rounded) == HMATH_OK); + assert(hmath_numeric_types_rounded_value(NULL, rounded, &child) == HMATH_OK); + assert(hmath_numeric_types_float16_bits(NULL, child, &result) == HMATH_OK); + char *numerator = NULL, *denominator = NULL; + assert(hmath_value_get_exact(result, &numerator, &denominator) == HMATH_OK); + assert(strcmp(numerator, "15462") == 0 && strcmp(denominator, "1") == 0); + hmath_value_string_free(numerator); + hmath_value_string_free(denominator); + hmath_numeric_types_release(result); + hmath_numeric_types_release(child); + hmath_numeric_types_release(rounded); + assert(hmath_numeric_types_big_float(NULL, 200, HMATH_NEAREST_EVEN, "1", "0", &unchanged) == HMATH_INVALID_ARGUMENT); + assert(unchanged == (hmath_numeric_value *)(uintptr_t)1); + assert(hmath_numeric_types_rounded(NULL, NULL, flags, 3, &unchanged) == HMATH_INVALID_ARGUMENT); + assert(hmath_numeric_types_float16_from_bits(NULL, 0, NULL) == HMATH_INVALID_ARGUMENT); + assert(hmath_numeric_types_kind(NULL) == 0); + hmath_numeric_types_release(NULL); + assert(hmath_runtime_shutdown() == HMATH_OK); + puts("Numeric C callback, ownership, flags and error contracts passed."); + return 0; +} diff --git a/test/native/numeric_variants.c b/test/native/numeric_variants.c new file mode 100644 index 0000000..e38593f --- /dev/null +++ b/test/native/numeric_variants.c @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_numeric.h" +#include +#include +#include +#include + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #condition, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) + +int main(void) { + CHECK(hmath_init() == HMATH_INIT_OK); + int8_t signed_result = 55; + CHECK(hmath_scalar_add_i8(NULL, INT8_MAX, 1, &signed_result) == HMATH_OK); + CHECK(signed_result == INT8_MIN); + CHECK(hmath_scalar_saturating_add_i8(NULL, INT8_MAX, 1, &signed_result) == HMATH_OK); + CHECK(signed_result == INT8_MAX); + signed_result = 55; + CHECK(hmath_scalar_checked_add_i8(NULL, INT8_MAX, 1, &signed_result) == HMATH_MATH_ERROR); + CHECK(signed_result == 55); + CHECK(strcmp(hmath_last_error_message(), "DomainError \"integer overflow\"") == 0); + uint64_t unsigned_result = 99; + CHECK(hmath_scalar_add_u64(NULL, UINT64_MAX, 1, &unsigned_result) == HMATH_OK); + CHECK(unsigned_result == 0); + + char *numerator = NULL, *denominator = NULL; + CHECK(hmath_scalar_add_rational(NULL, "1", "3", "1", "7", &numerator, &denominator) == + HMATH_OK); + CHECK(strcmp(numerator, "10") == 0 && strcmp(denominator, "21") == 0); + hmath_numeric_string_free(numerator); + hmath_numeric_string_free(denominator); + numerator = denominator = NULL; + CHECK(hmath_scalar_add_rational(NULL, "1", "0", "1", "7", &numerator, &denominator) == + HMATH_INVALID_ARGUMENT); + CHECK(numerator == NULL && denominator == NULL); + CHECK(hmath_scalar_positive_modulo(NULL, "-7", "5", &numerator) == HMATH_OK); + CHECK(strcmp(numerator, "3") == 0); + hmath_numeric_string_free(numerator); + + /* Counts describe logical rationals, not their numerator/denominator pairs. */ + const char *input[] = {"1", "3", "1", "7"}; + char **output = NULL; + size_t count = 999; + CHECK(hmath_scalar_prefix_sum_rational(NULL, input, 2, &output, &count) == HMATH_OK); + CHECK(count == 3); + CHECK(strcmp(output[0], "0") == 0 && strcmp(output[1], "1") == 0); + CHECK(strcmp(output[4], "10") == 0 && strcmp(output[5], "21") == 0); + for (size_t i = 0; i < 2 * count; ++i) + hmath_numeric_string_free(output[i]); + hmath_numeric_buffer_free(output); + + /* Original Haskell dot is bilinear, with no conjugation for Complex. */ + const double left[] = {1, 2}, right[] = {3, 4}; + double real = 99, imaginary = 99; + CHECK(hmath_linear_dot_c128(NULL, left, 1, right, 1, &real, &imaginary) == HMATH_OK); + CHECK(real == -5 && imaginary == 10); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/numerical_bindings.py b/test/native/numerical_bindings.py new file mode 100644 index 0000000..50fcb46 --- /dev/null +++ b/test/native/numerical_bindings.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Callback containment, exact payloads and independent numerical owners.""" + +import sys +import unittest +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from hmath import calculus as c +from hmath import matrix as m +from hmath import ode + + +class BrokenMessage(Exception): + def __str__(self): + raise RuntimeError("exception formatting must remain outside the C callback") + + +class NumericalContracts(unittest.TestCase): + def test_generic_estimate_keeps_exact_payload_and_independent_matrix(self): + original = m.from_list( + 1, 2, [Fraction(1, 10**5000 + 1), 10**5000], dtype="rational" + ) + estimate = c.estimate(original, -0.0, 7) + original.close() + result = c.estimate_value(estimate) + estimate.close() + self.assertEqual(result.to_list(), [Fraction(1, 10**5000 + 1), 10**5000]) + result.close() + with c.estimate((None, "x\0α\ud800", Fraction(7, 13)), 0.1, 4) as estimate: + self.assertEqual( + c.estimate_value(estimate), (None, "x\0α\ud800", Fraction(7, 13)) + ) + + def test_callback_can_reenter_and_close_original_method(self): + method = c.central() + calls = [] + + def function(x): + method.close() + calls.append(x) + return hmath.add(x * x, 0) + + self.assertAlmostEqual(c.derivative(method, 0.001, function, 3), 6, places=10) + self.assertTrue(calls) + with self.assertRaises(ValueError): + _ = method.info + + def test_unexpected_exception_identity_and_broken_formatter(self): + original = BrokenMessage() + with c.central() as method: + + def function(_): + raise original + + with self.assertRaises(BrokenMessage) as caught: + c.derivative(method, 0.001, function, 3) + self.assertIs(caught.exception, original) + + def test_structured_math_error_preserves_full_text(self): + message = "payload\0α\ud800" * 1000 + error = hmath.errors.NonConvergence(message, 17) + with c.central() as method: + + def function(_): + raise error + + with self.assertRaises(hmath.HMathError) as caught: + c.derivative(method, 0.001, function, 3) + self.assertEqual(caught.exception.math_error.details, (17,)) + self.assertEqual(caught.exception.math_error.message, message) + + def test_caught_reentrant_callback_failure_does_not_poison_outer_call(self): + from _hmath_native._numerical_base import _callback + + original = BrokenMessage() + active = [] + holder = [] + with c.central() as method: + + def function(x): + if active: + raise original + active.append(True) + try: + with self.assertRaises(BrokenMessage) as caught: + c.derivative(method, 0.001, holder[0], 0) + self.assertIs(caught.exception, original) + finally: + active.clear() + return x * x + + native = _callback(function, ["Double"]) + holder.append(native) + try: + self.assertAlmostEqual( + c.derivative(method, 0.001, native, 3), 6, places=10 + ) + finally: + holder.clear() + native.close() + + def test_trajectory_is_forced_before_callback_scope_ends(self): + calls = [] + with ode.rk4() as method, ode.default_ode_options() as options: + + def rhs(time, values): + calls.append(time) + return [-x for x in values] + + trajectory = ode.solve_ivp(method, options, 4, rhs, 0, 1, [1]) + before = len(calls) + states = ode.trajectory_states(trajectory) + trajectory.close() + self.assertEqual(len(calls), before) + self.assertEqual(len(states), 5) + self.assertAlmostEqual(states[-1][0], 0.3678942, places=6) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/optimization_bindings.py b/test/native/optimization_bindings.py new file mode 100644 index 0000000..dbda47a --- /dev/null +++ b/test/native/optimization_bindings.py @@ -0,0 +1,255 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Optimization contracts beyond direct source equivalence. + +Set HMATH_LIBRARY to the built native library and PYTHONPATH=bindings/python. +""" + +import ctypes as C +import gc +import threading +import unittest +import weakref +from concurrent.futures import ThreadPoolExecutor + +import hmath +from _hmath_native import _math_error as wire +from _hmath_native import _value as value +from hmath import errors +from hmath import optimization as opt + + +def raise_error(error): + def function(_): + raise error + + return function + + +class OptimizationContracts(unittest.TestCase): + def setUp(self): + hmath.initialize() + + def test_all_math_error_constructors_roundtrip(self): + payload = ("한국어\x00𝄞\ud800\udfff" * 3000) + "tail" + cases = [ + errors.NegativeDimensions((-2, 3)), + errors.ElementCountOverflow((2, 3)), + errors.ElementCountMismatch(5, 6), + errors.ShapeMismatch((1, 2), (3, 4)), + errors.InnerDimensionMismatch(5, 6), + errors.IndexOutOfBounds((1, 2), (3, 4)), + errors.SliceOutOfBounds((1, 2), (3, 4), (5, 6)), + errors.VectorLengthMismatch(5, 6), + errors.NonSquareMatrix((2, 3)), + errors.InvalidTolerance(), + errors.SingularMatrix(2), + errors.NearSingularMatrix(3), + errors.NonFiniteMatrixEntry((2, 3)), + errors.NonFiniteVectorEntry(4), + errors.NonFiniteResult(), + errors.RightHandSideMismatch(5, 6), + errors.DomainError(payload), + errors.InvalidArgument(payload), + errors.NonConvergence(payload, -3), + errors.RankDeficient(2), + errors.NotPositiveDefinite(3), + ] + for expected in cases: + with self.subTest(kind=expected.kind): + with self.assertRaises(hmath.HMathError) as caught: + opt.checked_value(raise_error(expected), [1]) + actual = caught.exception.math_error + self.assertEqual(caught.exception.status, 11) + self.assertEqual(actual.kind, expected.kind) + self.assertEqual(actual.details, expected.details) + self.assertEqual(actual.message, expected.message) + # Querying does not consume or clear the complete payload. + self.assertEqual( + wire.last_math_error(hmath._lib).message, expected.message + ) + self.assertEqual(opt.checked_value(lambda x: 2.0, [1]), 2.0) + self.assertIsNone(wire.last_math_error(hmath._lib)) + + def test_error_state_is_thread_local(self): + barrier = threading.Barrier(3) + + def run(index): + expected = errors.DomainError(f"thread {index}\x00tail") + with self.assertRaises(hmath.HMathError): + opt.checked_value(raise_error(expected), [1]) + barrier.wait() + actual = wire.last_math_error(hmath._lib) + barrier.wait() + opt.checked_value(lambda x: 1, [1]) + return actual.message + + with ThreadPoolExecutor(max_workers=3) as pool: + self.assertEqual( + list(pool.map(run, range(3))), [f"thread {i}\x00tail" for i in range(3)] + ) + + def test_recoverable_callback_math_error_stays_left(self): + # The original feasible barrier backtracking retries DomainError. A + # globally thrown callback error would abort at its first rejected step. + rejected = [] + + def objective(x): + if x[0] <= 0: + rejected.append(x[0]) + raise errors.DomainError("outside objective domain") + return x[0] * x[0] + + options = opt.OptimizeOptions(200, 50000, 1e-5, 0.25) + result = opt.constrained_minimize( + opt.LogBarrier, + options, + objective, + lambda x: [2 * x[0]], + [opt.LessEqual(lambda x: -x[0], lambda x: [-1])], + [1], + ) + self.assertTrue(rejected) + self.assertTrue(result.converged) + self.assertGreater(result.point[0], 0) + + def test_unexpected_exception_is_identical_after_cleanup(self): + for exception in [KeyboardInterrupt("stop"), ValueError("failure")]: + with self.assertRaises(type(exception)) as caught: + opt.checked_value(raise_error(exception), [1]) + self.assertIs(caught.exception, exception) + self.assertEqual(opt.checked_value(lambda x: 1, [1]), 1) + + def test_exception_string_failure_cannot_escape_callback(self): + class BrokenException(Exception): + def __str__(self): + raise RuntimeError("no message") + + exception = BrokenException() + with self.assertRaises(BrokenException) as caught: + opt.checked_value(raise_error(exception), [1]) + self.assertIs(caught.exception, exception) + + def test_callback_result_checks_preserve_source_conditions(self): + cases = [ + ( + lambda: opt.checked_value(lambda x: float("nan"), [1]), + errors.NonFiniteResult(), + ), + ( + lambda: opt.checked_gradient(lambda x: [], [1]), + errors.VectorLengthMismatch(1, 0), + ), + ( + lambda: opt.checked_gradient(lambda x: [float("inf")], [1]), + errors.NonFiniteResult(), + ), + ] + for call, expected in cases: + with self.subTest(kind=expected.kind): + with self.assertRaises(hmath.HMathError) as caught: + call() + self.assertEqual(caught.exception.math_error.kind, expected.kind) + self.assertEqual(caught.exception.math_error.details, expected.details) + + def test_monitor_stops_and_preserves_diagnostics(self): + observed = [] + + def monitor(result): + observed.append(result) + return False + + result = opt.minimize_gradient_with_callback( + monitor, + opt.GradientMethod.ADAM, + opt.OptimizeOptions(), + lambda x: x[0] ** 2, + lambda x: [2 * x[0]], + [3], + ) + self.assertEqual(result, opt.OptimizeResult([3.0], 9.0, 6.0, 0, 2, False)) + self.assertEqual(observed, [result]) + + def test_transitive_callback_ownership_and_reentrant_close(self): + class Gradient: + def __call__(self, point): + return [2 * v for v in point] + + callback = Gradient() + reference = weakref.ref(callback) + function = opt.mini_batch_gradient([callback]) + del callback + gc.collect() + self.assertIsNotNone(reference()) + self.assertEqual(function([3]), [6]) + function.close() + gc.collect() + self.assertIsNone(reference()) + holder = {} + + def reentrant(point): + holder["function"].close() + return point + + holder["function"] = opt.mini_batch_gradient([reentrant]) + self.assertEqual(holder["function"]([3]), [3]) + with self.assertRaises(ValueError): + holder["function"]([3]) + + def test_zz_lifetime_blocks_shutdown_and_releases(self): + function = opt.weighted_objective([1], [sum]) + with self.assertRaises(hmath.HMathError) as caught: + hmath.shutdown() + self.assertEqual(caught.exception.status, 9) + function.close() + # Other modules may retain nothing, and every failed callback above + # must have cleaned up its temporary Values and runtime reservations. + gc.collect() + hmath.shutdown() + + def test_generic_transpose_preserves_exact_values_and_ragged_rows(self): + from fractions import Fraction + + self.assertEqual( + opt.transpose([[10**100, Fraction(2, 3)], [None]]), + [[10**100, None], [Fraction(2, 3)]], + ) + + def test_word64_seed_is_checked_without_float_conversion(self): + options = opt.OptimizeOptions(1, 100, 1e-7, 0.1) + args = ( + opt.DifferentialEvolution, + 4, + 2**64 - 1, + options, + [(-1, 1)], + lambda x: x[0] ** 2, + ) + self.assertEqual(opt.global_minimize(*args), opt.global_minimize(*args)) + for seed in [-1, 2**64]: + with self.assertRaises((OverflowError, ValueError, hmath.HMathError)): + opt.global_minimize( + opt.DifferentialEvolution, + 4, + seed, + options, + [(-1, 1)], + lambda x: x[0] ** 2, + ) + + def test_failure_does_not_publish_output(self): + # Named C wrappers share the transactional output guarantee. + output = C.c_void_p(0x1234) + hmath.initialize() + status = value.api( + "hmath_optimization_checked_point", + C.c_int, + C.c_void_p, + C.c_void_p, + C.POINTER(C.c_void_p), + )(None, None, C.byref(output)) + self.assertEqual(status, 1) + self.assertEqual(output.value, 0x1234) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/optimization_contracts.c b/test/native/optimization_contracts.c new file mode 100644 index 0000000..099d65d --- /dev/null +++ b/test/native/optimization_contracts.c @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Compile and run as both C99 and C++17 against the same public ABI. */ +#include "hmath_optimization.h" +#include +#include +#include +#include + +static double number(const hmath_value *value) { + double real, imaginary; + assert(hmath_value_get_f64(value, &real, &imaginary) == HMATH_OK); + assert(imaginary == 0); + return real; +} +static hmath_value *scalar(double real) { + hmath_value *value = NULL; + assert(hmath_value_f64(NULL, real, &value) == HMATH_OK); + return value; +} +static hmath_status objective(const hmath_value *argument, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)error; + hmath_value *item = NULL; + assert(hmath_value_item(NULL, argument, 0, &item) == HMATH_OK); + double x = number(item); + hmath_value_release(item); + unsigned *calls = (unsigned *)userdata; + ++*calls; + return hmath_value_f64(NULL, x * x, out); +} +static hmath_status fail(const hmath_value *argument, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)argument; + (void)userdata; + (void)out; + static const char message[] = "domain\0full\xe2\x98\x83"; + error->kind = HMATH_MATH_DOMAIN_ERROR; + error->message = message; + error->message_length = sizeof message - 1; + return HMATH_MATH_ERROR; +} +static hmath_status identity(const hmath_value *argument, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)userdata; + (void)error; + hmath_value_retain((hmath_value *)argument); + *out = (hmath_value *)argument; + return HMATH_OK; +} +int main(void) { + assert(hmath_init() == HMATH_INIT_OK); + unsigned calls = 0; + hmath_value *options = NULL, *method = NULL, *function = NULL, *lower = scalar(-2), + *upper = scalar(3); + assert(hmath_optimization_default_optimize_options(NULL, &options) == HMATH_OK); + assert(hmath_optimization_brent_search_create(NULL, &method) == HMATH_OK); + assert(hmath_optimization_callback(NULL, 0, objective, &calls, &function) == HMATH_OK); + hmath_value *result = NULL, *point = NULL, *item = NULL; + assert(hmath_optimization_minimize_scalar(NULL, method, options, function, lower, upper, + &result) == HMATH_OK); + assert(calls > 1); + assert(hmath_optimization_opt_point(NULL, result, &point) == HMATH_OK); + assert(hmath_value_item(NULL, point, 0, &item) == HMATH_OK); + assert(fabs(number(item)) < 1e-7); + hmath_value_release(item); + hmath_value_release(point); + hmath_value_release(result); + + hmath_value *bad = NULL; + assert(hmath_optimization_callback(NULL, 0, fail, NULL, &bad) == HMATH_OK); + result = (hmath_value *)(uintptr_t)0x1234; + assert(hmath_optimization_minimize_scalar(NULL, method, options, bad, lower, upper, &result) == + HMATH_MATH_ERROR); + assert(result == (hmath_value *)(uintptr_t)0x1234); + hmath_math_error error; + assert(hmath_last_math_error(&error) == 1); + assert(error.kind == HMATH_MATH_DOMAIN_ERROR); + assert(error.message_length == sizeof "domain\0full\xe2\x98\x83" - 1); + assert(memcmp(error.message, "domain\0full\xe2\x98\x83", error.message_length) == 0); + assert(hmath_last_math_error(&error) == 1); /* a query does not consume */ + hmath_value *weight = scalar(1), *weights = NULL, *functions = NULL, *derived = NULL; + const hmath_value *items[1] = {weight}; + assert(hmath_value_list(NULL, items, 1, &weights) == HMATH_OK); + assert(hmath_last_math_error(&error) == 0); /* a checked success clears */ + items[0] = function; + assert(hmath_value_list(NULL, items, 1, &functions) == HMATH_OK); + assert(hmath_optimization_weighted_objective(NULL, weights, functions, &derived) == HMATH_OK); + hmath_value_release(functions); + hmath_value_release(function); /* derived owns its Haskell function closure */ + const hmath_value *arg_items[1] = {upper}; + hmath_value *args = NULL, *answer = NULL; + assert(hmath_value_list(NULL, arg_items, 1, &args) == HMATH_OK); + const hmath_value *argv[1] = {args}; + assert(hmath_optimization_function_apply(NULL, derived, argv, 1, &answer) == HMATH_OK); + assert(number(answer) == 9); + hmath_value_release(answer); + + /* A callback may return a borrowed input after explicitly retaining it. */ + hmath_value *gradient = NULL, *gradients = NULL, *batch = NULL; + assert(hmath_optimization_callback(NULL, 1, identity, NULL, &gradient) == HMATH_OK); + items[0] = gradient; + assert(hmath_value_list(NULL, items, 1, &gradients) == HMATH_OK); + assert(hmath_optimization_mini_batch_gradient(NULL, gradients, &batch) == HMATH_OK); + assert(hmath_optimization_function_apply(NULL, batch, argv, 1, &answer) == HMATH_OK); + assert(hmath_value_item(NULL, answer, 0, &item) == HMATH_OK); + assert(number(item) == 3); + hmath_value_release(item); + hmath_value_release(answer); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + + /* Old state handles keep their ABI and interoperate with Value states. */ + hmath_optimizer_state *state = NULL, *exported = NULL; + hmath_value *boxed = NULL; + assert(hmath_initialize_optimizer(NULL, 1, &state) == HMATH_OK); + assert(hmath_optimization_state_import(NULL, state, &boxed) == HMATH_OK); + hmath_optimizer_state_release(state); + assert(hmath_optimization_state_export(NULL, boxed, &exported) == HMATH_OK); + hmath_optimizer_state_release(exported); + hmath_value_release(boxed); + hmath_value_release(gradient); + hmath_value_release(gradients); + hmath_value_release(batch); + hmath_value_release(args); + hmath_value_release(derived); + hmath_value_release(weights); + hmath_value_release(weight); + hmath_value_release(bad); + hmath_value_release(method); + hmath_value_release(options); + hmath_value_release(lower); + hmath_value_release(upper); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/polynomial_bindings.py b/test/native/polynomial_bindings.py new file mode 100644 index 0000000..8151165 --- /dev/null +++ b/test/native/polynomial_bindings.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Callbacks, coefficient fidelity and Polynomial/Matrix lifetime integration.""" + +import math +import sys +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import matrix as m +from _hmath_native import polynomial as p +from _hmath_native._math_error import MathError, MathErrorKind + + +def must_fail(function, kind): + try: + function() + except hmath.HMathError as error: + assert error.math_error.kind == kind, error + return error + raise AssertionError("expected original MathError") + + +for dtype in ("float32", "float64", "integer", "rational", "complex64", "complex128"): + source = p.polynomial([1, 2, 0, 0], dtype=dtype) + assert source.degree == 1 and source.coefficients == [1, 2] + assert source == p.polynomial([1, 2], dtype=dtype) + zero = p.polynomial([], dtype=dtype) + assert zero.degree is None and zero.coefficients == [] + series = p.power_series([1, 2, 0, 0], dtype=dtype) + assert series.coefficients == [1, 2, 0, 0] + assert series != p.power_series([1, 2], dtype=dtype) + source.close() + zero.close() + series.close() +# Arbitrary precision never enters FP64, including generic Matrix arithmetic. +big = 10**6000 + 7 +with p.polynomial([big, 1], dtype="integer") as source: + assert p.evaluate_polynomial(source, 2) == big + 2 +with p.polynomial([Fraction(1, 10**5000 + 1), 0, 1], dtype="rational") as source: + companion = p.companion_matrix(source) +assert isinstance(companion, m.Matrix) and companion.dtype == "rational" +assert companion.to_list()[1] == -Fraction(1, 10**5000 + 1) +squared = m.multiply_checked(companion, companion) +companion.close() +assert squared.to_list() == [ + -Fraction(1, 10**5000 + 1), + 0, + 0, + -Fraction(1, 10**5000 + 1), +] +squared.close() +# Float32 stays Float32: construction rounds before Horner arithmetic. +with p.polynomial([16777217, 1], dtype="float32") as source: + assert p.evaluate_polynomial(source, 1) == 16777216 + companion = p.companion_matrix(source) +assert isinstance(companion, m.Matrix) and companion.dtype == "float32" +assert m.scale_matrix(1, companion).to_list() == companion.to_list() +companion.close() +# Source finite and callback exception policies. +calls = [] +with p.chebyshev_approximation(3, lambda x: (calls.append(x), x * x)[1]) as result: + assert len(calls) == 4 and result.dtype == "float64" + assert math.isclose(p.evaluate_polynomial(result, 0.4), 0.16, abs_tol=1e-14) +must_fail( + lambda: p.chebyshev_approximation( + -1, lambda _x: (_ for _ in ()).throw(AssertionError("must not run")) + ), + MathErrorKind.DOMAIN_ERROR, +) +must_fail( + lambda: p.chebyshev_approximation(2, lambda _x: float("nan")), + MathErrorKind.NON_FINITE_RESULT, +) +message = "callback\0α🙂\ud800" + + +def original_error(_x): + raise MathError(MathErrorKind.NON_CONVERGENCE, (17,), message) + + +error = must_fail( + lambda: p.chebyshev_approximation(2, original_error), MathErrorKind.NON_CONVERGENCE +) +assert error.math_error.details == (17,) and error.math_error.message == message +sentinel = KeyboardInterrupt("callback sentinel") + + +def interrupt(_x): + raise sentinel + + +try: + p.chebyshev_approximation(2, interrupt) +except KeyboardInterrupt as error: + assert error is sentinel +else: + raise AssertionError("Python callback exception was swallowed") +# Unsupported original coefficient instances fail without precision-changing fallback. +with p.power_series([1, 2], dtype="complex128") as source: + try: + p.log_series(source) + except hmath.HMathError as error: + assert error.status == 10 + else: + raise AssertionError("Complex lacks the original Ord instance") +with m.zero_matrix_checked(0, sys.maxsize, dtype="integer") as source: + assert source.shape == (0, sys.maxsize) + target = m.transpose_matrix(source) + assert target.shape == (sys.maxsize, 0) + target.close() +print("Polynomial coefficient/callback/Matrix ownership contracts passed") diff --git a/test/native/polynomial_contracts.c b/test/native/polynomial_contracts.c new file mode 100644 index 0000000..12a2220 --- /dev/null +++ b/test/native/polynomial_contracts.c @@ -0,0 +1,99 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_matrix_value.h" +#include "hmath_polynomial.h" +#include +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static hmath_status fail_callback(double input, double *out, void *userdata, + hmath_math_error *error) { + (void)input; + (void)out; + (void)userdata; + static const char message[] = {'x', '\0', (char)0xce, (char)0xb1}; + error->kind = HMATH_MATH_DOMAIN_ERROR; + error->message = message; + error->message_length = sizeof message; + return HMATH_MATH_ERROR; +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *zero = NULL, *one = NULL, *minus = NULL, *values = NULL, *p = NULL; + CHECK(hmath_value_rational(NULL, "0", "1", &zero) == HMATH_OK); + CHECK(hmath_value_rational(NULL, "1", "1", &one) == HMATH_OK); + CHECK(hmath_value_rational(NULL, "-1", "1", &minus) == HMATH_OK); + const hmath_value *items[] = {minus, zero, one, zero}; + CHECK(hmath_value_list(NULL, items, 4, &values) == HMATH_OK); + CHECK(hmath_polynomial_polynomial(NULL, zero, values, &p) == HMATH_OK); + int kind = -1, dtype = -1; + size_t count = 99; + CHECK(hmath_value_info(p, &kind, &dtype, &count) == HMATH_OK && kind == 6 && dtype == 3 && + count == 3); + hmath_value_release(values); + hmath_value_release(minus); + hmath_value_release(one); + hmath_value *matrix = NULL, *squared = NULL; + CHECK(hmath_polynomial_companion_matrix(NULL, p, &matrix) == HMATH_OK); + hmath_value_release(p); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + CHECK(hmath_value_info(matrix, &kind, &dtype, &count) == HMATH_OK && kind == 9 && dtype == 3 && + count == 4); + CHECK(hmath_matrix_value_multiply_checked(NULL, matrix, matrix, &squared) == HMATH_OK); + CHECK(hmath_matrix_value_to_list(NULL, squared, &values) == HMATH_OK); + const char *expected[] = {"1", "0", "0", "1"}; + for (ptrdiff_t i = 0; i < 4; i++) { + hmath_value *value = NULL; + char *n = NULL, *d = NULL; + CHECK(hmath_value_item(NULL, values, i, &value) == HMATH_OK); + CHECK(hmath_value_get_exact(value, &n, &d) == HMATH_OK && strcmp(n, expected[i]) == 0 && + strcmp(d, "1") == 0); + hmath_value_string_free(n); + hmath_value_string_free(d); + hmath_value_release(value); + } + hmath_value_release(values); + hmath_value_release(squared); + hmath_value *bad = NULL, *index = NULL, *result = (hmath_value *)(uintptr_t)1; + CHECK(hmath_value_index(NULL, -1, &bad) == HMATH_OK); + CHECK(hmath_value_index(NULL, 0, &index) == HMATH_OK); + CHECK(hmath_matrix_value_at(NULL, matrix, bad, index, &values) == HMATH_OK); + CHECK(hmath_value_info(values, &kind, &dtype, &count) == HMATH_OK && kind == 0); + hmath_value_release(values); + CHECK(hmath_matrix_value_at_checked(NULL, matrix, bad, index, &result) == HMATH_MATH_ERROR && + result == (hmath_value *)(uintptr_t)1); + hmath_math_error error; + CHECK(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_INDEX_OUT_OF_BOUNDS && + error.details[0] == 2 && error.details[2] == -1); + hmath_value_release(matrix); + hmath_value_release(bad); + hmath_value *maximum = NULL; + CHECK(hmath_value_index(NULL, PTRDIFF_MAX, &maximum) == HMATH_OK); + CHECK(hmath_matrix_value_zero_matrix_checked(NULL, zero, index, maximum, &matrix) == HMATH_OK); + CHECK(hmath_matrix_value_shape(NULL, matrix, &values) == HMATH_OK); + hmath_value *maximumInput = maximum; + CHECK(hmath_value_item(NULL, values, 1, &maximum) == HMATH_OK); + ptrdiff_t dimension = -1; + CHECK(hmath_value_get_index(maximum, &dimension) == HMATH_OK && dimension == PTRDIFF_MAX); + hmath_value_release(maximum); + hmath_value_release(values); + hmath_value_release(matrix); + /* Callback structured error retains constructor, Unicode and embedded NUL. */ + CHECK(hmath_polynomial_chebyshev_approximation(NULL, 2, fail_callback, NULL, &result) == + HMATH_MATH_ERROR && + result == (hmath_value *)(uintptr_t)1); + CHECK(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_DOMAIN_ERROR && + error.message_length == 4 && memcmp(error.message, "x\0\xce\xb1", 4) == 0); + hmath_value_release(zero); + hmath_value_release(index); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); /* maximum input was independently owned */ + hmath_value_release(maximumInput); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/rotations.c b/test/native/rotations.c new file mode 100644 index 0000000..6bc87d0 --- /dev/null +++ b/test/native/rotations.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_rotations.h" +#include "hmath_error.h" +#include +#include +#include +int main(void) { + hmath_value *one = NULL, *zero = NULL, *q = NULL, *rotation = NULL; + hmath_value *components = NULL, *component = NULL; + hmath_value *unchanged = (hmath_value *)(uintptr_t)1; + double real = 0, imaginary = 0; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_f64(NULL, 1, &one) == HMATH_OK); + assert(hmath_value_f64(NULL, 0, &zero) == HMATH_OK); + assert(hmath_quaternion_quaternion(NULL, one, zero, zero, zero, &q) == HMATH_OK); + assert(hmath_rotation_so3(NULL, q, &rotation) == HMATH_OK); + hmath_value_release(q); + assert(hmath_rotation_rotation_quaternion(NULL, rotation, &q) == HMATH_OK); + hmath_value_release(rotation); + assert(hmath_quaternion_components(NULL, q, &components) == HMATH_OK); + hmath_value_release(q); + assert(hmath_value_item(NULL, components, 0, &component) == HMATH_OK); + hmath_value_release(components); + assert(hmath_value_get_f64(component, &real, &imaginary) == HMATH_OK && real == 1); + hmath_value_release(component); + assert(hmath_quaternion_quaternion(NULL, zero, zero, zero, zero, &q) == HMATH_OK); + assert(hmath_quaternion_normalize(NULL, q, &unchanged) == HMATH_MATH_ERROR); + assert(unchanged == (hmath_value *)(uintptr_t)1); + hmath_math_error error; + assert(hmath_last_math_error(&error) && error.kind == HMATH_MATH_DOMAIN_ERROR); + assert(hmath_rotation_so3(NULL, one, &unchanged) == HMATH_INVALID_ARGUMENT); + assert(unchanged == (hmath_value *)(uintptr_t)1); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(q); + hmath_value_release(one); + hmath_value_release(zero); + assert(hmath_runtime_shutdown() == HMATH_OK); + puts("Quaternion/Rotation C ownership, distinct types and MathError contracts passed."); + return 0; +} diff --git a/test/native/scalar_extras.c b/test/native/scalar_extras.c new file mode 100644 index 0000000..4a2a30d --- /dev/null +++ b/test/native/scalar_extras.c @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_scalar_extras.h" +#include "hmath_error.h" +#include +#include +#include +#include +#include +int main(void) { + hmath_value *selector=NULL,*other=NULL,*value=NULL,*result=NULL,*item=NULL; + hmath_value *a=NULL,*b=NULL,*c=NULL,*negative=NULL; + assert(hmath_init()==HMATH_OK); + assert(hmath_trigonometry_c_sin(NULL,&selector)==HMATH_OK); + assert(hmath_value_complex_f32(NULL,0.25f,0.5f,&value)==HMATH_OK); + assert(hmath_trigonometry_complex_function(NULL,selector,value,&result)==HMATH_OK); + int kind=0,dtype=0;size_t count=0; + assert(hmath_value_info(result,&kind,&dtype,&count)==HMATH_OK && kind==1 && dtype==5); + float real=0,imaginary=0; + assert(hmath_value_get_f32(result,&real,&imaginary)==HMATH_OK); + assert(isfinite(real) && isfinite(imaginary)); + hmath_value_release(result);hmath_value_release(value); + assert(hmath_complex_sin(NULL,&other)==HMATH_OK); + hmath_value *unchanged=(hmath_value *)(uintptr_t)1; + assert(hmath_trigonometry_complex_function(NULL,other,selector,&unchanged)==HMATH_INVALID_ARGUMENT); + assert(unchanged==(hmath_value *)(uintptr_t)1); + hmath_value_release(other);hmath_value_release(selector); + assert(hmath_value_f64(NULL,-0.0,&a)==HMATH_OK); + assert(hmath_value_f64(NULL,-2.5,&b)==HMATH_OK); + assert(hmath_special_sf_result(NULL,a,b,&result)==HMATH_OK); + assert(hmath_special_sf_value(NULL,result,&item)==HMATH_OK); + double x=1,y=1;assert(hmath_value_get_f64(item,&x,&y)==HMATH_OK && signbit(x)); + hmath_value_release(item); + assert(hmath_special_sf_error(NULL,result,&item)==HMATH_OK); + assert(hmath_value_get_f64(item,&x,&y)==HMATH_OK && x==-2.5); + hmath_value_release(item);hmath_value_release(result);hmath_value_release(a);hmath_value_release(b); + assert(hmath_value_integer(NULL,"1234567890123456789012345678901234567890",&a)==HMATH_OK); + assert(hmath_value_integer(NULL,"0",&b)==HMATH_OK); + assert(hmath_value_integer(NULL,"2469135780246913578024691357802469135780",&c)==HMATH_OK); + assert(hmath_numbertheory_linear_diophantine(NULL,a,b,c,&result)==HMATH_OK); + assert(hmath_value_info(result,&kind,&dtype,&count)==HMATH_OK && kind==5 && count==4); + assert(hmath_value_item(NULL,result,0,&item)==HMATH_OK); + hmath_value_release(result);char *num=NULL,*den=NULL; + assert(hmath_value_get_exact(item,&num,&den)==HMATH_OK && strcmp(num,"2")==0); + hmath_value_string_free(num);hmath_value_string_free(den);hmath_value_release(item); + assert(hmath_value_index(NULL,-1,&negative)==HMATH_OK); + assert(hmath_numbertheory_partitions(NULL,negative,&unchanged)==HMATH_MATH_ERROR); + assert(unchanged==(hmath_value *)(uintptr_t)1); + hmath_math_error error;assert(hmath_last_math_error(&error)); + assert(hmath_runtime_shutdown()==HMATH_BUSY); + hmath_value_release(a);hmath_value_release(b);hmath_value_release(c);hmath_value_release(negative); + assert(hmath_runtime_shutdown()==HMATH_OK); + puts("Scalar extras C precision, raw SFResult, exact tuples, errors and lifetime contracts passed."); + return 0; +} diff --git a/test/native/spectral_bindings.py b/test/native/spectral_bindings.py new file mode 100644 index 0000000..b140b2d --- /dev/null +++ b/test/native/spectral_bindings.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Borrowed FFT storage, original error atomicity and generic payload owners.""" + +import sys +import unittest +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +import numpy as np +from hmath import fourier as f, matrix + + +class SpectralContracts(unittest.TestCase): + def plan(self, n): + with f.forward() as direction, f.automatic() as algorithm: + return f.plan_fft(direction, algorithm, n) + + def test_in_place_matches_original_and_keeps_storage(self): + samples = np.array([1 + 2j, 3 - 1j, 0, -2j], dtype=np.complex128) + expected = f.fft(samples.tolist()) + address = samples.ctypes.data + with self.plan(4) as plan: + self.assertIsNone(f.fft_in_place(plan, samples)) + self.assertEqual(samples.ctypes.data, address) + self.assertEqual(samples.tolist(), expected) + + def test_failure_leaves_storage_bits_unchanged(self): + with self.plan(4) as plan: + for samples in ( + np.array([1, 2], dtype=np.complex128), + np.array([1, complex(float("nan"), 2), 3, 4], dtype=np.complex128), + np.array([1, complex(float("inf"), 2), 3, 4], dtype=np.complex128), + ): + before = samples.tobytes() + with self.assertRaises(hmath.HMathError) as caught: + f.fft_in_place(plan, samples) + self.assertEqual(caught.exception.status, 11) + self.assertIsNotNone(caught.exception.math_error) + self.assertEqual(samples.tobytes(), before) + + def test_rejects_unsupported_buffers_without_mutation(self): + readonly = np.ones(4, dtype=np.complex128) + readonly.flags.writeable = False + unaligned = np.ndarray( + (4,), dtype=np.complex128, buffer=bytearray(65), offset=1 + ) + cases = ( + readonly, + unaligned, + np.ones(8, dtype=np.complex128)[::2], + np.ones(4, dtype=np.complex64), + np.ones((2, 2), dtype=np.complex128), + np.ones(4, dtype=np.dtype(">c16")), + ) + with self.plan(4) as plan: + for samples in cases: + before = samples.tobytes() + with self.assertRaises(TypeError): + f.fft_in_place(plan, samples) + self.assertEqual(samples.tobytes(), before) + + def test_generic_shift_keeps_exact_and_independent_matrix_payloads(self): + with matrix.from_list(1, 1, [10**5000], dtype="integer") as original: + shifted = f.fft_shift( + [original, Fraction(1, 10**5000 + 1), "x\0α\ud800", None, True] + ) + self.assertEqual(shifted[0:2], [None, True]) + owner = shifted[2] + try: + self.assertEqual(owner.to_list(), [10**5000]) + recovered = f.ifft_shift(shifted) + try: + self.assertEqual(recovered[0].to_list(), [10**5000]) + self.assertEqual( + recovered[1:], [Fraction(1, 10**5000 + 1), "x\0α\ud800", None, True] + ) + finally: + recovered[0].close() + finally: + owner.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/spectral_contracts.c b/test/native/spectral_contracts.c new file mode 100644 index 0000000..56a81b6 --- /dev/null +++ b/test/native/spectral_contracts.c @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_error.h" +#include "hmath_spectral.h" +#include +#include +#include +#include + +int main(void) { + hmath_value *direction = NULL, *algorithm = NULL, *count = NULL, *plan = NULL; + hmath_context *context = NULL; + hmath_math_error error; + double buffer[] = {1, 0, 2, 0, 3, 0, 4, 0}; + double before[8]; + assert(hmath_init() == HMATH_OK); + assert(hmath_fourier_value_forward(NULL, &direction) == HMATH_OK); + assert(hmath_fourier_value_automatic(NULL, &algorithm) == HMATH_OK); + assert(hmath_value_index(NULL, 4, &count) == HMATH_OK); + assert(hmath_fourier_value_plan_fft(NULL, direction, algorithm, count, &plan) == HMATH_OK); + hmath_value_release(direction); + hmath_value_release(algorithm); + hmath_value_release(count); + memcpy(before, buffer, sizeof buffer); + assert(hmath_fourier_value_fft_in_place(NULL, plan, buffer, 3) == HMATH_MATH_ERROR); + assert(memcmp(buffer, before, sizeof buffer) == 0); + assert(hmath_last_math_error(&error)); + assert(hmath_fourier_value_fft_in_place(NULL, plan, NULL, 4) == HMATH_MATH_ERROR); + buffer[2] = NAN; + memcpy(before, buffer, sizeof buffer); + assert(hmath_fourier_value_fft_in_place(NULL, plan, buffer, 4) == HMATH_MATH_ERROR); + assert(memcmp(buffer, before, sizeof buffer) == 0); + buffer[2] = 2; + assert(hmath_context_create(&context) == HMATH_OK); + hmath_context_cancel(context); + memcpy(before, buffer, sizeof buffer); + assert(hmath_fourier_value_fft_in_place(context, plan, buffer, 4) == HMATH_CANCELLED); + assert(memcmp(buffer, before, sizeof buffer) == 0); + hmath_context_release(context); + assert(hmath_fourier_value_fft_in_place(NULL, plan, buffer, 4) == HMATH_OK); + assert(fabs(buffer[0] - 10) < 1e-12); + assert(fabs(buffer[2] + 2) < 1e-12 && fabs(buffer[3] - 2) < 1e-12); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(plan); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/stochastic_bindings.py b/test/native/stochastic_bindings.py new file mode 100644 index 0000000..771e45a --- /dev/null +++ b/test/native/stochastic_bindings.py @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Complete immutable stream continuation, arbitrary elements and checked callbacks.""" + +import gc +import sys +import weakref +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import matrix_advanced +from _hmath_native import probability_values as p +from _hmath_native import random_values as r +from _hmath_native import statistics_values as s +from _hmath_native._linear_base import _callback +from _hmath_native._math_error import MathError, MathErrorKind + +for factory in [ + r.pcg32, + r.xoshiro256_star_star, + r.xoroshiro128_plus, + r.mt19937, + r.philox4x32, + r.threefry2x64, + r.cha_cha20, +]: + with factory() as generator: + state = r.seed_rng(generator, 2**64 - 1) + word, partial = r.next_word64(state) + assert isinstance(word, int) and 0 <= word < 2**64 and partial != state + serialized = r.serialize_rng(partial) + restored = r.restore_rng(serialized) + clone = r.clone_rng(partial) + assert restored == clone == partial + first, next1 = r.next_word64(restored) + second, next2 = r.next_word64(clone) + assert first == second and next1 == next2 + for value in [state, partial, restored, clone, next1, next2]: + value.close() +with r.pcg32() as generator: + state = r.seed_rng(generator, 42) +objects = [ + None, + True, + 10**6000 + 3, + Fraction(10**5000 + 1, 7), + "a\0α🙂\ud800", + ("x", [1, 2]), +] +shuffled, end = r.shuffle(objects, state) +assert all( + any(item == candidate for candidate in objects) for item in shuffled +) and len(shuffled) == len(objects) +end.close() +samples, end = r.sample_n(3, lambda rng: ("payload\0α", r.clone_rng(rng)), state) +assert samples == ["payload\0α"] * 3 and end == state +end.close() +calls = [] +message = "checked\0α🙂\ud800" + + +def failing_inverse(x): + calls.append(x) + raise MathError(MathErrorKind.NON_CONVERGENCE, (11,), message) + + +try: + r.inverse_transform(failing_inverse, state) +except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.NON_CONVERGENCE + assert error.math_error.details == (11,) and error.math_error.message == message +else: + raise AssertionError("checked callback Left was swallowed") +assert len(calls) == 1 + + +# Pure callback failure aborts instead of becoming a fabricated successful value. +def bad_ratio(_x): + raise MathError(MathErrorKind.DOMAIN_ERROR, (), message) + + +try: + r.rejection(3, bad_ratio, lambda rng: r.uniform(rng), state) +except hmath.HMathError as error: + assert error.math_error.message == message +else: + raise AssertionError("pure callback error was swallowed") +with p.new_gaussian_kde(-1, [1, 2]) as raw: + assert raw.parts == ("GaussianKDE", (-1.0, [1.0, 2.0])) +try: + p.gaussian_kde(-1, [1, 2]) +except hmath.HMathError: + pass +else: + raise AssertionError("checked KDE constructor stopped validating") +# Streaming state and statistical records retain Integer counts/source fields. +stream = s.empty_streaming() +for value in [1.0, 2.0, 3.0, 4.0]: + updated = s.update_streaming(stream, value) + stream.close() + stream = updated +assert s.streaming_result(False, stream) == (4, 2.5, 1.25) +stream.close() +with s.TestResult(1.5, 0.25, [2.0]) as result: + assert ( + result.test_statistic == 1.5 + and result.p_value == 0.25 + and result.degrees_of_freedom == [2.0] + ) + + +# A generic callback can return a newly-created callback with Python userdata. +# It stays callable after the sampler frame is gone, then releases that userdata. +class Userdata: + pass + + +references = [] + + +def callback_sample(rng): + userdata = Userdata() + references.append(weakref.ref(userdata)) + + def operation(row, column): + assert userdata is not None + return float(row + column) + + return _callback(operation, ["a"], "float64"), r.clone_rng(rng) + + +functions, continuation = r.sample_n(1, callback_sample, state) +gc.collect() +assert references[0]() is not None +with matrix_advanced.generate_matrix(1, 2, functions[0]) as matrix: + assert matrix.to_list() == [0.0, 1.0] +functions[0].close() +continuation.close() +del functions +gc.collect() +assert references[0]() is None +state.close() +print( + "Stochastic all7continuations/bufferedrestore/Word64/exactelements/checked-purecallbacks/constructors/streaming contracts passed" +) diff --git a/test/native/stochastic_contracts.c b/test/native/stochastic_contracts.c new file mode 100644 index 0000000..5656589 --- /dev/null +++ b/test/native/stochastic_contracts.c @@ -0,0 +1,73 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_stochastic.h" +#include +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, \ + hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +static hmath_status checked_failure(const hmath_value *input, void *userdata, hmath_value **out, + hmath_math_error *error) { + (void)input; + (void)userdata; + (void)out; + static const char message[] = {'s', '\0', (char)0xce, (char)0xb1}; + error->kind = HMATH_MATH_NON_CONVERGENCE; + error->details[0] = 7; + error->message = message; + error->message_length = sizeof message; + return HMATH_MATH_ERROR; +} +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *generator = NULL, *seed = NULL, *state = NULL, *pair = NULL, *word = NULL, + *next = NULL; + CHECK(hmath_stochastic_random_new_pcg32(NULL, &generator) == HMATH_OK); + CHECK(hmath_value_integral(NULL, HMATH_COEFFICIENT_UINT64, "18446744073709551615", &seed) == + HMATH_OK); + CHECK(hmath_stochastic_random_seed_rng(NULL, generator, seed, &state) == HMATH_OK); + hmath_value_release(generator); + hmath_value_release(seed); + CHECK(hmath_stochastic_random_next_word64(NULL, state, &pair) == HMATH_OK); + CHECK(hmath_value_item(NULL, pair, 0, &word) == HMATH_OK); + CHECK(hmath_value_item(NULL, pair, 1, &next) == HMATH_OK); + hmath_value_release(pair); + hmath_value_release(state); + int kind = -1, dtype = -1; + size_t count = 99; + CHECK(hmath_value_info(word, &kind, &dtype, &count) == HMATH_OK && kind == 1 && dtype == 13); + char *numerator = NULL, *denominator = NULL; + CHECK(hmath_value_get_exact(word, &numerator, &denominator) == HMATH_OK && + strlen(numerator) <= 20 && strcmp(denominator, "1") == 0); + hmath_value_string_free(numerator); + hmath_value_string_free(denominator); + hmath_value_release(word); + hmath_value *serialized = NULL, *restored = NULL, *same = NULL; + CHECK(hmath_stochastic_random_serialize_rng(NULL, next, &serialized) == HMATH_OK); + CHECK(hmath_stochastic_random_restore_rng(NULL, serialized, &restored) == HMATH_OK); + CHECK(hmath_stochastic_equal(NULL, next, restored, &same) == HMATH_OK); + int equal = 0; + CHECK(hmath_value_get_boolean(same, &equal) == HMATH_OK && equal == 1); + hmath_value_release(same); + hmath_value_release(serialized); + hmath_value_release(next); + CHECK(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value *callback = NULL, *out = (hmath_value *)(uintptr_t)1; + CHECK(hmath_linear_callback(NULL, checked_failure, NULL, &callback) == HMATH_OK); + CHECK(hmath_stochastic_random_inverse_transform(NULL, callback, restored, &out) == + HMATH_MATH_ERROR && + out == (hmath_value *)(uintptr_t)1); + hmath_math_error error; + CHECK(hmath_last_math_error(&error) == 1 && error.kind == HMATH_MATH_NON_CONVERGENCE && + error.details[0] == 7 && error.message_length == 4 && + memcmp(error.message, "s\0\xce\xb1", 4) == 0); + hmath_value_release(callback); + hmath_value_release(restored); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/structural_matrix_contracts.c b/test/native/structural_matrix_contracts.c new file mode 100644 index 0000000..7dcbe55 --- /dev/null +++ b/test/native/structural_matrix_contracts.c @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_matrix_value.h" +#include +#include +#define CHECK(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "line%d: %s\n", __LINE__, hmath_last_error_message()); \ + exit(1); \ + } \ + } while (0) +int main(void) { + CHECK(hmath_init() == HMATH_OK); + hmath_value *yes = NULL, *no = NULL, *one = NULL, *two = NULL, *list = NULL, *matrix = NULL, + *column = NULL, *output = NULL; + CHECK(hmath_value_boolean(NULL, 1, &yes) == HMATH_OK && + hmath_value_boolean(NULL, 0, &no) == HMATH_OK); + CHECK(hmath_value_index(NULL, 1, &one) == HMATH_OK && + hmath_value_index(NULL, 2, &two) == HMATH_OK); + const hmath_value *items[] = {yes, no}; + CHECK(hmath_value_list(NULL, items, 2, &list) == HMATH_OK); + CHECK(hmath_matrix_value_from_list_checked(NULL, no, one, two, list, &matrix) == HMATH_OK); + int kind = -1, dtype = -1; + size_t count = 0; + CHECK(hmath_value_info(matrix, &kind, &dtype, &count) == HMATH_OK && kind == 9 && + dtype == HMATH_MATRIX_BOOL && count == 2); + CHECK(hmath_matrix_value_transpose_matrix(NULL, matrix, &column) == HMATH_OK); + hmath_value_release(matrix); + hmath_value_release(list); + hmath_value_release(yes); + CHECK(hmath_matrix_value_to_list(NULL, column, &list) == HMATH_OK); + CHECK(hmath_value_item(NULL, list, 0, &output) == HMATH_OK); + int boolean = 0; + CHECK(hmath_value_get_boolean(output, &boolean) == HMATH_OK && boolean == 1); + hmath_value_release(output); + hmath_value_release(list); + output = (hmath_value *)(uintptr_t)1; + CHECK(hmath_matrix_value_zero_matrix(NULL, no, one, two, &output) == HMATH_UNSUPPORTED && + output == (hmath_value *)(uintptr_t)1); + hmath_value_release(column); + hmath_value_release(no); + hmath_value_release(one); + hmath_value_release(two); + CHECK(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/structured_contracts.c b/test/native/structured_contracts.c new file mode 100644 index 0000000..b2c7281 --- /dev/null +++ b/test/native/structured_contracts.c @@ -0,0 +1,75 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_error.h" +#include "hmath_graph.h" +#include "hmath_timeseries.h" +#include +#include + +static hmath_status failed_heuristic(ptrdiff_t vertex, void *userdata, double *out) { + int *calls = (int *)userdata; + (void)vertex; + (void)out; + ++*calls; + return HMATH_HASKELL_EXCEPTION; +} + +int main(void) { + hmath_value *flag = NULL, *count = NULL, *empty = NULL, *graph = NULL; + hmath_value *zero = NULL, *one = NULL, *unit = NULL, *result = NULL; + hmath_value *start = NULL, *step = NULL, *missing = NULL, *samples = NULL; + hmath_value *series = NULL; + hmath_value *sentinel = (hmath_value *)(uintptr_t)1; + hmath_context *context = NULL; + hmath_math_error error; + int kind = -1, dtype = -1, calls = 0; + size_t size = 99; + assert(hmath_init() == HMATH_OK); + assert(hmath_value_boolean(NULL, 0, &flag) == HMATH_OK); + assert(hmath_value_index(NULL, 3, &count) == HMATH_OK); + assert(hmath_value_index(NULL, 0, &zero) == HMATH_OK); + assert(hmath_value_index(NULL, 1, &one) == HMATH_OK); + assert(hmath_value_list(NULL, NULL, 0, &empty) == HMATH_OK); + assert(hmath_graph_graph(NULL, flag, count, empty, &graph) == HMATH_OK); + assert(hmath_graph_check_vertex(NULL, graph, zero, &unit) == HMATH_OK); + assert(hmath_value_info(unit, &kind, &dtype, &size) == HMATH_OK); + assert(kind == 5 && size == 0); /* () retains tuple identity. */ + hmath_value_release(unit); + assert(hmath_graph_a_star(NULL, graph, failed_heuristic, &calls, zero, one, &sentinel) == + HMATH_HASKELL_EXCEPTION); + assert(calls > 0 && sentinel == (hmath_value *)(uintptr_t)1); + assert(hmath_context_create(&context) == HMATH_OK); + hmath_context_cancel(context); + assert(hmath_graph_vertex_count(context, graph, &sentinel) == HMATH_CANCELLED); + assert(sentinel == (hmath_value *)(uintptr_t)1); + hmath_context_release(context); + hmath_value_release(graph); + hmath_value_release(flag); + hmath_value_release(count); + hmath_value_release(zero); + hmath_value_release(one); + + assert(hmath_value_f64(NULL, 0, &start) == HMATH_OK); + assert(hmath_value_f64(NULL, 1, &step) == HMATH_OK); + assert(hmath_value_none(NULL, &missing) == HMATH_OK); + { + const hmath_value *items[] = {missing, step}; + assert(hmath_value_list(NULL, items, 2, &samples) == HMATH_OK); + } + assert(hmath_timeseries_regular_series(NULL, start, step, samples, &series) == HMATH_OK); + hmath_value_release(samples); + hmath_value_release(missing); + hmath_value_release(start); + hmath_value_release(step); + assert(hmath_timeseries_series_values(NULL, series, &sentinel) == HMATH_MATH_ERROR); + assert(sentinel == (hmath_value *)(uintptr_t)1); + assert(hmath_last_math_error(&error) && error.kind == HMATH_MATH_INVALID_ARGUMENT); + assert(hmath_timeseries_observations(NULL, series, &result) == HMATH_OK); + hmath_value_release(series); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + assert(hmath_value_info(result, &kind, &dtype, &size) == HMATH_OK); + assert(kind == 4 && size == 2); + hmath_value_release(result); + hmath_value_release(empty); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/tensor_bindings.py b/test/native/tensor_bindings.py new file mode 100644 index 0000000..710aba3 --- /dev/null +++ b/test/native/tensor_bindings.py @@ -0,0 +1,351 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original typed tensors, lazy graph callbacks and actual pinned mutable contracts.""" + +import ctypes as C +import gc +import math +import unittest +import weakref +from fractions import Fraction + +import hmath +from _hmath_native import _tensor_core as t +from _hmath_native import _value as v +from _hmath_native import autodiff as ad +from _hmath_native import numeric_types as n +from _hmath_native._autodiff_value import export_value, import_value +from hmath import errors + + +class TensorContracts(unittest.TestCase): + def test_supported_element_types_roundtrip_without_promotion(self): + cases = [ + ("float64", [1.25, -2]), + ("float32", [1.25, -2]), + ("integer", [10**100, -3]), + ("rational", [Fraction(1, 3), Fraction(2, 7)]), + ("complex128", [1 + 2j, -3 + 4j]), + ("complex64", [1 + 2j, -3 + 4j]), + ("int8", [-128, 127]), + ("uint64", [0, 2**64 - 1]), + ("bool", [True, False]), + ("string", ["λ\x00\ud800", "𝄞"]), + ] + for dtype, values in cases: + with ( + self.subTest(dtype=dtype), + t.tensor([2], values, dtype=dtype) as tensor, + ): + self.assertEqual(tensor.values, values) + text = t.serialize_tensor(tensor) + with t.deserialize_tensor(text, dtype=dtype) as restored: + self.assertEqual(tensor, restored) + + def test_column_major_reverse_and_broadcast_views_keep_metadata(self): + original = t.tensor_column_major([2, 2], [1, 2, 3, 4], dtype="float32") + self.assertEqual(original.values, [1, 3, 2, 4]) + self.assertEqual(original.strides, [1, 2]) + self.assertEqual(original.layout, t.ColumnMajor) + view = t.slice_tensor(1, 1, 2, -1, original) + original.close() + with view: + self.assertEqual(view.values, [3, 1, 4, 2]) + self.assertEqual(view.strides, [1, -2]) + self.assertEqual(view.offset, 2) + with ( + t.broadcast_to([3, 2, 2], view) as broadcast, + t.contiguous(broadcast) as copy, + ): + self.assertEqual(broadcast.strides, [0, 1, -2]) + self.assertEqual(copy.values, view.values * 3) + self.assertTrue(copy.is_contiguous) + + def test_original_rank_and_shape_rules_do_not_inherit_legacy_caps(self): + with t.tensor([0] + [2] * 100, [], dtype="float32") as empty: + self.assertEqual(len(empty.shape), 101) + self.assertEqual(empty.numel, 0) + with t.tensor([], [7], dtype="integer") as scalar: + self.assertEqual(t.index_tensor(scalar, []), 7) + with t.nonzero(scalar) as indices: + self.assertEqual(indices.shape, [1, 0]) + with self.assertRaises(hmath.HMathError) as caught: + t.tensor([0, -1], [], dtype="integer") + self.assertEqual( + caught.exception.math_error.kind, errors.MathErrorKind.INVALID_ARGUMENT + ) + with self.assertRaises(hmath.HMathError): + t.new_mutable([2 ** (C.sizeof(C.c_ssize_t) * 8 - 1) - 1], 0) + + def test_original_class_requirements_are_rejected_without_casts(self): + with ( + t.tensor([1], [1], dtype="integer") as integer, + t.tensor([1], [1], dtype="complex128") as complex_tensor, + t.tensor([1], [True], dtype="bool") as logical, + ): + calls = [ + lambda: t.tensor_divide(integer, integer), + lambda: t.thaw_tensor(integer), + lambda: t.norm_axes([0], False, integer), + lambda: t.sort_tensor(complex_tensor), + lambda: t.tensor_add(logical, logical), + ] + for call in calls: + with self.assertRaises(hmath.HMathError) as caught: + call() + self.assertEqual(caught.exception.status, 10) + + def test_explicit_promotion_and_original_fixed_width_arithmetic(self): + with ( + t.tensor([1], [1.0000001], dtype="float32") as single, + t.tensor([1], [1], dtype="float64") as double, + ): + with self.assertRaises(hmath.HMathError): + t.tensor_add(single, double) + with t.promote_tensor("float64", single) as promoted: + self.assertEqual(promoted.values, single.values) + with ( + t.tensor([1], [127], dtype="int8") as maximum, + t.tensor_ones([1], dtype="int8") as one, + t.tensor_add(maximum, one) as wrapped, + ): + self.assertEqual(wrapped.values, [-128]) + with self.assertRaises((OverflowError, ValueError, hmath.HMathError)): + t.tensor([1], [128], dtype="int8") + + def test_masks_gather_scatter_and_duplicate_updates(self): + with ( + t.tensor([3], [1, 2, 3], dtype="integer") as original, + t.tensor([3], [True, False, True], dtype="bool") as mask, + ): + with t.masked_select(mask, original) as selected: + self.assertEqual(selected.values, [1, 3]) + with t.masked_fill(mask, 7, original) as filled: + self.assertEqual(filled.values, [7, 2, 7]) + with t.gather(0, [2, 0, 2], original) as gathered: + self.assertEqual(gathered.values, [3, 1, 3]) + with t.tensor([2], [4, 5], dtype="integer") as updates: + with t.scatter(0, [1, 1], updates, original) as last: + self.assertEqual(last.values, [1, 5, 3]) + with t.scatter_add(0, [1, 1], updates, original) as added: + self.assertEqual(added.values, [1, 11, 3]) + self.assertEqual(original.values, [1, 2, 3]) + + def test_typed_callback_arithmetic_and_borrowed_scalar_lifetime(self): + seen = [] + + def cube(value): + seen.append(value) + return value * value * value + + with ( + t.tensor([1], [1.0000001], dtype="float32") as tensor, + t.map_tensor(cube, tensor) as result, + ): + self.assertEqual(result.dtype, "float32") + self.assertEqual(result.values, [1.0000003576278687]) + with self.assertRaises(ValueError): + _ = seen[0].info + with ( + t.tensor([1], ["λ"], dtype="string") as tensor, + t.map_tensor(str.upper, tensor) as result, + ): + self.assertEqual(result.values, ["Λ"]) + with ( + t.tensor([2], [1, 0], dtype="integer") as tensor, + t.map_tensor(lambda x: x == 0, tensor, dtype="bool") as result, + ): + self.assertEqual(result.values, [False, True]) + + def test_numeric_dual_tensor_preserves_original_forward_fields(self): + with ( + v.scalar(3, "float32") as primal, + v.scalar(1, "float32") as tangent, + n.dual(primal, tangent, boxed=True) as dual, + ): + with ( + t.tensor([1], [dual], dtype=dual) as tensor, + t.map_tensor(lambda x: x * x, tensor) as result, + ): + fields = result.values + try: + with fields[0].primal as p, fields[0].tangent as q: + self.assertEqual(p.value, 9) + self.assertEqual(q.value, 6) + self.assertEqual(p.dtype, "float32") + finally: + for value in fields: + value.close() + with self.assertRaises(hmath.HMathError) as caught: + t.deserialize_tensor("([],[])", dtype=dual) + self.assertEqual(caught.exception.status, 10) + + def test_lazy_graph_transitive_owners_and_reentrant_close(self): + calls = [] + + class Square: + def __call__(self, value): + calls.append(1) + return value * value + + function = Square() + reference = weakref.ref(function) + tensor = t.tensor([2], [2, 3], dtype="float32") + leaf = t.input_graph(tensor) + graph = t.map_graph(function, leaf) + del function + tensor.close() + leaf.close() + gc.collect() + self.assertEqual(calls, []) + self.assertIsNotNone(reference()) + with graph.evaluate() as result: + self.assertEqual(result.values, [4, 9]) + graph.close() + gc.collect() + self.assertIsNone(reference()) + holder = {} + + def close_during_call(value): + holder["graph"].close() + return value + 1 + + with t.tensor([1], [2]) as tensor, t.input_graph(tensor) as leaf: + holder["graph"] = t.map_graph(close_during_call, leaf) + with holder["graph"].evaluate() as result: + self.assertEqual(result.values, [3]) + self.assertEqual(calls, [1, 1]) + + def test_callback_error_payload_and_exception_identity(self): + with t.tensor([1], [2], dtype="float32") as tensor: + + def fail(_): + raise errors.DomainError("λ\x00" + "long" * 1000) + + with self.assertRaises(hmath.HMathError) as caught: + t.map_tensor(fail, tensor) + self.assertEqual( + caught.exception.math_error.message, "λ\x00" + "long" * 1000 + ) + exception = KeyboardInterrupt("stop") + + def interrupt(_): + raise exception + + with self.assertRaises(KeyboardInterrupt) as caught: + t.map_tensor(interrupt, tensor) + self.assertIs(caught.exception, exception) + + def test_mutable_views_share_storage_and_freeze_is_a_copy(self): + with ( + t.new_mutable([2, 2], 0, dtype="float32") as original, + t.slice_mutable(1, 1, 2, -1, original) as reversed_view, + t.transpose_mutable(reversed_view) as transposed, + ): + t.write_mutable(transposed, [0, 1], 7) + self.assertEqual(t.read_mutable(original, [1, 1]), 7) + with t.freeze_tensor(transposed) as copied: + t.write_mutable(original, [1, 1], 9) + self.assertEqual(copied.values, [0, 7, 0, 0]) + with self.assertRaises(hmath.HMathError): + t.write_mutable(original, [2, 0], 4) + self.assertEqual(t.read_mutable(original, [1, 1]), 9) + + def test_borrowed_buffer_is_actual_strided_storage_and_scoped(self): + saved = [] + with ( + t.new_mutable([3], 1, dtype="float32") as original, + t.slice_mutable(0, 2, 3, -1, original) as reversed_view, + ): + + def update(buffer): + saved.append(buffer) + self.assertEqual(buffer.strides, [-1]) + self.assertEqual(buffer.itemsize, C.sizeof(C.c_float)) + buffer.pointer[buffer.strides[0]] = 7 + return buffer.shape + + self.assertEqual(t.with_mutable_buffer(reversed_view, update), [3]) + self.assertEqual(t.read_mutable(original, [1]), 7) + with self.assertRaises(ValueError): + _ = saved[0].pointer + with t.new_mutable([2], True, dtype="bool") as logical: + + def change_boolean(buffer): + self.assertEqual(buffer.itemsize, C.sizeof(C.c_int)) + self.assertEqual(buffer.alignment, t.mutable_alignment("bool")) + buffer.pointer[0] = 0 + + t.with_mutable_buffer(logical, change_boolean) + with logical.freeze() as frozen: + self.assertEqual(frozen.values, [False, True]) + + def test_nan_policy_matches_generic_source_and_eq(self): + with t.tensor([1], [float("nan")]) as tensor: + self.assertFalse(tensor == tensor) # noqa: PLR0124 - source Eq on NaN is non-reflexive + with t.map_tensor(lambda x: x * x, tensor) as result: + self.assertTrue(math.isnan(result.values[0])) + + def test_original_autodiff_dual_interchange_retains_nesting_and_order(self): + with ( + ad.Dual(Fraction(2, 3), Fraction(1, 7), dtype="rational") as original, + import_value(original) as value, + export_value(value) as restored, + ): + self.assertEqual(value.info[0], 289) + self.assertEqual(restored.primal, Fraction(2, 3)) + self.assertEqual(restored.tangent, Fraction(1, 7)) + with ( + ad.Dual(3, 1, dtype="float32") as inner, + ad.Dual(inner, inner) as nested, + import_value(nested) as value, + export_value(value) as restored, + restored.primal as primal, + ): + self.assertEqual(primal.primal, 3) + + def test_structural_exact_keeps_original_instances(self): + from hmath import algebra_api as algebra + from hmath import shape + + with ( + algebra.Exact(Fraction(1, 3)) as third, + algebra.tensor_construct([2], [third, third]) as original, + original.element_type as dtype, + ): + self.assertEqual(original.dtype_code, 18) + self.assertEqual(dtype.info[0], 294) + with t.tensor_full([3], third, dtype=dtype) as filled: + values = filled.values + try: + self.assertEqual( + [value.value for value in values], [Fraction(1, 3)] * 3 + ) + finally: + for value in values: + value.close() + with ( + shape.static_tensor([2], original) as static, + shape.dynamic_tensor(static) as dynamic, + ): + self.assertEqual(dynamic.type_name, "Exact") + self.assertEqual(dynamic.shape, [2]) + with t.sort_tensor(original) as sorted_values: + values = sorted_values.values + try: + self.assertEqual( + [value.value for value in values], [Fraction(1, 3)] * 2 + ) + finally: + for value in values: + value.close() + with self.assertRaises(hmath.HMathError) as error: + t.tensor_add(original, original) + self.assertEqual(error.exception.status, 10) + + def test_zz_every_temporary_owner_releases_runtime(self): + gc.collect() + hmath.shutdown() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/tensor_contracts.c b/test/native/tensor_contracts.c new file mode 100644 index 0000000..aa2ff67 --- /dev/null +++ b/test/native/tensor_contracts.c @@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +#include "hmath_tensor_bindings.h" +#include +#include +#include +#include +static hmath_status square(const hmath_value *arguments, void *userdata, hmath_value **out, + hmath_callback_error *error) { + (void)error; + hmath_value *item = NULL; + float value, imaginary; + assert(hmath_value_item(NULL, arguments, 0, &item) == HMATH_OK); + assert(hmath_value_get_f32(item, &value, &imaginary) == HMATH_OK); + hmath_value_release(item); + ++*(int *)userdata; + return hmath_value_f32(NULL, value * value, out); +} +static hmath_status mutate(void *pointer, const hmath_value *metadata, void *userdata, + hmath_value **out, hmath_callback_error *error) { + (void)userdata; + (void)error; + hmath_value *bytes = NULL; + ptrdiff_t itemsize; + assert(hmath_value_item(NULL, metadata, 3, &bytes) == HMATH_OK); + assert(hmath_value_get_index(bytes, &itemsize) == HMATH_OK && itemsize == sizeof(float)); + hmath_value_release(bytes); + ((float *)pointer)[0] = 7; + return hmath_value_none(NULL, out); +} +int main(void) { + assert(hmath_init() == HMATH_INIT_OK); + hmath_value *type = NULL, *dimension = NULL, *shape = NULL, *first = NULL, *second = NULL, + *elements = NULL, *tensor = NULL; + assert(hmath_value_f32(NULL, 0, &type) == HMATH_OK); + assert(hmath_value_index(NULL, 2, &dimension) == HMATH_OK); + const hmath_value *dims[] = {dimension}; + assert(hmath_value_list(NULL, dims, 1, &shape) == HMATH_OK); + assert(hmath_value_f32(NULL, 2, &first) == HMATH_OK); + assert(hmath_value_f32(NULL, 3, &second) == HMATH_OK); + const hmath_value *values[] = {first, second}; + assert(hmath_value_list(NULL, values, 2, &elements) == HMATH_OK); + assert(hmath_tensor_object_tensor(NULL, type, shape, elements, &tensor) == HMATH_OK); + int count = 0; + hmath_value *callback = NULL, *leaf = NULL, *graph = NULL, *result = NULL, *items = NULL, + *item = NULL; + assert(hmath_tensor_object_callback(NULL, square, &count, &callback) == HMATH_OK); + assert(hmath_tensor_object_input_graph(NULL, tensor, &leaf) == HMATH_OK); + assert(hmath_tensor_object_map_graph(NULL, type, callback, leaf, &graph) == HMATH_OK); + assert(count == 0); + hmath_value_release(callback); + hmath_value_release(leaf); + hmath_value_release(tensor); + assert(hmath_tensor_object_evaluate_graph(NULL, graph, &result) == HMATH_OK && count == 2); + assert(hmath_tensor_object_tensor_values(NULL, result, &items) == HMATH_OK); + assert(hmath_value_item(NULL, items, 1, &item) == HMATH_OK); + float real, imaginary; + assert(hmath_value_get_f32(item, &real, &imaginary) == HMATH_OK && real == 9); + hmath_value_release(item); + hmath_value_release(items); + hmath_value *mutable_tensor = NULL, *buffer_callback = NULL, *unit = NULL; + assert(hmath_tensor_object_thaw_tensor(NULL, result, &mutable_tensor) == HMATH_OK); + assert(hmath_tensor_object_buffer_callback(NULL, mutate, NULL, &buffer_callback) == HMATH_OK); + assert(hmath_tensor_object_with_mutable_buffer(NULL, mutable_tensor, buffer_callback, &unit) == + HMATH_OK); + hmath_value_release(unit); + hmath_value_release(buffer_callback); + hmath_value *frozen = NULL; + assert(hmath_tensor_object_freeze_tensor(NULL, mutable_tensor, &frozen) == HMATH_OK); + assert(hmath_tensor_object_tensor_values(NULL, frozen, &items) == HMATH_OK); + assert(hmath_value_item(NULL, items, 0, &item) == HMATH_OK); + assert(hmath_value_get_f32(item, &real, &imaginary) == HMATH_OK && real == 7); + hmath_value_release(item); + hmath_value_release(items); + hmath_value_release(frozen); + hmath_value_release(mutable_tensor); + hmath_value_release(result); + hmath_value *invalid = (hmath_value *)(uintptr_t)0x1234; + assert(hmath_tensor_object_tensor(NULL, type, shape, NULL, &invalid) == HMATH_INVALID_ARGUMENT); + assert(invalid == (hmath_value *)(uintptr_t)0x1234); + assert(hmath_runtime_shutdown() == HMATH_BUSY); + hmath_value_release(graph); + hmath_value_release(type); + hmath_value_release(dimension); + hmath_value_release(shape); + hmath_value_release(first); + hmath_value_release(second); + hmath_value_release(elements); + assert(hmath_runtime_shutdown() == HMATH_OK); + return 0; +} diff --git a/test/native/tensor_contracts.cpp b/test/native/tensor_contracts.cpp new file mode 100644 index 0000000..7bed1d6 --- /dev/null +++ b/test/native/tensor_contracts.cpp @@ -0,0 +1,3 @@ +/* SPDX-License-Identifier: MPL-2.0 */ +/* Exercise the identical public C contract from C++17. */ +#include "tensor_contracts.c" diff --git a/test/native/units_bindings.py b/test/native/units_bindings.py new file mode 100644 index 0000000..af865e6 --- /dev/null +++ b/test/native/units_bindings.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exact quantities, affine-temperature contracts and independent Units owners.""" + +import sys +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import units_values as u +from _hmath_native._math_error import MathErrorKind + +with u.Dimension([10**5000] + [0] * 8) as dimension: + assert dimension.exponents == [10**5000] + [0] * 8 +with u.length_dimension() as dimension: + original = u.Unit("unit\0α🙂\ud800", dimension, Fraction(1, 10**5000 + 1), 0) +assert original.name == "unit\0α🙂\ud800" +assert original.scale == Fraction(1, 10**5000 + 1) +quantity = u.Quantity(original, 10**6000 + 3) +original.close() +assert quantity.si_value == Fraction(10**6000 + 3, 10**5000 + 1) +quantity.close() +with u.celsius() as c, u.fahrenheit() as f, u.kelvin() as k: + assert u.convert(c, f, 100) == 212 + assert u.convert(f, c, 32) == 0 + absolute = u.quantity(c, 20) + difference = u.temperature_difference(c, 10) + assert u.in_unit(k, absolute) == Fraction(29315, 100) + assert u.in_unit(k, difference) == 10 + assert u.in_unit(f, difference) == 18 + shifted = u.add_quantity(absolute, difference) + assert u.in_unit(c, shifted) == 30 + shifted.close() + absoluteTen = u.quantity(k, 10) + assert absoluteTen != difference + absoluteTen.close() + try: + u.add_quantity(absolute, absolute) + except hmath.HMathError as error: + assert error.math_error.kind == MathErrorKind.DOMAIN_ERROR + assert error.math_error.message == "cannot add absolute temperatures" + else: + raise AssertionError("absolute-temperature addition changed") + absolute.close() + difference.close() +prefixes = u.si_prefixes() +assert ( + len(prefixes) == 24 + and prefixes[0].name == "quetta" + and prefixes[-1].name == "quecto" +) +assert [p.exponent for p in prefixes] == [ + 30, + 27, + 24, + 21, + 18, + 15, + 12, + 9, + 6, + 3, + 2, + 1, + -1, + -2, + -3, + -6, + -9, + -12, + -15, + -18, + -21, + -24, + -27, + -30, +] +for prefix in prefixes: + prefix.close() +with u.SIPrefix("custom\0name", "µ\ud800", -3) as prefix: + assert ( + prefix.name == "custom\0name" + and prefix.symbol == "µ\ud800" + and prefix.exponent == -3 + ) + with u.metre() as metre: + derived = u.prefixed(prefix, metre) +assert derived.name == "µ\ud800m" and derived.scale == Fraction(1, 1000) +derived.close() +print( + "Units exact exponents/scalars, NUL/Unicode/surrogates, affine semantics and owner lifetimes passed" +) diff --git a/test/native/value_bindings.py b/test/native/value_bindings.py new file mode 100644 index 0000000..e5252c5 --- /dev/null +++ b/test/native/value_bindings.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Lossless value transport and independent native/callback-owner lifetimes.""" + +import ctypes as C +import math +import sys +import weakref +from fractions import Fraction +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bindings/python")) +import hmath +from _hmath_native import _value as v + +values = [ + None, + False, + True, + 0, + -17, + 10**6000, + Fraction(10**5000 + 1, 7), + 1.25, + -0.0, + float("inf"), + complex(1, -2), + "A\0🙂\ud800", +] +for original in values: + result = v.decode(v.encode(original)) + assert result == original, (type(original), type(result)) +assert math.copysign(1, v.decode(v.encode(-0.0))) == -1 +assert math.isnan(v.decode(v.encode(float("nan")))) +assert v.decode(v.encode(([1, 2], (None, "x\0y"), Fraction(7, 11)))) == ( + [1, 2], + (None, "x\0y"), + Fraction(7, 11), +) +for dtype, number in [ + ("float32", 16777217), + ("float64", 16777217), + ("complex64", complex(16777217, 1)), + ("complex128", complex(16777217, 1)), + ("int8", -128), + ("uint8", 255), + ("uint64", 2**64 - 1), +]: + value = v.scalar(number, dtype) + assert value.dtype == dtype + decoded = v.decode(value) + if dtype == "float32": + assert decoded == 16777216 + elif dtype == "complex64": + assert decoded == complex(16777216, 1) + else: + assert decoded == number +for dtype, number in [("int8", 128), ("uint8", -1), ("uint64", 2**64)]: + try: + v.scalar(number, dtype) + except hmath.HMathError as error: + assert error.status == 3 + else: + raise AssertionError("bounded scalar silently wrapped") + + +class Owner: + pass + + +owner = Owner() +reference = weakref.ref(owner) +source = v.encode(3) +source._owners = (owner,) +container = v.encode([source]) +source.close() +del owner +assert reference() is not None +child = container.item(0) +container.close() +assert reference() is not None +assert v.decode(child) == 3 +assert reference() is None +value = v.encode(1) +clone = value.clone() +value.close() +assert v.decode(clone) == 1 +with v.encode("A\0🙂\ud800") as text: + assert text.info == (10, -1, 4) + buffer = (C.c_uint32 * 5)(99, 99, 99, 99, 99) + function = v.api( + "hmath_value_get_text", C.c_int, C.c_void_p, C.POINTER(C.c_uint32), C.c_size_t + ) + assert function(text._ptr, buffer, 3) == 8 and list(buffer) == [99] * 5 + assert function(text._ptr, buffer, 4) == 0 and list(buffer) == [ + 65, + 0, + 0x1F642, + 0xD800, + 99, + ] +with v.encode([1, 2]) as sequence: + try: + sequence.item(-1) + except hmath.HMathError as error: + assert error.status == 8 + else: + raise AssertionError("negative list index accepted") +with v.encode(1.0) as scalar: + number = C.c_ssize_t(99) + function = v.api( + "hmath_value_get_index", C.c_int, C.c_void_p, C.POINTER(C.c_ssize_t) + ) + assert function(scalar._ptr, C.byref(number)) == 1 and number.value == 99 + assert scalar.info == (1, 0, 0) + assert ( + hmath._lib.hmath_last_error_code() == 1 + ) # metadata query preserves error state + try: + hmath.shutdown() + except hmath.HMathError as error: + assert error.status == 9 + else: + raise AssertionError("runtime shut down with an owned Value") +hmath.shutdown() +print( + "Value exact integers/rationals, primitive dtype, Unicode/NUL/surrogates, bounded checks, containers, owner snapshots, queries and runtime pinning passed." +) diff --git a/test/release_candidate.py b/test/release_candidate.py new file mode 100644 index 0000000..db4fe7d --- /dev/null +++ b/test/release_candidate.py @@ -0,0 +1,542 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Real candidate-format parsing and mocked read-only preparation-run selection.""" + +import base64 +import hashlib +import io +import json +import os +import subprocess +import sys +import tarfile +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import select_release_candidate as selector +import verify_release_candidate as verifier + +VERSION = "1.2.3" +COMMIT = "a" * 40 +REPOSITORY = "wavefnd/hmath" + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def tar(path, prefix, files, links=None): + with tarfile.open(path, "w:gz") as archive: + for name, data in files.items(): + item = tarfile.TarInfo(prefix + "/" + name) + item.size = len(data) + archive.addfile(item, io.BytesIO(data)) + for name, target in (links or {}).items(): + item = tarfile.TarInfo(prefix + "/" + name) + item.type = tarfile.SYMTYPE + item.linkname = target + archive.addfile(item) + + +class Candidate: + def __init__(self, directory): + self.directory = Path(directory) + self.wheel_name = f"hmath_python-{VERSION}-py3-none-manylinux_2_28_x86_64.whl" + self.native = bytearray(64) + self.native[:6] = b"\x7fELF\x02\x01" + self.native[16:20] = b"\x03\x00>\x00" + self.native = bytes(self.native) + self.libraries = {"hmath_python.libs/libHSfixture.so": b"fixture dependency"} + self.metadata = f"Metadata-Version: 2.4\nName: hmath-python\nVersion: {VERSION}\n\n".encode() + self.wheel_metadata = b"Wheel-Version: 1.0\nRoot-Is-Purelib: false\nTag: py3-none-manylinux_2_28_x86_64\n\n" + self.project = f'[project]\nname="hmath-python"\nversion="{VERSION}"\n'.encode() + self.cabal = f"cabal-version: 3.0\nname: hmath\nversion: {VERSION}\n".encode() + self.sdk_native = self.native + self.sdk_libraries = self.libraries.copy() + self.python_prefix = f"hmath_python-{VERSION}" + self.cabal_prefix = f"hmath-{VERSION}" + self.write() + + def write(self): + wheel = self.directory / self.wheel_name + with zipfile.ZipFile(wheel, "w") as archive: + dist = f"hmath_python-{VERSION}.dist-info/" + archive.writestr(dist + "METADATA", self.metadata) + archive.writestr(dist + "WHEEL", self.wheel_metadata) + archive.writestr("_hmath_native/libhmath.so", self.native) + for name, data in self.libraries.items(): + archive.writestr(name, data) + tar( + self.directory / f"hmath_python-{VERSION}.tar.gz", + self.python_prefix, + {"pyproject.toml": self.project, "PKG-INFO": self.metadata}, + ) + tar( + self.directory / f"hmath-{VERSION}.tar.gz", + self.cabal_prefix, + {"hmath.cabal": self.cabal}, + ) + sdk = { + "manifest.json": json.dumps( + { + "version": VERSION, + "abi": 1, + "platform": "linux-x86_64", + "wheel": self.wheel_name, + "wheel_sha256": digest(wheel.read_bytes()), + } + ).encode(), + "lib/libhmath.so.1": self.sdk_native, + "include/hmath.h": b"fixture header", + "lib/pkgconfig/hmath.pc": b"fixture pkg-config", + "lib/cmake/HMath/HMathConfig.cmake": b"fixture CMake config", + "lib/cmake/HMath/HMathConfigVersion.cmake": b"fixture CMake version", + "share/licenses/hmath/LICENSE": b"MPL-2.0", + **self.sdk_libraries, + } + tar( + self.directory / f"hmath-{VERSION}-linux-x86_64.tar.gz", + f"hmath-{VERSION}-linux-x86_64", + sdk, + {"lib/libhmath.so": "libhmath.so.1"}, + ) + + def receipts(self): + paths = verifier.validate_artifacts(self.directory, VERSION) + records = [ + { + "path": p.name, + "sha256": digest(p.read_bytes()), + "bytes": p.stat().st_size, + } + for p in paths + ] + manifest = { + "version": VERSION, + "commit": COMMIT, + "abi": 1, + "candidate_run_id": "123", + "artifacts": records, + } + (self.directory / "release.json").write_text(json.dumps(manifest)) + (self.directory / "SHA256SUMS").write_text( + "".join(item["sha256"] + " " + item["path"] + "\n" for item in records) + + digest((self.directory / "release.json").read_bytes()) + + " release.json\n" + ) + return manifest + + +class CandidateValidation(unittest.TestCase): + def setUp(self): + self.work = tempfile.TemporaryDirectory(prefix="candidate-parser-test-") + self.addCleanup(self.work.cleanup) + self.fixture = Candidate(self.work.name) + self.directory = Path(self.work.name) + + def verify(self): + return verifier.verify_candidate(self.directory, COMMIT) + + def test_complete_candidate_and_idempotent_artifact_validation(self): + self.fixture.receipts() + self.assertEqual(len(verifier.validate_artifacts(self.directory, VERSION)), 4) + self.assertEqual(self.verify()["candidate_run_id"], "123") + + def test_selected_old_candidate_version_is_independent_of_controller(self): + self.fixture.receipts() + self.assertEqual( + verifier.verify_candidate(self.directory, COMMIT)["version"], VERSION + ) + self.assertEqual( + verifier.verify_candidate(self.directory, COMMIT, VERSION)["version"], + VERSION, + ) + with self.assertRaisesRegex(ValueError, "selected preparation run"): + verifier.verify_candidate(self.directory, COMMIT, "9.9.9") + + def test_reject_extra_stale_and_nonflat_files(self): + for name in [ + "notes.txt", + "hmath_python-9.9.9.tar.gz", + "hmath-1.2.3.tar.gz.bak", + ]: + with self.subTest(name=name): + path = self.directory / name + path.write_bytes(b"extra") + with self.assertRaises(ValueError): + verifier.validate_artifacts(self.directory, VERSION) + path.unlink() + path = self.directory / "nested" + path.mkdir() + with self.assertRaises(ValueError): + verifier.validate_artifacts(self.directory, VERSION) + + def test_reject_wheel_metadata_version_and_platform_disagreement(self): + for mutation in ["name", "version", "tag", "purelib", "elf"]: + with self.subTest(mutation=mutation): + candidate = Candidate(self.directory) + if mutation == "name": + candidate.metadata = candidate.metadata.replace( + b"hmath-python", b"other" + ) + if mutation == "version": + candidate.metadata = candidate.metadata.replace( + VERSION.encode(), b"9.9.9" + ) + if mutation == "tag": + candidate.wheel_metadata = candidate.wheel_metadata.replace( + b"x86_64", b"aarch64" + ) + if mutation == "purelib": + candidate.wheel_metadata = candidate.wheel_metadata.replace( + b"false", b"true" + ) + if mutation == "elf": + candidate.native = b"not a shared library" + candidate.sdk_native = candidate.native + candidate.write() + with self.assertRaises(ValueError): + verifier.validate_artifacts(self.directory, VERSION) + + def test_reject_source_package_version_prefix_and_name(self): + for mutation in [ + "python-version", + "python-prefix", + "cabal-version", + "cabal-prefix", + ]: + with self.subTest(mutation=mutation): + candidate = Candidate(self.directory) + if mutation == "python-version": + candidate.project = candidate.project.replace( + VERSION.encode(), b"9.9.9" + ) + if mutation == "python-prefix": + candidate.python_prefix = "hmath_python-9.9.9" + if mutation == "cabal-version": + candidate.cabal = candidate.cabal.replace( + VERSION.encode(), b"9.9.9" + ) + if mutation == "cabal-prefix": + candidate.cabal_prefix = "hmath-9.9.9" + candidate.write() + with self.assertRaises(ValueError): + verifier.validate_artifacts(self.directory, VERSION) + + def test_sdk_must_use_exact_wheel_native_and_dependencies(self): + self.fixture.sdk_native = self.fixture.native + b"different build" + self.fixture.write() + with self.assertRaisesRegex(ValueError, "native library differs"): + verifier.validate_artifacts(self.directory, VERSION) + self.fixture.sdk_native = self.fixture.native + self.fixture.sdk_libraries = { + "hmath_python.libs/libHSfixture.so": b"different runtime" + } + self.fixture.write() + with self.assertRaisesRegex(ValueError, "dependencies differ"): + verifier.validate_artifacts(self.directory, VERSION) + + def test_receipts_source_identity_and_complete_checksum_coverage(self): + for mutation in [ + "commit", + "version", + "run-id", + "missing-record", + "duplicate-record", + "size", + "checksum", + "extra-record", + ]: + with self.subTest(mutation=mutation): + manifest = self.fixture.receipts() + if mutation == "commit": + manifest["commit"] = "b" * 40 + if mutation == "version": + manifest["version"] = "9.9.9" + if mutation == "run-id": + manifest["candidate_run_id"] = "" + if mutation == "missing-record": + manifest["artifacts"].pop() + if mutation == "duplicate-record": + manifest["artifacts"].append(manifest["artifacts"][0]) + if mutation == "size": + manifest["artifacts"][0]["bytes"] += 1 + if mutation == "checksum": + manifest["artifacts"][0]["sha256"] = "0" * 64 + if mutation == "extra-record": + manifest["artifacts"].append( + {"path": "release.json", "bytes": 1, "sha256": "0" * 64} + ) + (self.directory / "release.json").write_text(json.dumps(manifest)) + with self.assertRaises((ValueError, TypeError)): + self.verify() + self.fixture.receipts() + (self.directory / "SHA256SUMS").write_text("0" * 64 + " extra\n") + with self.assertRaisesRegex(ValueError, "SHA256SUMS"): + self.verify() + + def test_receipt_extra_file_and_symlink_are_rejected(self): + self.fixture.receipts() + (self.directory / "surprise.txt").write_bytes(b"unmanifested") + with self.assertRaises(ValueError): + self.verify() + (self.directory / "surprise.txt").unlink() + original = self.directory / self.fixture.wheel_name + source = self.directory / "actual" + original.rename(source) + original.symlink_to(source) + with self.assertRaises(ValueError): + self.verify() + + def test_duplicate_and_traversal_tar_members_are_rejected(self): + path = self.directory / f"hmath-{VERSION}.tar.gz" + with tarfile.open(path, "w:gz") as archive: + for name in [ + f"hmath-{VERSION}/hmath.cabal", + f"hmath-{VERSION}/../hmath.cabal", + ]: + item = tarfile.TarInfo(name) + item.size = len(self.fixture.cabal) + archive.addfile(item, io.BytesIO(self.fixture.cabal)) + with self.assertRaisesRegex(ValueError, "unsafe artifact member"): + verifier.validate_artifacts(self.directory, VERSION) + + +def run_metadata(run_id=123, **changes): + return { + "id": run_id, + "repository": {"full_name": REPOSITORY}, + "path": selector.WORKFLOW, + "head_sha": COMMIT, + "head_branch": "master", + "event": "workflow_dispatch", + "status": "completed", + "conclusion": "success", + "created_at": f"2026-11-{run_id % 20 + 1:02d}T00:00:00Z", + **changes, + } + + +def source_metadata(version=VERSION): + source = '[project]\nname="hmath-python"\nversion="' + version + '"\n' + return { + "type": "file", + "encoding": "base64", + "content": base64.b64encode(source.encode()).decode(), + } + + +class CandidateSelection(unittest.TestCase): + def setUp(self): + self.version = patch.object(selector, "release_version", return_value=VERSION) + self.version.start() + self.addCleanup(self.version.stop) + + def test_explicit_run_is_checked_without_release_or_latest_queries(self): + with patch.object( + selector, "gh_read", side_effect=[run_metadata(), source_metadata()] + ) as read: + self.assertEqual( + selector.select_candidate(REPOSITORY, COMMIT, "123"), + { + "version": VERSION, + "candidate_run_id": "123", + "candidate_sha": COMMIT, + }, + ) + self.assertEqual( + read.call_args_list[0].args, (f"repos/{REPOSITORY}/actions/runs/123",) + ) + self.assertEqual( + read.call_args_list[1].args, + (f"repos/{REPOSITORY}/contents/pyproject.toml?ref={COMMIT}",), + ) + + def test_cli_emits_immutable_source_sha_and_version_without_reentry(self): + with tempfile.TemporaryDirectory(prefix="candidate-output-") as directory: + output = Path(directory) / "output" + with ( + patch.object( + selector, "gh_read", side_effect=[run_metadata(), source_metadata()] + ), + patch.object( + sys, + "argv", + [ + "select_release_candidate.py", + "--repository", + REPOSITORY, + "--commit", + COMMIT, + "--run-id", + "123", + ], + ), + patch.dict(os.environ, {"GITHUB_OUTPUT": str(output)}), + patch.object(sys, "stdout", new=io.StringIO()), + ): + selector.main() + self.assertEqual( + output.read_text(), + "candidate_run_id=123\ncandidate_sha=" + + COMMIT + + "\nversion=" + + VERSION + + "\n", + ) + + def test_reject_invalid_source_repository_workflow_event_status_and_branch(self): + for changed in [ + {"head_sha": "malformed"}, + {"repository": {"full_name": "other/repo"}}, + {"path": ".github/workflows/publish-python.yml"}, + {"head_branch": "feature"}, + {"event": "push"}, + {"conclusion": "failure"}, + {"status": "in_progress"}, + ]: + with ( + self.subTest(changed=changed), + patch.object(selector, "gh_read", return_value=run_metadata(**changed)), + self.assertRaises(ValueError), + ): + selector.select_candidate(REPOSITORY, COMMIT, "123") + + def test_explicit_old_source_survives_new_controller_commit_and_version(self): + with patch.object( + selector, "gh_read", side_effect=[run_metadata(), source_metadata("1.0.0")] + ): + selected = selector.select_candidate(REPOSITORY, "c" * 40, "123") + self.assertEqual( + selected, + {"version": "1.0.0", "candidate_run_id": "123", "candidate_sha": COMMIT}, + ) + + def test_existing_draft_receipt_wins_after_controller_workflow_fix(self): + receipt = json.dumps( + {"version": VERSION, "commit": COMMIT, "candidate_run_id": "123"} + ) + + def read(path, **_): + if "/releases?" in path: + return [ + [ + { + "tag_name": "v" + VERSION, + "draft": True, + "target_commitish": "master", + "assets": [{"name": "release.json", "id": 9}], + } + ] + ] + if "/releases/assets/9" in path: + return receipt + if path.endswith("/runs/123"): + return run_metadata() + if "/contents/pyproject.toml?ref=" + COMMIT in path: + return source_metadata() + raise AssertionError("must not select/rebuild a newer candidate: " + path) + + with patch.object(selector, "gh_read", side_effect=read): + selected = selector.select_candidate(REPOSITORY, "c" * 40) + self.assertEqual(selected["candidate_sha"], COMMIT) + self.assertEqual(selected["candidate_run_id"], "123") + + def test_existing_receipt_run_must_match_its_recorded_source(self): + release = [ + [{"tag_name": "v" + VERSION, "assets": [{"name": "release.json", "id": 9}]}] + ] + receipt = json.dumps( + {"version": VERSION, "commit": "b" * 40, "candidate_run_id": "123"} + ) + with ( + patch.object( + selector, "gh_read", side_effect=[release, receipt, run_metadata()] + ), + self.assertRaisesRegex(ValueError, "head_sha"), + ): + selector.select_candidate(REPOSITORY, "c" * 40) + + def test_invalid_existing_receipt_does_not_fall_back(self): + release = [ + [{"tag_name": "v" + VERSION, "assets": [{"name": "release.json", "id": 9}]}] + ] + receipt = json.dumps( + {"version": "9.9.9", "commit": COMMIT, "candidate_run_id": "123"} + ) + with ( + patch.object(selector, "gh_read", side_effect=[release, receipt]), + self.assertRaisesRegex(ValueError, "another version"), + ): + selector.select_candidate(REPOSITORY, COMMIT) + + def test_receipt_version_must_match_immutable_source_project(self): + release = [ + [{"tag_name": "v" + VERSION, "assets": [{"name": "release.json", "id": 9}]}] + ] + receipt = json.dumps( + {"version": VERSION, "commit": COMMIT, "candidate_run_id": "123"} + ) + with ( + patch.object( + selector, + "gh_read", + side_effect=[ + release, + receipt, + run_metadata(), + source_metadata("9.9.9"), + ], + ), + self.assertRaisesRegex(ValueError, "receipt version"), + ): + selector.select_candidate(REPOSITORY, COMMIT) + + def test_latest_successful_dispatch_at_exact_commit_is_selected(self): + older = run_metadata(122, created_at="2026-11-01T00:00:00Z") + newer = run_metadata(123, created_at="2026-11-02T00:00:00Z") + other = run_metadata(999, head_sha="b" * 40, created_at="2026-11-03T00:00:00Z") + with patch.object( + selector, + "gh_read", + side_effect=[ + [], + [{"workflow_runs": [older, other, newer]}], + newer, + source_metadata(), + ], + ): + selected = selector.select_candidate(REPOSITORY, COMMIT) + self.assertEqual(selected["candidate_run_id"], "123") + self.assertEqual(selected["candidate_sha"], COMMIT) + + def test_no_receipt_does_not_silently_select_an_unrelated_old_source(self): + with ( + patch.object( + selector, + "gh_read", + side_effect=[[], [{"workflow_runs": [run_metadata()]}]], + ), + self.assertRaisesRegex(ValueError, "no successful Prepare"), + ): + selector.select_candidate(REPOSITORY, "c" * 40) + + def test_read_errors_are_not_treated_as_an_absent_release(self): + error = subprocess.CompletedProcess([], 1, "", "gh: Forbidden (HTTP 403)") + with ( + patch.object(selector.subprocess, "run", return_value=error), + self.assertRaises(RuntimeError), + ): + selector.gh_read("repos/wavefnd/hmath/releases", missing=True) + absent = subprocess.CompletedProcess([], 1, "", "gh: Not Found (HTTP 404)") + with patch.object(selector.subprocess, "run", return_value=absent): + self.assertIsNone( + selector.gh_read("repos/wavefnd/hmath/releases", missing=True) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/release_publishing.py b/test/release_publishing.py new file mode 100644 index 0000000..7fec738 --- /dev/null +++ b/test/release_publishing.py @@ -0,0 +1,145 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exercise publishing recovery and collision handling without remote writes.""" + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + +import publish_github_release as publisher +from release_candidate import COMMIT, REPOSITORY, VERSION, Candidate, digest + + +class ReleasePublishing(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory(prefix="hmath-publish-test-") + self.addCleanup(directory.cleanup) + self.directory = Path(directory.name) + Candidate(self.directory).receipts() + self.calls = [] + self.releases = [] + self.resolved_target = COMMIT + + def asset(self, name): + return { + "name": name, + "digest": "sha256:" + digest((self.directory / name).read_bytes()), + } + + def existing(self, target=COMMIT, assets=(), draft=True): + release = { + "tag_name": "v" + VERSION, + "target_commitish": target, + "draft": draft, + "prerelease": False, + "assets": [self.asset(name) for name in assets], + } + self.releases.append(release) + return release + + def gh(self, *arguments): + self.calls.append(arguments) + if arguments[:3] == ("api", "--paginate", "--slurp"): + return json.dumps([self.releases]) + if arguments[0] == "api" and "/commits/" in arguments[1]: + return self.resolved_target + "\n" + return "" + + def run_publisher(self, stage=True, tag=None): + argv = [ + "publisher", + str(self.directory), + "--repository", + REPOSITORY, + "--commit", + COMMIT, + ] + if stage: + argv.append("--stage-only") + with ( + patch.object(sys, "argv", argv), + patch.object(publisher, "gh", side_effect=self.gh), + patch.object(publisher, "tag_target", return_value=tag), + ): + publisher.main() + + def writes(self): + return [call for call in self.calls if call[0] == "release"] + + def test_stage_persists_receipt_first_and_does_not_publish(self): + self.run_publisher() + writes = self.writes() + self.assertEqual(writes[0][:2], ("release", "create")) + self.assertIn("--draft", writes[0]) + self.assertEqual(Path(writes[1][3]).name, "release.json") + self.assertEqual(len([w for w in writes if w[1] == "upload"]), 6) + self.assertFalse(any("--draft=false" in w for w in writes)) + + def test_partial_upload_resumes_with_identical_files(self): + self.existing(assets=["release.json", "SHA256SUMS"]) + self.run_publisher(stage=False, tag=COMMIT) + writes = self.writes() + self.assertEqual(len([w for w in writes if w[1] == "upload"]), 4) + self.assertIn("--draft=false", writes[-1]) + self.assertFalse(any(w[1] == "create" for w in writes)) + + def test_different_asset_is_rejected_before_all_writes(self): + existing = self.existing(assets=["release.json", "SHA256SUMS"]) + existing["assets"][1]["digest"] = "sha256:" + "0" * 64 + with self.assertRaisesRegex(ValueError, "differs"): + self.run_publisher() + self.assertEqual(self.writes(), []) + + def test_unrelated_asset_or_wrong_tag_is_rejected_before_all_writes(self): + existing = self.existing() + existing["assets"] = [{"name": "unrelated.zip"}] + with self.assertRaisesRegex(ValueError, "outside this candidate"): + self.run_publisher() + self.assertEqual(self.writes(), []) + self.calls.clear() + with self.assertRaisesRegex(ValueError, "another source commit"): + self.run_publisher(tag="b" * 40) + self.assertEqual(self.writes(), []) + + def test_moving_draft_branch_is_pinned_before_index_uploads(self): + self.existing(target="master", assets=["release.json"]) + self.resolved_target = "b" * 40 + self.run_publisher() + first = self.writes()[0] + self.assertEqual(first[:2], ("release", "edit")) + self.assertEqual(first[-2:], ("--target", COMMIT)) + + def test_moving_branch_without_receipt_or_wrong_pinned_sha_is_rejected(self): + self.existing(target="master") + self.resolved_target = "b" * 40 + with self.assertRaisesRegex(ValueError, "another source commit"): + self.run_publisher() + self.assertEqual(self.writes(), []) + self.releases.clear() + self.existing(target="b" * 40, assets=["release.json"]) + with self.assertRaisesRegex(ValueError, "another source commit"): + self.run_publisher() + self.assertEqual(self.writes(), []) + + def test_backfill_does_not_replace_newer_latest_release(self): + self.existing(assets=[p.name for p in self.directory.iterdir()]) + self.releases.append( + {"tag_name": "v9.0.0", "draft": False, "prerelease": False} + ) + self.run_publisher(stage=False, tag=COMMIT) + self.assertEqual(len(self.writes()), 1) + self.assertIn("--latest=false", self.writes()[0]) + + def test_finalization_is_idempotent(self): + self.existing(assets=[p.name for p in self.directory.iterdir()], draft=False) + self.run_publisher(stage=False, tag=COMMIT) + self.assertEqual(len(self.writes()), 1) + self.assertIn("--latest=true", self.writes()[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/build_c_sdk.py b/tools/build_c_sdk.py new file mode 100644 index 0000000..44fe93e --- /dev/null +++ b/tools/build_c_sdk.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Package the repaired wheel's exact native library as a relocatable C SDK. + +Keep auditwheel's library directory and relative RPATH layout intact. No +second native build or system GHC installation is needed by C consumers. +""" + +import argparse +import gzip +import hashlib +import json +import re +import shutil +import subprocess +import tarfile +import tempfile +import zipfile +from email.parser import Parser +from pathlib import Path, PurePosixPath + +import tomllib + +ROOT = Path(__file__).resolve().parent.parent + + +def package(wheel, output, epoch): + version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + name = f"hmath-{version}-linux-x86_64" + with tempfile.TemporaryDirectory(prefix="hmath-sdk-") as work: + prefix = Path(work) / name + (prefix / "lib").mkdir(parents=True) + with zipfile.ZipFile(wheel) as archive: + metadata_names = [ + n for n in archive.namelist() if n.endswith(".dist-info/METADATA") + ] + if len(metadata_names) != 1: + raise ValueError("expected exactly one wheel METADATA") + metadata = Parser().parsestr(archive.read(metadata_names[0]).decode()) + if metadata["Name"] != "hmath-python" or metadata["Version"] != version: + raise ValueError("wheel name/version differs from this source checkout") + wheel_metadata = archive.read( + metadata_names[0].removesuffix("METADATA") + "WHEEL" + ).decode() + if not re.search( + r"^Tag: py3-none-manylinux_[\w.]*x86_64$", wheel_metadata, re.MULTILINE + ): + raise ValueError("the C SDK requires a repaired Linux x86-64 wheel") + libraries = [ + n + for n in archive.namelist() + if n.startswith("hmath_python.libs/") and not n.endswith("/") + ] + if not libraries: + raise ValueError("wheel has no bundled auditwheel dependencies") + native = prefix / "lib/libhmath.so.1" + native.write_bytes(archive.read("_hmath_native/libhmath.so")) + for entry in libraries: + parts = PurePosixPath(entry).parts + if len(parts) != 2 or parts[1] in (".", ".."): + raise ValueError("unexpected bundled library path") + destination = prefix / entry + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(archive.read(entry)) + for entry in archive.namelist(): + if entry.startswith("_hmath_native/licenses/") and not entry.endswith( + "/" + ): + destination = ( + prefix / "share/licenses/hmath" / PurePosixPath(entry).name + ) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(archive.read(entry)) + # A SONAME alias is necessary for executables linked with -lhmath. + (prefix / "lib/libhmath.so").symlink_to("libhmath.so.1") + rpath = subprocess.check_output(["readelf", "-d", str(native)], text=True) + if "$ORIGIN/../hmath_python.libs" not in rpath: + raise ValueError( + "unexpected auditwheel RPATH; SDK relocation would be unsafe" + ) + subprocess.run( + ["python3", str(ROOT / "tools/check_abi.py"), str(native)], check=True + ) + (prefix / "include").mkdir() + # Internal provider adapter headers are intentionally not installed. + for header in sorted((ROOT / "include").glob("hmath*.h")): + if header.name != "hmath_backend.h": + shutil.copy2(header, prefix / "include" / header.name) + licenses = prefix / "share/licenses/hmath" + licenses.mkdir(parents=True, exist_ok=True) + shutil.copy2(ROOT / "LICENSE", licenses / "LICENSE") + variables = { + "VERSION": version, + "LIBDIR": "lib", + "INCLUDEDIR": "include", + "LIBRARY": "libhmath.so.1", + "CMAKE_PREFIX_RELATIVE": "../../..", + "PC_PREFIX_RELATIVE": "../..", + } + for source, destination in [ + ("meson/hmath.pc.in", "lib/pkgconfig/hmath.pc"), + ("meson/cmake/HMathConfig.cmake.in", "lib/cmake/HMath/HMathConfig.cmake"), + ( + "meson/cmake/HMathConfigVersion.cmake.in", + "lib/cmake/HMath/HMathConfigVersion.cmake", + ), + ]: + text = (ROOT / source).read_text() + for key, value in variables.items(): + text = text.replace("@" + key + "@", value) + target = prefix / destination + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text) + (prefix / "manifest.json").write_text( + json.dumps( + { + "version": version, + "abi": 1, + "platform": "linux-x86_64", + "wheel": wheel.name, + "wheel_sha256": hashlib.sha256(wheel.read_bytes()).hexdigest(), + }, + indent=2, + ) + + "\n" + ) + output.mkdir(parents=True, exist_ok=True) + target = output / (name + ".tar.gz") + with ( + target.open("wb") as file, + gzip.GzipFile( + fileobj=file, mode="wb", filename="", mtime=epoch + ) as compressed, + tarfile.open(fileobj=compressed, mode="w") as archive, + ): + for path in sorted(prefix.rglob("*")): + info = archive.gettarinfo( + str(path), str(path.relative_to(prefix.parent)) + ) + info.uid = info.gid = 0 + info.uname = info.gname = "" + info.mtime = epoch + if info.isfile(): + info.mode = 0o644 + with path.open("rb") as content: + archive.addfile(info, content) + else: + info.mode = 0o755 + archive.addfile(info) + return target + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("wheel", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--epoch", type=int, required=True) + args = parser.parse_args() + print(package(args.wheel, args.output, args.epoch)) + + +if __name__ == "__main__": + main() diff --git a/tools/build_docs.py b/tools/build_docs.py index fdc5e8d..35e099f 100644 --- a/tools/build_docs.py +++ b/tools/build_docs.py @@ -43,6 +43,21 @@ raise SystemExit(f"Haddock reference not found: {reference}") interface = reference / "hmath.haddock" check_reference(interface) +for generator in sorted((root / "tools").glob("generate_*bindings.py")): + subprocess.run([sys.executable, str(generator), "--check"], cwd=root, check=True) +for generator in ( + "generate_numeric_types.py", + "generate_scalar_extras.py", + "generate_numeric_objects.py", +): + subprocess.run( + [sys.executable, "tools/" + generator, "--check"], cwd=root, check=True + ) +subprocess.run( + [sys.executable, "tools/check_binding_coverage.py", "--interface", str(interface)], + cwd=root, + check=True, +) subprocess.run( [sys.executable, "tools/check_haskell_doc_examples.py"], cwd=root, check=True ) diff --git a/tools/build_python_wheel.sh b/tools/build_python_wheel.sh index 98a1c7e..ff34354 100644 --- a/tools/build_python_wheel.sh +++ b/tools/build_python_wheel.sh @@ -36,6 +36,13 @@ HMATH_BUILD_LIBRARY="$work/libhmath.so" "$python" -m build --wheel --outdir "$wo "$python" -m build --sdist --outdir /io/dist "$python" -m auditwheel show /io/dist/*.whl +# C and Haskell distributions use the same checkout and native wheel. C +# consumers get exactly the repaired library tested by Python consumers. +mkdir -p /io/dist/native +release_epoch=${SOURCE_DATE_EPOCH:-0} +"$python" /io/tools/build_c_sdk.py /io/dist/*.whl --output /io/dist/native --epoch "$release_epoch" +cabal sdist --output-directory=/io/dist/native + # An sdist must really build without the wheel staging environment variable. mkdir "$work/source" tar -xf /io/dist/hmath_python-*.tar.gz -C "$work/source" diff --git a/tools/check_abi.py b/tools/check_abi.py index 168cd57..364476b 100644 --- a/tools/check_abi.py +++ b/tools/check_abi.py @@ -17,9 +17,29 @@ def main(): for line in (root / "test/abi-symbols.txt").read_text().splitlines() if line and not line.startswith("#") } + expected.update( + (root / "bindings/schema/numeric-symbols.txt").read_text().splitlines() + ) + for header in (root / "include").glob("hmath*.h"): + expected.update( + re.findall( + r"HMATH_API\s+[\w\s*]+?\b(hmath_\w+)\s*\(", + header.read_text(), + ) + ) dynamic = subprocess.check_output(["readelf", "-d", str(args.library)], text=True) if not re.search(r"\(SONAME\).*\[libhmath\.so\.1\]", dynamic): raise RuntimeError("C ABI epoch 1 requires SONAME libhmath.so.1") + undefined = subprocess.check_output( + ["nm", "-D", "--undefined-only", str(args.library)], text=True + ) + internal = { + line.split()[-1] + for line in undefined.splitlines() + if line.split() and line.split()[-1].startswith(("hm_", "hmath_")) + } + if internal: + raise RuntimeError(f"Unresolved internal FFI symbols: {sorted(internal)}") output = subprocess.check_output( ["nm", "-D", "--defined-only", str(args.library)], text=True ) diff --git a/tools/check_algebra_equivalence.py b/tools/check_algebra_equivalence.py new file mode 100644 index 0000000..d48d75b --- /dev/null +++ b/tools/check_algebra_equivalence.py @@ -0,0 +1,458 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Direct source oracle for every algebra operation and actual instance family.""" + +import argparse +import importlib +import os +import subprocess +import sys +import tempfile +from fractions import Fraction as Q +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_algebra_bindings import MODULES, mode, specification +from generate_linear_bindings import snake + +ROOT = Path(__file__).resolve().parent.parent + + +def normalized(value, modules, precision=64): + from _hmath_native import vector + from _hmath_native._foundation_base import FoundationValue + from _hmath_native._linear_base import LinearValue + from _hmath_native._matrix_base import Matrix + from _hmath_native._tensor_object import Tensor + from _hmath_native.polynomial import Polynomial + + if isinstance(value, FoundationValue): + name = value.source_type.rsplit(".", 1)[-1] + a = modules["HMath.Algebra"] + p = modules["HMath.API.Algebra"] + if name == "Exact": + return "X(" + normalized(p.get_exact(value), modules, precision) + ")" + if name == "Additive": + part = a.get_additive(value) + try: + return "A(" + normalized(part, modules, precision) + ")" + finally: + close(part) + if name == "Modular": + return ( + "Z(" + + normalized( + (a.modular_modulus(value), a.modular_value(value)), + modules, + precision, + ) + + ")" + ) + if name == "FiniteField": + return ( + "F(" + + normalized( + ( + a.field_characteristic(value), + a.field_degree(value), + a.field_cardinality(value), + a.field_modulus(value), + ), + modules, + precision, + ) + + ")" + ) + if name == "FieldElement": + return ( + "E(" + + normalized(a.field_element_coefficients(value), modules, precision) + + ")" + ) + raise TypeError(name) + if isinstance(value, Polynomial): + return ( + "P[" + + ",".join(normalized(x, modules, precision) for x in value.coefficients) + + "]" + ) + if isinstance(value, Matrix): + r, c = value.shape + values = value.to_list() + try: + return ( + f"M{r}:{c}[" + + ",".join(normalized(x, modules, precision) for x in values) + + "]" + ) + finally: + close(values) + if isinstance(value, Tensor): + p = modules["HMath.API.Algebra"] + values = p.tensor_elements(value) + try: + return ( + "TENSOR(" + + normalized((p.tensor_dimensions(value), values), modules, precision) + + ")" + ) + finally: + close(values) + if isinstance(value, LinearValue): + return ( + "VECTOR(" + + normalized(vector.vector_values(value), modules, precision) + + ")" + ) + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, Q): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + return f"F{precision}:" + str(bits(value, precision)) + if isinstance(value, complex): + return ( + f"C{precision}:" + + str(bits(value.real, precision)) + + ":" + + str(bits(value.imag, precision)) + ) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(c)) for c in value) + "]" + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(normalized(x, modules, precision) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import algebra as a + from _hmath_native import algebra_api as p + from _hmath_native import autodiff as ad + from _hmath_native import polynomial as poly + from _hmath_native import vector + + modules = { + m: importlib.import_module("_hmath_native." + ns) + for m, (_alias, ns) in MODULES.items() + } + owners = [] + tests = [] + expressions = [] + + def own(value): + owners.append(value) + return value + + field = own(a.finite_field(32, 2, [1, 1, 1])) + modulus = own(a.modular(7, 3)) + element = own(a.field_element(field, [0, 1])) + base_poly = own(poly.polynomial([1, 2], dtype="rational")) + exact = own(p.Exact(Q(2, 3))) + matrix = own(p.matrix_construct(2, 2, [Q(1), Q(2), Q(3), Q(4)])) + tensor = own(p.tensor_construct([2], [Q(1), Q(2)])) + vec = own(vector.vector([Q(1), Q(2)], dtype="rational")) + dual = own(ad.Dual(Q(2), Q(3), dtype="rational")) + objects = { + "Modular": (modulus, "z"), + "FiniteField": (field, "f"), + "FieldElement": (element, "e"), + "Exact": (exact, "P.Exact(2%3)"), + "Matrix": (matrix, "mat"), + "Tensor": (tensor, "ten"), + "Vector": (vec, "vec"), + "Dual": (dual, "AD.Dual(2%1)(3%1)"), + } + entries, _ = specification() + + def typed(type_name): + if type_name == "Integer": + return 2, "(2::Integer)", "integer", 64 + if type_name == "Rational": + return Q(2, 3), "(2%3::Rational)", "rational", 64 + if type_name == "Float": + return 0.75, "(0.75::Float)", "float32", 32 + if type_name == "Double": + return 0.75, "(0.75::Double)", "float64", 64 + if type_name == "Complex Double": + return complex(0.75, 0.25), "(0.75:+0.25::Complex Double)", "complex128", 64 + if type_name == "P.Exact": + return exact, "(P.Exact(2%3))", exact, 64 + if type_name == "Poly.Polynomial Rational": + return base_poly, "pol", base_poly, 64 + raise ValueError(type_name) + + def argument(spec, e, index, type_name): + name = e["name"] + head, *children = spec + if head in ("a", "s"): + return typed(type_name)[:2] + if head == "v": + x, h, *_ = typed(type_name) + return [x, x], "[" + h + "," + h + "]" + if head == "Additive": + x, h, dt, _ = typed(type_name) + return own(a.Additive(x, dtype=dt)), "A.Additive(" + h + ")" + if head in objects: + return objects[head] + if head == "Integer": + value = 2 + if name == "modular": + value = 7 if index == 0 else 3 + if name in ("finiteField", "primeField"): + value = 2 + return value, str(value) + if head == "Int": + return ( + (32, "32") + if name + in ("finiteField", "primeField", "fieldElements", "finiteFieldLaws") + else (2, "2") + ) + if head == "Rational": + return Q(2, 3), "(2%3)" + if head == "list": + if name == "groupLaws": + x, h, dt, _ = typed(type_name) + return [own(a.Additive(x, dtype=dt))], "[A.Additive(" + h + ")]" + if name in ("fieldElement", "finiteField") and children[0] == ["Integer"]: + return [1, 1, 1], "[1,1,1]" + if children[0] == ["Integer"]: + return [1, 2], "[1,2]" + if children[0] == ["Int"]: + return [2], "[2]" + value, h = argument(children[0], e, index, type_name) + return [value, value], "[" + h + "," + h + "]" + if head == "tuple": + values = [] + hs = [] + for i, s in enumerate(children): + x, h = argument(s, e, i, type_name) + values.append(x) + hs.append(h) + return tuple(values), "(" + ",".join(hs) + ")" + raise ValueError(spec) + + def hs_type(spec, type_name): + head, *children = spec + if head in ("a", "s"): + return "(" + type_name + ")" + if head == "v": + return "[" + type_name + "]" + if head == "list": + return "[" + hs_type(children[0], type_name) + "]" + if head == "tuple": + return "(" + ",".join(hs_type(s, type_name) for s in children) + ")" + head = { + "Additive": "A.Additive", + "Modular": "A.Modular", + "FiniteField": "A.FiniteField", + "FieldElement": "A.FieldElement", + "Exact": "P.Exact", + "Matrix": "M.Matrix", + "Tensor": "T.Tensor", + "Vector": "V.Vector", + "Dual": "AD.Dual", + "MathError": "HMath.Error.MathError", + }.get(head, head) + return ( + "(" + + head + + ( + " " + " ".join(hs_type(s, type_name) for s in children) + if children + else "" + ) + + ")" + ) + + for entry in entries: + selected = mode(entry) + name = entry["name"] + if selected == "old": + variants = ["Integer", "Rational", "Poly.Polynomial Rational"] + elif selected == "module": + variants = ["Integer", "Rational"] + elif selected == "api": + variants = [ + "Integer", + "Rational", + "Float", + "Double", + "Complex Double", + "P.Exact", + ] + else: + variants = ["Rational"] + if name in ("inverseField", "fieldLaws"): + variants = ["Rational"] + if name == "invert": + variants = [x for x in variants if x != "Integer"] + if name in ("machineEpsilon", "finiteScalar"): + variants = ["Float", "Double", "Complex Double"] + for type_name in variants: + values = [] + hsargs = [] + for index, spec in enumerate(entry["args"]): + value, h = argument(spec, entry, index, type_name) + values.append(value) + hsargs.append(h) + dtype = typed(type_name)[2] + precision = typed(type_name)[3] + kwargs = {"dtype": dtype} if selected != "value" else {} + alias = MODULES[entry["module"]][0] + expression = ( + "(" + + alias + + "." + + name + + (" " + " ".join("(" + h + ")" for h in hsargs) if hsargs else "") + + "::" + + hs_type(entry["result"], type_name) + + ")" + ) + # Group instances are Additive; source groupLaws retains its actual + # polymorphic input and does not pretend Integer itself is a Group. + if name == "groupLaws": + expression = "A.groupLaws(" + hsargs[0] + ")" + if name == "machineEpsilon": + expression = "P.machineEpsilon(Proxy::Proxy(" + type_name + "))" + checked = entry["result"][:2] == ["Either", ["MathError"]] + expressions.append(("ok" if checked else "enc") + "(" + expression + ")") + function = getattr( + modules[entry["module"]], name if entry["constructor"] else snake(name) + ) + tests.append( + ( + function, + values, + kwargs, + entry["module"] + "." + name + "[" + type_name + "]", + 64 if name == "machineEpsilon" else precision, + ) + ) + # Every structural MatrixLike/TensorLike element family also exercises exact + # construction and extraction through the ordinary shared object owners. + for type_name, values, hsvalues, dtype in [ + ("Bool", [True, False], "[True,False]", "bool"), + ("String", ["a\0α", "β"], '["a\\NULα","β"]', "string"), + ("P.Exact", [exact, exact], "[P.Exact(2%3),P.Exact(2%3)]", exact), + ]: + tests.append( + ( + p.matrix_construct, + [1, 2, values], + {"dtype": dtype}, + "matrixConstruct[" + type_name + "]", + 64, + ) + ) + expressions.append( + "ok(P.matrixConstruct 1 2 " + + hsvalues + + "::Either HMath.Error.MathError(M.Matrix(" + + type_name + + ")))" + ) + tests.append( + ( + p.tensor_construct, + [[2], values], + {"dtype": dtype}, + "tensorConstruct[" + type_name + "]", + 64, + ) + ) + expressions.append( + "ok(P.tensorConstruct [2] " + + hsvalues + + "::Either HMath.Error.MathError(T.Tensor(" + + type_name + + ")))" + ) + imports = """import qualified HMath.Algebra as A +import qualified HMath.API.Algebra as P +import qualified HMath.Polynomial as Poly +import qualified HMath.Tensor as T +import qualified HMath.Vector as V +import qualified HMath.Autodiff as AD +import Data.Proxy(Proxy(..)) +import Data.Char(ord) +""" + source = ( + HASKELL.split("pR=")[0] + .replace("import qualified HMath.Polynomial as P", imports) + .replace("(P.Polynomial a)", "(Poly.Polynomial a)") + .replace("P.coefficients", "Poly.coefficients") + .replace("(P.PowerSeries a)", "(Poly.PowerSeries a)") + .replace("P.seriesCoefficients", "Poly.seriesCoefficients") + .replace("P.RationalFunction", "Poly.RationalFunction") + .replace("P.rationalNumerator", "Poly.rationalNumerator") + .replace("P.rationalDenominator", "Poly.rationalDenominator") + ) + source += """instance E Char where enc c="I"++show(ord c) +instance(E a,E b,E c,E d)=>E(a,b,c,d)where enc(a,b,c,d)="T["++intercalate ","[enc a,enc b,enc c,enc d]++"]" +instance E a=>E(A.Additive a)where enc x="A("++enc(A.getAdditive x)++")" +instance E P.Exact where enc x="X("++enc(P.getExact x)++")" +instance E A.Modular where enc x="Z("++enc(A.modularModulus x,A.modularValue x)++")" +instance E A.FiniteField where enc x="F("++enc(A.fieldCharacteristic x,A.fieldDegree x,A.fieldCardinality x,A.fieldModulus x)++")" +instance E A.FieldElement where enc x="E("++enc(A.fieldElementCoefficients x)++")" +instance E a=>E(V.Vector a)where enc x="VECTOR("++enc(V.vectorValues x)++")" +instance E a=>E(T.Tensor a)where enc x="TENSOR("++enc(T.tensorShape x,T.tensorValues x)++")" +right=either(error.show)id +f=right(A.finiteField 32 2 [1,1,1]) +z=right(A.modular 7 3) +e=A.fieldElement f [0,1] +pol=Poly.polynomial [1,2]::Poly.Polynomial Rational +mat=right(P.matrixConstruct 2 2 [1,2,3,4])::M.Matrix Rational +ten=right(P.tensorConstruct [2] [1,2])::T.Tensor Rational +vec=V.vector [1,2]::V.Vector Rational +main=mapM_ putStrLn [EXPRESSIONS] +""".replace("EXPRESSIONS", ",\n ".join(expressions)) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "Oracle.hs" + path.write_text(source) + result = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if result.returncode: + raise SystemExit(result.stderr) + expected = result.stdout.splitlines() + if len(expected) != len(tests): + raise AssertionError((len(expected), len(tests))) + try: + for (function, values, kwargs, name, precision), wanted in zip(tests, expected): + try: + value = function(*values, **kwargs) + actual = normalized(value, modules, precision) + close(value) + except hmath.HMathError as error: + actual = "E" + str(error.math_error) + if actual != wanted: + raise AssertionError((name, actual, wanted)) + finally: + for value in owners: + value.close() + print( + f"Algebra direct Haskell equivalence: {len(tests)} cases;67 operations;85 new source symbols plus existing innerProduct" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_api_docs.py b/tools/check_api_docs.py index cd12a6f..c71315c 100644 --- a/tools/check_api_docs.py +++ b/tools/check_api_docs.py @@ -199,6 +199,15 @@ def check_reference(interface=None): *python_signatures(), ) } + from generate_numeric_bindings import generate + + for name, generated in generate().items(): + path = ROOT / name + if not path.exists() or path.read_text() != generated: + raise ValueError(f"Stale numeric API implementation/reference: {name}") + counts["Numeric functions (C/Python)"] = len( + json.loads((ROOT / "bindings/schema/numeric.json").read_text())["functions"] + ) c = set() c_parameters, c_signatures = {}, {} for header in ("hmath.h", "hmath_dlpack.h"): diff --git a/tools/check_autodiff_coefficients.py b/tools/check_autodiff_coefficients.py new file mode 100644 index 0000000..aed4677 --- /dev/null +++ b/tools/check_autodiff_coefficients.py @@ -0,0 +1,224 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original forward-mode instances over every supported concrete coefficient type.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_tensor_equivalence import SOURCE as TENSOR_SOURCE +from check_tensor_equivalence import close, encode + +ROOT = Path(__file__).resolve().parent.parent +SOURCE = TENSOR_SOURCE.split("checked=")[0] +SOURCE = SOURCE.replace( + "class Enc a", + "import qualified HMath.Autodiff as A\nimport qualified HMath.Numeric as N\nclass Enc a", +) +for name in ["Int16", "Int32", "Int64", "Word8", "Word16", "Word32", "Word"]: + SOURCE += "instance Enc " + name + ' where enc x="I"++show x\n' +SOURCE += r""" +instance Enc a=>Enc(A.Dual a) where enc x="AD["++enc(A.primal x)++","++enc(A.tangent x)++"]" +instance Enc a=>Enc(N.Dual a) where enc x="ND["++enc(N.primal x)++","++enc(N.tangent x)++"]" +instance Enc a=>Enc(N.Quaternion a) where enc(N.Quaternion a b c d)="Q["++intercalate ","(map enc[a,b,c,d])++"]" +main=sequence_(map(putStrLn)[CASES]) +""" + + +def cases(ad, numeric): + owned = [] + + def keep(value): + owned.append(value) + return value + + selected = [] + + def add(name, hs, call, code=None): + selected.append((name, "enc(" + hs + ")", call, code)) + + definitions = [ + ("float64", "Double", "1.0000001", 1.0000001, 0), + ("float32", "Float", "1.0000001", 1.0000001, 1), + ("integer", "Integer", "10^100", 10**100, 2), + ("rational", "Rational", "2%3", Fraction(2, 3), 3), + ("complex128", "Complex Double", "1.2:+0.3", 1.2 + 0.3j, 4), + ("complex64", "Complex Float", "1.2:+0.3", 1.2 + 0.3j, 5), + ("int8", "Int8", "120", 120, 6), + ("int16", "Int16", "30000", 30000, 7), + ("int32", "Int32", "2000000000", 2000000000, 8), + ("int64", "Int64", "8000000000000000000", 8 * 10**18, 9), + ("uint8", "Word8", "250", 250, 10), + ("uint16", "Word16", "60000", 60000, 11), + ("uint32", "Word32", "4000000000", 4000000000, 12), + ("uint64", "Word64", "16000000000000000000", 16 * 10**18, 13), + ("intp", "Int", "123", 123, 14), + ("uintp", "Word", "321", 321, 15), + ] + for dtype, hs, point, value, code in definitions: + add( + "Num " + dtype, + r"A.forward(\x->x*x*x+2*x)(" + point + "::" + hs + ")", + lambda dtype=dtype, value=value: ad.forward( + lambda x: x * x * x + 2 * x, value, dtype=dtype + ), + code, + ) + add( + "nested " + dtype, + r"A.forward(\x->x*x*x)(A.Dual(" + point + "::" + hs + ")1)", + lambda dtype=dtype, value=value: ad.forward( + lambda x: x * x * x, keep(ad.Dual(value, 1, dtype=dtype)) + ), + code, + ) + if code in (0, 1, 3, 4, 5): + add( + "Fractional " + dtype, + "A.forward recip(" + point + "::" + hs + ")", + lambda dtype=dtype, value=value: ad.forward( + lambda x: 1 / x, value, dtype=dtype + ), + code, + ) + if code in (0, 1, 4, 5): + add( + "Floating " + dtype, + "A.forward(\\x->sin x+exp x)(" + point + "::" + hs + ")", + lambda dtype=dtype, value=value: ad.forward( + lambda x: ad.sin(x) + ad.exp(x), value, dtype=dtype + ), + code, + ) + for dtype, hs, point, value, code in definitions: + primal = keep(numeric.number(value, dtype)) + tangent = keep(numeric.number(1, dtype)) + leaf = keep(numeric.dual(primal, tangent, boxed=True)) + add( + "Numeric.Dual Num " + dtype, + r"A.forward(\x->x*x*x+2*x)(N.Dual(" + point + "::" + hs + ")1)", + lambda leaf=leaf: ad.forward(lambda x: x * x * x + 2 * x, leaf), + code, + ) + if code in (0, 1, 3, 4, 5): + add( + "Numeric.Dual Fractional " + dtype, + "A.forward recip(N.Dual(" + point + "::" + hs + ")1)", + lambda leaf=leaf: ad.forward(lambda x: 1 / x, leaf), + code, + ) + if code in (0, 1, 4, 5): + add( + "Numeric.Dual Floating " + dtype, + "A.forward exp(N.Dual(" + point + "::" + hs + ")1)", + lambda leaf=leaf: ad.forward(ad.exp, leaf), + code, + ) + with numeric.number(1.0000001, "float32") as p, numeric.number(1, "float32") as one: + first = keep(numeric.dual(p, one, boxed=True)) + second = keep(numeric.dual(first, first, boxed=True)) + add( + "nested Numeric.Dual", + r"A.forward(\x->x*x*x)(N.Dual(N.Dual(1.0000001::Float)1)(N.Dual 1.0000001 1))", + lambda: ad.forward(lambda x: x * x * x, second), + 1, + ) + for dtype, hs, code in [("float64", "Double", 0), ("float32", "Float", 1)]: + parts = [keep(numeric.number(v, dtype)) for v in [1.2, 0.3, 0.4, 0.5]] + leaf = keep(numeric.quaternion(*parts, boxed=True)) + add( + "Quaternion Num " + dtype, + r"A.forward(\x->x*x*x+2*x)(N.Quaternion(1.2::" + hs + ")0.3 0.4 0.5)", + lambda leaf=leaf: ad.forward(lambda x: x * x * x + 2 * x, leaf), + code, + ) + return selected, owned + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + from _hmath_native import _tensor_core as tensor + from _hmath_native import autodiff as ad + from _hmath_native import numeric_types as numeric + from _hmath_native._numeric_types_runtime import NumericValue + + def enc(value, code): + if isinstance(value, ad.Dual): + parts = (value.primal, value.tangent) + try: + return "AD[" + ",".join(enc(x, code) for x in parts) + "]" + finally: + close(parts) + if isinstance(value, NumericValue): + kind, dtype, _ = value.info + if kind == 1 and dtype == 20: + parts = (value.primal, value.tangent) + try: + return "ND[" + ",".join(enc(x, code) for x in parts) + "]" + finally: + close(parts) + if kind == 1 and dtype == 21: + parts = value.components + try: + return "Q[" + ",".join(enc(x, code) for x in parts) + "]" + finally: + close(parts) + return encode(value.value, tensor, code) + if isinstance(value, (tuple, list)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(enc(x, code) for x in value) + + "]" + ) + return encode(value, tensor, code) + + selected, owned = cases(ad, numeric) + try: + with tempfile.TemporaryDirectory(prefix="hmath-ad-coefficients-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text( + SOURCE.replace("CASES", ",\n ".join(hs for _, hs, _, _ in selected)) + ) + subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-i" + str(ROOT / "src"), + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + for (name, _, call, code), reference in zip(selected, expected, strict=True): + value = call() + try: + actual = enc(value, code) + finally: + close(value) + if actual != reference: + raise AssertionError(f"{name}: native {actual}, original {reference}") + print( + f"AD coefficient equivalence: {len(selected)} original typed forward sequences match exact values/IEEE bits and nested original Dual/Quaternion components." + ) + finally: + close(owned) + + +if __name__ == "__main__": + main() diff --git a/tools/check_autodiff_equivalence.py b/tools/check_autodiff_equivalence.py new file mode 100644 index 0000000..80027c9 --- /dev/null +++ b/tools/check_autodiff_equivalence.py @@ -0,0 +1,233 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare native AD bindings with independent direct calls to HMath.Autodiff.""" + +import argparse +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SOURCE = r"""import qualified HMath.Autodiff as A +import Data.Complex +import Data.List (intercalate) +import GHC.Float (castDoubleToWord64,float2Double) +import Data.Ratio (numerator,denominator,(%)) +checked = either (error . show) id +objective [x,y] = x*x+x*y +objective _ = error "arity" +vector [x,y] = [x*y,x+y] +vector _ = error "arity" +emit = putStrLn . intercalate "," . map (show . castDoubleToWord64) +main = do + let (value,g) = checked (A.valueAndGradient objective [3,4]) + emit (value:g) + emit (checked (A.gradient objective [3,4])) + emit (concat (checked (A.hessian objective [3,4]))) + emit (concat (checked (A.jacobian vector [2,3]))) + emit (checked (A.jvp vector [2,3] [1,2])) + emit (checked (A.vjp vector [2,3] [1,2])) + emit (checked (A.hvp objective [3,4] [2,-1])) + emit [checked (A.gradientCheck 1e-5 objective [3,4])] + let z = checked (A.complexGradient (\[x,y] -> x*x+y*y) (3:+4)) + emit [realPart z,imagPart z] + let (p,t) = A.forward (\x -> x*x*x) (3::Double) + emit [p,t] + let (ps,ts) = checked (A.forwardJVP (\[x,y] -> [x*y]) [2,3] [1,2]) + emit (ps++ts) + let state=checked (A.zeroGradients 2) + let accumulated=checked (A.accumulateGradients state [3,4]) + emit (A.accumulatedGradient accumulated) + emit (A.accumulatedGradient (A.resetGradients accumulated)) + emit (A.accumulatedGradient (checked (A.gradientHook (Right . map negate) accumulated))) + emit (checked (A.clipGradient 2 [3,4])) + emit (checked (A.gradient (\xs -> let m=checked (A.adTensor [2,2] xs) in A.adSum (checked (A.adMatmul m m))) [1,2,3,4])) + emit (checked (A.gradient (\xs -> let m=checked (A.adTensor [1] xs) in A.adSum (checked (A.adBroadcast [2,3] m))) [2])) + emit (checked (A.gradient (\xs -> let m=checked (A.adTensor [2] xs) in A.adSum (checked (A.adContract [0] [0] m m))) [2,3])) + let point=A.variable 0 + let next=checked (A.differentiableStep 0.1 (\[x] -> x*x) [point]) + case next of { [point] -> emit (checked (A.gradient (const point) [3])); _ -> error "step arity" } + let rule [x] = Right (x*x*x,[3*x*x]) + let (cv,cg) = checked (A.valueAndGradient (\xs -> A.customOperation rule xs) [2]) + emit (cv:cg) + let (uv,ug) = checked (A.valueAndGradient (\[x] -> A.customUnary (\v -> v*v*v) (\v -> 3*v*v) x) [2]) + emit (uv:ug) + let (pv,pg) = checked (A.valueAndGradient (\xs -> A.checkpoint (\[x] -> x*x) xs) [3]) + emit (pv:pg) + let (nv,ng) = checked (A.valueAndGradient (\xs -> A.checkpoint (\[x] -> A.customUnary (\v -> v*v) (\v -> 2*v) x) xs) [3]) + emit (nv:ng) + let (nestedValue,nestedDerivative) = A.forward (\x -> x*x*x) (A.Dual (3::Double) 1) + emit [A.primal nestedValue,A.tangent nestedValue,A.primal nestedDerivative,A.tangent nestedDerivative] + let (floatValue,floatDerivative) = A.forward (\x -> x*x*x) (1.0000001::Float) + emit [float2Double floatValue,float2Double floatDerivative] + let (integerValue,integerDerivative) = A.forward (\x -> x*x) (10^100::Integer) + putStrLn ("E:" ++ intercalate "," (map show [integerValue,integerDerivative])) + let (ratioValue,ratioDerivative) = A.forward recip (2%3::Rational) + putStrLn ("E:" ++ intercalate "," (map show [numerator ratioValue,denominator ratioValue,numerator ratioDerivative,denominator ratioDerivative])) + let (branchValue,branchDerivative) = A.forward (\x -> if x < 0 then negate x else x*x) (-2::Double) + emit [branchValue,branchDerivative] +""" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + from _hmath_native import autodiff as ad + + with tempfile.TemporaryDirectory(prefix="hmath-ad-oracle-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text(SOURCE) + subprocess.run( + [ + "ghc", + "-O1", + "-i" + str(ROOT / "src"), + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + + def objective(xs): + x, y = xs + return x * x + x * y + + def vector(xs): + x, y = xs + return [x * y, x + y] + + value, g = ad.value_and_gradient(objective, [3, 4]) + actual = [ + [value, *g], + ad.gradient(objective, [3, 4]), + [value for row in ad.hessian(objective, [3, 4]) for value in row], + [value for row in ad.jacobian(vector, [2, 3]) for value in row], + ad.jvp(vector, [2, 3], [1, 2]), + ad.vjp(vector, [2, 3], [1, 2]), + ad.hvp(objective, [3, 4], [2, -1]), + [ad.gradient_check(1e-5, objective, [3, 4])], + ] + z = ad.complex_gradient(lambda xs: xs[0] * xs[0] + xs[1] * xs[1], 3 + 4j) + actual.append([z.real, z.imag]) + actual.append(list(ad.forward(lambda x: x * x * x, 3))) + ps, ts = ad.forward_jvp(lambda xs: [xs[0] * xs[1]], [2, 3], [1, 2]) + actual.append(ps + ts) + with ( + ad.zero_gradients(2) as state, + ad.accumulate_gradients(state, [3, 4]) as accumulated, + ): + actual.append(accumulated.accumulated_gradient) + with ad.reset_gradients(accumulated) as reset: + actual.append(reset.accumulated_gradient) + with ad.gradient_hook(lambda xs: [-x for x in xs], accumulated) as changed: + actual.append(changed.accumulated_gradient) + actual.append(ad.clip_gradient(2, [3, 4])) + + def matmul(xs): + with ( + ad.ad_tensor([2, 2], xs) as tensor, + ad.ad_matmul(tensor, tensor) as product, + ): + return ad.ad_sum(product) + + actual.append(ad.gradient(matmul, [1, 2, 3, 4])) + + def broadcast(xs): + with ( + ad.ad_tensor([1], xs) as tensor, + ad.ad_broadcast([2, 3], tensor) as product, + ): + return ad.ad_sum(product) + + actual.append(ad.gradient(broadcast, [2])) + + def contract(xs): + with ( + ad.ad_tensor([2], xs) as tensor, + ad.ad_contract([0], [0], tensor, tensor) as product, + ): + return ad.ad_sum(product) + + actual.append(ad.gradient(contract, [2, 3])) + with ad.variable(0) as point: + updated = ad.differentiable_step(0.1, lambda xs: xs[0] * xs[0], [point]) + try: + actual.append(ad.gradient(updated[0], [3])) + finally: + for value in updated: + value.close() + for objective, point in [ + ( + lambda xs: ad.custom_operation( + lambda values: (values[0] ** 3, [3 * values[0] ** 2]), xs + ), + [2], + ), + ( + lambda xs: ad.custom_unary(lambda x: x * x * x, lambda x: 3 * x * x, xs[0]), + [2], + ), + (lambda xs: ad.checkpoint(lambda ys: ys[0] * ys[0], xs), [3]), + ( + lambda xs: ad.checkpoint( + lambda ys: ad.custom_unary(lambda x: x * x, lambda x: 2 * x, ys[0]), xs + ), + [3], + ), + ]: + value, derivatives = ad.value_and_gradient(objective, point) + actual.append([value, *derivatives]) + with ad.Dual(3, 1) as seed: + value, derivative = ad.forward(lambda x: x * x * x, seed) + with value, derivative: + actual.append( + [value.primal, value.tangent, derivative.primal, derivative.tangent] + ) + actual.append(list(ad.forward(lambda x: x * x * x, 1.0000001, dtype="float32"))) + actual.append( + ("exact", list(ad.forward(lambda x: x * x, 10**100, dtype="integer"))) + ) + value, derivative = ad.forward(lambda x: 1 / x, Fraction(2, 3), dtype="rational") + actual.append( + ( + "exact", + [ + value.numerator, + value.denominator, + derivative.numerator, + derivative.denominator, + ], + ) + ) + actual.append(list(ad.forward(lambda x: -x if x < 0 else x * x, -2))) + assert len(actual) == len(expected) + for index, (result, reference) in enumerate(zip(actual, expected)): + if isinstance(result, tuple) and result[0] == "exact": + encoded = "E:" + ",".join(map(str, result[1])) + else: + encoded = ",".join( + str(struct.unpack("!Q", struct.pack("!d", value))[0]) + for value in result + ) + assert encoded == reference, (index, result, encoded, reference) + print( + f"{len(actual)} AD operation sequences match direct Haskell evaluation bit for bit." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_binding_coverage.py b/tools/check_binding_coverage.py new file mode 100644 index 0000000..a962ce3 --- /dev/null +++ b/tools/check_binding_coverage.py @@ -0,0 +1,264 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Audit public Haskell symbols and concrete C/Python specializations. + +Missing bindings remain visible; an implemented specialization does not mean +all instances of a polymorphic Haskell function have been exposed. +""" + +import argparse +import ast +import json +import re +from pathlib import Path + +from check_api_docs import read_haddock +from generate_numeric_bindings import namespace, prefix +from numeric_specializations import binding_variants + +ROOT = Path(__file__).resolve().parent.parent + + +def python_members(module, seen=None): + """Inspect declarations without importing a native library during preflight.""" + seen = set() if seen is None else seen + if module in seen: + return set() + seen.add(module) + path = ROOT / "bindings/python/_hmath_native" / (module + ".py") + if not path.is_file(): + return set() + names = set() + for node in ast.parse(path.read_text()).body: + if isinstance(node, ast.Assign): + names.update(t.id for t in node.targets if isinstance(t, ast.Name)) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + elif isinstance(node, (ast.FunctionDef, ast.ClassDef)): + names.add(node.name) + if isinstance(node, ast.ClassDef): + for member in node.body: + if isinstance(member, ast.FunctionDef): + names.add(node.name + "." + member.name) + elif isinstance(member, ast.Assign): + names.update( + node.name + "." + t.id + for t in member.targets + if isinstance(t, ast.Name) + ) + elif isinstance(member, ast.AnnAssign) and isinstance( + member.target, ast.Name + ): + names.add(node.name + "." + member.target.id) + elif isinstance(node, ast.ImportFrom) and node.level == 1 and node.module: + imported = python_members(node.module, seen) + for alias in node.names: + if alias.name == "*": + names.update(imported) + else: + target = alias.asname or alias.name + names.add(target) + names.update( + target + item[len(alias.name) :] + for item in imported + if item.startswith(alias.name + ".") + ) + return names + + +def validate_targets(bound): + headers = "\n".join(p.read_text() for p in (ROOT / "include").glob("hmath*.h")) + c_names = set(re.findall(r"\b(?:hmath_\w+|HMATH_\w+)\b", headers)) + python_cache = {} + public_modules = {} + for node in ast.parse((ROOT / "bindings/python/hmath.py").read_text()).body: + if isinstance(node, ast.ImportFrom) and node.module == "_hmath_native": + public_modules.update( + (alias.asname or alias.name, alias.name) for alias in node.names + ) + for symbol, item in bound.items(): + if ( + not item.get("c") + or not item.get("python") + or not item.get("specializations") + ): + raise ValueError(f"Incomplete binding mapping: {symbol}") + if not set(item["c"]) <= c_names: + raise ValueError(f"Unknown C binding declaration: {symbol}") + for target in [item["python"], *item.get("python_aliases", [])]: + parts = target.split(".", 2) + if len(parts) != 3 or parts[0] != "hmath": + raise ValueError(f"Invalid Python binding path: {symbol}") + if parts[1] not in python_cache: + module = public_modules.get(parts[1], parts[1]) + python_cache[parts[1]] = python_members(module) + if parts[2] not in python_cache[parts[1]]: + raise ValueError( + f"Unknown Python binding declaration: {symbol}: {target}" + ) + + +def object_bindings(bound, known, directory): + """Merge only explicitly declared extensions of an existing schema file.""" + mappings = { + p.name: json.loads(p.read_text()) for p in directory.glob("*objects.json") + } + loaded = {"numeric.json"} + owners = {symbol: "numeric.json" for symbol in bound} + while mappings: + progress = False + for name, mapping in list(mappings.items()): + parent = mapping.get("extends") + if parent and parent not in loaded: + continue + seen = set() + for item in mapping["bindings"]: + symbol = item["symbol"] + if symbol not in known or symbol in seen: + raise ValueError(f"Unknown or duplicate object binding: {symbol}") + seen.add(symbol) + target = {key: value for key, value in item.items() if key != "symbol"} + if parent: + if symbol not in bound or owners.get(symbol) != parent: + raise ValueError( + f"Extension {name} has no base binding in {parent}: {symbol}" + ) + base = bound[symbol] + for field in ("c", "specializations"): + base[field] = list(dict.fromkeys(base[field] + target[field])) + if target["python"] != base["python"]: + aliases = base.setdefault("python_aliases", []) + if target["python"] not in aliases: + aliases.append(target["python"]) + else: + if symbol in bound: + raise ValueError( + f"Duplicate object binding without declared extension: {symbol}" + ) + bound[symbol] = target + owners[symbol] = name + loaded.add(name) + del mappings[name] + progress = True + if not progress: + raise ValueError( + "Missing or cyclic object schema extensions: " + + ", ".join(sorted(mappings)) + ) + + +def additional_specializations(bound, directory): + """Validate additive instance paths without counting another source symbol.""" + for path in directory.glob("*-specializations.json"): + seen = set() + for item in json.loads(path.read_text())["additional_specializations"]: + symbol = item["symbol"] + if symbol not in bound or symbol in seen: + raise ValueError(f"Unknown or duplicate specialization: {symbol}") + seen.add(symbol) + base = bound[symbol] + if item["additional_c"] in base["c"] or not item["instances"]: + raise ValueError(f"Invalid additional specialization: {symbol}") + base["c"].append(item["additional_c"]) + base["specializations"].append(item["instances"]) + target = "hmath." + item["python"].removeprefix("hmath.") + if target != base["python"]: + aliases = base.setdefault("python_aliases", []) + if target not in aliases: + aliases.append(target) + + +def inventory(interface): + # Haddock builds private pages to resolve links. Those helpers are not public + # unless an exposed module actually re-exports them. Keep their canonical + # defining names when they are re-exported, rather than dropping Internal.*. + stanza = re.search( + r"^library\s*\n.*?^\s+exposed-modules:(.*?)^\s+other-modules:", + (ROOT / "hmath.cabal").read_text(), + re.MULTILINE | re.DOTALL, + ) + if not stanza: + raise ValueError("cannot find the library's exposed module declarations") + exposed = set(re.findall(r"\bHMath(?:\.\w+)*\b", stanza[1])) + symbols = {} + for module in read_haddock(interface)["inst_ifaces"]: + if module["module"].split("$")[-1] not in exposed: + continue + for symbol in module["visible_exports"]: + if not symbol.startswith("$hmath-"): + continue + _, _, defining_module, name = symbol.split("$", 3) + key = defining_module + "." + name + item = symbols.setdefault( + key, + { + "symbol": key, + "kind": "type-or-constructor" + if name[0].isupper() or name.startswith(":") + else "function-or-field", + "exported_from": [], + }, + ) + item["exported_from"].append(module["module"].split("$")[-1]) + return sorted(symbols.values(), key=lambda item: item["symbol"]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--interface", type=Path) + parser.add_argument("--update-inventory", action="store_true") + parser.add_argument("--report", type=Path) + parser.add_argument( + "--require-complete", + action="store_true", + help="Fail release preparation while public symbols remain unmapped", + ) + args = parser.parse_args() + if args.require_complete and not args.interface: + parser.error("--require-complete requires a freshly built --interface") + path = ROOT / "bindings/schema/public-api.json" + declared = json.loads(path.read_text()) + if args.interface: + actual = inventory(args.interface) + if args.update_inventory: + declared["symbols"] = actual + path.write_text(json.dumps(declared, indent=2) + "\n") + elif actual != declared["symbols"]: + parser.exit(1, "Haskell public inventory changed; audit and update it.\n") + elif args.update_inventory: + parser.error("--update-inventory requires --interface") + known = {entry["symbol"] for entry in declared["symbols"]} + bound = {} + functions = json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + for function in functions: + symbol = function["module"] + "." + function["name"] + if symbol not in known or symbol in bound: + raise ValueError(f"Unknown or duplicate binding: {symbol}") + variants = binding_variants(function) + bound[symbol] = { + "specializations": [v["dtype"] or "exact" for v in variants], + "c": [prefix(function) + v["suffix"] for v in variants], + "python": "hmath." + namespace(function) + "." + function["python"], + } + object_bindings(bound, known, ROOT / "bindings/schema") + additional_specializations(bound, ROOT / "bindings/schema") + validate_targets(bound) + report = { + entry["symbol"]: bound.get(entry["symbol"], {"status": "pending"}) + for entry in declared["symbols"] + } + if args.report: + args.report.write_text(json.dumps(report, indent=2) + "\n") + print( + f"{len(known)} public symbols: {len(bound)} with explicit bindings/specializations; " + f"{len(known) - len(bound)} pending." + ) + if args.require_complete and known - bound.keys(): + parser.exit( + 1, "Release preparation blocked: public API bindings remain pending.\n" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_buffer_equivalence.py b/tools/check_buffer_equivalence.py new file mode 100644 index 0000000..ab72801 --- /dev/null +++ b/tools/check_buffer_equivalence.py @@ -0,0 +1,574 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare original Buffer operations, concrete Storable instances and scoped contracts.""" + +import argparse +import gc +import math +import os +import struct +import subprocess +import sys +import tempfile +from concurrent.futures import ThreadPoolExecutor +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def bits(value, width=64): + if math.isnan(value): + return "nan" + return str( + struct.unpack( + "!Q" if width == 64 else "!I", + struct.pack("!d" if width == 64 else "!f", value), + )[0] + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import _value as V + from _hmath_native import buffer_values as b + + cases = [] + owners = [] + + def own(value): + owners.append(value) + return value + + def case(label, expression, call): + cases.append((label, expression, call)) + + def list_of(encoder, values): + return "[" + ",".join(encoder(x) for x in values) + "]" + + huge = 10**150 + 7 + integer_box = own(b.Boxed([huge, -huge, 0])) + integer_hs = f"B.lazyBoxed [{huge},-{huge},0::Integer]" + case( + "lazyBoxed", + "pure(Right(list show(B.boxedValues(" + integer_hs + "))))", + lambda: list_of(str, integer_box.values), + ) + case( + "strictBoxed", + f"pure(Right(list show(B.boxedValues(B.strictBoxed [{huge},-{huge},0::Integer]))))", + lambda: list_of(str, own(b.strict_boxed([huge, -huge, 0])).values), + ) + case( + "boxedLength", + f"pure(Right(show(B.boxedLength({integer_hs}))))", + lambda: str(b.boxed_length(integer_box)), + ) + case( + "mapStrict", + f"pure(Right(list show(B.boxedValues(B.mapStrict(+1)({integer_hs})))))", + lambda: list_of(str, own(b.map_strict(lambda x: x + 1, integer_box)).values), + ) + case( + "emptyBoxed", + "pure(Right(list show(B.boxedValues(B.lazyBoxed []::B.Boxed Integer))))", + lambda: list_of(str, own(b.lazy_boxed([])).values), + ) + rationals = [Fraction(huge, 7), Fraction(-5, 17)] + rational_box = own(b.strict_boxed(rationals)) + rat = lambda x: str(x.numerator) + "/" + str(x.denominator) + case( + "boxedRational", + f"pure(Right(list rational(B.boxedValues(B.strictBoxed [{huge}%7,(-5)%17]))))", + lambda: list_of(rat, rational_box.values), + ) + case( + "mapRational", + f"pure(Right(list rational(B.boxedValues(B.mapStrict(*2)(B.strictBoxed [{huge}%7,(-5)%17])))))", + lambda: list_of(rat, own(b.map_strict(lambda x: x * 2, rational_box)).values), + ) + doubles = [0.0, -0.0, math.inf, -math.inf, math.nan, 1e-300] + double_hs = "[0,castWord64ToDouble 9223372036854775808,1/0,-1/0,0/0,1e-300]" + unboxed = own(b.unboxed_double(doubles)) + case( + "unboxedDouble", + f"pure(Right(list fp64(B.unboxedValues(B.unboxedDouble(opaque {double_hs})))))", + lambda: list_of(bits, unboxed.values), + ) + case( + "unboxedToBoxed", + f"pure(Right(list fp64(B.boxedValues(B.unboxedToBoxed(B.unboxedDouble(opaque {double_hs}))))))", + lambda: list_of(bits, own(b.unboxed_to_boxed(unboxed)).values), + ) + double_box = own(b.Boxed(doubles)) + case( + "boxedToUnboxed", + f"pure(Right(list fp64(B.unboxedValues(B.boxedToUnboxed(B.lazyBoxed(opaque {double_hs}))))))", + lambda: list_of(bits, own(b.boxed_to_unboxed(double_box)).values), + ) + + def st_copy(): + def action(region): + before = region.read(0) + b.write_st_buffer(region, 1, 9) + frozen = own(b.freeze_st_buffer(region)) + other = own(b.thaw_st_buffer(region, integer_box)) + other.write(0, 12) + second = own(other.freeze()) + return ( + str(before) + + ";" + + list_of(str, frozen.values) + + ";" + + list_of(str, second.values) + ) + + return b.run_st_buffer(integer_box, action) + + case( + "ST read/write/freeze/thaw", + f'pure(Right(B.runSTBuffer ({integer_hs}) $ \\s -> do before <- B.readSTBuffer s 0;_ <- B.writeSTBuffer s 1 9;frozen <- B.freezeSTBuffer s;other <- B.thawSTBuffer({integer_hs});_ <- B.writeSTBuffer other 0 12;second <- B.freezeSTBuffer other;pure(show(right before)++";"++list show(B.boxedValues frozen)++";"++list show(B.boxedValues second)) ))', + st_copy, + ) + for index in (-1, 3): + case( + "ST read invalid " + str(index), + f"pure(B.runSTBuffer({integer_hs})(\\s -> fmap(fmap show)(B.readSTBuffer s ({index}))))", + lambda index=index: str( + b.run_st_buffer(integer_box, lambda region: region.read(index)) + ), + ) + case( + "ST write invalid " + str(index), + f"pure(B.runSTBuffer({integer_hs})(\\s -> fmap(fmap show)(B.writeSTBuffer s ({index}) 1)))", + lambda index=index: str( + b.run_st_buffer(integer_box, lambda region: region.write(index, 1)) + ), + ) + case( + "ST frozen independence", + f"pure(Right(B.runSTBuffer({integer_hs}) $ \\s -> do f <- B.freezeSTBuffer s;_ <- B.writeSTBuffer s 0 13;pure(list show(B.boxedValues f))))", + lambda: b.run_st_buffer( + integer_box, lambda region: _st_frozen(region, own, list_of) + ), + ) + + storage = [ + ( + "float64", + "Double", + "castWord64ToDouble 9223372036854775808", + "1.25", + -0.0, + 1.25, + "fp64", + bits, + ), + ( + "float32", + "Float", + "castWord32ToFloat 2147483648", + "1.25", + -0.0, + 1.25, + "fp32", + lambda x: bits(x, 32), + ), + ( + "complex128", + "Complex Double", + "(0.25:+castWord64ToDouble 9223372036854775808)", + "((-2):+1.5)", + complex(0.25, -0.0), + complex(-2, 1.5), + "(cx fp64)", + lambda x: bits(x.real) + "," + bits(x.imag), + ), + ( + "complex64", + "Complex Float", + "(0.25:+castWord32ToFloat 2147483648)", + "((-2):+1.5)", + complex(0.25, -0.0), + complex(-2, 1.5), + "(cx fp32)", + lambda x: bits(x.real, 32) + "," + bits(x.imag, 32), + ), + ] + for dtype, typ, low, high in [ + ("int8", "Int8", -128, 127), + ("int16", "Int16", -32768, 32767), + ("int32", "Int32", -(2**31), 2**31 - 1), + ("int64", "Int64", -(2**63), 2**63 - 1), + ("uint8", "Word8", 0, 255), + ("uint16", "Word16", 0, 65535), + ("uint32", "Word32", 0, 2**32 - 1), + ("uint64", "Word64", 0, 2**64 - 1), + ("intp", "Int", -(2**63), 2**63 - 1), + ("uintp", "Word", 0, 2**64 - 1), + ]: + storage.append((dtype, typ, str(low), str(high), low, high, "show", str)) + storage.extend( + [ + ("bool", "Bool", "False", "True", False, True, "show", lambda x: str(x)), + ( + "char", + "Char", + "'\\xD800'", + "'\\xAC00'", + "\ud800", + "가", + "(show . ord)", + lambda x: str(ord(x)), + ), + ] + ) + for dtype, typ, hs_initial, hs_changed, initial, changed, enc, encode in storage: + io = own(b.new_io_buffer(3, initial, dtype=dtype)) + typed_initial = "(opaque (" + hs_initial + ")::" + typ + ")" + typed_changed = "(" + hs_changed + "::" + typ + ")" + code = {"bool": 16, "char": 17}.get(dtype, V.DTYPES.get(dtype)) + hs_setup = "do io <- checked(B.newIOBuffer 3 " + typed_initial + ");" + + def check_storage(io=io, changed=changed, encode=encode): + b.write_io_buffer(io, 1, changed) + frozen = own(b.freeze_io_buffer(io)) + return ( + encode(b.read_io_buffer(io, 1)) + + ";" + + list_of(encode, frozen.values) + + ";" + + ",".join(str(x) for x in io.layout) + ) + + case( + dtype + " new/write/read/freeze/layout", + hs_setup + + "_ <- checked(B.writeIOBuffer io 1 " + + typed_changed + + ");x <- checked(B.readIOBuffer io 1);f <- B.freezeIOBuffer io;pure(Right(" + + enc + + ' x++";"++list ' + + enc + + '(B.boxedValues f)++";"++intercalate ","(map show[' + + str(code) + + ",sizeOf(undefined::" + + typ + + "),alignment(undefined::" + + typ + + "),B.ioBufferLength io])))", + check_storage, + ) + + def check_thaw(initial=initial, changed=changed, dtype=dtype, encode=encode): + source = own(b.Boxed([initial, changed], dtype=dtype)) + copy = own(b.thaw_io_buffer(source)) + copy.write(0, changed) + frozen = own(copy.freeze()) + return list_of(encode, source.values) + ";" + list_of(encode, frozen.values) + + case( + dtype + " thaw copy", + "do original <- pure(B.lazyBoxed[" + + typed_initial + + "," + + typed_changed + + "]); io <- checked(B.thawIOBuffer original);_ <- checked(B.writeIOBuffer io 0 " + + typed_changed + + ");f <- B.freezeIOBuffer io;pure(Right(list " + + enc + + '(B.boxedValues original)++";"++list ' + + enc + + "(B.boxedValues f)))", + check_thaw, + ) + + def check_pointer(initial=initial, changed=changed, dtype=dtype, encode=encode): + io = own(b.IOBuffer(2, initial, dtype=dtype)) + + def callback(pointer, count): + first = pointer.read(0) + pointer.write(1, changed) + return encode(first) + "," + str(count) + + result = b.with_io_buffer(io, callback) + return result + ";" + list_of(encode, own(io.freeze()).values) + + case( + dtype + " withIOBuffer", + "do io <- checked(B.newIOBuffer 2 " + + typed_initial + + ");r <- B.withIOBuffer io(\\p n -> do x <- peekElemOff p 0;pokeElemOff p 1 " + + typed_changed + + ";pure(" + + enc + + ' x++","++show n));f <- B.freezeIOBuffer io;pure(Right(r++";"++list ' + + enc + + "(B.boxedValues f)))", + check_pointer, + ) + for index in (-1, 3): + case( + dtype + " bad read " + str(index), + hs_setup + + "fmap(fmap(" + + enc + + "))(B.readIOBuffer io (" + + str(index) + + "))", + lambda io=io, index=index, encode=encode: encode(io.read(index)), + ) + case( + dtype + " bad write " + str(index), + hs_setup + + "fmap(fmap show)(B.writeIOBuffer io (" + + str(index) + + ") " + + typed_changed + + ")", + lambda io=io, index=index, changed=changed: str( + io.write(index, changed) + ), + ) + case( + dtype + " negative allocation", + "fmap(fmap(show . B.ioBufferLength))(B.newIOBuffer (-1) " + + typed_initial + + ")", + lambda dtype=dtype, initial=initial: str( + len(own(b.new_io_buffer(-1, initial, dtype=dtype))) + ), + ) + case( + "allocation byte overflow", + "fmap(fmap(show . B.ioBufferLength))(B.newIOBuffer maxBound (0::Double))", + lambda: str(len(own(b.IOBuffer(sys.maxsize, 0.0)))), + ) + + lines = [ + "module Main where", + "import qualified HMath.API.Buffer as B", + "import HMath.Error", + "import Foreign.Storable", + "import Data.Int", + "import Data.Word", + "import Data.Complex", + "import Data.Ratio", + "import Data.Char(ord)", + "import Data.List(intercalate)", + "import GHC.Float", + "opaque :: a -> a", + "opaque x=x", + "{-# NOINLINE opaque #-}", + 'list e xs="["++intercalate ","(map e xs)++"]"', + 'fp64 x=if isNaN x then "nan" else show(castDoubleToWord64 x)', + 'fp32 x=if isNaN x then "nan" else show(castFloatToWord32 x)', + 'cx e x=e(realPart x)++","++e(imagPart x)', + 'rational x=show(numerator x)++"/"++show(denominator x)', + "right(Right x)=x", + "right(Left e)=error(show e)", + "checked action=action >>= either (fail . show) pure", + "emit :: IO(Either MathError String) -> IO ()", + 'emit action=action >>= either (putStrLn . ("ERR:"++) . show) (putStrLn . ("OK:"++))', + "main=do", + ] + for _, expression, _ in cases: + lines.append(" emit(" + expression + ")") + with tempfile.TemporaryDirectory(prefix="hmath-buffer-oracle-") as directory: + path = Path(directory) + (path / "Main.hs").write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-outputdir", + directory, + "-stubdir", + directory, + str(path / "Main.hs"), + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + for (label, _, call), wanted in zip(cases, expected): + try: + actual = "OK:" + call() + except hmath.HMathError as error: + assert error.math_error is not None, (label, error) + actual = "ERR:" + str(error.math_error) + assert actual == wanted, (label, actual, wanted) + + _scope_contracts(b, own, hmath) + _io_contracts(b, own, hmath) + for owner in reversed(owners): + owner.close() + gc.collect() + print( + f"Buffer: {len(expected)} direct Haskell cases; ST/Ptr expiry, callback exceptions, reentry, exact generic values, every standard Storable instance and concurrent IO contracts passed." + ) + + +def _st_frozen(region, own, list_of): + frozen = own(region.freeze()) + region.write(0, 13) + return list_of(str, frozen.values) + + +def _scope_contracts(b, own, hmath): + retained = [] + source = own(b.Boxed([1, 2])) + + def region_action(region): + retained.append(region) + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(region.read, 0) + try: + future.result(timeout=5) + except hmath.HMathError as error: + assert "another thread" in str(error) + else: + raise AssertionError("cross-thread ST operation succeeded") + return region.freeze() + + frozen = own(b.run_st_buffer(source, region_action)) + assert frozen.values == [1, 2] + region = retained[0] + assert not region.active + for action in ( + lambda: region.read(0), + lambda: region.write(0, 3), + region.freeze, + lambda: region.thaw(source), + ): + try: + action() + except hmath.HMathError as error: + assert "scope has ended" in str(error) + else: + raise AssertionError("ST scope escaped") + region.close() + sentinel = ValueError("original callback failure") + + def fail(region): + retained.append(region) + raise sentinel + + try: + b.run_st_buffer(source, fail) + except ValueError as error: + assert error is sentinel + else: + raise AssertionError("ST callback exception lost") + assert not retained[-1].active + retained[-1].close() + try: + b.map_strict(lambda _: (_ for _ in ()).throw(sentinel), source) + except ValueError as error: + assert error is sentinel + else: + raise AssertionError("mapStrict callback exception lost") + + +def _io_contracts(b, own, hmath): + retained = [] + io = own(b.IOBuffer(16, 0, dtype="int64")) + sentinel = LookupError("original pointer callback failure") + + def borrow(pointer, count): + assert count == 16 and pointer.active and pointer.address > 0 + retained.append(pointer) + pointer.write(0, 7) + assert len(io) == 16 + for action in ( + lambda: io.read(0), + lambda: io.write(0, 1), + io.freeze, + lambda: io.with_pointer(lambda *_: None), + ): + try: + action() + except hmath.HMathError as error: + assert "cannot reenter" in str(error) + else: + raise AssertionError("borrowed IO buffer reentry succeeded") + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(pointer.read, 0) + try: + future.result(timeout=5) + except hmath.HMathError as error: + assert "another thread" in str(error) + else: + raise AssertionError("cross-thread pointer operation succeeded") + raise sentinel + + try: + io.with_pointer(borrow) + except LookupError as error: + assert error is sentinel + else: + raise AssertionError("pointer callback exception lost") + assert io.read(0) == 7 + pointer = retained[0] + assert not pointer.active + for action in ( + lambda: pointer.read(0), + lambda: pointer.write(0, 1), + lambda: pointer.address, + lambda: pointer.layout, + ): + try: + action() + except hmath.HMathError as error: + assert "scope has ended" in str(error) + else: + raise AssertionError("borrowed pointer escaped") + pointer.close() + with ThreadPoolExecutor(max_workers=4) as pool: + list(pool.map(lambda index: io.write(index, index * 3), range(16))) + assert list(pool.map(io.read, range(16))) == [index * 3 for index in range(16)] + frozen = own(io.freeze()) + copy = own(b.thaw_io_buffer(frozen)) + io.close() + assert copy.read(7) == 21 + copy.write(7, 99) + assert frozen.values[7] == 21 + # Common Bool/Text Values carry dtype=-1; their Storable storage witnesses + # remain actual Bool/Char rather than numeric coefficient type codes. + from _hmath_native import _value as V + + for dtype, initial in (("bool", True), ("char", "\0")): + value = own(V.encode(initial)) + storage = own(b.new_io_buffer(1, value, dtype=dtype)) + storage.write(0, value) + assert storage.read(0) == initial + source = own(b.Boxed([value], dtype=dtype)) + copied = own(b.thaw_io_buffer(source)) + assert copied.read(0) == initial + empty = own(b.Boxed([])) + empty_io = own(b.thaw_io_buffer(empty, dtype="float32")) + assert len(empty_io) == 0 and empty_io.dtype == "float32" + for value in (10**100, Fraction(1, 3)): + try: + b.new_io_buffer( + 1, value, dtype="integer" if isinstance(value, int) else "rational" + ) + except hmath.HMathError as error: + assert "Storable" in str(error) + else: + raise AssertionError("invented Storable instance") + + +if __name__ == "__main__": + main() diff --git a/tools/check_c_sdk.py b/tools/check_c_sdk.py new file mode 100644 index 0000000..5bc04e7 --- /dev/null +++ b/tools/check_c_sdk.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exercise a relocated C SDK in an environment without GHC or Python HMath.""" + +import argparse +import ctypes +import json +import os +import shlex +import subprocess +import tarfile +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("archive", type=Path) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="hmath-sdk-relocation-") as work: + directory = Path(work) + with tarfile.open(args.archive) as archive: + archive.extractall(directory, filter="data") + prefixes = list(directory.glob("hmath-*")) + if len(prefixes) != 1: + raise ValueError("expected exactly one SDK prefix") + prefix = prefixes[0].rename(directory / "relocated prefix") + metadata = json.loads((prefix / "manifest.json").read_text()) + library = ctypes.CDLL(str(prefix / "lib/libhmath.so.1")) + library.hmath_library_version.restype = ctypes.c_char_p + assert library.hmath_library_version().decode() == metadata["version"] + assert library.hmath_abi_version() == metadata["abi"] + env = { + k: v + for k, v in os.environ.items() + if k not in ("LD_LIBRARY_PATH", "HMATH_LIBRARY", "PYTHONPATH") + } + env["PKG_CONFIG_PATH"] = str(prefix / "lib/pkgconfig") + flags = shlex.split( + subprocess.check_output( + ["pkg-config", "--cflags", "--libs", "hmath"], env=env, text=True + ) + ) + for compiler, standard, source in [ + ("cc", "c99", "numeric_contracts.c"), + ("c++", "c++17", "numeric_contracts.cpp"), + ("cc", "c99", "matrix_contracts.c"), + ("cc", "c99", "autodiff_contracts.c"), + ("cc", "c99", "execution_smoke.c"), + ("cc", "c99", "header_c99.c"), + ("c++", "c++17", "header_c99.c"), + ("cc", "c99", "foundation_contracts.c"), + ("cc", "c11", "numeric_objects_contracts.c"), + ("c++", "c++17", "numeric_objects_contracts.cpp"), + ("cc", "c99", "buffer_contracts.c"), + ("c++", "c++17", "buffer_contracts.cpp"), + ("cc", "c99", "tensor_contracts.c"), + ("c++", "c++17", "tensor_contracts.cpp"), + ("cc", "c99", "deeplearning_contracts.c"), + ("c++", "c++17", "deeplearning_contracts.cpp"), + ("cc", "c99", "autodiff_checked_contracts.c"), + ("c++", "c++17", "autodiff_checked_contracts.cpp"), + ("cc", "c99", "spectral_contracts.c"), + ]: + target = directory / ("consumer-" + Path(source).stem + "-" + standard) + subprocess.run( + [ + compiler, + "-Wall", + "-Wextra", + "-Werror", + "-std=" + standard, + str(ROOT / "test/native" / source), + *flags, + "-Wl,-rpath," + str(prefix / "lib"), + "-o", + str(target), + ], + env=env, + check=True, + ) + subprocess.run([str(target)], env=env, check=True) + consumer = directory / "cmake-consumer" + consumer.mkdir() + (consumer / "client.c").write_bytes( + (ROOT / "test/native/numeric_contracts.c").read_bytes() + ) + (consumer / "CMakeLists.txt").write_text( + "cmake_minimum_required(VERSION 3.16)\nproject(sdk_consumer C)\n" + "find_package(HMath 1.0 CONFIG REQUIRED)\nadd_executable(client client.c)\n" + "target_link_libraries(client PRIVATE HMath::hmath)\n" + ) + build = directory / "cmake-build" + subprocess.run( + [ + "cmake", + "-S", + str(consumer), + "-B", + str(build), + "-DHMath_DIR=" + str(prefix / "lib/cmake/HMath"), + ], + env=env, + check=True, + ) + subprocess.run(["cmake", "--build", str(build)], env=env, check=True) + subprocess.run([str(build / "client")], env=env, check=True) + # Loading through the SDK must resolve bundled GHC libraries there. + if Path("/proc/self/maps").exists(): + for line in Path("/proc/self/maps").read_text().splitlines(): + if "libHS" in line or "libhmath" in line: + assert str(prefix) in line, line + print( + "Relocated C/C++ SDK: installed headers, pkg-config, runtime dependencies PASS" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_deeplearning_equivalence.py b/tools/check_deeplearning_equivalence.py new file mode 100644 index 0000000..26781db --- /dev/null +++ b/tools/check_deeplearning_equivalence.py @@ -0,0 +1,633 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare deep-learning bindings directly with original Haskell algorithms.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from check_tensor_equivalence import SOURCE as TENSOR_SOURCE +from check_tensor_equivalence import close, encode + +ROOT = Path(__file__).resolve().parent.parent +SOURCE = ( + TENSOR_SOURCE.split("checked=")[0] + + r""" +import_placeholder +instance(Enc a,Enc b,Enc c)=>Enc(a,b,c) where enc(a,b,c)="T["++enc a++","++enc b++","++enc c++"]" +instance Enc R.RNG where enc=enc.R.serializeRNG +instance Enc L.BatchNormState where enc s=enc(L.runningMean s,L.runningVariance s,L.batchesSeen s) +instance Enc L.ConvOptions where enc s="Options["++enc(L.convolutionStride s)++","++enc(L.convolutionPadding s)++","++enc(L.convolutionDilation s)++","++enc(L.convolutionGroups s)++"]" +instance Enc P.QuantizedTensor where enc s=enc(P.quantizedValues s,P.quantizationScales s,P.quantizationZeroPoints s) +instance Enc P.LossScaler where enc s=enc(P.lossScale s,P.scaleGrowthInterval s,P.finiteSteps s) +instance Enc Q.ClassificationMetrics where enc s="Metrics["++enc(Q.accuracy s)++","++enc(Q.precisionByClass s)++","++enc(Q.recallByClass s)++","++enc(Q.f1ByClass s)++"]" +instance Enc L.KVCache where enc=enc.L.cacheValues +checked=either(error.show)id +make dims xs=checked(T.tensor dims xs)::T.Tensor Double +x=make[2,2][1.1,-2.3,3.7,4.2] +w=make[2,2][0.5,0.7,-0.8,1.2] +image=make[1,1,4][1,2,3,4] +kernel=make[1,1,2][0.3,0.7] +options=L.ConvOptions[1][0][1]1 +rng=R.seedRNG R.PCG32 42 +state=L.BatchNormState[0,0][1,1]0 +scale=P.LossScaler 128 2 0 +admake dims xs=checked(A.adTensor dims xs) +adresult point out=out >>= (\result->A.valueAndGradient(\_->A.adSum result)point) +adx=admake[2,2](map A.variable[0..3]) +adw=admake[2,2](map A.constant[0.5,0.7,-0.8,1.2]) +main=sequence_(map(>>=putStrLn)[CASES]) +""" +) +SOURCE = SOURCE.replace("import_placeholder\n", "").replace( + "class Enc a", + "import qualified HMath.DeepLearning.Core as C\nimport qualified HMath.DeepLearning.Layers as L\nimport qualified HMath.DeepLearning.Precision as P\nimport qualified HMath.DeepLearning.Metrics as Q\nimport qualified HMath.Autodiff as A\nimport qualified HMath.Random as R\nclass Enc a", +) + + +def cases(n, t, ad, r): + owned = [] + + def keep(value): + owned.append(value) + return value + + def make(shape, data): + return keep(t.tensor(shape, data)) + + x = make([2, 2], [1.1, -2.3, 3.7, 4.2]) + w = make([2, 2], [0.5, 0.7, -0.8, 1.2]) + image = make([1, 1, 4], [1, 2, 3, 4]) + kernel = make([1, 1, 2], [0.3, 0.7]) + options = n.ConvOptions([1], [0], [1], 1) + state = n.BatchNormState([0, 0], [1, 1], 0) + scale = n.LossScaler(128, 2, 0) + generator = keep(r.pcg32()) + rng = keep(r.seed_rng(generator, 42)) + selected = [] + + def add(name, hs, call): + selected.append((name, "pure(enc(" + hs + "))", call)) + + def scalar_ad(method, point): + return ad.value_and_gradient( + lambda xs: n.activation_expr(method, xs[0]), [point] + ) + + activations = [ + ("Sigmoid", n.Sigmoid), + ("Tanh", n.Tanh), + ("ReLU", n.ReLU), + ("LeakyReLU 0.2", n.LeakyReLU(0.2)), + ("PReLU 0.3", n.PReLU(0.3)), + ("ELU 0.8", n.ELU(0.8)), + ("SELU", n.SELU), + ("GELU", n.GELU), + ("SiLU", n.SiLU), + ("Mish", n.Mish), + ("Softplus", n.Softplus), + ("Softsign", n.Softsign), + ("HardSigmoid", n.HardSigmoid), + ("HardSwish", n.HardSwish), + ] + for hs, method in activations: + for point in [-0.75, 0, 1.25]: + add( + "activation " + hs + str(point), + "C.activation(C." + hs + ")(" + str(point) + ")", + lambda method=method, point=point: n.activation(method, point), + ) + add( + "activationDerivative " + hs + str(point), + "C.activationDerivative(C." + hs + ")(" + str(point) + ")", + lambda method=method, point=point: n.activation_derivative( + method, point + ), + ) + add( + "activationExpr " + hs, + "A.valueAndGradient(\\xs->C.activationExpr(C." + hs + ")(head xs))[-0.75]", + lambda method=method: scalar_ad(method, -0.75), + ) + losses = [ + ("MeanSquaredError", n.MeanSquaredError, [0.2, 0.8], [0.4, 0.6]), + ("MeanAbsoluteError", n.MeanAbsoluteError, [0.2, 0.8], [0.4, 0.6]), + ("Huber 0.3", n.Huber(0.3), [0.2, 0.8], [0.4, 0.6]), + ("SmoothL1 0.3", n.SmoothL1(0.3), [0.2, 0.8], [0.4, 0.6]), + ("BinaryCrossEntropy", n.BinaryCrossEntropy, [0.2, 0.8], [0.4, 0.6]), + ("CategoricalCrossEntropy", n.CategoricalCrossEntropy, [0.2, 0.8], [0.4, 0.6]), + ("NegativeLogLikelihood", n.NegativeLogLikelihood, [0.2, 0.8], [-0.4, -0.6]), + ("KLDivergence", n.KLDivergence, [0.2, 0.8], [0.4, 0.6]), + ("CosineLoss", n.CosineLoss, [0.2, 0.8], [0.4, 0.6]), + ("Hinge 1", n.Hinge(1), [-1, 1], [0.4, 0.6]), + ] + for hs, method, target, prediction in losses: + args = str(target) + str(prediction) + for hsfn, pyfn in [("loss", n.loss), ("lossGradient", n.loss_gradient)]: + add( + hsfn + hs, + "C." + hsfn + "(C." + hs + ")C.Mean " + args, + lambda method=method, target=target, prediction=prediction, pyfn=pyfn: ( + pyfn(method, n.Mean, target, prediction) + ), + ) + add( + "lossExpr" + hs, + "A.valueAndGradient(C.lossExpr(C." + + hs + + ")C.Mean " + + str(target) + + ")" + + str(prediction), + lambda method=method, target=target, prediction=prediction: ( + ad.value_and_gradient( + lambda xs: n.loss_expr(method, n.Mean, target, xs), prediction + ) + ), + ) + for hsfn, pyfn in [ + ("softmax", n.softmax), + ("logSoftmax", n.log_softmax), + ("sparsemax", n.sparsemax), + ]: + add(hsfn, "C." + hsfn + "[-3,1,2]", lambda pyfn=pyfn: pyfn([-3, 1, 2])) + for hsfn, pyfn in [ + ("softmaxExpr", n.softmax_expr), + ("logSoftmaxExpr", n.log_softmax_expr), + ("sparsemaxExpr", n.sparsemax_expr), + ]: + add( + hsfn, + "A.jacobian(C." + hsfn + ")[-3,1,2]", + lambda pyfn=pyfn: ad.jacobian(pyfn, [-3, 1, 2]), + ) + entries = [ + ("gatedLinearUnit", "gated_linear_unit", "[1,2][-1,3]", ([1, 2], [-1, 3])), + ( + "binaryCrossEntropyLogits", + "binary_cross_entropy_logits", + "C.Sum[0,1][-1000,1000]", + (n.Sum, [0, 1], [-1000, 1000]), + ), + ( + "categoricalCrossEntropyLogits", + "categorical_cross_entropy_logits", + "[0.2,0.8][1000,1001]", + ([0.2, 0.8], [1000, 1001]), + ), + ("regularization", "regularization", "0.3 0.4[-2,3]", (0.3, 0.4, [-2, 3])), + ( + "contrastiveLoss", + "contrastive_loss", + "2 False[1,2][1.5,3]", + (2, False, [1, 2], [1.5, 3]), + ), + ( + "tripletLoss", + "triplet_loss", + "0.5[1,2][1.5,2][2,3]", + (0.5, [1, 2], [1.5, 2], [2, 3]), + ), + ( + "focalLoss", + "focal_loss", + "0.25 2[0,1][0.2,0.8]", + (0.25, 2, [0, 1], [0.2, 0.8]), + ), + ("diceLoss", "dice_loss", "0.1[0,1][0.2,0.8]", (0.1, [0, 1], [0.2, 0.8])), + ("iouLoss", "iou_loss", "0.1[0,1][0.2,0.8]", (0.1, [0, 1], [0.2, 0.8])), + ( + "ctcLoss", + "ctc_loss", + "0[1][[-0.3,-1.3],[-0.2,-1.7]]", + (0, [1], [[-0.3, -1.3], [-0.2, -1.7]]), + ), + ( + "ctcLossGradient", + "ctc_loss_gradient", + "0[1][[-0.3,-1.3],[-0.2,-1.7]]", + (0, [1], [[-0.3, -1.3], [-0.2, -1.7]]), + ), + ] + for hs, py, args, values in entries: + add( + hs, + "C." + hs + " " + args, + lambda py=py, values=values: getattr(n, py)(*values), + ) + add( + "ctcLossExpr", + r"A.valueAndGradient(\xs->checked(C.ctcLossExpr 0[1][take 2 xs,drop 2 xs]))[-0.3,-1.3,-0.2,-1.7]", + lambda: ad.value_and_gradient( + lambda xs: n.ctc_loss_expr(0, [1], [xs[:2], xs[2:]]), + [-0.3, -1.3, -0.2, -1.7], + ), + ) + add( + "dropout training", + "L.dropout L.Training 0.3 rng x", + lambda: n.dropout(n.Training.TRAINING, 0.3, rng, x), + ) + add( + "dropout inference", + "L.dropout L.Inference 0.3 rng x", + lambda: n.dropout(n.Inference, 0.3, rng, x), + ) + add( + "spatial dropout", + "L.spatialDropout L.Training 0.4 rng image", + lambda: n.spatial_dropout(n.Training.TRAINING, 0.4, rng, image), + ) + for mode, tag in [(n.Training.TRAINING, "Training"), (n.Inference, "Inference")]: + add( + "batch norm" + tag, + "L.batchNorm L." + tag + " 0.1 1e-5[1,2][0,0]state x", + lambda mode=mode: n.batch_norm(mode, 0.1, 1e-5, [1, 2], [0, 0], state, x), + ) + for hs, py, args, values in [ + ("layerNorm", "layer_norm", "1 1e-5 x", (1, 1e-5, x)), + ("rmsNorm", "rms_norm", "1 1e-5 x", (1, 1e-5, x)), + ("instanceNorm", "instance_norm", "1e-5 image", (1e-5, image)), + ("groupNorm", "group_norm", "1 1e-5 image", (1, 1e-5, image)), + ("weightNorm", "weight_norm", "0[1,2]x", (0, [1, 2], x)), + ]: + add( + hs, + "L." + hs + " " + args, + lambda py=py, values=values: getattr(n, py)(*values), + ) + initializers = [ + ("XavierUniform", n.XavierUniform), + ("XavierNormal", n.XavierNormal), + ("KaimingUniform", n.KaimingUniform), + ("KaimingNormal", n.KaimingNormal), + ("Orthogonal 0.9", n.Orthogonal(0.9)), + ("TruncatedNormal 0 1 2", n.TruncatedNormal(0, 1, 2)), + ] + for hs, method in initializers: + add( + "initialize" + hs, + "L.initializeWeights(L." + hs + ")2 2[2,2]rng", + lambda method=method: n.initialize_weights(method, 2, 2, [2, 2], rng), + ) + add("embedding", "L.embedding x[1,0,1]", lambda: n.embedding(x, [1, 0, 1])) + add("dense", "L.dense x w[0.1,0.2]", lambda: n.dense(x, w, [0.1, 0.2])) + for hs, py in [ + ("convolution", "convolution"), + ("depthwiseConvolution", "depthwise_convolution"), + ]: + add( + hs, + "L." + hs + " options image kernel[0.1]", + lambda py=py: getattr(n, py)(options, image, kernel, [0.1]), + ) + add( + "transposed conv", + "L.transposedConvolution[0]options image kernel[0.1]", + lambda: n.transposed_convolution([0], options, image, kernel, [0.1]), + ) + for hs, py, args, values in [ + ( + "pooling", + "pooling", + "L.MaxPool[2][1][0]image", + (n.MaxPool, [2], [1], [0], image), + ), + ( + "pooling", + "pooling", + "L.AveragePool[2][1][1]image", + (n.AveragePool, [2], [1], [1], image), + ), + ( + "adaptivePooling", + "adaptive_pooling", + "L.MaxPool[2]image", + (n.MaxPool, [2], image), + ), + ( + "globalPooling", + "global_pooling", + "L.AveragePool image", + (n.AveragePool, image), + ), + ]: + add( + hs + args, + "L." + hs + " " + args, + lambda py=py, values=values: getattr(n, py)(*values), + ) + add( + "attention", + "L.scaledDotProductAttention x w x(Just[[True,False],[False,False]])(Just[[0.1,0.2],[0,0]])", + lambda: n.scaled_dot_product_attention( + x, w, x, [[True, False], [False, False]], [[0.1, 0.2], [0, 0]] + ), + ) + add( + "multihead", + "L.multiheadAttention 2 x w x Nothing", + lambda: n.multihead_attention(2, x, w, x, None), + ) + add("causal", "L.causalMask 2 3 1", lambda: n.causal_mask(2, 3, 1)) + add( + "rotary", "L.rotaryEmbedding 10000 3 x", lambda: n.rotary_embedding(10000, 3, x) + ) + add( + "sinusoidal", + "L.sinusoidalEncoding 3 5 2", + lambda: n.sinusoidal_encoding(3, 5, 2), + ) + add("alibi", "L.alibiBias 0.4 2 3 1", lambda: n.alibi_bias(0.4, 2, 3, 1)) + add("empty cache", "L.emptyCache 4 2 2", lambda: n.empty_cache(4, 2, 2)) + cache = keep(n.empty_cache(4, 2, 2)) + appended = keep(n.append_cache(cache, x, w)) + add( + "append cache", + r"L.emptyCache 4 2 2 >>= \c->L.appendCache c x w", + lambda: n.append_cache(cache, x, w), + ) + add( + "cache values", + r"L.cacheValues(checked(L.emptyCache 4 2 2 >>= \c->L.appendCache c x w))", + lambda: n.cache_values(appended), + ) + add( + "feed forward", + "L.transformerFeedForward C.GELU x w[0.1,0.2]w[0.3,0.4]", + lambda: n.transformer_feed_forward(n.GELU, x, w, [0.1, 0.2], w, [0.3, 0.4]), + ) + + def adtensor_result(operation, point=(1.1, -2.3, 3.7, 4.2)): + def objective(xs): + with ( + ad.ad_tensor([2, 2], xs) as tx, + ad.ad_tensor([2, 2], [0.5, 0.7, -0.8, 1.2]) as tw, + operation(tx, tw) as result, + ): + return ad.ad_sum(result) + + return ad.value_and_gradient(objective, point) + + add( + "denseAD", + "adresult[1.1,-2.3,3.7,4.2](L.denseAD adx adw[0.1,0.2])", + lambda: adtensor_result(lambda tx, tw: n.dense_ad(tx, tw, [0.1, 0.2])), + ) + for hs, py in [("layerNormAD", "layer_norm_ad"), ("rmsNormAD", "rms_norm_ad")]: + add( + hs, + "adresult[1.1,-2.3,3.7,4.2](L." + hs + " 1 1e-5 adx)", + lambda py=py: adtensor_result(lambda tx, tw: getattr(n, py)(1, 1e-5, tx)), + ) + add( + "attentionAD", + "adresult[1.1,-2.3,3.7,4.2](L.scaledDotProductAttentionAD adx adw adx(Just[[True,False],[True,True]]))", + lambda: adtensor_result( + lambda tx, tw: n.scaled_dot_product_attention_ad( + tx, tw, tx, [[True, False], [True, True]] + ) + ), + ) + + def convad(): + def objective(xs): + with ( + ad.ad_tensor([1, 1, 4], xs) as tx, + ad.ad_tensor([1, 1, 2], [0.3, 0.7]) as tw, + n.convolution_ad(options, tx, tw, [0.1]) as out, + ): + return ad.ad_sum(out) + + return ad.value_and_gradient(objective, [1, 2, 3, 4]) + + add( + "convolutionAD", + "adresult[1,2,3,4](L.convolutionAD options(admake[1,1,4](map A.variable[0..3]))(admake[1,1,2](map A.constant[0.3,0.7]))[0.1])", + convad, + ) + for scheme, tag in [(n.Symmetric, "Symmetric"), (n.Asymmetric, "Asymmetric")]: + for axis in [None, 0]: + hs = ( + "P.quantize P." + + tag + + (" Nothing" if axis is None else "(Just 0)") + + " x" + ) + qt = keep(n.quantize(scheme, axis, x)) + add( + "quantize" + tag + str(axis), + hs, + lambda scheme=scheme, axis=axis: n.quantize(scheme, axis, x), + ) + add( + "dequantize" + tag + str(axis), + hs + " >>= P.dequantize", + lambda qt=qt: n.dequantize(qt), + ) + left = keep(n.quantize(n.Symmetric, 0, x)) + right = keep(n.quantize(n.Asymmetric, 1, w)) + add( + "int8Gemm", + "do a<-P.quantize P.Symmetric(Just 0)x;b<-P.quantize P.Asymmetric(Just 1)w;P.int8Gemm a b", + lambda: n.int8_gemm(left, right), + ) + for precision, tag in [(n.FP16, "FP16"), (n.BF16, "BF16")]: + add( + "reducedGemm" + tag, + "P.reducedGemm P." + tag + " x w", + lambda precision=precision: n.reduced_gemm(precision, x, w), + ) + for hs, py, args, values in [ + ("initialLossScaler", "initial_loss_scaler", "128 2", (128, 2)), + ("scaleLoss", "scale_loss", "scale 0.3", (scale, 0.3)), + ( + "unscaleGradients", + "unscale_gradients", + "scale[128,256]", + (scale, [128, 256]), + ), + ( + "unscaleGradients", + "unscale_gradients", + "scale[1/0]", + (scale, [float("inf")]), + ), + ("updateLossScaler", "update_loss_scaler", "True scale", (True, scale)), + ("updateLossScaler", "update_loss_scaler", "False scale", (False, scale)), + ("gradientNorm", "gradient_norm", "[3,4]", ([3, 4],)), + ("clipGradients", "clip_gradients", "2[3,4]", (2, [3, 4])), + ]: + add( + hs + args, + "P." + hs + " " + args, + lambda py=py, values=values: getattr(n, py)(*values), + ) + for hs, py, args, values in [ + ( + "confusionMatrix", + "confusion_matrix", + "3[0,1,1,2][0,2,1,2]", + (3, [0, 1, 1, 2], [0, 2, 1, 2]), + ), + ( + "classificationMetrics", + "classification_metrics", + "3[0,1,1,2][0,2,1,2]", + (3, [0, 1, 1, 2], [0, 2, 1, 2]), + ), + ( + "topKAccuracy", + "top_k_accuracy", + "2[0,2][[1,2,3],[2,1,3]]", + (2, [0, 2], [[1, 2, 3], [2, 1, 3]]), + ), + ( + "rocAUC", + "roc_auc", + "[False,True,False,True][0.1,0.8,0.4,0.8]", + ([False, True, False, True], [0.1, 0.8, 0.4, 0.8]), + ), + ( + "prAUC", + "pr_auc", + "[False,True,False,True][0.1,0.8,0.4,0.8]", + ([False, True, False, True], [0.1, 0.8, 0.4, 0.8]), + ), + ("perplexity", "perplexity", "[0.2,0.7,1.1]", ([0.2, 0.7, 1.1],)), + ("cosineSimilarityMatrix", "cosine_similarity_matrix", "x w", (x, w)), + ( + "marginRankingLoss", + "margin_ranking_loss", + "0.3[1,2][0.5,3][1,-1]", + (0.3, [1, 2], [0.5, 3], [1, -1]), + ), + ]: + add( + hs, + "Q." + hs + " " + args, + lambda py=py, values=values: getattr(n, py)(*values), + ) + for name, hs, call in [ + ("badELU", "C.activation(C.ELU 0)1", lambda: n.activation(n.ELU(0), 1)), + ("emptySoftmax", "C.softmax[]", lambda: n.softmax([])), + ( + "badProbability", + "C.loss C.BinaryCrossEntropy C.Mean[1][0]", + lambda: n.loss(n.BinaryCrossEntropy, n.Mean, [1], [0]), + ), + ( + "badDropout", + "L.dropout L.Training 1 rng x", + lambda: n.dropout(n.Training.TRAINING, 1, rng, x), + ), + ("badCache", "L.emptyCache 0 1 1", lambda: n.empty_cache(0, 1, 1)), + ( + "badQuantization", + "P.quantize P.Symmetric(Just 7)x", + lambda: n.quantize(n.Symmetric, 7, x), + ), + ( + "badMetric", + "Q.rocAUC[True,True][0.1,0.2]", + lambda: n.roc_auc([True, True], [0.1, 0.2]), + ), + ]: + add(name, hs, call) + return selected, owned + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import _neural_base as n + from _hmath_native import _tensor_core as t + from _hmath_native import autodiff as ad + from _hmath_native import random_values as r + + def enc(value): + if isinstance(value, n.QuantizedTensor): + return enc((value.values, value.scales, value.zero_points)) + if isinstance(value, n.KVCache): + outputs = n.cache_values(value) + try: + return enc(outputs) + finally: + close(outputs) + if isinstance(value, r.RNG): + return enc(value.serialize()) + if isinstance(value, n.BatchNormState): + return enc((value.running_mean, value.running_variance, value.batches_seen)) + if isinstance(value, n.LossScaler): + return enc((value.scale, value.growth_interval, value.finite_steps)) + if isinstance(value, n.ClassificationMetrics): + return ( + "Metrics[" + + ",".join( + enc(x) + for x in [value.accuracy, value.precision, value.recall, value.f1] + ) + + "]" + ) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(enc(x) for x in value) + + "]" + ) + return encode(value, t) + + selected, owned = cases(n, t, ad, r) + try: + with tempfile.TemporaryDirectory(prefix="hmath-neural-oracle-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text( + SOURCE.replace("CASES", ",\n ".join(expr for _, expr, _ in selected)) + ) + subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-i" + str(ROOT / "src"), + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + for (name, _, call), reference in zip(selected, expected, strict=True): + value = None + try: + value = call() + actual = enc(value) + except hmath.HMathError as error: + if error.math_error is None: + raise + actual = "ERR" + str(error.math_error) + finally: + close(value) + if actual != reference: + raise AssertionError(f"{name}: native {actual}, original {reference}") + print( + f"Deep-learning equivalence: {len(selected)} independent original Haskell sequences match IEEE bits, full state/RNG, graph values/gradients and errors." + ) + finally: + close(owned) + + +if __name__ == "__main__": + main() diff --git a/tools/check_execution.py b/tools/check_execution.py new file mode 100644 index 0000000..b86071a --- /dev/null +++ b/tools/check_execution.py @@ -0,0 +1,221 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Validate explicit buffer execution, dtype and BLAS ABI with protocol spies.""" + +import argparse +import ctypes as C +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + parser.add_argument("--compiler", default="cc") + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + import numpy as np + from _hmath_native import execution as ex + + def fails(status, call, *arguments, **keywords): + try: + call(*arguments, **keywords) + except hmath.HMathError as error: + assert error.status == status, (status, error.status, str(error)) + return str(error) + raise AssertionError("operation unexpectedly succeeded") + + with tempfile.TemporaryDirectory(prefix="hmath-execution-") as directory: + spies = {} + for name, flags in [ + ("lp64", []), + ("ilp64", ["-DILP64"]), + ("no-sgemm", ["-DNO_SGEMM"]), + ]: + path = Path(directory) / (name + ".so") + subprocess.run( + [ + args.compiler, + "-std=c11", + "-O2", + "-ffp-contract=off", + "-shared", + "-fPIC", + *flags, + str(ROOT / "test/native/execution_blas_spy.c"), + "-o", + str(path), + ], + check=True, + ) + spy = C.CDLL(str(path)) + spy.hm_spy_pointer.argtypes = [C.c_uint] + spy.hm_spy_pointer.restype = C.c_size_t + spy.hm_spy_ldc.restype = C.c_int64 + spy.hm_spy_alpha32.restype = C.c_float + spies[name] = (path, spy) + for dtype in [np.float32, np.float64]: + a = np.array([[1, 2], [3, 4]], dtype=dtype) + b = np.array([[2, 0], [1, 2]], dtype=dtype) + for provider, path in [("reference", None), ("openblas", spies["lp64"][0])]: + with ex.Execution(provider, library_path=path) as engine: + out = np.ones((2, 2), dtype=dtype) + assert engine.gemm(a, b, out, alpha=2, beta=3) is out + np.testing.assert_array_equal( + out, np.array([[11, 11], [23, 19]], dtype=dtype) + ) + assert out.dtype == dtype + # Non-consecutive rows are accepted, with untouched padding. + ap = np.full((2, 3), np.nan, dtype=dtype) + ap[:, :2] = a + bp = np.full((2, 3), np.nan, dtype=dtype) + bp[:, :2] = b + cp = np.full((2, 3), np.nan, dtype=dtype) + cp[:, :2] = 0 + engine.gemm(ap[:, :2], bp[:, :2], cp[:, :2]) + np.testing.assert_array_equal(cp[:, :2], a @ b) + assert np.isnan(cp[:, 2]).all() + if path: + spy = spies["lp64"][1] + assert [spy.hm_spy_pointer(i) for i in range(3)] == [ + ap.ctypes.data, + bp.ctypes.data, + cp.ctypes.data, + ] + assert spy.hm_spy_ldc() == 3 + before = a.copy() + fails(1, engine.gemm, a, b, a) + np.testing.assert_array_equal(a, before) + out.fill(0) + out[0, 0] = np.nan + assert ( + fails(11, engine.gemm, a, b, out, beta=0) + == "NonFiniteVectorEntry 10" + ) + with np.errstate(over="ignore", invalid="ignore"): + huge = np.array([[np.finfo(dtype).max]], dtype=dtype) + twice = np.array([[2]], dtype=dtype) + target = np.zeros((1, 1), dtype=dtype) + assert ( + fails(11, engine.gemm, huge, twice, target) + == "NonFiniteVectorEntry 0" + ) + assert np.isinf(target[0, 0]) if path else target[0, 0] == 0 + with ex.Execution(max_elements=3) as limited: + out = np.zeros((2, 2), dtype=dtype) + fails(3, limited.gemm, a, b, out) + assert not out.any() + with ex.Execution(max_multiply_adds=7) as limited: + fails(3, limited.gemm, a, b, out) + path, spy = spies["lp64"] + with ex.Execution("openblas", library_path=path) as engine: + a = np.ones((1025, 1), dtype=np.float32) + b = np.ones((1, 1025), dtype=np.float32) + out = np.zeros((1025, 1025), dtype=np.float32) + engine.gemm(a, b, out) + assert out.size > 1048576 and np.all(out == 1) + before32, before64 = spy.hm_spy_calls32(), spy.hm_spy_calls64() + a = np.ones((257, 257), dtype=np.float32) + out = np.zeros_like(a) + engine.gemm(a, a, out) + assert 257**3 > 16777216 and np.all(out == 257) + assert ( + spy.hm_spy_calls32() == before32 + 1 + and spy.hm_spy_calls64() == before64 + ) + assert [spy.hm_spy_pointer(i) for i in range(3)] == [ + a.ctypes.data, + a.ctypes.data, + out.ctypes.data, + ] + # Explicit float32 scalars round at the float32 boundary. + one = np.ones((1, 1), dtype=np.float32) + zero = np.zeros_like(one) + engine.gemm(one, one, zero, alpha=16777217) + assert spy.hm_spy_alpha32() == 16777216 and zero[0, 0] == 16777216 + # SGEMM is optional at provider-open time; a missing symbol does not + # prevent double-precision use and never causes implicit conversion. + with ex.Execution("openblas", library_path=spies["no-sgemm"][0]) as engine: + a = np.ones((1, 1), dtype=np.float64) + out = np.zeros_like(a) + engine.gemm(a, a, out) + assert out[0, 0] == 1 + a = a.astype(np.float32) + out = np.zeros_like(a) + fails(10, engine.gemm, a, a, out) + assert out[0, 0] == 0 + # Validate leading dimensions at the selected BLAS integer width. + for name, bits in [("lp64", 32), ("ilp64", 64)]: + with ex.Execution( + "openblas", integer_bits=bits, library_path=spies[name][0] + ) as engine: + a = C.c_float(2) + b = C.c_float(3) + c = C.c_float(0) + view_a = ex._View(C.addressof(a), 1, 1, 1, 1) + view_b = ex._View(C.addressof(b), 1, 1, 1, 1) + view_c = ex._View(C.addressof(c), 1, 1, 1, 2**31 + 1) + call = ex._api( + "hmath_execution_gemm_f32", + C.c_int, + C.c_void_p, + C.c_void_p, + C.c_float, + C.POINTER(ex._View), + C.POINTER(ex._View), + C.c_float, + C.POINTER(ex._View), + ) + status = call( + engine._ptr, + None, + 1, + C.byref(view_a), + C.byref(view_b), + 0, + C.byref(view_c), + ) + assert status == (1 if bits == 32 else 0), status + assert c.value == (0 if bits == 32 else 6) + if bits == 64: + assert spies[name][1].hm_spy_ldc() == 2**31 + 1 + # Huge zero-element shapes are valid and must not enumerate empty rows. + with ex.Execution() as engine: + limit = (1 << (C.sizeof(C.c_ssize_t) * 8 - 1)) - 1 + a = ex._View(None, 0, 0, limit, limit) + b = ex._View(None, 0, limit, 0, 0) + out = ex._View(None, 0, 0, 0, 0) + call = ex._api( + "hmath_execution_gemm_f32", + C.c_int, + C.c_void_p, + C.c_void_p, + C.c_float, + C.POINTER(ex._View), + C.POINTER(ex._View), + C.c_float, + C.POINTER(ex._View), + ) + hmath._check( + call(engine._ptr, None, 1, C.byref(a), C.byref(b), 0, C.byref(out)) + ) + fails( + 10, + ex.Execution, + "openblas", + library_path=Path(directory) / "missing.so", + ) + hmath.shutdown() + print( + "Execution reference, SGEMM/DGEMM no-copy routing, FP32 scalar/storage, padded rows, LP64/ILP64, >1M elements, >16M work, zero shapes, limits, aliases and failure-output contracts passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_expression_equivalence.py b/tools/check_expression_equivalence.py new file mode 100644 index 0000000..2b60f56 --- /dev/null +++ b/tools/check_expression_equivalence.py @@ -0,0 +1,641 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-Haskell oracle for positioned expressions and symbolic APIs.""" + +import argparse +import dataclasses +import os +import struct +import subprocess +import sys +import tempfile +from enum import IntEnum +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SOURCE = r"""{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +import qualified HMath.Expression as E +import qualified HMath.Symbolic as S +import qualified HMath.Polynomial as P +import qualified Data.Map.Strict as Map +import Data.List (intercalate,elemIndex) +import Data.Char(ord) +import Data.Ratio +import Data.Complex +import Data.Word +import GHC.Float(castDoubleToWord64) +class Enc a where enc :: a -> String +instance Enc Int where enc x="I"++show x +instance Enc Word64 where enc x="I"++show x +instance Enc Bool where enc x=if x then "B1" else "B0" +instance Enc Rational where enc x="R"++show(numerator x)++"/"++show(denominator x) +instance Enc Double where enc x="F"++show(castDoubleToWord64 x) +instance Enc (Complex Double) where enc (x:+y)="C["++enc x++","++enc y++"]" +instance {-# OVERLAPPING #-} Enc String where enc s="U["++intercalate "," (map(show.ord)s)++"]" +instance {-# OVERLAPPABLE #-} Enc a=>Enc[a] where enc xs="L["++intercalate "," (map enc xs)++"]" +instance (Enc a,Enc b)=>Enc(a,b) where enc(a,b)="T["++enc a++","++enc b++"]" +instance (Enc a,Enc b,Enc c)=>Enc(a,b,c) where enc(a,b,c)="T["++enc a++","++enc b++","++enc c++"]" +instance Enc a=>Enc(Maybe a) where enc Nothing="N";enc(Just x)=enc x +instance Enc () where enc ()="N" +instance Enc a=>Enc(Either E.ExprError a) where enc(Left x)="ERR"++enc x;enc(Right x)=enc x +instance Enc E.SourcePos where enc(E.SourcePos a b c)="Pos"++enc(a,b,c) +instance Enc E.Limits where enc l="Limits"++enc[E.maximumSteps l,E.maximumDepth l,E.maximumNodes l,E.maximumInputChars l,E.maximumIntegerBits l,E.maximumCacheEntries l] +enum name values x=name++"#"++show(case elemIndex x values of Just i->i;Nothing->error "enum") +instance Enc E.UnaryOp where enc=enum "UnaryOp" [E.Negate] +instance Enc E.BinaryOp where enc=enum "BinaryOp" [E.Add,E.Subtract,E.Multiply,E.Divide,E.Power] +instance Enc E.NamedConstant where enc=enum "NamedConstant" [E.Pi,E.Euler,E.Tau] +instance Enc E.Precision where enc=enum "Precision" [E.ExactRational,E.Float64] +instance Enc E.ErrorKind where enc=enum "ErrorKind" [E.SyntaxError,E.UnknownName,E.TypeMismatch,E.DomainFailure,E.NonFinite,E.StepLimit,E.DepthLimit,E.MemoryLimit,E.InvalidLimits,E.Unsupported] +instance Enc S.Property where enc=enum "Property" [S.Real,S.NonZero,S.Positive,S.NonNegative,S.Integral,S.Negative,S.NonPositive] +instance Enc S.Direction where enc=enum "Direction" [S.FromLeft,S.FromRight,S.TwoSided] +instance Enc S.RelationOp where enc=enum "RelationOp" [S.Equal,S.NotEqual,S.Less,S.LessEqual,S.Greater,S.GreaterEqual] +instance Enc E.ExprError where enc(E.ExprError k p m)="Error"++enc(k,p,m) +instance Enc E.Value where enc(E.ExactValue q)="Exact"++enc q;enc(E.FloatValue x)="Float"++enc x +instance Enc E.Expr where enc(E.Expr pos node)="Expr["++enc pos++","++enc node++"]" +node tag fields="Node"++show tag++"["++intercalate "," fields++"]" +instance Enc E.ExprNode where + enc n=case n of + E.Literal q->node 0[enc q] + E.Variable x->node 1[enc x] + E.Constant x->node 2[enc x] + E.Unary op x->node 3[enc op,enc x] + E.Binary op x y->node 4[enc op,enc x,enc y] + E.Call name xs->node 5[enc name,enc xs] + E.Let name x y->node 6[enc name,enc x,enc y] +instance Enc E.Registry where enc= ("Registry"++).enc.E.allowedFunctions +instance Enc E.Compiled where enc=("Compiled"++).enc.E.compiledNodeCount +instance Enc E.ExpressionCache where enc=("Cache"++).enc.E.cacheSize +instance Enc S.Pattern where + enc n=case n of + S.Any name->"Pattern0["++enc name++"]" + S.Exactly x->"Pattern1["++enc x++"]" + S.UnaryPattern op x->"Pattern2["++enc op++","++enc x++"]" + S.BinaryPattern op x y->"Pattern3["++enc op++","++enc x++","++enc y++"]" + S.CallPattern name xs->"Pattern4["++enc name++","++enc xs++"]" +instance Enc S.PolynomialFactorization where enc(S.PolynomialFactorization a b)="Factors"++enc(a,b) +instance Enc S.Series where enc(S.Series a b c)="Series"++enc(a,b,c) +instance Enc S.RewriteRule where enc(S.RewriteRule a b c)="Rule"++enc(a,b,c) +instance Enc S.Relation where enc(S.Relation a b c)="Relation"++enc(a,b,c) +instance Enc S.LimitResult where + enc(S.FiniteLimit x)="FiniteLimit"++enc[x] + enc S.PositiveInfinity="PositiveInfinityL[]" + enc S.NegativeInfinity="NegativeInfinityL[]" + enc S.DoesNotExist="DoesNotExistL[]" +instance Enc S.RelationResult where + enc(S.Truth x)="Truth"++enc[x] + enc(S.Unresolved x)="Unresolved"++enc[x] +instance Enc S.LinearSolution where + enc S.Inconsistent="InconsistentL[]" + enc(S.ParametricSolution a b)="ParametricSolutionT["++enc a++","++enc b++"]" +instance Enc a=>Enc(S.Guarded a) where enc(S.Guarded a b)="Guarded"++enc(a,b) +instance Enc S.SymbolicMatrix where enc=("Matrix"++).enc.S.matrixExpressions +instance Enc(P.Polynomial Rational) where enc=("Polynomial"++).enc.P.coefficients +instance Enc(P.PowerSeries Rational) where enc=("PowerSeries"++).enc.P.seriesCoefficients +l=E.defaultLimits +o=S.defaultSymbolicOptions +p text=either(error.show)id(E.parseExpression l text) +f=p "x^2+x" +x=E.variable "x" +y=E.variable "y" +zero=E.literal 0 +one=E.literal 1 +pat=S.BinaryPattern E.Add (S.Any "a") (S.Any "a") +rule=S.RewriteRule pat (E.binary E.Multiply (E.literal 2) (E.variable "a")) [] +m=either(error.show)id(S.symbolicMatrix o [[x,one],[zero,y]]) +jet=either(error.show)id(S.formalPowerSeries o [1,2,0,0]) +main=mapM_ putStrLn [CASES] +""" + + +def close(value): + if isinstance(value, (list, tuple)): + for item in value: + close(item) + elif dataclasses.is_dataclass(value): + for field in dataclasses.fields(value): + close(getattr(value, field.name)) + elif hasattr(value, "close"): + value.close() + + +def encode(value, e, s, poly): + def enc(x): + return encode(x, e, s, poly) + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, IntEnum): + return type(value).__name__ + "#" + str(int(value)) + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + return "F" + str(struct.unpack("=Q", struct.pack("=d", value))[0]) + if isinstance(value, complex): + return "C[" + enc(value.real) + "," + enc(value.imag) + "]" + if isinstance(value, str): + return "U[" + ",".join(str(ord(c)) for c in value) + "]" + if isinstance(value, e.SourcePos): + return "Pos" + enc((value.offset, value.line, value.column)) + if isinstance(value, e.Limits): + return "Limits" + enc( + [getattr(value, f.name) for f in dataclasses.fields(value)] + ) + if isinstance(value, e.ExprError): + return "Error" + enc((value.kind, value.position, value.message)) + if isinstance(value, e.ExactValue): + return "Exact" + enc(Fraction(value.value)) + if isinstance(value, e.FloatValue): + return "Float" + enc(float(value.value)) + if isinstance(value, e.Expr): + with value.node as node: + return "Expr[" + enc(value.position) + "," + enc(node) + "]" + if isinstance(value, (e.ExprNode, s.Pattern)): + fields = value.fields + try: + return ( + ("Node" if isinstance(value, e.ExprNode) else "Pattern") + + str(fields[0]) + + "[" + + ",".join(enc(x) for x in fields[1:]) + + "]" + ) + finally: + close(fields) + if isinstance(value, e.Registry): + return "Registry" + enc(e.allowed_functions(value)) + if isinstance(value, e.Compiled): + return "Compiled" + enc(e.compiled_node_count(value)) + if isinstance(value, e.ExpressionCache): + return "Cache" + enc(e.cache_size(value)) + if isinstance(value, s.PolynomialFactorization): + return "Factors" + enc((value.leading, value.terms)) + if isinstance(value, s.Series): + return "Series" + enc((value.center, value.minimum_power, value.terms)) + if isinstance(value, s.RewriteRule): + return "Rule" + enc((value.pattern, value.replacement, value.requirements)) + if isinstance(value, s.Relation): + return "Relation" + enc((value.operator, value.left, value.right)) + if isinstance(value, (s.LimitResult, s.RelationResult, s.LinearSolution)): + values = value.arguments + return value.name + enc( + tuple(values) if value.name == "ParametricSolution" else list(values) + ) + if isinstance(value, s.Guarded): + return "Guarded" + enc((value.value, value.conditions)) + if isinstance(value, s.SymbolicMatrix): + rows = s.matrix_expressions(value) + try: + return "Matrix" + enc(rows) + finally: + close(rows) + if isinstance(value, poly.Polynomial): + return "Polynomial" + enc(value.coefficients) + if isinstance(value, poly.PowerSeries): + return "PowerSeries" + enc(value.coefficients) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(enc(x) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +def cases(e, s): + owned = [] + + def keep(value): + owned.append(value) + return value + + l = e.default_limits() + o = s.default_symbolic_options() + owned.append(o) + reg = keep(e.default_registry()) + empty = keep(e.empty_registry()) + x = keep(e.variable("x")) + y = keep(e.variable("y")) + zero = keep(e.literal(0)) + one = keep(e.literal(1)) + + def p(text): + return keep(e.parse_expression(l, text)) + + f = p("x^2+x") + pat = keep(s.BinaryPattern(e.Add, keep(s.Any("a")), keep(s.Any("a")))) + rule = s.RewriteRule( + pat, keep(e.binary(e.Multiply, keep(e.literal(2)), keep(e.variable("a")))), [] + ) + matrix = keep(s.symbolic_matrix(o, [[x, one], [zero, y]])) + jet = keep(s.formal_power_series(o, [1, 2, 0, 0])) + rows = [] + + def add(name, hs, call): + rows.append((name, hs, call)) + + add("limits", "l", lambda: l) + add("position", "E.SourcePos (-3) 2 9", lambda: e.SourcePos(-3, 2, 9)) + add( + "raw AST", + "E.Expr (E.SourcePos 7 2 3) (E.Binary E.Add x (E.literal (2%3)))", + lambda: e.Expr( + e.SourcePos(7, 2, 3), + keep(e.Binary(e.Add, x, keep(e.literal(Fraction(2, 3))))), + ), + ) + for text in [ + "-2^2", + "let a = x+1 in a*a", + "sin(x)+pi", + "x +\n 2*y", + "1.25e-2 + 2//3", + ]: + hs = "E.parseExpression l " + repr(text).replace("'", '"').replace("\\n", "\\n") + add("parse " + text, hs, lambda text=text: e.parse_expression(l, text)) + add("pretty", "E.prettyExpression f", lambda: e.pretty_expression(f)) + add("free", "E.freeVariables f", lambda: e.free_variables(f)) + add("validate", "E.validateExpression l f", lambda: e.validate_expression(l, f)) + add( + "exact", + 'E.evaluateExpression l E.ExactRational E.defaultRegistry (Map.fromList [("x",E.ExactValue (2%3))]) f', + lambda: e.evaluate_expression( + l, e.ExactRational, reg, {"x": e.ExactValue(Fraction(2, 3))}, f + ), + ) + add( + "float", + 'E.evaluateText l E.Float64 E.defaultRegistry Map.empty "sin(pi/2)+sqrt(4)"', + lambda: e.evaluate_text(l, e.Float64, reg, {}, "sin(pi/2)+sqrt(4)"), + ) + add( + "type check", + 'E.typeCheckExpression l E.ExactRational E.defaultRegistry (Map.fromList [("x",E.ExactValue 2)]) f', + lambda: e.type_check_expression( + l, e.ExactRational, reg, {"x": e.ExactValue(2)}, f + ), + ) + add( + "registry", + 'E.registerFunction "root" E.Sqrt E.emptyRegistry', + lambda: e.register_function("root", e.Sqrt, empty), + ) + add( + "allowed", + "E.allowedFunctions E.defaultRegistry", + lambda: e.allowed_functions(reg), + ) + add("compiled", "E.compileExpression l f", lambda: e.compile_expression(l, f)) + compiled = keep(e.compile_expression(l, f)) + add( + "compiled evaluate", + 'E.compileExpression l f >>= E.evaluateCompiled l E.ExactRational E.defaultRegistry (Map.fromList [("x",E.ExactValue (2%3))])', + lambda: e.evaluate_compiled( + l, e.ExactRational, reg, {"x": e.ExactValue(Fraction(2, 3))}, compiled + ), + ) + add( + "optimize", + 'E.optimizeExpression l E.ExactRational (p "(2+3)*(x+0)")', + lambda: e.optimize_expression(l, e.ExactRational, p("(2+3)*(x+0)")), + ) + cache = keep(e.empty_expression_cache()) + add( + "cache", + 'E.cachedExpression l "x*x+x*x" E.emptyExpressionCache', + lambda: e.cached_expression(l, "x*x+x*x", cache), + ) + add( + "scientific", + "E.formatScientific 4 (E.ExactValue (2%3))", + lambda: e.format_scientific(4, e.ExactValue(Fraction(2, 3))), + ) + add( + "radix", + "E.formatRadix 16 (E.ExactValue (255%16))", + lambda: e.format_radix(16, e.ExactValue(Fraction(255, 16))), + ) + add("serialize", "E.serializeExpression l f", lambda: e.serialize_expression(l, f)) + serialized = e.serialize_expression(l, f) + add( + "deserialize", + "E.serializeExpression l f >>= E.deserializeExpression l", + lambda: e.deserialize_expression(l, serialized), + ) + add("hash", "E.expressionHash l f", lambda: e.expression_hash(l, f)) + for name in [ + "normalize", + "simplify", + "expand", + "collectTerms", + "trigonometricSimplify", + "logarithmicSimplify", + ]: + py = { + "collectTerms": "collect_terms", + "trigonometricSimplify": "trigonometric_simplify", + "logarithmicSimplify": "logarithmic_simplify", + }.get(name, name) + add( + name, + "S." + name + ' o (p "(x+1)*(x-1)")', + lambda py=py: getattr(s, py)(o, p("(x+1)*(x-1)")), + ) + add( + "factor", + 'S.factorPolynomial o "x" (p "x^2-1")', + lambda: s.factor_polynomial(o, "x", p("x^2-1")), + ) + add( + "rational simplify", + 'S.rationalSimplify o "x" (p "(x^2-1)/(x-1)")', + lambda: s.rational_simplify(o, "x", p("(x^2-1)/(x-1)")), + ) + add( + "substitute", + 'S.substitute l [("x",y)] (p "let y = 2 in x+y")', + lambda: s.substitute(l, [("x", y)], p("let y = 2 in x+y")), + ) + add( + "prove", + "S.proves S.noAssumptions S.Positive (E.literal 2)", + lambda: s.proves(o.assumptions, s.Positive, keep(e.literal(2))), + ) + add( + "match", + 'S.matchPattern l pat (p "x+x")', + lambda: s.match_pattern(l, pat, p("x+x")), + ) + add( + "rewrite", + 'S.applyRewrite o rule (p "x+x")', + lambda: s.apply_rewrite(o, rule, p("x+x")), + ) + add("derivative", 'S.differentiate o "x" f', lambda: s.differentiate(o, "x", f)) + add( + "gradient", + 'S.gradient o ["x","y"] (p "x^2+x*y")', + lambda: s.gradient(o, ["x", "y"], p("x^2+x*y")), + ) + add( + "jacobian", + 'S.jacobian o ["x","y"] [p "x*y",p "x+y"]', + lambda: s.jacobian(o, ["x", "y"], [p("x*y"), p("x+y")]), + ) + add( + "hessian", + 'S.hessian o ["x","y"] (p "x^2+x*y")', + lambda: s.hessian(o, ["x", "y"], p("x^2+x*y")), + ) + add( + "integrate basic", + 'S.integrateBasic o "x" f', + lambda: s.integrate_basic(o, "x", f), + ) + add( + "by parts", + 'S.integrateByParts o "x" x (p "exp(x)")', + lambda: s.integrate_by_parts(o, "x", x, p("exp(x)")), + ) + add( + "substitution integral", + 'S.integrateSubstitution o "x" "t" (p "x^2") (p "exp(t)") (p "2*x*exp(x^2)")', + lambda: s.integrate_substitution( + o, "x", "t", p("x^2"), p("exp(t)"), p("2*x*exp(x^2)") + ), + ) + add( + "rational integral", + 'S.integrateRational o "x" one (p "x^2+1")', + lambda: s.integrate_rational(o, "x", one, p("x^2+1")), + ) + for name, source in [("Finite", "(x^2-1)/(x-1)"), ("Pole", "1/x")]: + center = 1 if name == "Finite" else 0 + for hs, direction in [ + ("FromLeft", s.FromLeft), + ("FromRight", s.FromRight), + ("TwoSided", s.TwoSided), + ]: + add( + "limit " + name + hs, + 'S.symbolicLimit o "x" ' + + str(center) + + " S." + + hs + + ' (p "' + + source + + '")', + lambda source=source, center=center, direction=direction: ( + s.symbolic_limit(o, "x", Fraction(center), direction, p(source)) + ), + ) + for name, py in [ + ("taylorSeries", "taylor_series"), + ("laurentSeries", "laurent_series"), + ]: + text = "1/(1-x)" if name == "taylorSeries" else "1/(x^2*(1-x))" + add( + name, + "S." + name + ' o "x" 0 3 (p "' + text + '")', + lambda py=py, text=text: getattr(s, py)(o, "x", Fraction(0), 3, p(text)), + ) + add( + "maclaurin", + 'S.maclaurinSeries o "x" 3 (p "exp(x)")', + lambda: s.maclaurin_series(o, "x", 3, p("exp(x)")), + ) + add( + "formal series", + "S.formalPowerSeries o [1,2,0,0]", + lambda: s.formal_power_series(o, [1, 2, 0, 0]), + ) + add( + "formal multiply", + "S.multiplyFormalSeries o jet jet", + lambda: s.multiply_formal_series(o, jet, jet), + ) + add( + "formal reciprocal", + "S.reciprocalFormalSeries o jet", + lambda: s.reciprocal_formal_series(o, jet), + ) + add("polynomial", 'S.toPolynomial o "x" f', lambda: s.to_polynomial(o, "x", f)) + polynomial = keep(s.to_polynomial(o, "x", f)) + add( + "from polynomial", + 'S.fromPolynomial "x" (P.polynomial [0,1,1])', + lambda: s.from_polynomial("x", polynomial), + ) + add( + "exact roots", + 'S.exactPolynomialRoots o "x" (p "(x-1)^2*(x+2)")', + lambda: s.exact_polynomial_roots(o, "x", p("(x-1)^2*(x+2)")), + ) + add( + "numeric roots", + 'S.numericalPolynomialRoots o "x" (p "x^2-1")', + lambda: s.numerical_polynomial_roots(o, "x", p("x^2-1")), + ) + add( + "relation", + "S.simplifyRelation o (S.Relation S.Less one (E.literal 2))", + lambda: s.simplify_relation(o, s.Relation(s.Less, one, keep(e.literal(2)))), + ) + add( + "inequality", + 'S.solveLinearInequality o "x" (S.Relation S.Less (p "-2*x+3") one)', + lambda: s.solve_linear_inequality(o, "x", s.Relation(s.Less, p("-2*x+3"), one)), + ) + add( + "linear system", + 'S.solveLinearEquations o ["x","y"] [(x,E.literal 2)]', + lambda: s.solve_linear_equations(o, ["x", "y"], [(x, keep(e.literal(2)))]), + ) + add( + "matrix", + "S.symbolicMatrix o [[x,one],[zero,y]]", + lambda: s.symbolic_matrix(o, [[x, one], [zero, y]]), + ) + add("matrix rows", "S.matrixExpressions m", lambda: s.matrix_expressions(matrix)) + add("matrix add", "S.matrixAdd o m m", lambda: s.matrix_add(o, matrix, matrix)) + add( + "matrix multiply", + "S.matrixMultiply o m m", + lambda: s.matrix_multiply(o, matrix, matrix), + ) + add( + "determinant", + "S.symbolicDeterminant o m", + lambda: s.symbolic_determinant(o, matrix), + ) + add( + "eigenvalues", + "S.symbolicEigenvalues o m", + lambda: s.symbolic_eigenvalues(o, matrix), + ) + add( + "numerical substitute", + 'S.numericalSubstitution o E.ExactRational [("x",E.ExactValue (2%3))] f', + lambda: s.numerical_substitution( + o, e.ExactRational, [("x", e.ExactValue(Fraction(2, 3)))], f + ), + ) + add("latex", "S.toLaTeX l f", lambda: s.to_la_te_x(l, f)) + add("mathml", "S.toMathML l f", lambda: s.to_math_ml(l, f)) + errors = [ + ("syntax", 'E.parseExpression l ")"', lambda: e.parse_expression(l, ")")), + ( + "unknown", + 'E.evaluateText l E.ExactRational E.defaultRegistry Map.empty "λ"', + lambda: e.evaluate_text(l, e.ExactRational, reg, {}, "λ"), + ), + ( + "type", + 'E.evaluateText l E.ExactRational E.defaultRegistry Map.empty "sin(1)"', + lambda: e.evaluate_text(l, e.ExactRational, reg, {}, "sin(1)"), + ), + ( + "domain", + 'E.evaluateText l E.ExactRational E.defaultRegistry Map.empty "1/0"', + lambda: e.evaluate_text(l, e.ExactRational, reg, {}, "1/0"), + ), + ( + "step", + 'E.parseExpression (l{E.maximumSteps=1}) "1"', + lambda: e.parse_expression(dataclasses.replace(l, maximum_steps=1), "1"), + ), + ( + "depth", + 'E.parseExpression (l{E.maximumDepth=1}) "1"', + lambda: e.parse_expression(dataclasses.replace(l, maximum_depth=1), "1"), + ), + ( + "memory", + 'E.parseExpression (l{E.maximumInputChars=1}) "12"', + lambda: e.parse_expression( + dataclasses.replace(l, maximum_input_chars=1), "12" + ), + ), + ( + "invalid", + "E.validateLimits (l{E.maximumSteps=0})", + lambda: e.validate_limits(dataclasses.replace(l, maximum_steps=0)), + ), + ( + "unsupported", + 'S.integrateBasic o "x" (p "exp(x^2)")', + lambda: s.integrate_basic(o, "x", p("exp(x^2)")), + ), + ] + for name, hs, call in errors: + add("error " + name, hs, call) + return rows, owned + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import expression as e + from _hmath_native import polynomial as poly + from _hmath_native import symbolic as s + + selected, owned = cases(e, s) + try: + with tempfile.TemporaryDirectory( + prefix="hmath-expression-oracle-" + ) as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text( + SOURCE.replace( + "CASES", ",".join("enc (" + hs + ")" for _, hs, _ in selected) + ) + ) + subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-i" + str(ROOT / "src"), + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + for (name, _, call), reference in zip(selected, expected, strict=True): + output = None + try: + output = call() + actual = encode(output, e, s, poly) + except hmath.HMathError as error: + if error.expression_error is None: + raise + actual = "ERR" + encode(error.expression_error, e, s, poly) + finally: + close(output) + if actual != reference: + raise AssertionError(f"{name}: binding {actual}, original {reference}") + print( + f"Expression/Symbolic equivalence: {len(selected)} independent original Haskell operation sequences match exact ASTs/positions, rational data, binary64 bits, conditions and errors." + ) + finally: + close(owned) + + +if __name__ == "__main__": + main() diff --git a/tools/check_foundation_equivalence.py b/tools/check_foundation_equivalence.py new file mode 100644 index 0000000..c15c499 --- /dev/null +++ b/tools/check_foundation_equivalence.py @@ -0,0 +1,572 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-source oracle for persistent/discrete/convergence APIs.""" + +import argparse +import importlib +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_foundation_bindings import MODULES, pyname, specification + +ROOT = Path(__file__).resolve().parent.parent + + +def normalized(value, modules): + import hmath + from _hmath_native._foundation_base import FoundationValue + + if isinstance(value, FoundationValue): + d, s = modules["HMath.DataStructure"], modules["HMath.Discrete"] + name = value.source_type.rsplit(".", 1)[-1] + if name == "Fenwick": + observation = d.fenwick_prefix(2, value) + elif name == "SegmentTree": + observation = d.segment_range(0, 2, value) + elif name == "SparseTable": + observation = d.sparse_minimum(0, 2, value) + elif name == "DisjointSparseTable": + observation = d.disjoint_range(0, 2, value) + elif name in ("Heap", "BinaryHeap", "IndexedHeap"): + pop = { + "Heap": d.heap_pop, + "BinaryHeap": d.binary_pop, + "IndexedHeap": d.indexed_pop, + }[name] + observation = [] + current = value.clone() + try: + while True: + result = pop(current) + current.close() + current = None + if result is None: + break + item, current = result + observation.append(item) + finally: + close(current) + elif name == "UnionFind": + observation = d.components(value) + elif name == "Bloom": + observation = ( + [d.bloom_member(x, value) for x in [0, 1, 7, 42]], + d.bloom_false_positive_bound(value), + ) + elif name == "CountMin": + observation = ( + [d.count_min_estimate(x, value) for x in [0, 1, 7, 42]], + d.count_min_error_bound(value), + ) + elif name == "HyperLogLog": + observation = d.hll_estimate(value) + elif name == "Reservoir": + observation = d.reservoir_values(value) + elif name == "OnlineQuantiles": + try: + observation = d.online_quantile(0.5, value) + except hmath.HMathError as error: + return "O" + name + "(E" + str(error.math_error) + ")" + elif name == "MultiSet": + observation = s.multiset_entries(value) + elif name == "BitSet": + observation = (s.bit_width(value), s.bit_value(value)) + else: + observation = value.parts + try: + return "O" + name + "(" + normalized(observation, modules) + ")" + finally: + close(observation) + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + return "F64:" + str(bits(value, 64)) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(c)) for c in value) + "]" + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(normalized(x, modules) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +class Fixtures: + def __init__(self, modules): + self.modules = modules + self.owned = [] + + def own(self, value, expression): + if hasattr(value, "close"): + self.owned.append(value) + return value, expression + + def object(self, name): + d = self.modules["HMath.DataStructure"] + s = self.modules["HMath.Discrete"] + v = self.modules["HMath.API.Convergence"] + if name == "Fenwick": + return self.own(d.fenwick([1, 2, 3]), "right(D.fenwick [1,2,3])") + if name == "SegmentTree": + return self.own(d.segment_tree([1, 2, 3]), "right(D.segmentTree [1,2,3])") + if name == "SparseTable": + return self.own(d.sparse_table([1, 2, 3]), "right(D.sparseTable [1,2,3])") + if name == "DisjointSparseTable": + return self.own( + d.disjoint_sparse_table([1, 2, 3]), + "right(D.disjointSparseTable [1,2,3])", + ) + if name == "Heap": + return self.own( + d.heap_from_list([1, 2, 3]), "(D.heapFromList [1,2,3]::D.Heap Integer)" + ) + if name == "BinaryHeap": + return self.own(d.binary_heap([1, 2, 3]), "right(D.binaryHeap [1,2,3])") + if name == "IndexedHeap": + heap, _ = self.own(d.indexed_heap(), "D.indexedHeap") + return self.own( + d.indexed_set(2, 10, heap), "D.indexedSet 2 10 D.indexedHeap" + ) + if name == "UnionFind": + return self.own(d.union_find(3), "right(D.unionFind 3)") + if name == "Bloom": + return self.own(d.bloom(32, 3), "right(D.bloom 32 3)") + if name == "CountMin": + return self.own(d.count_min(16, 3), "right(D.countMin 16 3)") + if name == "HyperLogLog": + return self.own(d.hyper_log_log(4), "right(D.hyperLogLog 4)") + if name == "Reservoir": + return self.own( + d.reservoir(3, 42), "(right(D.reservoir 3 42)::D.Reservoir Integer)" + ) + if name == "OnlineQuantiles": + return self.own(d.online_quantiles(8), "right(D.onlineQuantiles 8)") + if name == "MultiSet": + return self.own( + s.multiset([1, 2, 2]), "(S.multiset [1,2,2]::S.MultiSet Integer)" + ) + if name == "BitSet": + return self.own(s.bit_set(8, 5), "right(S.bitSet 8 5)") + if name == "Prop": + return self.own(s.variable(0), "S.Variable 0") + if name == "Implicant": + return self.own(s.Implicant(1, 2), "S.Implicant 1 2") + if name == "StopReason": + return self.own(v.residual_satisfied(), "V.ResidualSatisfied") + if name == "IterationOptions": + return self.own(v.IterationOptions(5, 0.0, 0.0), "V.IterationOptions 5 0 0") + if name == "Convergence": + reason, _hs = self.object("StopReason") + return self.own( + v.Convergence(7, 1, 0.0, reason), + "(V.Convergence 7 1 0 V.ResidualSatisfied::V.Convergence Integer)", + ) + raise ValueError(name) + + def argument(self, spec, name, index): + head, *args = spec + if head in TYPES: + return self.object(head) + if head == "a": + return 2, "(2::Integer)" + if head == "e": + return "missing", '"missing"' + if head == "Int": + value = 1 + if name in ("permutationsOf", "combinationsOf"): + value = 100 if index == 0 else 2 + elif name in ("derangements", "integerPartitions", "setPartitions"): + value = 100 if index == 0 else 3 + elif name in ("subsets", "cartesianProduct", "multisetPermutations"): + value = 100 + elif name in ("runLengthDecode", "memoizedDP"): + value = 100 if index == 0 else 3 + elif name in ("truthTable",): + value = 2 + elif name == "quineMcCluskey": + value = 20 if index == 0 else 2 + elif name in ("bloom", "countMin"): + value = 16 if index == 0 else 3 + elif name in ("hyperLogLog",) or name in ( + "onlineQuantiles", + "unionFind", + "pascalTriangle", + "tabulateDP", + "ternarySearch", + ): + value = 4 + elif name in ( + "fenwickRange", + "segmentRange", + "sparseMinimum", + "disjointRange", + ): + value = 0 if index == 0 else 2 + elif name in ("union", "connected"): + value = index + elif name == "IterationOptions": + value = 5 + return value, str(value) + if head == "Integer": + return (2, "2") + if head == "Word64": + return (42, "42") + if head == "Double": + value = 0.5 + if name == "ternarySearch": + value = 0.0 if index == 2 else 2.0 + return value, str(value) + if head == "Rational": + return Fraction(1, 2), "(1%2)" + if head == "Bool": + return True, "True" + if head == "String": + return "operation", '"operation"' + if head == "Maybe": + return 2, "Just(2::Integer)" + if head == "Either": + c = self.modules["HMath.API.Convergence"] + return self.own(c.right(2), "(Right 2::Either String Integer)") + if head == "list": + if args[0] == ["a"]: + return [1, 2, 3], "([1,2,3]::[Integer])" + if args[0] == ["Integer"]: + return [1, 2, 3], "[1,2,3]" + if args[0] == ["Double"]: + return [0.0, 1.0, 2.0], "[0,1,2]" + if args[0] == ["Bool"]: + return [True, False], "[True,False]" + if args[0] == ["Rational"]: + return [Fraction(1), Fraction(1)], [1, 1].__str__() + if args[0] == ["list", ["Bool"]]: + return [[True, False], [False, True]], "[[True,False],[False,True]]" + item, hs = self.argument(args[0], name, index) + return [item], "[" + hs + "]" + if head == "tuple": + values = [] + expressions = [] + for i, child in enumerate(args): + value, hs = self.argument(child, name, i) + values.append(value) + expressions.append(hs) + return tuple(values), "(" + ",".join(expressions) + ")" + if head == "function": + if name == "ternarySearch": + return lambda x: (x - 1.0) ** 2, "(\\x -> (x-1)*(x-1))" + if name == "divideConquerDP": + return lambda i, j: float(i + j), "(\\i j -> fromIntegral(i+j))" + if name == "tabulateDP": + return lambda i: [], "(const [])" + if name == "memoizedDP": + return lambda i: (i, []), "(\\i -> (toInteger i,[]))" + if name == "iterateUntil": + if index == 1: + return lambda x: x + 1, "(Right . (+1))" + if index == 2: + return lambda x: float( + max(0, 4 - x) + ), "(\\x -> Right(fromInteger(max 0 (4-x))))" + return lambda a, b: a == b, "(==)" + raise ValueError((spec, name, index)) + + +def hs_type(spec): + head, *args = spec + if head == "a": + return "Integer" + if head == "e": + return "String" + if head == "MathError": + return "HMath.Error.MathError" + if head == "list": + return "[" + hs_type(args[0]) + "]" + if head == "tuple": + return "(" + ",".join(hs_type(s) for s in args) + ")" + if head in TYPES: + head = TYPES[head]["alias"] + "." + head + return "(" + head + (" " + " ".join(hs_type(s) for s in args) if args else "") + ")" + + +def instances(entries, types): + out = [ + 'instance E Char where enc c="I"++show(ord c)\ninstance E Word64 where enc x="I"++show x\ninstance E () where enc ()="N"\ninstance(E a,E b,E c,E d)=>E(a,b,c,d)where enc(a,b,c,d)="T["++intercalate ","[enc a,enc b,enc c,enc d]++"]"\ninstance(E a,E b)=>E(Either a b)where enc(Left e)="OEither("++enc("Left",e)++")";enc(Right x)="OEither("++enc("Right",x)++")"\nright=either(error.show)id\ndrain pop value=case pop value of Nothing->[];Just(x,next)->x:drain pop next\n' + ] + observations = { + "Fenwick": "enc(right(D.fenwickPrefix 2 value))", + "SegmentTree": "enc(right(D.segmentRange 0 2 value))", + "SparseTable": "enc(right(D.sparseMinimum 0 2 value))", + "DisjointSparseTable": "enc(right(D.disjointRange 0 2 value))", + "Heap": "enc(drain D.heapPop value)", + "BinaryHeap": "enc(drain D.binaryPop value)", + "IndexedHeap": "enc(drain D.indexedPop value)", + "UnionFind": "enc(D.components value)", + "Bloom": "enc(map(\\x -> D.bloomMember x value)[0,1,7,42],D.bloomFalsePositiveBound value)", + "CountMin": "enc(map(\\x -> D.countMinEstimate x value)[0,1,7,42],D.countMinErrorBound value)", + "HyperLogLog": "enc(D.hllEstimate value)", + "Reservoir": "enc(D.reservoirValues value)", + "OnlineQuantiles": "ok(D.onlineQuantile 0.5 value)", + "MultiSet": "enc(S.multisetEntries value)", + "BitSet": "enc(S.bitWidth value,S.bitValue value)", + } + for name, t in types.items(): + params = t["params"] + constraints = "" + if params: + constraints = ( + "(" + + ",".join( + ("Ord " + p if name in ("Heap", "MultiSet") else "E " + p) + for p in params + ) + + ",E " + + params[0] + + ") => " + ) + out.append( + "instance " + + constraints + + "E(" + + t["alias"] + + "." + + name + + (" " + " ".join(params) if params else "") + + ')where\n enc value="O' + + name + + '("++(' + ) + if name in observations: + expr = observations[name] + else: + variants = [] + for e in entries: + if not e["constructor"] or e["result"][0] != name: + continue + vs = ["p" + str(i) for i in range(len(e["args"]))] + variants.append( + t["alias"] + + "." + + e["name"] + + " " + + " ".join(vs) + + ' -> "T["++enc("' + + e["name"] + + '")++",T["++intercalate ","[' + + ",".join("enc " + v for v in vs) + + ']++"]]"' + ) + expr = "case value of {" + ";".join(variants) + "}" + out.append(expr + ')++")"\n') + return "".join(out) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import algebra_api, autodiff, polynomial, tensor + + entries, types, _ = specification() + global TYPES + TYPES = types + modules = { + m: importlib.import_module("_hmath_native." + ns) + for m, (_alias, ns, _public) in MODULES.items() + } + tests = [] + expressions = [] + owners = [] + for e in entries: + fixture = Fixtures(modules) + values = [] + hsargs = [] + for index, spec in enumerate(e["args"]): + value, hs = fixture.argument(spec, e["name"], index) + values.append(value) + hsargs.append(hs) + operation = MODULES[e["module"]][0] + "." + e["name"] + expression = ( + "(" + + operation + + " " + + " ".join("(" + h + ")" for h in hsargs) + + "::" + + hs_type(e["result"]) + + ")" + ) + if e["name"] == "Converged": + expression = ( + "(case " + hsargs[0] + " of V.Converged x -> Just x;_ -> Nothing)" + ) + checked = e["result"][:2] == ["Either", ["MathError"]] + expressions.append( + "putStrLn(" + ("ok" if checked else "enc") + " " + expression + ")" + ) + tests.append( + ( + getattr(modules[e["module"]], pyname(e, types)), + values, + e["module"] + "." + e["name"], + ) + ) + owners += fixture.owned + + def owned(value): + owners.append(value) + return value + + def counts(values): + result = modules["HMath.Algorithms"].run_length_encode(values) + try: + return [count for _, count in result] + finally: + close(result) + + p = owned(polynomial.polynomial([1, 0], dtype="rational")) + q = owned(polynomial.polynomial([2], dtype="rational")) + series = owned(polynomial.power_series([1, 0], dtype="rational")) + short_series = owned(polynomial.power_series([1], dtype="rational")) + numerator = owned(polynomial.polynomial([1], dtype="rational")) + denominator = owned(polynomial.polynomial([1, 1], dtype="rational")) + rf = owned(polynomial.rational_function(numerator, denominator)) + exact = owned(algebra_api.Exact(Fraction(1, 3))) + equality_cases = [ + ( + "Polynomial", + [p, p, q], + "[P.polynomial [1,0],P.polynomial [1,0],P.polynomial [2]]::[P.Polynomial Rational]", + ), + ( + "PowerSeries", + [series, series, short_series], + "[P.powerSeries [1,0],P.powerSeries [1,0],P.powerSeries [1]]::[P.PowerSeries Rational]", + ), + ( + "RationalFunction", + [rf, rf], + "[right(P.rationalFunction(P.polynomial[1])(P.polynomial[1,1])),right(P.rationalFunction(P.polynomial[1])(P.polynomial[1,1]))]", + ), + ] + for dtype, values, hs_values, hstype in [ + ("integer", [1, 2], "[1,2]", "Integer"), + ("bool", [True, False], "[True,False]", "Bool"), + ("string", ["α\0", "β"], '["α\\NUL","β"]', "String"), + (exact, [exact, exact], "[API.Exact(1%3),API.Exact(1%3)]", "API.Exact"), + ]: + matrix = owned(algebra_api.matrix_construct(1, 2, values, dtype=dtype)) + equality_cases.append( + ( + "Matrix-" + hstype, + [matrix, matrix], + "let x=right(M.fromListChecked 1 2 (" + + hs_values + + "::[" + + hstype + + "])) in [x,x]", + ) + ) + value = owned(algebra_api.tensor_construct([2], values, dtype=dtype)) + equality_cases.append( + ( + "Tensor-" + hstype, + [value, value], + "let x=right(T.tensor[2](" + + hs_values + + "::[" + + hstype + + "])) in [x,x]", + ) + ) + nan = owned(tensor.tensor([1], [float("nan")])) + equality_cases.append( + ("Tensor-NaN", [nan, nan], "let x=right(T.tensor[1][0/0::Double]) in [x,x]") + ) + value = owned(tensor.tensor([2, 2], [1.0, 1.0, 1.0, 1.0])) + view = owned(tensor.transpose_tensor(value)) + equality_cases.append( + ( + "Tensor-logical-view", + [value, view], + "let x=right(T.tensor[2,2][1,1,1,1::Double]);y=right(T.transposeTensor x) in [x,y]", + ) + ) + dual = owned(autodiff.Dual(1 + 2j, 3 + 4j, dtype="complex128")) + different = owned(autodiff.Dual(1 + 2j, 5 + 6j, dtype="complex128")) + equality_cases.append( + ( + "AD-Dual-Complex-full-Eq", + [dual, dual, different], + "[AD.Dual(1:+2)(3:+4),AD.Dual(1:+2)(3:+4),AD.Dual(1:+2)(5:+6)]::[AD.Dual(Complex Double)]", + ) + ) + for name, values, expression in equality_cases: + tests.append((counts, [values], "original Eq " + name)) + expressions.append( + "putStrLn(enc(map snd(A.runLengthEncode(" + expression + "))))" + ) + imports = ( + "\n".join( + "import qualified " + m + " as " + a for m, (a, *_) in MODULES.items() + ) + + "\nimport Data.Char(ord)\nimport Data.Word(Word64)\nimport qualified HMath.Tensor as T\nimport qualified HMath.API.Algebra as API\nimport qualified HMath.Autodiff as AD\n" + ) + source = HASKELL.split("pR=")[0].replace( + "import qualified HMath.Polynomial as P", + imports + "\nimport qualified HMath.Polynomial as P", + ) + source = ( + "{-# LANGUAGE PatternSynonyms #-}\n" + + source + + instances(entries, types) + + "main=do\n " + + "\n ".join(expressions) + + "\n" + ) + with tempfile.TemporaryDirectory() as directory: + oracle = Path(directory) / "Oracle.hs" + oracle.write_text(source) + result = subprocess.run( + ["runghc", "-isrc", str(oracle)], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + if result.returncode: + raise SystemExit(result.stderr) + lines = result.stdout.splitlines() + if len(lines) != len(tests): + raise AssertionError((len(lines), len(tests))) + try: + for (function, values, name), expected in zip(tests, lines): + try: + value = function(*values) + actual = normalized(value, modules) + close(value) + except hmath.HMathError as error: + actual = "E" + str(error.math_error) + if actual != expected: + raise AssertionError((name, actual, expected)) + finally: + for owner in owners: + owner.close() + print( + f"Foundation direct Haskell equivalence: {len(tests)} operations/constructors;148 source symbols" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_geometry_equivalence.py b/tools/check_geometry_equivalence.py new file mode 100644 index 0000000..c139c14 --- /dev/null +++ b/tools/check_geometry_equivalence.py @@ -0,0 +1,513 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare every concrete Geometry function with independent original Haskell calls.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_geometry_bindings import TYPES, entries, public_name, result_type +from generate_graph_bindings import split_top + +ROOT = Path(__file__).resolve().parent.parent + + +def fp(value): + return ( + "nan" + if math.isnan(value) + else str(struct.unpack("!Q", struct.pack("!d", value))[0]) + ) + + +def hsencode(typ): + if typ in TYPES: + return "(show :: G." + typ + " -> String)" + if typ == "IndexedTriangle": + return hsencode("(Int,Int,Int)") + if typ == "Matrix Double": + return "matrix" + if typ == "Ordering": + return "(\\x -> show (case x of LT -> (-1::Int);EQ -> 0;GT -> 1))" + if typ == "Double": + return "fp" + if typ in ("Int", "Bool"): + return "show" + if typ.startswith("Maybe (Maybe "): + inner = typ[len("Maybe (Maybe ") : -1] + return ( + '(\\x -> case x of Nothing -> "N0";Just Nothing -> "N1";Just (Just y) -> "N2("++' + + hsencode(inner) + + ' y++")")' + ) + if typ.startswith("Maybe "): + return ( + '(maybe "Nothing" (\\x -> "Just("++' + + hsencode(typ[6:].strip()) + + ' x++")"))' + ) + if typ.startswith("["): + return "(list " + hsencode(typ[1:-1]) + ")" + if typ.startswith("("): + parts = split_top(typ[1:-1], ",") + variables = ["v" + str(k) for k in range(len(parts))] + if len(parts) == 1: + return hsencode(parts[0]) + return ( + "(\\(" + + ",".join(variables) + + ') -> "("++intercalate ";" [' + + ",".join(hsencode(t) + " " + v for t, v in zip(parts, variables)) + + ']++")")' + ) + raise AssertionError(typ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import geometry as g + from _hmath_native import matrix as m + from _hmath_native._value import Value + + owners = [] + + def own(x): + owners.append(x) + return x + + p2 = [own(g.p2(*p)) for p in [(0, 0), (2, 0), (0, 2), (0.5, 0.5), (1, -1), (1, 1)]] + p3 = [ + own(g.p3(*p)) + for p in [ + (0, 0, 0), + (1, 0, 0), + (0, 1, 0), + (0, 0, 1), + (0.25, 0.5, 0.25), + (0, 0, 2), + (0, 0, -2), + (1, 1, 1), + ] + ] + nd = [ + own(g.point_nd_raw(p)) + for p in [ + [0, 0, 0], + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0.25, 0.5, 0.25], + [1, 1, 1], + [-1, -1, -1], + ] + ] + bad2 = own(g.p2(math.nan, 0)) + bad3 = own(g.p3(math.nan, 0, 0)) + badnd = own(g.point_nd_raw([math.nan])) + line = own(g.line(nd[0], nd[3])) + parallel = own(g.line(nd[3], nd[1])) + coincident = own(g.line(nd[0], nd[1])) + segment = own(g.segment(nd[0], nd[5])) + plane = own(g.plane(p3[3], 0)) + plane_x = own(g.plane(p3[1], 0)) + plane_shift = own(g.plane(p3[3], 1)) + triangle = own(g.triangle(p2[0], p2[1], p2[2])) + triangle_b = own(g.triangle(p2[3], p2[1], p2[2])) + rectangle = own(g.rectangle(g.p2(-1, -1), g.p2(3, 3))) + circle = own(g.circle(p2[0], 1)) + circle_b = own(g.circle(g.p2(1, 0), 1)) + ellipse = own(g.ellipse(p2[0], 2, 1, 0.3)) + polygon = own(g.polygon(p2[:3])) + polygon_b = own(g.polygon([p2[3], p2[1], p2[2]])) + sphere = own(g.sphere(p3[0], 1)) + box = own(g.aabb(nd[6], nd[5])) + obb = own(g.obb(p3[0], p3[1:4], p3[7])) + capsule = own(g.capsule(p3[0], p3[5], 1)) + cylinder = own(g.cylinder(p3[0], p3[5], 1)) + cone = own(g.cone(p3[0], p3[5], 1)) + ray = own(g.ray(p3[6], p3[3])) + identity = own(m.identity_checked(4)) + linear = own(m.identity_checked(3)) + wrong_matrix = own(m.from_list_checked(2, 3, [1, 0, 0, 0, 1, 0])) + frustum = own(g.extract_frustum(identity)) + cloud = own(g.point_cloud(nd[:6])) + index = own(g.build_spatial_index(g.kd_tree(), cloud)) + neighbor = own(g.neighbor_query([(0, 0.5), (1, 0.25)], 2, True)) + penetration = own(g.penetration(0.25, p2[3], 0.5, 2)) + kd = own(g.kd_tree()) + badkind = own(g.spatial_hash(math.nan)) + metric = own(g.euclidean()) + badmetric = own(g.minkowski(-1)) + hull = own(g.monotone_chain()) + operation = own(g.intersection()) + fixed = { + "Line": (line, "lineA"), + "Ray": (ray, "rayA"), + "Segment": (segment, "segmentA"), + "Plane": (plane, "planeA"), + "Triangle": (triangle, "triangleA"), + "Rectangle": (rectangle, "rectangleA"), + "Circle": (circle, "circleA"), + "Ellipse": (ellipse, "ellipseA"), + "Polygon": (polygon, "polygonA"), + "Sphere": (sphere, "sphereA"), + "AABB": (box, "boxA"), + "OBB": (obb, "obbA"), + "Capsule": (capsule, "capsuleA"), + "Cylinder": (cylinder, "cylinderA"), + "Cone": (cone, "coneA"), + "Frustum": (frustum, "frustumA"), + "PointCloud": (cloud, "cloudA"), + "SpatialIndex": (index, "indexA"), + "NeighborQuery": (neighbor, "neighborA"), + "Penetration": (penetration, "penetrationA"), + "HullAlgorithm": (hull, "G.MonotoneChain"), + "BooleanOperation": (operation, "G.Intersection"), + } + + def encode(typ, value): + if typ in TYPES: + return g.describe(value) + if typ == "IndexedTriangle": + return encode("(Int,Int,Int)", value) + if typ == "Matrix Double": + return ( + str(value.shape[0]) + + "," + + str(value.shape[1]) + + ":" + + encode("[Double]", value.to_list()) + ) + if typ == "Double": + return fp(value) + if typ == "Ordering": + return str(int(value)) + if typ in ("Int", "Bool"): + return str(value) + if typ.startswith("Maybe (Maybe "): + inner = typ[len("Maybe (Maybe ") : -1] + return ( + "N0" + if not value[0] + else "N1" + if value[1] is None + else "N2(" + encode(inner, value[1]) + ")" + ) + if typ.startswith("Maybe "): + return ( + "Nothing" + if value is None + else "Just(" + encode(typ[6:].strip(), value) + ")" + ) + if typ.startswith("["): + return "[" + ",".join(encode(typ[1:-1], x) for x in value) + "]" + if typ.startswith("("): + fields = split_top(typ[1:-1], ",") + return ( + encode(fields[0], value) + if len(fields) == 1 + else "(" + ";".join(encode(t, x) for t, x in zip(fields, value)) + ")" + ) + raise AssertionError(typ) + + def fixture(entry, typ, k, bad): + name = entry["name"] + if typ == "Point2": + if bad: + return bad2, "bad2" + if name in ("lineIntersection", "segmentIntersection"): + j = [0, 1, 4, 5][k] + elif name in ("triangleLocation", "polygonLocation", "ellipseContains"): + j = 3 + else: + j = min(k, 3) + return p2[j], "p2" + str(j) + if typ == "Point3": + if bad: + return bad3, "bad3" + j = ( + [6, 0, 2][k] + if name == "lookAt" + else 4 + if name + in ( + "sphereSDF", + "capsuleSDF", + "cylinderSDF", + "coneSDF", + "obbSDF", + "pointPlaneDistance", + "sphereContains", + ) + else k % 4 + ) + return p3[j], "p3" + str(j) + if typ == "PointND": + return (badnd, "badnd") if bad else (nd[4 + k % 2], "nd" + str(4 + k % 2)) + if typ == "SpatialKind": + return (badkind, "G.SpatialHash (0/0)") if bad else (kd, "G.KDTree") + if typ == "Metric": + return (badmetric, "G.Minkowski (-1)") if bad else (metric, "G.Euclidean") + if typ in fixed: + if k > 0 and typ in ("Plane", "Triangle", "Polygon", "Circle"): + return { + "Plane": (plane_x, "planeX"), + "Triangle": (triangle_b, "triangleB"), + "Polygon": (polygon_b, "polygonB"), + "Circle": (circle_b, "circleB"), + }[typ] + return fixed[typ] + if typ == "Matrix Double": + return ( + (wrong_matrix, "wrongMatrix") + if bad + else (linear, "linearA") + if name == "affineTransform" + else (identity, "identityA") + ) + if typ == "Int": + value = -1 if bad else (30 if name in ("gjk", "epa", "nearestQuery") else 2) + return value, "(" + str(value) + ")" + if typ == "Bool": + return not bad, "False" if bad else "True" + if typ == "Double": + if bad: + return math.inf, "(1/0)" + value = ( + [-1, 1, -1, 1, 1, 10][k] + if name == "orthographic" + else [1, 1, 1, 10][k] + if name == "perspective" + else 1e-8 + if name == "epa" + else 0.25 * (k + 1) + ) + return value, "(" + str(value) + ")" + if typ == "[Point2]": + return ([], "[]") if bad else (p2[:3], "[p20,p21,p22]") + if typ == "[Point3]": + return ([], "[]") if bad else (p3[1:4], "[p31,p32,p33]") + if typ == "[PointND]": + return ([], "[]") if bad else (nd[:6], "[nd0,nd1,nd2,nd3,nd4,nd5]") + if typ == "[Plane]": + planes = [] if bad else [plane] * 6 + return planes, "[]" if bad else "replicate 6 planeA" + if typ == "[Double]": + return ( + ([math.nan], "[0/0]") if bad else ([0.25, 0.5, 0.75], "[0.25,0.5,0.75]") + ) + if typ == "[[Double]]": + return ( + ([], "[]") + if bad + else ([[1, 0, 0], [0, 1, 0], [0, 0, 1]], "[[1,0,0],[0,1,0],[0,0,1]]") + ) + if typ == "[(Int, Int)]": + return ([(-1, 1)], "[(-1,1)]") if bad else ([(0, 1)], "[(0,1)]") + if typ == "[(Int, Double)]": + return ([(0, 0.5), (1, 0.25)], "[(0,0.5),(1,0.25)]") + if typ == "(Point3, Point3, Point3)": + return ((p3[0], p3[1], p3[2]), "(p30,p31,p32)") + raise AssertionError((name, typ)) + + lines = [ + "import qualified HMath.Geometry as G", + "import qualified HMath.Matrix as M", + "import HMath.Error (MathError)", + "import Data.List (intercalate)", + "import GHC.Float", + 'fp x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'list e xs="["++intercalate "," (map e xs)++"]"', + 'matrix x=let (a,b)=M.shape x in show a++","++show b++":"++list fp (M.toList x)', + "right (Right x)=x", + "right (Left e)=error (show e)", + "emit :: (a->String)->Either MathError a->IO ()", + 'emit e (Right x)=putStrLn ("OK:"++e x)', + 'emit _ (Left e)=putStrLn ("ERR:"++show e)', + ] + for j, (a, b) in enumerate([(0, 0), (2, 0), (0, 2), (0.5, 0.5), (1, -1), (1, 1)]): + lines.append("p2" + str(j) + "=G.P2 (" + str(a) + ") (" + str(b) + ")") + for j, values in enumerate( + [ + (0, 0, 0), + (1, 0, 0), + (0, 1, 0), + (0, 0, 1), + (0.25, 0.5, 0.25), + (0, 0, 2), + (0, 0, -2), + (1, 1, 1), + ] + ): + lines.append( + "p3" + str(j) + "=G.P3 " + " ".join("(" + str(x) + ")" for x in values) + ) + for j, values in enumerate( + [ + [0, 0, 0], + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0.25, 0.5, 0.25], + [1, 1, 1], + [-1, -1, -1], + ] + ): + lines.append("nd" + str(j) + "=G.PointND " + str(values)) + lines += [ + "bad2=G.P2 (0/0) 0", + "bad3=G.P3 (0/0) 0 0", + "badnd=G.PointND [0/0]", + "lineA=G.Line nd0 nd3", + "parallel=G.Line nd3 nd1", + "coincident=G.Line nd0 nd1", + "segmentA=G.Segment nd0 nd5", + "planeA=G.Plane p33 0", + "planeX=G.Plane p31 0", + "planeShift=G.Plane p33 1", + "triangleA=G.Triangle p20 p21 p22", + "triangleB=G.Triangle p23 p21 p22", + "rectangleA=G.Rectangle (G.P2 (-1) (-1)) (G.P2 3 3)", + "circleA=G.Circle p20 1", + "circleB=G.Circle (G.P2 1 0) 1", + "ellipseA=G.Ellipse p20 2 1 0.3", + "polygonA=G.Polygon [p20,p21,p22]", + "polygonB=G.Polygon [p23,p21,p22]", + "sphereA=G.Sphere p30 1", + "boxA=G.AABB nd6 nd5", + "obbA=G.OBB p30 [p31,p32,p33] p37", + "capsuleA=G.Capsule p30 p35 1", + "cylinderA=G.Cylinder p30 p35 1", + "coneA=G.Cone p30 p35 1", + "rayA=G.Ray p36 p33", + "identityA=right (M.identityChecked 4::Either MathError (M.Matrix Double))", + "linearA=right (M.identityChecked 3::Either MathError (M.Matrix Double))", + "wrongMatrix=right (M.fromListChecked 2 3 [1,0,0,0,1,0::Double])", + "frustumA=right (G.extractFrustum identityA)", + "cloudA=right (G.pointCloud [nd0,nd1,nd2,nd3,nd4,nd5])", + "indexA=right (G.buildSpatialIndex G.KDTree cloudA)", + "neighborA=G.NeighborQuery [(0,0.5),(1,0.25)] 2 True", + "penetrationA=G.Penetration 0.25 p23 0.5 2", + "main=do", + ] + cases = [] + for entry in entries(): + argtypes = split_top(entry["signature"], "->")[:-1] + result, checked = result_type(entry["signature"]) + for bad in (False, True): + values = [fixture(entry, t, k, bad) for k, t in enumerate(argtypes)] + call = "G." + entry["name"] + "".join(" (" + hs + ")" for _, hs in values) + if not checked: + call = "Right (" + call + ")" + lines.append(" emit " + hsencode(result) + " (" + call + ")") + cases.append((entry, result, [x for x, _ in values], bad)) + extras = [ + ( + "line-parallel", + "G.linePlaneIntersection parallel planeA", + "Maybe (Maybe Point3)", + lambda: g.line_plane_intersection(parallel, plane), + ), + ( + "line-coincident", + "G.linePlaneIntersection coincident planeA", + "Maybe (Maybe Point3)", + lambda: g.line_plane_intersection(coincident, plane), + ), + ( + "plane-parallel", + "G.planeIntersection planeA planeShift", + "Maybe (Maybe Line)", + lambda: g.plane_intersection(plane, plane_shift), + ), + ( + "plane-coincident", + "G.planeIntersection planeA planeA", + "Maybe (Maybe Line)", + lambda: g.plane_intersection(plane, plane), + ), + ] + for _, call, result, _ in extras: + lines.append(" emit " + hsencode(result) + " (" + call + ")") + with tempfile.TemporaryDirectory(prefix="hmath-geometry-oracle-") as directory: + path = Path(directory) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-outputdir", + directory, + "-stubdir", + directory, + str(source), + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + + def close(value): + if isinstance(value, Value) or hasattr(value, "close"): + value.close() + elif isinstance(value, (tuple, list)): + for child in value: + close(child) + + for k, (entry, result, values, bad) in enumerate(cases): + value = None + try: + value = getattr(g, public_name(entry))(*values) + actual = "OK:" + encode(result, value) + except hmath.HMathError as error: + assert error.math_error is not None, (entry["name"], error) + actual = "ERR:" + str(error.math_error) + finally: + close(value) + assert actual == expected[k], (entry["name"], bad, actual, expected[k]) + for k, (label, _, result, function) in enumerate(extras, len(cases)): + value = function() + try: + assert "OK:" + encode(result, value) == expected[k], ( + label, + value, + expected[k], + ) + finally: + close(value) + assert g.line_plane_intersection(parallel, plane) == (False, None) + assert g.line_plane_intersection(coincident, plane) == (True, None) + parent = g.circle(p2[0], -1) + label, fields = parent.parts + parent.close() + assert label == "Circle" and fields[1] == -1 and fields[0].coordinates == [0, 0] + fields[0].close() + assert p2[0] == g.p2(0, 0) + assert p2[0] != p2[1] + with bad2.clone().decode() as duplicate: + assert bad2 != duplicate # original Double NaN Eq remains non-reflexive + for owner in owners: + owner.close() + print( + f"Geometry: {len(expected)} direct Haskell cases, original structured errors, all nested Maybe states, constructor fields and ownership passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_graph_equivalence.py b/tools/check_graph_equivalence.py new file mode 100644 index 0000000..eee9d8e --- /dev/null +++ b/tools/check_graph_equivalence.py @@ -0,0 +1,337 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare every public Graph adapter with independently executed Haskell.""" + +import argparse +import json +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_graph_bindings import snake, split_top + +ROOT = Path(__file__).resolve().parent.parent +HASKELL = r"""{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +import qualified HMath.Graph as G +import qualified HMath.Error as E +import Data.List (intercalate) +import Data.Char (ord) +import GHC.Float (castDoubleToWord64) +class Encode a where enc :: a -> String +instance Encode Int where enc x="I"++show x +instance Encode Integer where enc x="I"++show x +instance Encode Double where enc x="F"++show(castDoubleToWord64 x) +instance Encode Bool where enc x=if x then "B1" else "B0" +instance Encode () where enc ()="T[]" +instance {-# OVERLAPPING #-} Encode String where enc x="S"++show(map ord x) +instance {-# OVERLAPPABLE #-} Encode a => Encode [a] where enc xs="L["++intercalate "," (map enc xs)++"]" +instance Encode a => Encode (Maybe a) where enc Nothing="N"; enc(Just x)=enc x +instance (Encode a,Encode b) => Encode(a,b) where enc(a,b)="T["++enc a++","++enc b++"]" +instance (Encode a,Encode b,Encode c) => Encode(a,b,c) where enc(a,b,c)="T["++enc a++","++enc b++","++enc c++"]" +instance Encode G.Graph where enc x="G"++enc(G.serializeGraph x) +instance Encode G.Edge where enc x="Edge["++intercalate "," [enc(G.edgeId x),enc(G.edgeFrom x),enc(G.edgeTo x),enc(G.edgeWeight x)]++"]" +instance Encode G.CSR where enc x="CSR["++intercalate "," [enc(G.csrDirected x),enc(G.csrVertices x),enc(G.csrOffsets x),enc(G.csrTargets x),enc(G.csrWeights x),enc(G.csrIds x),enc(G.csrOrientations x)]++"]" +instance Encode G.BipartiteGraph where enc x="B"++enc(G.serializeBipartiteGraph x) +instance Encode G.Hypergraph where enc x="H"++enc(G.serializeHypergraph x) +instance Encode G.Network where enc x="Network"++enc(G.networkEdges x) +instance Encode G.NetworkEdge where enc x="NE["++intercalate "," [enc(G.networkEdgeId x),enc(G.networkFrom x),enc(G.networkTo x),enc(G.networkCapacity x),enc(G.networkCost x)]++"]" +instance Encode G.FlowResult where enc x="Flow"++enc(G.flowValue x,G.edgeFlows x,G.flowCost x) +ok :: Encode a => Either E.MathError a -> String +ok=either (("E"++).show) enc +right (Right x)=x +right (Left e)=error(show e) +g=right(G.graph False 4 [(0,1,1),(1,2,2),(2,3,3),(0,3,10)]) +dag=right(G.graph True 4 [(0,1,1),(1,2,2),(2,3,3)]) +bip=right(G.bipartiteGraph 2 2 [(0,0,1),(0,1,2),(1,0,3)]) +hyper=right(G.hypergraph 4 [[0,1],[1,2,3],[]]) +net=right(G.network 4 [(0,1,10^40,2),(1,3,10^40,3),(0,2,7,1),(2,3,7,1)]) +edge=G.Edge 9 2 1 (-0.0) +csr=G.toCSR g +ne=G.NetworkEdge 5 1 2 (10^50) (-7) +flow=G.FlowResult (10^50) [3,10^50] (-9) +main=mapM_ putStrLn [EXPRESSIONS] +""" + + +def close(value): + if hasattr(value, "close"): + value.close() + elif isinstance(value, (list, tuple)): + for item in value: + close(item) + + +def encode(value, graph): + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return "F" + str(struct.unpack("!Q", struct.pack("!d", value))[0]) + if isinstance(value, str): + return "S" + json.dumps(list(map(ord, value)), separators=(",", ":")) + if isinstance(value, (tuple, list)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(v, graph) for v in value) + + "]" + ) + if isinstance(value, graph.Graph): + return "G" + encode(graph.serialize_graph(value), graph) + if isinstance(value, graph.BipartiteGraph): + return "B" + encode(graph.serialize_bipartite_graph(value), graph) + if isinstance(value, graph.Hypergraph): + return "H" + encode(graph.serialize_hypergraph(value), graph) + if isinstance(value, graph.Network): + edges = graph.network_edges(value) + try: + return "Network" + encode(edges, graph) + finally: + close(edges) + if isinstance(value, graph.FlowResult): + return "Flow" + encode( + (graph.flow_value(value), graph.edge_flows(value), graph.flow_cost(value)), + graph, + ) + fields = { + graph.Edge: ("Edge", ["edge_id", "edge_from", "edge_to", "edge_weight"]), + graph.CSR: ( + "CSR", + [ + "csr_directed", + "csr_vertices", + "csr_offsets", + "csr_targets", + "csr_weights", + "csr_ids", + "csr_orientations", + ], + ), + graph.NetworkEdge: ( + "NE", + [ + "network_edge_id", + "network_from", + "network_to", + "network_capacity", + "network_cost", + ], + ), + } + for type_, (label, getters) in fields.items(): + if isinstance(value, type_): + return ( + label + + "[" + + ",".join( + encode(getattr(graph, name)(value), graph) for name in getters + ) + + "]" + ) + raise TypeError(type(value)) + + +def cases(graph): + owners = {} + + def owner(name, value): + owners[name] = value + return value + + g = owner("g", graph.graph(False, 4, [(0, 1, 1), (1, 2, 2), (2, 3, 3), (0, 3, 10)])) + owner("dag", graph.graph(True, 4, [(0, 1, 1), (1, 2, 2), (2, 3, 3)])) + owner("bip", graph.bipartite_graph(2, 2, [(0, 0, 1), (0, 1, 2), (1, 0, 3)])) + owner("hyper", graph.hypergraph(4, [[0, 1], [1, 2, 3], []])) + owner( + "net", + graph.network( + 4, [(0, 1, 10**40, 2), (1, 3, 10**40, 3), (0, 2, 7, 1), (2, 3, 7, 1)] + ), + ) + owner("edge", graph.edge(9, 2, 1, -0.0)) + owner("csr", graph.to_csr(g)) + owner("ne", graph.network_edge(5, 1, 2, 10**50, -7)) + owner("flow", graph.flow_result(10**50, [3, 10**50], -9)) + defaults = { + "Graph": "g", + "Edge": "edge", + "CSR": "csr", + "BipartiteGraph": "bip", + "Hypergraph": "hyper", + "Network": "net", + "NetworkEdge": "ne", + "FlowResult": "flow", + } + overrides = { + "Edge": ([9, 2, 1, -0.0], ["9", "2", "1", "(-0.0)"]), + "CSR": ( + [False, 1, [0, 0], [], [], [], []], + ["False", "1", "[0,0]", "[]", "[]", "[]", "[]"], + ), + "NetworkEdge": ([5, 1, 2, 10**50, -7], ["5", "1", "2", "(10^50)", "(-7)"]), + "FlowResult": ([10**50, [3, 10**50], -9], ["(10^50)", "[3,10^50]", "(-9)"]), + "graph": ( + [False, 3, [(0, 0, 1), (0, 1, 2), (0, 1, 3)]], + ["False", "3", "[(0,0,1),(0,1,2),(0,1,3)]"], + ), + "bipartiteGraph": ([2, 2, [(0, 1, 3)]], ["2", "2", "[(0,1,3)]"]), + "hypergraph": ([4, [[0, 1], [2, 3]]], ["4", "[[0,1],[2,3]]"]), + "network": ([2, [(0, 1, 10**50, -3)]], ["2", "[(0,1,10^50,-3)]"]), + "aStar": ([g, lambda _: 0.0, 0, 3], ["g", "(const 0)", "0", "3"]), + "kShortestPaths": ([1000, 3, g, 0, 3], ["1000", "3", "g", "0", "3"]), + "randomWalk": ([8, 2**64 - 1, g, 0], ["8", "maxBound", "g", "0"]), + "twoOptTour": ([1000, g, [0, 1, 2, 3, 0]], ["1000", "g", "[0,1,2,3,0]"]), + "modularity": ([g, [0, 0, 1, 1]], ["g", "[0,0,1,1]"]), + "pageRank": ([1000, 1e-8, 0.85, g], ["1000", "1e-8", "0.85", "g"]), + "katzCentrality": ( + [1000, 1e-8, 0.01, 1.0, g], + ["1000", "1e-8", "0.01", "1", "g"], + ), + "hungarian": ([[[10**50, 3], [2, 10**50]]], ["[[10^50,3],[2,10^50]]"]), + } + for name in ( + "fordFulkerson", + "edmondsKarp", + "dinic", + "pushRelabel", + "minimumCostMaximumFlow", + "minimumCut", + ): + overrides[name] = ([10000, owners["net"], 0, 3], ["10000", "net", "0", "3"]) + for name, string in [ + ("deserializeGraph", graph.serialize_graph(g)), + ("deserializeBipartiteGraph", graph.serialize_bipartite_graph(owners["bip"])), + ("deserializeHypergraph", graph.serialize_hypergraph(owners["hyper"])), + ]: + corresponding = { + "deserializeGraph": "G.serializeGraph g", + "deserializeBipartiteGraph": "G.serializeBipartiteGraph bip", + "deserializeHypergraph": "G.serializeHypergraph hyper", + }[name] + overrides[name] = ([string], ["(" + corresponding + ")"]) + orientations = [(0, 1), (1, 2), (2, 3), (0, 3)] + overrides["fromAdjacencyList"] = ( + [False, graph.adjacency_list(g), orientations], + ["False", "(G.adjacencyList g)", "[(0,1),(1,2),(2,3),(0,3)]"], + ) + overrides["fromLabeledAdjacencyMatrix"] = ( + [False, graph.adjacency_matrix(g), orientations], + ["False", "(G.adjacencyMatrix g)", "[(0,1),(1,2),(2,3),(0,3)]"], + ) + overrides["fromAdjacencyMatrix"] = ( + [True, [[[], [2.0]], [[], []]]], + ["True", "[[[],[2]],[[],[]]]"], + ) + entries = json.loads((ROOT / "bindings/schema/graph-functions.json").read_text())[ + "functions" + ] + result = [] + for entry in entries: + name = entry["name"] + if name in overrides: + arguments, expressions = overrides[name] + else: + arguments, expressions = [], [] + for typ in split_top(entry["signature"], "->")[:-1]: + if typ in defaults: + key = defaults[typ] + arguments.append(owners[key]) + expressions.append(key) + elif typ == "Int": + arguments.append(1000 if not arguments else 0) + expressions.append(str(arguments[-1])) + elif typ == "Double": + arguments.append(1e-8) + expressions.append("1e-8") + elif typ == "Bool": + arguments.append(False) + expressions.append("False") + elif typ == "[Int]": + arguments.append([0, 2]) + expressions.append("[0,2]") + else: + raise ValueError((name, typ)) + call = "G." + name + " " + " ".join(expressions) + checked = split_top(entry["signature"], "->")[-1].startswith("Either MathError") + result.append( + (snake(name), arguments, ("ok (" if checked else "enc (") + call + ")") + ) + # Invalid source inputs and exhausted budgets must retain the original Left. + result += [ + ("graph", [False, 513, []], "ok(G.graph False 513 [])"), + ( + "graph", + [False, 2, [(0, 1, float("inf"))]], + "ok(G.graph False 2 [(0,1,1/0)])", + ), + ("check_vertex", [g, -1], "ok(G.checkVertex g (-1))"), + ("require_undirected", [owners["dag"]], "ok(G.requireUndirected dag)"), + ("exact_coloring", [0, g], "ok(G.exactColoring 0 g)"), + ("dinic", [0, owners["net"], 0, 3], "ok(G.dinic 0 net 0 3)"), + ("deserialize_graph", ["bad\0input"], 'ok(G.deserializeGraph "bad\\0input")'), + ("longest_dag_paths", [owners["dag"], 0], "ok(G.longestDAGPaths dag 0)"), + ] + return result, owners + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + graph = hmath.graph + fixtures, owners = cases(graph) + try: + with tempfile.TemporaryDirectory(prefix="hmath-graph-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text( + HASKELL.replace( + "EXPRESSIONS", ",\n ".join(case[2] for case in fixtures) + ) + ) + process = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if process.returncode: + raise RuntimeError(process.stderr) + expected = process.stdout.splitlines() + actual = [] + for name, arguments, _ in fixtures: + try: + result = getattr(graph, name)(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(result, graph)) + finally: + close(result) + failures = [ + (i, fixtures[i][0], want, got) + for i, (want, got) in enumerate(zip(expected, actual)) + if want != got + ] + if len(expected) != len(actual) or failures: + raise AssertionError(f"Graph oracle mismatches: {failures[:12]}") + print( + f"Graph direct Haskell equivalence: {len(actual)} cases, all107 public functions/constructors" + ) + finally: + for owner in owners.values(): + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_image_equivalence.py b/tools/check_image_equivalence.py new file mode 100644 index 0000000..78bf896 --- /dev/null +++ b/tools/check_image_equivalence.py @@ -0,0 +1,460 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Validate all Image bindings against independent original Haskell evaluations.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_graph_bindings import split_top +from generate_image_bindings import SPECS, TYPES + +ROOT = Path(__file__).resolve().parent.parent + + +def fp(value): + return ( + "nan" + if math.isnan(value) + else str(struct.unpack("!Q", struct.pack("!d", value))[0]) + ) + + +def hsencode(typ): + if typ == "Image": + return "image" + if typ == "Tensor Double": + return "tensor" + if typ == "Double": + return "fp" + if typ in ("Int", "Bool"): + return "show" + if typ == "()": + return '(const "unit")' + if typ in TYPES: + return '(const "' + typ + '")' + if typ.startswith("["): + return "(list " + hsencode(typ[1:-1]) + ")" + if typ.startswith("("): + parts = split_top(typ[1:-1], ",") + variables = ["v" + str(n) for n in range(len(parts))] + return ( + "(\\(" + + ",".join(variables) + + ') -> "("++intercalate ";" [' + + ",".join(hsencode(t) + " " + v for t, v in zip(parts, variables)) + + ']++")")' + ) + raise AssertionError(typ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import image as i + from _hmath_native._value import Value + + owners = [] + + def own(x): + owners.append(x) + return x + + img = own(i.image([3, 3], 1, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])) + other = own(i.image([3, 3], 1, [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1])) + badimg = own(i.image([2], 1, [0, 1])) + rgb = own(i.image([3, 3], 3, [0.1, 0.2, 0.3] * 9)) + needle = own(i.image([2, 2], 1, [0.1, 0.2, 0.3, 0.5])) + binary = own(i.image([3, 3], 1, [0, 1, 0, 1, 1, 0, 0, 0, 1])) + tensor = own(i.to_tensor(img)) + bad_tensor = own(i.tensor([9], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])) + clamp = own(i.clamp()) + bad_boundary = own(i.constant(math.nan)) + sobel = own(i.sobel()) + scharr = own(i.scharr()) + erosion = own(i.erosion()) + closing = own(i.closing()) + squared = own(i.squared_difference()) + correlation = own(i.normalized_correlation()) + bilinear = own(i.bilinear()) + lanczos = own(i.lanczos()) + axis = own(i.axis_connected()) + fully = own(i.fully_connected()) + srgb = own(i.srgb()) + hsv = own(i.hsv()) + + def encode(typ, x): + if typ == "Image": + return ( + "I" + + encode("[Int]", i.image_shape(x)) + + ":" + + str(i.image_channels(x)) + + ":" + + encode("[Double]", i.image_values(x)) + ) + if typ == "Tensor Double": + return ( + "T" + + encode("[Int]", i.tensor_shape(x)) + + ":" + + encode("[Double]", i.tensor_values(x)) + ) + if typ == "Double": + return fp(x) + if typ in ("Int", "Bool"): + return str(x) + if typ == "()": + return "unit" + if typ in TYPES: + assert isinstance(x, getattr(i, TYPES[typ][3])), (typ, type(x)) + return typ + if typ.startswith("["): + return "[" + ",".join(encode(typ[1:-1], v) for v in x) + "]" + if typ.startswith("("): + return ( + "(" + + ";".join(encode(t, v) for t, v in zip(split_top(typ[1:-1], ","), x)) + + ")" + ) + raise AssertionError(typ) + + def fixture(entry, name, typ, bad): + function = entry["name"] + if typ == "Image": + if bad: + return badimg, "badimg" + if function in ("convertColor", "grayscale"): + return rgb, "rgb" + if function in ("distanceTransform", "connectedComponents"): + return binary, "binary" + if name == "needle": + return needle, "needle" + return (other, "other") if name == "b" else (img, "img") + if typ == "Tensor Double": + return (bad_tensor, "badTensor") if bad else (tensor, "tensorA") + if typ == "Boundary": + return (bad_boundary, "C.Constant (0/0)") if bad else (clamp, "C.Clamp") + if typ == "GradientOperator": + return (scharr, "F.Scharr") if bad else (sobel, "F.Sobel") + if typ == "Morphology": + return (closing, "F.Closing") if bad else (erosion, "F.Erosion") + if typ == "TemplateMetric": + return ( + (correlation, "M.NormalizedCorrelation") + if bad + else (squared, "M.SquaredDifference") + ) + if typ == "Interpolation": + return (lanczos, "S.Lanczos") if bad else (bilinear, "S.Bilinear") + if typ == "Connectivity": + return (fully, "S.FullyConnected") if bad else (axis, "S.AxisConnected") + if typ == "ColorSpace": + return (hsv, "K.HSV") if name == "destination" else (srgb, "K.SRGB") + if typ == "Int": + value = ( + -1 + if bad + else { + "channels": 1, + "index": 0, + "bins": 4, + "radius": 1, + "window": 2, + }.get(name, 1) + ) + return value, "(" + str(value) + ")" + if typ == "Double": + value = ( + math.inf + if bad + else { + "low": 0.1, + "high": 0.8, + "factor": 1.2, + "pivot": 0.5, + "power": 2, + "level": 0.5, + "sigma": 0.8, + "sigma_space": 0.8, + "sigma_range": 0.3, + "amount": 0.2, + "data_range": 1, + "clip_limit": 1, + "fill": -0.25, + "offset": 0.1, + }.get(name, 0.25) + ) + return value, "(1/0)" if bad else "(" + str(value) + ")" + if typ == "Bool": + return not bad, "False" if bad else "True" + if typ == "(Int, Int)": + value = (-1, 0) if bad else (0, 0) if name == "origin" else (2, 2) + return value, str(value) + if typ == "[Image]": + return ([], "[]") if bad else ([img, other], "[img,other]") + if typ == "[Int]": + value = ( + [] + if bad + else [1, 1] + if name == "coordinates" + else [3, 3, 1] + if entry["module"] == "HMath.Tensor" + else [3, 3] + ) + return value, str(value) + if typ == "[Double]": + value = ( + [] + if bad + else [1 / 9] * 9 + if name == "weights" + else [1, 1] + if name == "spacing" + else [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] + ) + haskell = ( + "[]" + if bad + else "replicate 9 (1/9)" + if name == "weights" + else str(value) + ) + return value, haskell + if typ == "[Bool]": + return ([], "[]") if bad else ([True] * 9, "replicate 9 True") + if typ == "[[Double]]": + return ( + ([], "[]") + if bad + else ([[1, 0, 0], [0, 1, 0], [0, 0, 1]], "[[1,0,0],[0,1,0],[0,0,1]]") + ) + if typ == "(Double -> Double)": + return ( + (lambda _: math.nan, "(\\_ -> 0/0)") + if bad + else (lambda x: x * x + 0.1, "(\\x -> x*x+0.1)") + ) + if typ == "(Double -> Double -> Double)": + return ( + (lambda _x, _y: math.nan, "(\\_ _ -> 0/0)") + if bad + else (lambda x, y: x - y, "(\\x y -> x-y)") + ) + raise AssertionError((function, name, typ)) + + lines = [ + "import qualified HMath.Image.Core as C", + "import qualified HMath.Image.Filter as F", + "import qualified HMath.Image.Histogram as H", + "import qualified HMath.Image.Measure as M", + "import qualified HMath.Image.Spatial as S", + "import qualified HMath.Image.Color as K", + "import qualified HMath.Tensor as T", + "import HMath.Error (MathError)", + "import Data.List (intercalate)", + "import GHC.Float", + 'fp x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'list e xs="["++intercalate "," (map e xs)++"]"', + 'image x="I"++list show (C.imageShape x)++":"++show (C.imageChannels x)++":"++list fp (C.imageValues x)', + 'tensor x="T"++list show (T.tensorShape x)++":"++list fp (T.tensorValues x)', + "right (Right x)=x", + "right (Left e)=error (show e)", + "emit :: (a->String)->Either MathError a->IO ()", + 'emit e (Right x)=putStrLn ("OK:"++e x)', + 'emit _ (Left e)=putStrLn ("ERR:"++show e)', + "img=right (C.image [3,3] 1 [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])", + "other=right (C.image [3,3] 1 [0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1])", + "badimg=right (C.image [2] 1 [0,1])", + "rgb=right (C.image [3,3] 3 (concat (replicate 9 [0.1,0.2,0.3])))", + "needle=right (C.image [2,2] 1 [0.1,0.2,0.3,0.5])", + "binary=right (C.image [3,3] 1 [0,1,0,1,1,0,0,0,1])", + "tensorA=right (C.toTensor img)", + "badTensor=right (T.tensor [9] [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9::Double])", + "main=do", + ] + qualifiers = {module: qualifier for _, (module, qualifier, _, _) in TYPES.items()} + qualifiers["HMath.Image.Histogram"] = "H" + cases = [] + for entry in SPECS: + for bad in (False, True): + values = [fixture(entry, name, typ, bad) for name, typ in entry["args"]] + call = ( + qualifiers[entry["module"]] + + "." + + entry["name"] + + "".join(" (" + hs + ")" for _, hs in values) + ) + if not entry["checked"]: + call = "Right (" + call + ")" + lines.append(" emit " + hsencode(entry["result"]) + " (" + call + ")") + cases.append((entry, [value for value, _ in values], bad)) + # Every enum branch is consumed by the original numerical operation. + extras = [] + for name in ["Sobel", "Prewitt", "Scharr"]: + enum = own( + getattr( + i, {"Sobel": "sobel", "Prewitt": "prewitt", "Scharr": "scharr"}[name] + )() + ) + extras.append( + ( + "gradient-" + name, + "F.gradient F." + name + " C.Reflect img", + "(Image, Image, Image, Image)", + lambda enum=enum: i.gradient(enum, i.reflect(), img), + ) + ) + for name in ["Erosion", "Dilation", "Opening", "Closing"]: + enum = own(getattr(i, name.lower())()) + extras.append( + ( + "morphology-" + name, + "F.morphology F." + + name + + " C.Wrap [3,3] [True,False,False,True,True,False,False,False,False] img", + "Image", + lambda enum=enum: i.morphology( + enum, + i.wrap(), + [3, 3], + [True, False, False, True, True, False, False, False, False], + img, + ), + ) + ) + for name in ["Clamp", "Reflect", "Wrap"]: + enum = own(getattr(i, name.lower())()) + extras.append( + ( + "boundary-" + name, + "F.gaussianBlur C." + name + " 0.8 2 img", + "Image", + lambda enum=enum: i.gaussian_blur(enum, 0.8, 2, img), + ) + ) + for name, py in [ + ("Nearest", "nearest"), + ("Bilinear", "bilinear"), + ("Bicubic", "bicubic"), + ("Lanczos", "lanczos"), + ]: + enum = own(getattr(i, py)()) + extras.append( + ( + "interpolation-" + name, + "S.resize S." + name + " C.Reflect (2,4) img", + "Image", + lambda enum=enum: i.resize(enum, i.reflect(), (2, 4), img), + ) + ) + for name, py in [ + ("SRGB", "srgb"), + ("LinearRGB", "linear_rgb"), + ("HSV", "hsv"), + ("HSL", "hsl"), + ("XYZ", "xyz"), + ("Lab", "lab"), + ("YCbCr", "y_cb_cr"), + ]: + enum = own(getattr(i, py)()) + extras.append( + ( + "color-" + name, + "K.convertColor K.SRGB K." + name + " rgb", + "Image", + lambda enum=enum: i.convert_color(srgb, enum, rgb), + ) + ) + for _, call, typ, _ in extras: + lines.append(" emit " + hsencode(typ) + " (" + call + ")") + with tempfile.TemporaryDirectory(prefix="hmath-image-oracle-") as directory: + path = Path(directory) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-outputdir", + directory, + "-stubdir", + directory, + str(source), + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + len(extras) + + def close(value): + if isinstance(value, Value): + value.close() + elif isinstance(value, (tuple, list)): + for child in value: + close(child) + + for index, (entry, values, bad) in enumerate(cases): + result = None + try: + result = getattr( + i, __import__("generate_graph_bindings").snake(entry["name"]) + )(*values) + actual = "OK:" + encode(entry["result"], result) + except hmath.HMathError as error: + assert error.math_error is not None, (entry["name"], error) + actual = "ERR:" + str(error.math_error) + finally: + close(result) + assert actual == expected[index], (entry["name"], bad, actual, expected[index]) + for index, (label, _, typ, function) in enumerate(extras, len(cases)): + result = function() + try: + assert "OK:" + encode(typ, result) == expected[index], ( + label, + encode(typ, result), + expected[index], + ) + finally: + close(result) + child = i.to_tensor(img) + img.close() + assert i.tensor_shape(child) == [3, 3, 1] + child.close() + + def fail(_): + raise LookupError("image callback failed") + + try: + i.map_image(fail, other) + raise AssertionError("callback error swallowed") + except LookupError as error: + assert str(error) == "image callback failed" + result = i.map_image(lambda x: x + i.pixel(other, [0, 0])[0], other) + assert i.image_values(result)[0] == 1.8 + result.close() + for owner in owners: + owner.close() + print( + f"Image: {len(expected)} direct Haskell cases, all enum branches, exact Tensor interchange and callback ownership passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_install.py b/tools/check_install.py index 1888726..d89f42a 100644 --- a/tools/check_install.py +++ b/tools/check_install.py @@ -64,6 +64,27 @@ def main(): env=env, ) run([str(target)], env=env) + # Exercise the newly installed headers, not include/ from the checkout. + for compiler, standard, source in [ + ("cc", "c99", "numeric_contracts.c"), + ("c++", "c++17", "numeric_contracts.cpp"), + ]: + target = Path(temporary) / ("numeric-" + standard) + run( + [ + compiler, + "-Wall", + "-Wextra", + "-Werror", + "-std=" + standard, + str(root / "test/native" / source), + *flags, + "-o", + str(target), + ], + env=env, + ) + run([str(target)], env=env) config = next(stage.rglob("HMathConfig.cmake")) cmake_build = Path(temporary) / "cmake" run( diff --git a/tools/check_interchange_bindings_equivalence.py b/tools/check_interchange_bindings_equivalence.py new file mode 100644 index 0000000..82ef4fe --- /dev/null +++ b/tools/check_interchange_bindings_equivalence.py @@ -0,0 +1,805 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent source oracle for fixed-width array, format and scoped IO APIs.""" + +import argparse +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_graph_bindings import snake + +ROOT = Path(__file__).resolve().parent.parent +ELEMENTS = [ + ("bool", "Bool", [True, False, False, True], "[True,False,False,True]"), + ("int8", "Int8", [-128, -1, 0, 127], "[-128,-1,0,127]"), + ("uint8", "Word8", [0, 1, 128, 255], "[0,1,128,255]"), + ("int16", "Int16", [-32768, -1, 0, 32767], "[-32768,-1,0,32767]"), + ("uint16", "Word16", [0, 1, 32768, 65535], "[0,1,32768,65535]"), + ("int32", "Int32", [-(2**31), -1, 0, 2**31 - 1], "[-2147483648,-1,0,2147483647]"), + ("uint32", "Word32", [0, 1, 2**31, 2**32 - 1], "[0,1,2147483648,4294967295]"), + ( + "int64", + "Int64", + [-(2**63), -(2**53) - 1, 2**53 + 1, 2**63 - 1], + "[-9223372036854775808,-9007199254740993,9007199254740993,9223372036854775807]", + ), + ( + "uint64", + "Word64", + [0, 1, 2**53 + 1, 2**64 - 1], + "[0,1,9007199254740993,18446744073709551615]", + ), + ("float32", "Float", [0.0, 1 / 3, -0.0, 1.0], "[0,1/3,(-0.0),1]"), + ("float64", "Double", [0.0, 1 / 3, -0.0, 1.0], "[0,1/3,(-0.0),1]"), + ( + "complex64", + "Complex Float", + [1 + 2j, 3 - 4j, 0j, 1j], + "[1:+2,3:+(-4),0:+0,0:+1]", + ), + ( + "complex128", + "Complex Double", + [1 + 2j, 3 - 4j, 0j, 1j], + "[1:+2,3:+(-4),0:+0,0:+1]", + ), +] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import algebra_api + from _hmath_native import interchange as i + from _hmath_native._bytes import Bytes + from _hmath_native._interchange_error import InterchangeError + from _hmath_native._matrix_base import Matrix + from _hmath_native._tensor_object import Tensor + + owners = [] + tests = [] + expressions = [] + covered = set() + + def own(value): + owners.append(value) + return value + + limits = own(i.default_limits()) + little = own(i.little_endian()) + big = own(i.big_endian()) + c = own(i.c_order()) + f = own(i.f_order()) + dtype = own(i.f64()) + array = own( + i.from_values(limits, little, [2, 2], [1.5, -0.0, 3.0, 4.0], dtype="float64") + ) + binary = own(i.encode_binary(limits, array)) + raw = own(i.raw_encode(limits, little, c, array)) + npy = own(i.encode_npy(limits, c, array)) + text = own(i.encode_text(limits, array)) + csv = own(i.encode_delimited(limits, ",", array)) + market = own(i.encode_matrix_market(limits, array)) + + def encode(value, precision=64): + if isinstance(value, Bytes): + return "BYTES" + str(list(bytes(value))).replace(" ", "") + if isinstance(value, i.Array): + fields = [ + i.array_d_type(value), + i.array_endian(value), + i.array_shape(value), + i.array_strides(value), + i.array_offset(value), + i.array_bytes(value), + i.array_metadata(value), + ] + try: + return "ARR(" + ",".join(encode(x, precision) for x in fields) + ")" + finally: + close(fields) + if isinstance(value, i.DType): + return "DT" + str(i.dtype_code(value)) + if isinstance(value, i.Endian): + with ( + i.put_element(value, 4660, dtype="uint16") as program, + i.put_bytes(program) as data, + ): + return "EN" + encode(data) + if isinstance(value, i.Order): + return "ORDER" + encode(i.dense_strides(value, 8, [2, 3])) + if isinstance(value, i.Compression): + try: + with i.compress(limits, value, b"hello\0hello") as data: + return "COMP" + encode(data) + except hmath.HMathError as error: + return "COMP!" + encode(error.interchange_error) + if isinstance(value, i.Limits): + return "LIMITS" + encode( + ( + i.max_bytes(value), + i.max_elements(value), + i.max_rank(value), + i.max_metadata(value), + i.max_archive_entries(value), + ) + ) + if isinstance(value, i.PutProgram): + with i.put_bytes(value) as data: + return encode(data) + if isinstance(value, InterchangeError): + return "ERR" + str(int(value.kind)) + "(" + encode(value.message) + ")" + if isinstance(value, Matrix): + return ( + "M" + + str(value.shape[0]) + + ":" + + str(value.shape[1]) + + "[" + + ",".join(encode(x, precision) for x in value.to_list()) + + "]" + ) + if isinstance(value, Tensor): + return ( + "TENSOR(" + + encode(algebra_api.tensor_dimensions(value), precision) + + "," + + encode(algebra_api.tensor_elements(value), precision) + + ")" + ) + if value is None: + return "N" + if isinstance(value, tuple) and not value: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return f"F{precision}:" + str(bits(value, precision)) + if isinstance(value, complex): + return ( + f"C{precision}:" + + str(bits(value.real, precision)) + + ":" + + str(bits(value.imag, precision)) + ) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(x)) for x in value) + "]" + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(x, precision) for x in value) + + "]" + ) + raise TypeError(type(value)) + + def add( + name, + arguments, + expression, + checked=False, + kwargs=None, + precision=64, + io=False, + function=None, + ): + covered.add(name) + tests.append( + ( + function or getattr(i, snake(name)), + arguments, + kwargs or {}, + precision, + name, + ) + ) + expressions.append( + ("fmap " + ("ic" if checked else "enc") + " (" + expression + ")") + if io + else "pure(" + ("ic" if checked else "enc") + "(" + expression + "))" + ) + + entries = json.loads( + (ROOT / "bindings/schema/interchange-functions.json").read_text() + )["functions"] + constructors = { + "Bool8", + "I8", + "U8", + "I16", + "U16", + "I32", + "U32", + "I64", + "U64", + "F32", + "F64", + "C64", + "C128", + "LittleEndian", + "BigEndian", + "COrder", + "FOrder", + "RawDeflate", + "Zlib", + "Gzip", + } + for e in entries: + if e["name"] in constructors: + add(e["name"], [], "I." + e["name"]) + for name in ("InvalidData", "Unsupported", "LimitExceeded", "InterchangeIOError"): + add(name, ["message\0α"], "I." + name + ' "message\\NULα"') + add("Limits", [1024, 100, 3, 256, 4], "I.Limits 1024 100 3 256 4") + add("defaultLimits", [], "I.defaultLimits") + for name in ( + "maxBytes", + "maxElements", + "maxRank", + "maxMetadata", + "maxArchiveEntries", + ): + add(name, [limits], "I." + name + " lim") + add( + "array", + [limits, dtype, little, [2, 2], [16, 8], 0, raw], + "I.array lim I.F64 I.LittleEndian [2,2] [16,8] 0 raw", + True, + ) + add( + "contiguousArray", + [limits, dtype, little, c, [2, 2], raw], + "I.contiguousArray lim I.F64 I.LittleEndian I.COrder [2,2] raw", + True, + ) + for name in ( + "arrayBytes", + "arrayDType", + "arrayEndian", + "arrayMetadata", + "arrayOffset", + "arrayShape", + "arrayStrides", + "elementCount", + "byteOffsets", + ): + add(name, [array], "I." + name + " arr") + add("denseStrides", [f, 8, [2, 3]], "I.denseStrides I.FOrder 8 [2,3]") + add("elementBytes", [dtype], "I.elementBytes I.F64") + add("validateShape", [limits, [2, 3]], "I.validateShape lim [2,3]", True) + add( + "withMetadata", + [limits, [("title", "α\0"), ("unit", "m")], array], + 'I.withMetadata lim [("title","α\\NUL"),("unit","m")] arr', + True, + ) + add( + "rawEncode", + [limits, big, f, array], + "I.rawEncode lim I.BigEndian I.FOrder arr", + True, + ) + add( + "rawDecode", + [limits, dtype, little, c, [2, 2], raw], + "I.rawDecode lim I.F64 I.LittleEndian I.COrder [2,2] raw", + True, + ) + add( + "repack", [limits, big, f, array], "I.repack lim I.BigEndian I.FOrder arr", True + ) + add("boundedInt", ["budget", 100, 101], 'I.boundedInt "budget" 100 101', True) + add("checkLimits", [limits], "I.checkLimits lim", True) + add( + "guardI", + [False, i.invalid_data("failed")], + 'I.guardI False(I.InvalidData "failed")', + True, + ) + for name, data, hsdata in [ + ("decodeBinary", binary, "binary"), + ("decodeNpy", npy, "npy"), + ("decodeText", text, "text"), + ("decodeMatrixMarket", market, "market"), + ]: + add(name, [limits, data], "I." + name + " lim " + hsdata, True) + for name in ("encodeBinary", "encodeText", "encodeMatrixMarket"): + add(name, [limits, array], "I." + name + " lim arr", True) + add( + "crc32", + [b"hello\0world"], + "I.crc32(B.pack [104,101,108,108,111,0,119,111,114,108,100])", + ) + add("encodeNpy", [limits, f, array], "I.encodeNpy lim I.FOrder arr", True) + add("encodeDelimited", [limits, ",", array], "I.encodeDelimited lim ',' arr", True) + add( + "decodeDelimited", + [limits, ",", dtype, csv], + "I.decodeDelimited lim ',' I.F64 csv", + True, + ) + add("compressionAvailable", [], "I.compressionAvailable", io=True) + for dtype_name, hstype, values, hsvalues in ELEMENTS: + precision = 32 if dtype_name in ("float32", "complex64") else 64 + for endian, hsendian in [(little, "I.LittleEndian"), (big, "I.BigEndian")]: + typed_array = own( + i.from_values(limits, endian, [2, 2], values, dtype=dtype_name) + ) + source = ( + "right(I.fromValues lim " + + hsendian + + " [2,2] (" + + hsvalues + + "::[" + + hstype + + "]))" + ) + add( + "elementType", + [], + "I.elementType(Proxy::Proxy(" + hstype + "))", + kwargs={"dtype": dtype_name}, + ) + add( + "fromValues", + [limits, endian, [2, 2], values], + "I.fromValues lim " + + hsendian + + " [2,2] (" + + hsvalues + + "::[" + + hstype + + "])", + True, + {"dtype": dtype_name}, + precision, + ) + add( + "toValues", + [typed_array], + "I.toValues(" + + source + + ")::Either I.InterchangeError [" + + hstype + + "]", + True, + {"dtype": dtype_name}, + precision, + ) + add( + "toMatrix", + [typed_array], + "I.toMatrix(" + + source + + ")::Either I.InterchangeError(M.Matrix(" + + hstype + + "))", + True, + {"dtype": dtype_name}, + precision, + ) + add( + "toTensor", + [typed_array], + "I.toTensor(" + + source + + ")::Either I.InterchangeError(T.Tensor(" + + hstype + + "))", + True, + {"dtype": dtype_name}, + precision, + ) + matrix = own(i.to_matrix(typed_array, dtype=dtype_name)) + tensor = own(i.to_tensor(typed_array, dtype=dtype_name)) + add( + "fromMatrix", + [limits, endian, matrix], + "I.fromMatrix lim " + + hsendian + + "(right(M.fromListChecked 2 2 (" + + hsvalues + + "::[" + + hstype + + "])))", + True, + precision=precision, + ) + add( + "fromTensor", + [limits, endian, tensor], + "I.fromTensor lim " + + hsendian + + "(right(T.tensor [2,2] (" + + hsvalues + + "::[" + + hstype + + "])))", + True, + precision=precision, + ) + program = own(i.get_element(endian, dtype=dtype_name)) + put = own(i.put_element(endian, values[1], dtype=dtype_name)) + data = own(i.put_bytes(put)) + add( + "putElement", + [endian, values[1]], + "I.putElement " + + hsendian + + " ((" + + hsvalues + + "::[" + + hstype + + "])!!1)", + kwargs={"dtype": dtype_name}, + precision=precision, + ) + add( + "getElement", + [endian], + "I.runDecoder(I.getElement " + + hsendian + + "::Get(" + + hstype + + "))(BL.toStrict(runPut(I.putElement " + + hsendian + + " ((" + + hsvalues + + "::[" + + hstype + + "])!!1))))", + True, + {"dtype": dtype_name}, + precision, + function=lambda en, dtype=dtype_name, data=data: i.run_decoder( + i.get_element(en, dtype=dtype), data + ), + ) + add( + "runDecoder", + [program, data], + "I.runDecoder(I.getElement " + + hsendian + + "::Get(" + + hstype + + "))(BL.toStrict(runPut(I.putElement " + + hsendian + + " ((" + + hsvalues + + "::[" + + hstype + + "])!!1))))", + True, + precision=precision, + ) + compression_available = i.compression_available() + for method, constructor in [ + ("raw_deflate", "RawDeflate"), + ("zlib", "Zlib"), + ("gzip", "Gzip"), + ]: + codec = own(getattr(i, method)()) + add( + "compress", + [limits, codec, b"hello\0hello"], + "I.compress lim I." + constructor + " payload", + True, + io=True, + ) + if compression_available: + compressed = own(i.compress(limits, codec, b"hello\0hello")) + add( + "decompress", + [limits, codec, 11, compressed], + "I.compress lim I." + + constructor + + " payload >>= either(pure.Left)(I.decompress lim I." + + constructor + + " 11)", + True, + io=True, + ) + archive = own(i.encode_npz(limits, False, [("alpha", array)])) + add( + "encodeNpz", + [limits, False, [("alpha", array)]], + 'I.encodeNpz lim False [("alpha",arr)]', + True, + io=True, + ) + add( + "decodeNpz", + [limits, archive], + 'I.encodeNpz lim False [("alpha",arr)] >>= either(pure.Left)(I.decodeNpz lim)', + True, + io=True, + ) + specification = own(i.raw_spec(dtype, little, c, [2, 2])) + + def scoped_observation(operation, spec=specification, payload=raw): + with tempfile.TemporaryDirectory(prefix="hmath-bindings-map-") as directory: + path = Path(directory) / "array.raw" + path.write_bytes(bytes(payload)) + + def callback(mapping): + if operation == "shape": + return i.mapped_shape(mapping) + if operation == "bytes": + return i.mapped_read_bytes(mapping, 8, 16) + if operation == "value": + return i.mapped_value(mapping, [1, 0]) + return ( + i.mapped_shape(mapping), + i.mapped_read_bytes(mapping, 8, 16), + i.mapped_value(mapping, [1, 0]), + ) + + return i.with_mapped_array(limits, spec, path, callback) + + for name, operation, expression in [ + ("mappedShape", "shape", "mapShape"), + ("mappedReadBytes", "bytes", "mapBytes"), + ("mappedValue", "value", "mapValue"), + ("withMappedArray", "all", "mapAll"), + ("RawSpec", "all", "mapAll"), + ]: + add( + name, + [], + expression, + True, + io=True, + function=lambda operation=operation: scoped_observation(operation), + ) + + def read_file(): + with tempfile.TemporaryDirectory(prefix="hmath-bindings-read-") as directory: + path = Path(directory) / "array.hmath" + path.write_bytes(bytes(binary)) + return i.read_array_file( + limits, lambda data: i.decode_binary(limits, data), path + ) + + def write_file(): + with tempfile.TemporaryDirectory(prefix="hmath-bindings-write-") as directory: + path = Path(directory) / "array.hmath" + i.write_array_file( + limits, + lambda budget, value: i.encode_binary(budget, value), + path, + array, + ) + return own(i.Bytes(path.read_bytes())) + + def read_chunks(): + with tempfile.TemporaryDirectory(prefix="hmath-bindings-stream-") as directory: + path = Path(directory) / "array.raw" + path.write_bytes(bytes(raw)) + observed = [] + + def consume(value): + observed.append(i.to_values(value)) + return True + + with i.open_handle(path, "rb") as handle: + i.read_raw_chunks(limits, specification, 2, handle, consume) + return observed + + def write_chunks(): + with tempfile.TemporaryDirectory(prefix="hmath-bindings-stream-") as directory: + path = Path(directory) / "array.raw" + chunks = [bytes(raw)[:16], bytes(raw)[16:]] + requests = [] + + def produce(maximum): + requests.append(maximum) + return chunks.pop(0) if chunks else None + + with i.open_handle(path, "wb") as handle: + i.write_raw_chunks(limits, specification, 2, handle, produce) + return requests, own(i.Bytes(path.read_bytes())) + + for name, function, expression in [ + ("readArrayFile", read_file, "readFileArray"), + ("writeArrayFile", write_file, "writeFileArray"), + ("readRawChunks", read_chunks, "readChunks"), + ("writeRawChunks", write_chunks, "writeChunks"), + ]: + add(name, [], expression, True, io=True, function=function) + for type_name, hstype, values, hsvalues in ELEMENTS: + + def mapped_typed(type_name=type_name, values=values): + with ( + i.from_values(limits, big, [2, 2], values, dtype=type_name) as value, + i.raw_encode(limits, big, f, value) as encoded, + i.element_type(dtype=type_name) as element, + i.raw_spec(element, big, f, [2, 2]) as spec, + tempfile.TemporaryDirectory(prefix="hmath-typed-map-") as directory, + ): + path = Path(directory) / "typed.raw" + path.write_bytes(bytes(encoded)) + return i.with_mapped_array( + limits, + spec, + path, + lambda mapping: i.mapped_value(mapping, [1, 0], dtype=type_name), + ) + + add( + "mappedValue", + [], + "mapTyped(Proxy::Proxy(" + + hstype + + "))(" + + hsvalues + + "::[" + + hstype + + "])", + True, + precision=32 if type_name in ("float32", "complex64") else 64, + io=True, + function=mapped_typed, + ) + imports = """import qualified HMath.Interchange as I +import qualified HMath.Interchange.Array as IA +import qualified HMath.Interchange.Binary as IB +import qualified HMath.Tensor as T +import Data.Binary.Get(Get) +import Data.Binary.Put(Put,runPut) +import qualified Data.ByteString as B +import qualified Data.ByteString.Lazy as BL +import Data.Proxy(Proxy(..)) +import Data.Int +import Data.Word +import Data.Char(ord) +import System.IO.Unsafe(unsafePerformIO) +import qualified System.IO as File +import Data.IORef +import Control.Monad(join) +""" + source = HASKELL.split("pR=")[0].replace( + "import qualified HMath.Polynomial as P", + imports + "\nimport qualified HMath.Polynomial as P", + ) + source = "{-# LANGUAGE RankNTypes #-}\n" + source + source += ( + """instance E Char where enc x="I"++show(ord x) +instance E Int8 where enc x="I"++show x +instance E Int16 where enc x="I"++show x +instance E Int32 where enc x="I"++show x +instance E Int64 where enc x="I"++show x +instance E Word8 where enc x="I"++show x +instance E Word16 where enc x="I"++show x +instance E Word32 where enc x="I"++show x +instance E Word64 where enc x="I"++show x +instance E () where enc ()="N" +instance E B.ByteString where enc x="BYTES["++intercalate ","(map show(B.unpack x))++"]" +instance E Put where enc=enc . BL.toStrict . runPut +instance(E a,E b,E c,E d,E e)=>E(a,b,c,d,e)where enc(a,b,c,d,e)="T["++intercalate ","[enc a,enc b,enc c,enc d,enc e]++"]" +instance E I.DType where enc x="DT"++show(fromEnum x) +instance E I.Endian where enc x="EN"++enc(I.putElement x (4660::Word16)) +instance E I.Order where enc x="ORDER"++enc(I.denseStrides x 8 [2,3]) +instance E I.Compression where enc x="COMP"++ic(unsafePerformIO(I.compress I.defaultLimits x payload)) +instance E I.Limits where enc x="LIMITS"++enc(I.maxBytes x,I.maxElements x,I.maxRank x,I.maxMetadata x,I.maxArchiveEntries x) +instance E I.InterchangeError where enc errorValue=case errorValue of I.InvalidData x->"ERR0("++enc x++")";I.Unsupported x->"ERR1("++enc x++")";I.LimitExceeded x->"ERR2("++enc x++")";I.InterchangeIOError x->"ERR3("++enc x++")" +instance E I.Array where enc x="ARR("++intercalate ","[enc(I.arrayDType x),enc(I.arrayEndian x),enc(I.arrayShape x),enc(I.arrayStrides x),enc(I.arrayOffset x),enc(I.arrayBytes x),enc(I.arrayMetadata x)]++")" +instance E a=>E(T.Tensor a)where enc x="TENSOR("++enc(T.tensorShape x)++","++enc(T.tensorValues x)++")" +ic :: E a=>Either I.InterchangeError a->String +ic=either (("!"++).enc)enc +right :: Show e=>Either e a->a +right=either(error.show)id +lim=I.defaultLimits +arr=right(I.fromValues lim I.LittleEndian [2,2] [1.5,(-0.0),3,4::Double]) +binary=right(I.encodeBinary lim arr) +raw=right(I.rawEncode lim I.LittleEndian I.COrder arr) +npy=right(I.encodeNpy lim I.COrder arr) +text=right(I.encodeText lim arr) +csv=right(I.encodeDelimited lim ',' arr) +market=right(I.encodeMatrixMarket lim arr) +payload=B.pack [104,101,108,108,111,0,104,101,108,108,111] +spec=I.RawSpec I.F64 I.LittleEndian I.COrder [2,2] +rawPath="ORACLE_DIRECTORY/input.raw" +binaryPath="ORACLE_DIRECTORY/input.hmath" +outputPath="ORACLE_DIRECTORY/output.hmath" +streamPath="ORACLE_DIRECTORY/output.raw" +mapped :: (forall s. I.MappedArray s->IO a)->IO(Either I.InterchangeError a) +mapped action=B.writeFile rawPath raw >>I.withMappedArray lim spec rawPath action +mapShape=mapped(pure . I.mappedShape) +mapBytes=fmap join(mapped(\\mapping->I.mappedReadBytes mapping 8 16)) +mapValue=fmap join(mapped(\\mapping->I.mappedValue mapping [1,0]::IO(Either I.InterchangeError Double))) +mapAll=mapped(\\mapping->do bytes<-right <$>I.mappedReadBytes mapping 8 16;number<-right <$>I.mappedValue mapping [1,0]::IO Double;pure(I.mappedShape mapping,bytes,number)) +readFileArray=B.writeFile binaryPath binary >>I.readArrayFile lim (I.decodeBinary lim) binaryPath +writeFileArray=do result<-I.writeArrayFile lim I.encodeBinary outputPath arr;bytes<-B.readFile outputPath;pure(bytes <$ result) +readChunks=do + B.writeFile rawPath raw + ref<-newIORef [] + result<-File.withBinaryFile rawPath File.ReadMode(\\handle->I.readRawChunks lim spec 2 handle(\\value->modifyIORef' ref(++[right(I.toValues value)::[Double]]) >>pure(Right True))) + observed<-readIORef ref + pure(observed <$result) +writeChunks=do + ref<-newIORef[B.take 16 raw,B.drop 16 raw] + calls<-newIORef [] + let produce amount=do modifyIORef' calls(++[amount]);pieces<-readIORef ref;case pieces of {[]->pure(Right Nothing);piece:rest->writeIORef ref rest >>pure(Right(Just piece))} + result<-File.withBinaryFile streamPath File.WriteMode(\\handle->I.writeRawChunks lim spec 2 handle produce) + requests<-readIORef calls;bytes<-B.readFile streamPath + pure((requests,bytes) <$result) +mapTyped :: I.Element a=>Proxy a->[a]->IO(Either I.InterchangeError a) +mapTyped proxy values=do + let arrayValue=right(I.fromValues lim I.BigEndian [2,2] values) + content=right(I.rawEncode lim I.BigEndian I.FOrder arrayValue) + specification=I.RawSpec(I.elementType proxy)I.BigEndian I.FOrder[2,2] + B.writeFile rawPath content + I.withMappedArray lim specification rawPath(\\mapping->right <$>I.mappedValue mapping [1,0]) +main=sequence [EXPRESSIONS] >>=mapM_ putStrLn +""".replace("EXPRESSIONS", ",\n ".join(expressions)) + .replace("I.boundedInt", "IA.boundedInt") + .replace("I.byteOffsets", "IA.byteOffsets") + .replace("I.checkLimits", "IA.checkLimits") + .replace("I.guardI", "IA.guardI") + .replace("I.runDecoder", "IB.runDecoder") + ) + with tempfile.TemporaryDirectory(prefix="hmath-interchange-oracle-") as temporary: + path = Path(temporary) / "Oracle.hs" + path.write_text(source.replace("ORACLE_DIRECTORY", temporary)) + command = [ + "ghc", + "--make", + "-O0", + "-fmax-errors=3", + "-isrc", + "-outputdir", + str(Path(temporary) / "build"), + str(path), + "cbits/interchange_io.c", + "-o", + str(Path(temporary) / "oracle"), + ] + if compression_available: + command += ["-optc-DHMATH_HAVE_ZLIB", "-lz"] + result = subprocess.run( + command, cwd=ROOT, capture_output=True, text=True, check=False + ) + if result.returncode: + raise SystemExit(result.stderr) + result = subprocess.run( + [str(Path(temporary) / "oracle")], + capture_output=True, + text=True, + check=False, + ) + if result.returncode: + raise SystemExit(result.stderr) + lines = result.stdout.splitlines() + if len(lines) != len(tests): + raise AssertionError((len(lines), len(tests))) + try: + for (function, arguments, kwargs, precision, name), expected in zip( + tests, lines + ): + try: + result = function(*arguments, **kwargs) + actual = encode(result, precision) + close(result) + except hmath.HMathError as error: + actual = "!" + encode(error.interchange_error) + if actual != expected: + raise AssertionError((name, kwargs, actual, expected)) + finally: + for owner in owners: + owner.close() + remaining = {e["name"] for e in entries} - covered + print( + f"Interchange direct Haskell equivalence: {len(tests)} cases;{len(covered)} named operations;13 exact Element instances; remaining scoped-IO contracts: {sorted(remaining)}" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_linear_equivalence.py b/tools/check_linear_equivalence.py new file mode 100644 index 0000000..1dbe994 --- /dev/null +++ b/tools/check_linear_equivalence.py @@ -0,0 +1,660 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Direct original-source oracle for all linear-domain functions/records.""" + +import argparse +import importlib +import json +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_linear_bindings import MODULES, generic_entry, hs_type, signatures, snake + +ROOT = Path(__file__).resolve().parent.parent + + +def normalize(value, precision, modules): + from _hmath_native._linear_base import LinearValue + from _hmath_native._matrix_base import LU, QR, Matrix + + if isinstance(value, LinearValue): + module, name = value.source_type.rsplit(".", 1) + target = modules[module] + if name == "Vector": + fields = target.vector_values(value) + elif name == "FixedVector": + fields = target.fixed_values(value) + elif name == "SparseVector": + fields = target.sparse_vector_values(value) + elif name == "Sparse": + fields = (target.sparse_shape(value), target.sparse_entries(value)) + elif name == "SparseTensor": + fields = ( + target.sparse_tensor_shape(value), + target.sparse_tensor_entries(value), + ) + elif name == "SparseLU": + fields = ( + target.sparse_lu_lower(value), + target.sparse_lu_upper(value), + target.sparse_lu_permutation(value), + ) + elif name == "SparseQR": + fields = target.sparse_qr_upper(value) + elif name == "Preconditioner": + fields = target.apply_preconditioner(value, [1, 1]) + elif name == "Backend": + fields = target.backend_info(value) + else: + fields = value.parts + try: + return value.source_type + "(" + normalize(fields, precision, modules) + ")" + finally: + close(fields) + if isinstance(value, Matrix): + r, c = value.shape + return ( + f"M{r}:{c}[" + + ",".join(normalize(x, precision, modules) for x in value.to_list()) + + "]" + ) + if isinstance(value, LU): + target = modules["HMath.Matrix.Decomposition"] + from _hmath_native import matrix as m + + fields = (m.lu_lower(value), m.lu_upper(value), m.lu_permutation(value)) + try: + return "LU(" + normalize(fields, precision, modules) + ")" + finally: + close(fields) + if isinstance(value, QR): + from _hmath_native import matrix as m + + fields = ( + m.qr_q(value), + m.qr_r(value), + m.qr_permutation(value), + m.qr_rank(value), + ) + try: + return "QR(" + normalize(fields, precision, modules) + ")" + finally: + close(fields) + if value is None: + return "N" + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(x)) for x in value) + "]" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return f"F{precision}:" + str(bits(value, precision)) + if isinstance(value, complex): + return ( + f"C{precision}:" + + str(bits(value.real, precision)) + + ":" + + str(bits(value.imag, precision)) + ) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(normalize(x, precision, modules) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +class Fixtures: + def __init__(self, modules, types, dtype): + self.modules = modules + self.types = types + self.dtype = dtype + self.owned = [] + self.hstype = { + "float32": "Float", + "float64": "Double", + "rational": "Rational", + "integer": "Integer", + "complex128": "Complex Double", + "complex64": "Complex Float", + }[dtype] + + def own(self, value, expression): + if hasattr(value, "close"): + self.owned.append(value) + return value, expression + + def type(self, spec): + return ( + hs_type(spec, self.types) + .replace("(a)", "(" + self.hstype + ")") + .replace("(b)", "(" + self.hstype + ")") + .replace("(c)", "(" + self.hstype + ")") + ) + + def coefficient(self, value=0.0001): + if self.dtype == "integer": + value = int(value) + elif self.dtype == "rational": + value = Fraction(str(value)) + elif self.dtype.startswith("complex"): + value = complex(value) + return value, ( + "(" + str(value.numerator) + "%" + str(value.denominator) + ")" + ) if isinstance(value, Fraction) else "(" + str(value.real) + " :+ " + str( + value.imag + ) + ")" if isinstance(value, complex) else str(value) + + def matrix(self, coefficient=None): + from _hmath_native import matrix as m + + coefficient = coefficient or ["a"] + dtype = {"Double": "float64", "Rational": "rational"}.get( + coefficient[0], self.dtype + ) + if coefficient[0] == "Complex": + dtype = ( + "complex64" + if coefficient[1] == ["Float"] + or coefficient[1] == ["a"] + and self.dtype == "float32" + else "complex128" + ) + value = m.from_list_checked(2, 2, [2, 0, 0, 3], dtype=dtype) + hstype = { + "float32": "Float", + "float64": "Double", + "rational": "Rational", + "integer": "Integer", + "complex128": "Complex Double", + "complex64": "Complex Float", + }[dtype] + return self.own( + value, + "(right(M.fromListChecked 2 2 [2,0,0,3]) :: M.Matrix (" + hstype + "))", + ) + + def object(self, name): + typ = self.types[name] + module = self.modules[typ["module"]] + alias = typ["alias"] + generic = "a" in typ["params"] + + def invoke(fn, args, expr): + value = getattr(module, fn)( + *args, **({"dtype": self.dtype} if generic else {}) + ) + return self.own( + value, + "(" + + expr + + " :: " + + ( + "V.FixedVector 2 (" + self.hstype + ")" + if name == "FixedVector" + else alias + + "." + + name + + (" (" + self.hstype + ")" if generic else "") + ) + + ")", + ) + + if name == "Vector": + return invoke("vector", [[1, 2, 3]], "V.vector [1,2,3]") + if name == "FixedVector": + return invoke("fixed_vector", [2, [1, 2]], "right(V.fixedVector @2 [1,2])") + if name == "SparseVector": + return invoke( + "sparse_vector", + [3, [(0, 1), (2, 2)]], + "right(V.sparseVector 3 [(0,1),(2,2)])", + ) + if name == "Sparse": + return invoke( + "sparse", + [2, 2, [(0, 0, 2), (1, 1, 3)]], + "right(S.sparse 2 2 [(0,0,2),(1,1,3)])", + ) + if name == "SparseTensor": + return invoke( + "sparse_tensor", + [[2, 2], [([0, 0], 2), ([1, 1], 3)]], + "right(S.sparseTensor [2,2] [([0,0],2),([1,1],3)])", + ) + if name in ("SparseFormat", "SparseLU", "SparseQR"): + value, hs = self.object("Sparse") + fn, expr = { + "SparseFormat": ("to_csr", "S.toCSR " + hs), + "SparseLU": ("sparse_lu", "right(S.sparseLU 0 " + hs + ")"), + "SparseQR": ("sparse_qr", "right(S.sparseQR " + hs + ")"), + }[name] + args = [0, value] if name == "SparseLU" else [value] + return invoke(fn, args, expr) + if name == "Preconditioner": + return invoke( + "identity_preconditioner", [2], "right(I.identityPreconditioner 2)" + ) + if name == "Backend": + return invoke("pure_backend", [], "B.pureBackend") + if name in ("Provider", "IntegerABI", "BackendLayout", "Transpose"): + fn, hs = { + "Provider": ("pure", "B.Pure"), + "IntegerABI": ("lp64", "B.LP64"), + "BackendLayout": ("row_major", "B.RowMajor"), + "Transpose": ("no_transpose", "B.NoTranspose"), + }[name] + return invoke(fn, [], hs) + if name == "BackendRequest": + return invoke("auto_backend", [], "B.AutoBackend") + if name == "IterativeOptions": + return self.own( + module.IterativeOptions(0.0001, 0.0001, 12, dtype=self.dtype), + "(I.IterativeOptions 0.0001 0.0001 12 :: I.IterativeOptions (" + + self.hstype + + "))", + ) + if name == "SparseSpectralOptions": + return self.own( + module.SparseSpectralOptions( + 0.0001, 0.0001, 12, 100000, dtype=self.dtype + ), + "(P.SparseSpectralOptions 0.0001 0.0001 12 100000 :: P.SparseSpectralOptions (" + + self.hstype + + "))", + ) + fields = json.loads( + (ROOT / "bindings/schema/linear-functions.json").read_text() + )["fields"][name] + values = [] + expressions = [] + for field, spec in fields: + value, expression = self.argument(spec, name, len(values), field) + values.append(value) + expressions.append(expression) + constructor = getattr(module, name) + value = constructor(*values, **({"dtype": self.dtype} if generic else {})) + return self.own( + value, + "(" + + alias + + "." + + name + + " " + + " ".join("(" + x + ")" for x in expressions) + + " :: " + + alias + + "." + + name + + (" (" + self.hstype + ")" if generic else "") + + ")", + ) + + def argument(self, spec, name, index, field=""): + head, *args = spec + if head in self.types: + return self.object(head) + if head == "Matrix": + return self.matrix(args[0]) + if head == "a": + return self.coefficient( + 0.0001 + if any(x in field.lower() for x in ["tolerance", "residual"]) + or "tol" in name.lower() + else 0.25 + ) + if head == "Double": + return 0.25, "(0.25::Double)" + if head == "Rational": + return Fraction(1, 4), "(1%4)" + if head == "Integer": + return 2, "2" + if head == "Int": + value = ( + 50 if "iteration" in field.lower() or "limit" in field.lower() else 2 + ) + return value, str(value) + if head == "Bool": + return False, "False" + if head == "String": + return "test", '"test"' + if head == "Complex": + return complex(0.25, 0), "(0.25:+0)" + if head == "Maybe": + return None, "Nothing" + if head == "tuple": + values = [] + expressions = [] + for i, child in enumerate(args): + value, expression = self.argument(child, name, i, field) + values.append(value) + expressions.append(expression) + return tuple(values), "(" + ",".join(expressions) + ")" + if head == "list": + child = args[0] + if child == ["Int"]: + value = ( + [0, 1, 2] + if name in ("CSR", "CSC", "BSR") and index == 2 + else [1, 0] + if name == "permutationMatrix" + else [1, 1] + if name == "blockJacobiPreconditioner" + else [0, 1] + if name in ("CSR", "CSC", "BSR", "ELLPACK") + else [2, 2] + ) + return value, str(value) + if child == ["a"]: + values = ( + [1, 2, 3] + if name in ("vector", "sparseVectorValues") + else [1, 1, 1, 1] + if name == "matrixFromLayout" + else [1, 1] + ) + return values, str(values) + if child == ["Double"]: + return [1.0, 1.0], "[1,1]" + if child == ["Rational"]: + return [Fraction(2), Fraction(3)], "[2,3]" + value, expression = self.argument(child, name, index, field) + return [value], "[" + expression + "]" + if head == "function": + if name == "generateMatrix": + return ( + lambda row, column: row + column, + "(\\row column -> fromIntegral(row+column))", + ) + if name == "zipMatrixWith": + return lambda a, b: a + b, "(+)" + raise ValueError((name, index, spec)) + + +def oracle_instances(types, fields, entries): + out = [ + 'instance E () where enc ()="N"\ninstance E Char where enc x="I"++show(ord x)\nright :: Either EError.MathError a -> a\nright=either(error.show) id\n' + ] + for name, typ in types.items(): + alias = typ["alias"] + generic = "a" in typ["params"] + ctx = ( + "(E a" + + ( + ",RealFloat a" + if name == "Preconditioner" + else ",Num a" + if name == "SparseVector" + else "" + ) + + ") => " + if generic + else "" + ) + target = ( + "V.FixedVector n a" + if name == "FixedVector" + else alias + "." + name + (" a" if generic else "") + ) + out.append( + "instance " + + ctx + + "E (" + + target + + ') where\n enc value="' + + typ["module"] + + "." + + name + + '("++(' + ) + if name == "Vector": + expr = "enc(V.vectorValues value)" + elif name == "FixedVector": + expr = "enc(V.fixedValues value)" + elif name == "SparseVector": + expr = "enc(V.sparseVectorValues value)" + elif name == "Sparse": + expr = "enc(S.sparseShape value,S.sparseEntries value)" + elif name == "SparseTensor": + expr = "enc(S.sparseTensorShape value,S.sparseTensorEntries value)" + elif name == "SparseLU": + expr = "enc(S.sparseLULower value,S.sparseLUUpper value,S.sparseLUPermutation value)" + elif name == "SparseQR": + expr = "enc(S.sparseQRUpper value)" + elif name == "Preconditioner": + expr = "ok(I.applyPreconditioner value [1,1])" + elif name == "Backend": + expr = "enc(B.backendInfo value)" + else: + constructors = [ + e for e in entries if e["constructor"] and e["result"][0] == name + ] + parts = [] + for entry in constructors: + variables = ["p" + str(i) for i in range(len(entry["args"]))] + # Encode public variant fields as the same (constructor, tuple) transport. + encoded = ( + '"T["++enc("' + + entry["name"] + + '")++",T["++intercalate "," [' + + ",".join("enc " + v for v in variables) + + ']++"]]"' + ) + parts.append( + alias + + "." + + entry["name"] + + " " + + " ".join(variables) + + " -> " + + encoded + ) + expr = "case value of {" + ";".join(parts) + "}" + out.append(expr + ')++")"\n') + out.append( + 'instance E(LU.LU Double) where enc value="LU("++enc(LU.luLower value,LU.luUpper value,LU.luPermutation value)++")"\n' + ) + out.append( + 'instance E(QR.QR Double) where enc value="QR("++enc(QR.qrQ value,QR.qrR value,QR.qrPermutation value,QR.qrRank value)++")"\n' + ) + out.append( + 'instance(E a,E b,E c,E d)=>E(a,b,c,d) where enc(a,b,c,d)="T["++intercalate "," [enc a,enc b,enc c,enc d]++"]"\n' + ) + return "".join(out) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + os.environ["HMATH_BACKEND"] = "pure" + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + entries, types, fields, _missing = signatures() + modules = { + m: importlib.import_module("_hmath_native." + ns) + for m, (_alias, ns) in MODULES.items() + } + fixtures = [] + expressions = [] + owners = [] + for entry in entries: + for dtype, precision in ( + [("float32", 32), ("float64", 64)] + if generic_entry(entry) + else [("float64", 64)] + ): + factory = Fixtures(modules, types, dtype) + arguments = [] + hsargs = [] + specs = entry["args"] + if entry["name"] == "fixedVector": + specs = [["Int"], ["list", ["a"]]] + try: + for index, spec in enumerate(specs): + value, expression = factory.argument(spec, entry["name"], index) + arguments.append(value) + hsargs.append(expression) + except BaseException: + for owner in factory.owned: + owner.close() + raise + name = ( + entry["name"] + if entry["constructor"] and entry["name"] in types + else snake(entry["name"]) + ) + function = getattr(modules[entry["module"]], name) + expression = ( + MODULES[entry["module"]][0] + + "." + + entry["name"] + + " " + + " ".join("(" + x + ")" for x in hsargs) + ) + if entry["name"] == "fixedVector": + expression = "V.fixedVector @2 (" + hsargs[1] + ")" + signature = factory.type(entry["result"]) + expression = "(" + expression + " :: " + signature + ")" + if entry["name"] == "fixedVector": + expression = ( + "(V.fixedVector @2 (" + + hsargs[1] + + ") :: Either EError.MathError(V.FixedVector 2 (" + + factory.hstype + + ")))" + ) + if entry["name"] == "fixedValues": + signature = None + result_spec = entry["result"] + if result_spec[0] == "IO": + expression = ( + expression + + " >>= putStrLn . " + + ("ok" if result_spec[1][0] == "Either" else "enc") + ) + else: + expression = ( + "putStrLn (" + + ("ok" if result_spec[0] == "Either" else "enc") + + " " + + expression + + ")" + ) + fixtures.append( + ( + function, + arguments, + {"dtype": dtype} if generic_entry(entry) else {}, + precision, + entry["module"] + "." + entry["name"], + ) + ) + expressions.append(expression) + owners.extend(factory.owned) + try: + imports = ( + "import System.IO (hSetBuffering,stdout,stderr,BufferMode(..),hPutStrLn)\nimport Data.Char(ord)\nimport qualified HMath.Error as EError\nimport qualified HMath.Error as E\nimport qualified HMath.Matrix.LU as LU\nimport qualified HMath.Matrix.QR as QR\n" + + "".join( + "import qualified " + m + " as " + a + "\n" + for m, (a, _ns) in MODULES.items() + ) + ) + source = HASKELL.replace( + "import Data.Complex", imports + "import Data.Complex" + ).split("main=mapM_ putStrLn")[0] + source = ( + "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeApplications #-}\n" + + source + + oracle_instances(types, fields, entries) + + "\nmain=do\n hSetBuffering stdout LineBuffering\n hSetBuffering stderr LineBuffering\n sequence_\n [ " + + "\n , ".join( + '(hPutStrLn stderr "' + + str(i) + + " " + + fixtures[i][-1] + + '") >> (' + + expression + + ")" + for i, expression in enumerate(expressions) + ) + + "\n ]\n" + ) + with tempfile.TemporaryDirectory(prefix="hmath-linear-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + shim = Path(directory) / "libhmath_oracle_backend.so" + subprocess.run( + [ + "cc", + "-shared", + "-fPIC", + "-std=c11", + "-Iinclude", + "cbits/backend.c", + "-ldl", + "-lm", + "-o", + str(shim), + ], + cwd=ROOT, + check=True, + capture_output=True, + ) + result = subprocess.run( + [ + "runghc", + "-isrc", + "-L" + directory, + "-lhmath_oracle_backend", + str(path), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if result.returncode: + Path("/tmp/hmath-linear-oracle-failed.hs").write_text(source) + raise RuntimeError(result.stderr[-10000:]) + expected = result.stdout.splitlines() + actual = [] + for function, arguments, kwargs, precision, name in fixtures: + try: + value = function(*arguments, **kwargs) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append( + "N" if value is None else normalize(value, precision, modules) + ) + finally: + close(value) + failures = [ + (fixtures[i][-1], expected[i], actual[i]) + for i in range(min(len(expected), len(actual))) + if expected[i] != actual[i] + ] + if failures or len(expected) != len(actual): + raise AssertionError(f"{len(failures)} mismatches: {failures[:15]}") + print( + f"Linear direct Haskell equivalence: {len(actual)} cases;270public operations/constructors,284source symbols" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_machinelearning_equivalence.py b/tools/check_machinelearning_equivalence.py new file mode 100644 index 0000000..a41856c --- /dev/null +++ b/tools/check_machinelearning_equivalence.py @@ -0,0 +1,617 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare the complete ML bridge against independent original Haskell calls.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from generate_graph_bindings import snake, split_top +from generate_machinelearning_bindings import metadata + +ROOT = Path(__file__).resolve().parent.parent + + +def fp(value): + return ( + "nan" + if math.isnan(value) + else str(struct.unpack("!Q", struct.pack("!d", value))[0]) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import autodiff as ad + from _hmath_native import backend, graph + from _hmath_native import expression as expr_module + from _hmath_native import machinelearning as m + from _hmath_native import numeric_types as numeric + from _hmath_native._math_error import MathError, MathErrorKind + from _hmath_native._value import Value + + data = metadata() + types = {e["name"] for e in data["types"]} + owners = [] + + def own(x): + owners.append(x) + return x + + xs = [[0.1, 0.2], [0.3, 0.4], [0.6, 0.1], [1.1, 1.3], [1.4, 1.8], [1.8, 1.2]] + zs = [[0.2, 0.1], [0.4, 0.3], [0.1, 0.7], [1.3, 1.1], [1.8, 1.4], [1.2, 1.8]] + ys = [0.4, 0.9, 1.3, 2.6, 3.2, 4.0] + labels = [0, 0, 0, 1, 1, 1] + binary = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] + signed = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0] + cfg = own(m.ml_config(8, 1e-7, 0.05, 42)) + badcfg = own(m.ml_config(-1, 1e-7, 0.05, 42)) + cache = {"MLConfig": cfg} + lines = [ + "import qualified HMath.MachineLearning as M", + "import qualified HMath.Autodiff as A", + "import qualified HMath.Backend as B", + "import qualified HMath.Graph.Core as G", + "import qualified HMath.Expression as E", + "import HMath.Error (MathError)", + "import Data.List (intercalate)", + "import Data.Ratio", + "import Data.Word (Word64)", + "import GHC.Float", + 'fp x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'list e xs="["++intercalate "," (map e xs)++"]"', + "right (Right x)=x", + "right (Left e)=error (show e)", + "emit :: (a->String)->Either MathError a->IO ()", + 'emit e (Right x)=putStrLn ("OK:"++e x)', + 'emit _ (Left e)=putStrLn ("ERR:"++show e)', + "cfg=M.MLConfig 8 1e-7 0.05 42", + "badcfg=M.MLConfig (-1) 1e-7 0.05 42", + "xs=" + str(xs), + "zs=" + str(zs), + "ys=" + str(ys), + "labels=[0,0,0,1,1,1::Int]", + "binary=[0,0,0,1,1,1::Double]", + "signed=[-1,-1,-1,1,1,1::Double]", + "encoder=right (M.fitEncoder [1,10^100+1,1::Integer])", + "genericFit=M.Fit xs 3 0.25 False", + "foldA=M.Fold [0,1,2] [3,4,5]", + "folds=right (M.kFold 42 2 6)", + "hierarchy=right (M.hierarchical M.Average xs)", + ] + recipe = { + "Penalty": ("M.Lasso 0.1", lambda: m.lasso(0.1)), + "LinearModel": ( + "M.fitted (right (M.fitLinear cfg (M.Lasso 0.1) xs ys))", + lambda: m.fitted(m.fit_linear(cfg, m.lasso(0.1), xs, ys)), + ), + "BayesianLinear": ( + "right (M.fitBayesian 1 1 xs ys)", + lambda: m.fit_bayesian(1, 1, xs, ys), + ), + "RecursiveLS": ( + "right (M.recursiveLS 2 0.99 1)", + lambda: m.recursive_ls(2, 0.99, 1), + ), + "GLMFamily": ("M.BinomialLogit", m.binomial_logit), + "GLM": ( + "M.fitted (right (M.fitGLM cfg M.BinomialLogit 0.1 xs binary))", + lambda: m.fitted(m.fit_glm(cfg, m.binomial_logit(), 0.1, xs, binary)), + ), + "MultinomialModel": ( + "M.fitted (right (M.fitMultinomial cfg 0.1 xs labels))", + lambda: m.fitted(m.fit_multinomial(cfg, 0.1, xs, labels)), + ), + "Kernel": ("M.RBFKernel 0.5", lambda: m.rbf_kernel(0.5)), + "SVM": ( + "M.fitted (right (M.fitSVM cfg (M.RBFKernel 0.5) 1 xs signed))", + lambda: m.fitted(m.fit_svm(cfg, m.rbf_kernel(0.5), 1, xs, signed)), + ), + "GaussianProcess": ( + "right (M.fitGaussianProcess (M.RBFKernel 0.5) 0.1 xs ys)", + lambda: m.fit_gaussian_process(m.rbf_kernel(0.5), 0.1, xs, ys), + ), + "GPClassifier": ( + "M.fitted (right (M.fitGPClassifier cfg (M.RBFKernel 0.5) xs binary))", + lambda: m.fitted(m.fit_gp_classifier(cfg, m.rbf_kernel(0.5), xs, binary)), + ), + "BayesFamily": ("M.GaussianBayes", m.gaussian_bayes), + "NaiveBayes": ( + "right (M.fitNaiveBayes M.GaussianBayes 1 xs labels)", + lambda: m.fit_naive_bayes(m.gaussian_bayes(), 1, xs, labels), + ), + "Discriminant": ( + "right (M.fitDiscriminant False 0.1 xs labels)", + lambda: m.fit_discriminant(False, 0.1, xs, labels), + ), + "IndexKind": ("M.KDTree", m.kd_tree), + "SpatialIndex": ( + "right (M.buildIndex M.KDTree 2 xs)", + lambda: m.build_index(m.kd_tree(), 2, xs), + ), + "NeighborResult": ( + "M.NeighborResult [(0,0.1),(1,0.2)] 2 True", + lambda: m.neighbor_result([(0, 0.1), (1, 0.2)], 2, True), + ), + "LSH": ("right (M.buildLSH 42 2 2 1 xs)", lambda: m.build_lsh(42, 2, 2, 1, xs)), + "IsolationForest": ( + "right (M.fitIsolationForest 42 3 4 xs)", + lambda: m.fit_isolation_forest(42, 3, 4, xs), + ), + "OneClassSVM": ( + "M.fitted (right (M.fitOneClassSVM cfg (M.RBFKernel 0.5) 0.5 xs))", + lambda: m.fitted(m.fit_one_class_svm(cfg, m.rbf_kernel(0.5), 0.5, xs)), + ), + "PCA": ("right (M.fitPCA 1 xs)", lambda: m.fit_pca(1, xs)), + "IncrementalPCA": ( + "right (M.incrementalPCA 2 >>= (`M.updatePCA` xs))", + lambda: m.update_pca(m.incremental_pca(2), xs), + ), + "KernelPCA": ( + "right (M.fitKernelPCA 1 (M.RBFKernel 0.5) xs)", + lambda: m.fit_kernel_pca(1, m.rbf_kernel(0.5), xs), + ), + "ICA": ( + "M.fitted (right (M.fitICA cfg 1 xs))", + lambda: m.fitted(m.fit_ica(cfg, 1, xs)), + ), + "FactorAnalysis": ( + "M.fitted (right (M.fitFactorAnalysis cfg 1 0.1 xs))", + lambda: m.fitted(m.fit_factor_analysis(cfg, 1, 0.1, xs)), + ), + "CCA": ("right (M.fitCCA 1 0.1 xs zs)", lambda: m.fit_cca(1, 0.1, xs, zs)), + "PLS": ( + "M.fitted (right (M.fitPLS cfg 1 xs zs))", + lambda: m.fitted(m.fit_pls(cfg, 1, xs, zs)), + ), + "Scaling": ("M.Standardize", m.standardize), + "Scaler": ( + "right (M.fitScaler M.Standardize xs)", + lambda: m.fit_scaler(m.standardize(), xs), + ), + "QuantileTransformer": ( + "right (M.fitQuantileTransformer xs)", + lambda: m.fit_quantile_transformer(xs), + ), + "PowerTransform": ("M.YeoJohnson 0.5", lambda: m.yeo_johnson(0.5)), + "Imputation": ("M.MeanImpute", m.mean_impute), + "Imputer": ( + "right (M.fitImputer M.MeanImpute xs)", + lambda: m.fit_imputer(m.mean_impute(), xs), + ), + "UnknownCategory": ("M.RejectUnknown", m.reject_unknown), + "Fold": ("foldA", lambda: m.fold([0, 1, 2], [3, 4, 5])), + "ClusterModel": ( + "M.fitted (right (M.kMeans cfg 2 xs))", + lambda: m.fitted(m.k_means(cfg, 2, xs)), + ), + "GaussianMixture": ( + "M.fitted (right (M.fitGaussianMixture cfg 2 0.1 xs))", + lambda: m.fitted(m.fit_gaussian_mixture(cfg, 2, 0.1, xs)), + ), + "Linkage": ("M.Average", m.average), + "Merge": ("M.Merge 0 1 0.5 2", lambda: m.merge(0, 1, 0.5, 2)), + } + encoder = own(m.fit_encoder([1, 10**100 + 1, 1])) + generic_fit = own(m.fit(xs, 3, 0.25, False)) + hierarchy = m.hierarchical(m.average(), xs) + owners.extend(hierarchy) + for name, (expression, call) in recipe.items(): + variable = "value" + name + lines.append(variable + "=" + expression) + cache[name] = own(call()) + cache["Encoder Value"] = encoder + + def encoder_kind(kind): + kind = kind.strip() + if kind == "a": + return "Dataset" + if kind == "p": + return "Integer" + if kind.startswith("Fit "): + return "Fit " + encoder_kind(kind[4:]) + if kind == "Encoder a": + return "Encoder Integer" + if kind.startswith("["): + return "[" + encoder_kind(kind[1:-1]) + "]" + if kind.startswith("("): + return ( + "(" + + ",".join(encoder_kind(t) for t in split_top(kind[1:-1], ",")) + + ")" + ) + return kind + + def hse(kind): + kind = kind.strip() + if kind == "Dataset": + return "(list (list fp))" + if kind.startswith("Fit "): + return "(fit " + hse(kind[4:].strip("()")) + ")" + if kind.startswith("Encoder "): + return "encoderWire" + if kind in types: + return "show" + if kind == "Double": + return "fp" + if kind in ("Int", "Word64", "Integer", "Bool"): + return "(show :: " + kind + " -> String)" + if kind.startswith("Maybe "): + return '(maybe "Nothing" (\\x -> "Just("++' + hse(kind[6:]) + ' x++")"))' + if kind.startswith("["): + return "(list " + hse(kind[1:-1]) + ")" + if kind.startswith("("): + fields = split_top(kind[1:-1], ",") + if len(fields) == 1: + return hse(fields[0]) + vs = ["v" + str(k) for k in range(len(fields))] + return ( + "(\\(" + + ",".join(vs) + + ') -> "("++intercalate ";" [' + + ",".join(hse(t) + " " + v for t, v in zip(fields, vs)) + + ']++")")' + ) + raise AssertionError(kind) + + def encode(kind, value): + kind = kind.strip() + if kind == "Dataset": + return encode("[[Double]]", value) + if kind.startswith("Fit "): + payload = m.fitted(value) + try: + return ( + "F(" + + encode(kind[4:].strip("()"), payload) + + ";" + + str(m.fit_iterations(value)) + + ";" + + fp(m.fit_residual(value)) + + ";" + + str(m.fit_converged(value)) + + ")" + ) + finally: + if isinstance(payload, Value): + payload.close() + if kind.startswith("Encoder "): + return encode("[Integer]", m.label_decode(value, [0, 1])) + if kind in types: + return m.describe(value) + if kind == "Double": + return fp(value) + if kind in ("Int", "Word64", "Integer", "Bool"): + return str(value) + if kind.startswith("Maybe "): + return ( + "Nothing" if value is None else "Just(" + encode(kind[6:], value) + ")" + ) + if kind.startswith("["): + return "[" + ",".join(encode(kind[1:-1], x) for x in value) + "]" + if kind.startswith("("): + fields = split_top(kind[1:-1], ",") + return ( + encode(fields[0], value) + if len(fields) == 1 + else "(" + ";".join(encode(t, x) for t, x in zip(fields, value)) + ")" + ) + raise AssertionError(kind) + + def fixture(entry, typ, k, bad): + name = entry["name"] + raw = split_top(entry["signature"].split("=>")[-1].strip(), "->")[:-1] + if typ == "MLConfig": + return (badcfg, "badcfg") if bad else (cfg, "cfg") + if typ == "Fit a": + return generic_fit, "genericFit" + if typ == "Encoder a": + return encoder, "encoder" + if typ in recipe: + return cache[typ], "value" + typ + if typ == "Dataset": + if bad: + return [], "[]" + if name == "inversePCA": + return [[0.1], [0.2]], "[[0.1],[0.2]]" + return (zs, "zs") if k > 0 and raw[k - 1] == "Dataset" else (xs, "xs") + if typ == "Word64": + return 42, "42" + if typ == "Int": + if bad: + return -1, "(-1)" + if name == "recursiveLS" or name == "buildLSH": + value = 2 + elif name == "fitIsolationForest": + value = 3 if k == 1 else 4 + elif name == "nearestNeighbors": + value = 2 if k == 0 else 20 + elif name in ( + "knnRegress", + "knnClassify", + "queryLSH", + "localOutlierFactor", + ): + value = 2 + elif name == "trainTestSplit": + value = 6 + elif name == "kFold": + value = 2 if k == 1 else 6 + elif name == "stratifiedKFold": + value = 2 + elif name == "cutHierarchy": + value = 2 if k == 0 else 6 + elif name == "dbscan" or name == "optics": + value = 2 + elif name in ("isomap", "umap"): + value = 2 if k == 1 else 1 + else: + value = 1 + return value, str(value) + if typ == "Double": + if bad: + return math.inf, "(1/0)" + value = 0.25 + if name in ("recursiveLS",): + value = 0.99 if k == 1 else 1 + elif name == "fitBayesian": + value = 1 + elif name in ( + "fitSVM", + "fitGaussianProcess", + "fitDiscriminant", + "fitCCA", + "fitFactorAnalysis", + ): + value = 0.1 if name != "fitSVM" else 1 + elif name == "fitOneClassSVM": + value = 0.5 + elif name in ("fitNaiveBayes", "kernel", "queryLSH", "fitGaussianMixture"): + value = 0.1 if name == "fitGaussianMixture" else 1 + elif name in ("fitGLM", "fitMultinomial", "fitRobust"): + value = 0.1 + elif name == "trainTestSplit": + value = 0.33 + elif name == "tsne": + value = 2 + elif name == "umap": + value = 0.1 if k == 3 else 1 + elif name == "affinityPropagation": + value = 0.5 if k == 1 else -1 + elif name in ( + "spectralClustering", + "meanShift", + "dbscan", + "optics", + "extractOPTICS", + ): + value = 1 + return value, "(" + str(value) + ")" + if typ == "Bool": + return not bad, "False" if bad else "True" + if typ == "a": + return xs, "xs" + if typ == "[Double]": + if bad: + return [], "[]" + if name in ("kernel", "updateRecursiveLS", "nearestNeighbors", "queryLSH"): + return [0.25, 0.3], "[0.25,0.3]" + if name in ("fitGLM", "fitGPClassifier"): + return binary, "binary" + if name == "fitSVM": + return signed, "signed" + if name == "fitWeighted" and k == 2: + return [1.0] * 6, "replicate 6 1" + return ys, "ys" + if typ == "[Int]": + return ([], "[]") if bad else (labels, "labels") + if typ == "[a]": + if bad: + return ([], "[]") if name == "fitEncoder" else ([2], "[2::Integer]") + if name == "stratifiedKFold": + return labels, "map toInteger labels" + return [1, 10**100 + 1, 1], "[1,10^100+1,1::Integer]" + if typ == "[p]": + return ([], "[]") if bad else ([1, 2, 3], "[1,2,3::Integer]") + if typ == "[Fold]": + return ([], "[]") if bad else ([cache["Fold"]], "[foldA]") + if typ == "[Merge]": + return hierarchy, "hierarchy" + if typ == "[(Int, Double)]": + return [(0, 0.1), (1, 0.2)], "[(0,0.1),(1,0.2)]" + if typ == "[(Int, Maybe Double, Maybe Double)]": + return [ + (0, None, None), + (1, 1.0, 1.0), + ], "[(0,Nothing,Nothing),(1,Just 1,Just 1)]" + if "->" in typ: + return ( + (lambda _p, _f: math.nan, "(\\_ _ -> Right (0/0))") + if bad + else ( + lambda p, f: p + len(m.validation_indices(f)), + "(\\p f -> Right (fromInteger p+fromIntegral (length (M.validationIndices f))))", + ) + ) + raise AssertionError((name, typ)) + + lines += [ + 'fit e x="F("++e (M.fitted x)++";"++show (M.fitIterations x)++";"++fp (M.fitResidual x)++";"++show (M.fitConverged x)++")"', + "encoderWire :: M.Encoder Integer -> String", + "encoderWire x=list show (right (M.labelDecode x [0,1]))", + "main=do", + ] + cases = [] + for entry in data["functions"]: + pieces = split_top(entry["signature"].split("=>")[-1].strip(), "->") + arguments = pieces[:-1] + result = pieces[-1] + checked = result.startswith("Either MathError ") + result = result.removeprefix("Either MathError ") + for bad in (False, True): + values = [fixture(entry, t, k, bad) for k, t in enumerate(arguments)] + call = "M." + entry["name"] + "".join(" (" + hs + ")" for _, hs in values) + if not checked: + call = "Right (" + call + ")" + kind = encoder_kind(result) + if entry["name"] == "labelDecode": + kind = "[Integer]" + lines.append(" emit " + hse(kind) + " (" + call + ")") + cases.append((entry, kind, [value for value, _ in values], bad)) + ad_labels = [ + own(ad.Dual(1, 2, dtype="integer")), + own(ad.Dual(1, 1, dtype="integer")), + own(ad.Dual(0, 9, dtype="integer")), + ] + provider_labels = [ + own(backend.pure()), + own(backend.blis()), + own(backend.open_blas()), + ] + edge_labels = [own(graph.edge(2, 0, 1, 0.5)), own(graph.edge(1, 0, 1, 0.5))] + expr_labels = [ + own(expr_module.variable("x")), + own(expr_module.parse_expression(expr_module.default_limits(), " x ")), + own(expr_module.variable("y")), + ] + extras = [ + ( + "AD original Ord", + "let xs=[A.Dual 1 2,A.Dual 1 1,A.Dual 0 9::A.Dual Integer] in M.fitEncoder xs >>= \\enc -> M.labelEncode enc xs", + ad_labels, + ), + ( + "Backend original Ord", + "let xs=[B.Pure,B.BLIS,B.OpenBLAS] in M.fitEncoder xs >>= \\enc -> M.labelEncode enc xs", + provider_labels, + ), + ( + "Graph Edge original Ord", + "let xs=[G.Edge 2 0 1 0.5,G.Edge 1 0 1 0.5] in M.fitEncoder xs >>= \\enc -> M.labelEncode enc xs", + edge_labels, + ), + ( + "Expr position-insensitive Eq", + 'let xs=[E.variable "x",right (E.parseExpression E.defaultLimits " x "),E.variable "y"] in M.fitEncoder xs >>= \\enc -> M.labelEncode enc xs', + expr_labels, + ), + ] + for _, call, _ in extras: + lines.append(" emit (list show) (" + call + ")") + with tempfile.TemporaryDirectory(prefix="hmath-ml-oracle-") as directory: + path = Path(directory) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-Iinclude", + "-optc-std=c11", + "-outputdir", + directory, + "-stubdir", + directory, + str(source), + "cbits/backend.c", + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + len(extras) + + def close(value): + if isinstance(value, Value) or hasattr(value, "close"): + value.close() + elif isinstance(value, (list, tuple)): + for child in value: + close(child) + + for k, (entry, kind, values, bad) in enumerate(cases): + result = None + try: + result = getattr(m, snake(entry["name"]))(*values) + actual = "OK:" + encode(kind, result) + except hmath.HMathError as error: + assert error.math_error is not None, (entry["name"], error) + actual = "ERR:" + str(error.math_error) + finally: + close(result) + assert actual == expected[k], (entry["name"], bad, actual, expected[k]) + for k, (label, _, labels_input) in enumerate(extras, len(cases)): + with m.fit_encoder(labels_input) as encoded: + actual = "OK:" + encode("[Int]", m.label_encode(encoded, labels_input)) + assert actual == expected[k], (label, actual, expected[k]) + # Exact/generic categorical dictionaries and independent retained owners. + for labels_in in [ + [10**200, 1, 10**200], + [Fraction(1, 3), Fraction(1, 7), Fraction(1, 3)], + ["λ\0", "a\ud800", "λ\0"], + [True, False, True], + [(2, "a"), (1, "b"), (2, "a")], + [[2, 1], [1, 2], [2, 1]], + ]: + with m.fit_encoder(labels_in) as enc: + codes = m.label_encode(enc, labels_in) + assert m.label_decode(enc, codes) == labels_in + with ( + numeric.number(1, "float32") as scalar, + m.fit_encoder([scalar, numeric.number(2, "float32")]) as enc, + ): + assert m.label_decode(enc, [0, 1]) == [1.0, 2.0] + with m.fit_encoder([[], []], prototype=[0]) as enc: + assert m.label_encode(enc, [[]]) == [0] + with m.fit_encoder([None, None], prototype=0) as enc: + assert m.label_decode(enc, [0]) == [None] + + def failure(_p, _f): + raise LookupError("ML callback failed") + + try: + m.grid_search([1], [cache["Fold"]], failure) + raise AssertionError("callback error swallowed") + except LookupError as error: + assert str(error) == "ML callback failed" + + def domain(_p, _f): + raise MathError(MathErrorKind.DOMAIN_ERROR, message="validation failed") + + try: + m.grid_search([1], [cache["Fold"]], domain) + raise AssertionError("MathError swallowed") + except hmath.HMathError as error: + assert ( + error.math_error.kind == MathErrorKind.DOMAIN_ERROR + and error.math_error.message == "validation failed" + ) + record = m.fit(cache["LinearModel"], 3, 0.25, False) + child = m.fitted(record) + record.close() + assert m.predict_linear(child, xs) == m.predict_linear(cache["LinearModel"], xs) + child.close() + for owner in owners: + owner.close() + print( + f"MachineLearning: {len(expected)} direct Haskell cases plus exact labels, prototypes, checked callbacks and model ownership passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_matrix_equivalence.py b/tools/check_matrix_equivalence.py new file mode 100644 index 0000000..993bedf --- /dev/null +++ b/tools/check_matrix_equivalence.py @@ -0,0 +1,277 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare all dense Matrix/LU/QR bindings with independent Haskell calls.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_matrix_bindings import S, snake + +ROOT = Path(__file__).resolve().parent.parent + + +def fixture(module, name, kinds, bad): + result = [] + for index, kind in enumerate(kinds): + if kind in "lq": + result.append(("object", kind)) + elif kind == "m": + matrix = "b" if index > 0 else "a" + if bad and index > 0: + matrix = "wrong" + if bad and name in ("luDecompose", "determinant", "inverse"): + matrix = "singular" + if bad and name == "qrDecompose": + matrix = "nonfinite" + result.append(("object", matrix)) + elif kind == "f": + result.append(("real", -1.0 if bad else 0.25)) + elif kind == "i": + value = 2 + if name.startswith("reshape"): + value = [1, 4][index] if not bad else 3 + elif name.startswith("at"): + value = [0, 0, 1][index] if not bad else -1 + elif name.startswith("sliceMatrix"): + value = [0, 1, 2, 1][index] if not bad else -1 + elif bad: + value = -1 + result.append(("int", value)) + elif kind == "v": + values = [0.0, 2.0, 1.0, 3.0] if name.startswith("fromList") else [1.0, 2.0] + if bad and not name.startswith("fromList"): + values = [1.0] + result.append(("vector", values)) + return result + + +def hsarg(item, precision): + kind, value = item + if kind == "object": + return value + str(precision) + if kind == "real": + return f"({value} :: {'Float' if precision == 32 else 'Double'})" + if kind == "int": + return f"({value})" + return ( + "(" + + repr(value).replace(" ", "") + + " :: [" + + ("Float" if precision == 32 else "Double") + + "])" + ) + + +def hsencode(kind, precision): + return { + "m": "matrix", + "l": "lowerUpper", + "q": "orthogonal", + "v": "vector", + "p": "indices", + "i": "show", + "f": "fp", + }[kind] + (str(precision) if kind not in "pi" else "") + + +def fp(value, precision): + if math.isnan(value): + return "NaN" + return str( + struct.unpack( + "!I" if precision == 32 else "!Q", + struct.pack("!f" if precision == 32 else "!d", value), + )[0] + ) + + +def encode(value, kind, precision, matrix): + if kind == "m": + return ( + str(value.shape[0]) + + "," + + str(value.shape[1]) + + ":" + + ",".join(fp(x, precision) for x in value.to_list()) + ) + if kind == "l": + with matrix.lu_lower(value) as lower, matrix.lu_upper(value) as upper: + return ( + encode(lower, "m", precision, matrix) + + ";" + + encode(upper, "m", precision, matrix) + + ";" + + encode(matrix.lu_permutation(value), "p", precision, matrix) + ) + if kind == "q": + with matrix.qr_q(value) as q, matrix.qr_r(value) as r: + return ( + encode(q, "m", precision, matrix) + + ";" + + encode(r, "m", precision, matrix) + + ";" + + encode(matrix.qr_permutation(value), "p", precision, matrix) + + ";" + + str(matrix.qr_rank(value)) + ) + if kind == "v": + return ",".join(fp(x, precision) for x in value) + if kind == "p": + return ",".join(str(x) for x in value) + return str(value) if kind == "i" else fp(value, precision) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import matrix + + lines = [ + "{-# LANGUAGE ScopedTypeVariables #-}", + "import Control.Exception", + "import Data.List (intercalate)", + "import GHC.Float", + "import HMath.Error", + "import qualified HMath.Matrix as M", + "import qualified HMath.Matrix.LU as L", + "import qualified HMath.Matrix.QR as Q", + "emit :: (a -> String) -> Either MathError a -> IO ()", + 'emit encode result = (do let text = either (("ERR:" ++) . show) (("OK:" ++) . encode) result', + " evaluate (length text)", + ' putStrLn text) `catch` (\\(_ :: SomeException) -> putStrLn "EXCEPTION")', + 'emitMaybe encode result = case result of Nothing -> putStrLn "NONE"; Just value -> emit encode (Right value)', + 'indices = intercalate "," . map show', + ] + for precision, real in [(32, "Float"), (64, "Double")]: + p = str(precision) + for name, rows, columns, values in [ + ("a", 2, 2, "[0,2,1,3]"), + ("b", 2, 2, "[2,1,0,2]"), + ("wrong", 1, 4, "[1,2,3,4]"), + ("singular", 2, 2, "[1,2,2,4]"), + ("nonfinite", 2, 2, "[0/0,2,1,3]"), + ]: + lines.append(f"{name}{p} :: M.Matrix {real}") + lines.append( + f"Right {name}{p} = M.fromListChecked {rows} {columns} {values}" + ) + lines.extend( + [ + f"Right l{p} = L.luDecompose a{p}", + f"Right q{p} = Q.qrDecompose a{p}", + f'fp{p} x = if isNaN x then "NaN" else show (cast{"FloatToWord32" if precision == 32 else "DoubleToWord64"} x)', + f'vector{p} = intercalate "," . map fp{p}', + f'matrix{p} value = let (r,c)=M.shape value in show r ++ "," ++ show c ++ ":" ++ vector{p} (M.toList value)', + f'lowerUpper{p} f = matrix{p} (L.luLower f) ++ ";" ++ matrix{p} (L.luUpper f) ++ ";" ++ indices (L.luPermutation f)', + f'orthogonal{p} f = matrix{p} (Q.qrQ f) ++ ";" ++ matrix{p} (Q.qrR f) ++ ";" ++ indices (Q.qrPermutation f) ++ ";" ++ show (Q.qrRank f)', + ] + ) + lines.append("main = do") + cases = [] + for precision in [32, 64]: + for mod, name, kinds, out, mode, expression in S: + for bad in [False, True]: + items = fixture(mod, name, kinds, bad) + arguments = [hsarg(item, precision) for item in items] + if expression: + call = expression + for index in reversed(range(len(arguments))): + call = call.replace("a" + str(index), arguments[index]) + else: + call = mod + "." + name + " " + " ".join(arguments) + prefix = "emitMaybe" if mode == "maybe" else "emit" + if mode == "pure": + call = "Right (" + call + ")" + lines.append( + " " + prefix + " " + hsencode(out, precision) + " (" + call + ")" + ) + cases.append((precision, mod, name, kinds, out, mode, items)) + with tempfile.TemporaryDirectory(prefix="hmath-matrix-oracle-") as directory: + path = Path(directory) + (path / "Main.hs").write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O2", + "-i" + str(ROOT / "src"), + "-outputdir", + directory, + str(path / "Main.hs"), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + fixtures_by_precision = {} + owned = [] + try: + for precision in [32, 64]: + dtype = "float32" if precision == 32 else "float64" + objects = {} + for name, rows, columns, values in [ + ("a", 2, 2, [0, 2, 1, 3]), + ("b", 2, 2, [2, 1, 0, 2]), + ("wrong", 1, 4, [1, 2, 3, 4]), + ("singular", 2, 2, [1, 2, 2, 4]), + ("nonfinite", 2, 2, [float("nan"), 2, 1, 3]), + ]: + objects[name] = matrix.from_list_checked( + rows, columns, values, dtype=dtype + ) + owned.append(objects[name]) + objects["l"], objects["q"] = ( + matrix.lu_decompose(objects["a"]), + matrix.qr_decompose(objects["a"]), + ) + owned.extend([objects["l"], objects["q"]]) + fixtures_by_precision[precision] = objects + for case, oracle in zip(cases, expected): + precision, mod, name, kinds, out, mode, items = case + arguments = [ + fixtures_by_precision[precision][value] if kind == "object" else value + for kind, value in items + ] + kwargs = ( + {} + if any(kind in "mlq" for kind in kinds) + else {"dtype": "float32" if precision == 32 else "float64"} + ) + value = None + try: + value = getattr(matrix, snake(name))(*arguments, **kwargs) + actual = ( + "NONE" + if value is None + else "OK:" + encode(value, out, precision, matrix) + ) + except hmath.HMathError as error: + actual = "EXCEPTION" if error.status == 6 else "ERR:" + str(error) + finally: + if value is not None and out in "mlq": + value.close() + assert actual == oracle, (precision, mod, name, arguments, actual, oracle) + finally: + for value in owned: + value.close() + hmath.shutdown() + print( + f"{len(cases)} direct Haskell ↔ C/Python Matrix/LU/QR cases passed; 52 source functions covered including shape/toList helpers." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_matrix_value_equivalence.py b/tools/check_matrix_value_equivalence.py new file mode 100644 index 0000000..ea7e37b --- /dev/null +++ b/tools/check_matrix_value_equivalence.py @@ -0,0 +1,171 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare all generic Matrix core operations against original Haskell calls.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, close, encode +from generate_matrix_bindings import S, snake + +ROOT = Path(__file__).resolve().parent.parent + + +def fixtures(matrix): + result, owners = [], [] + for dtype, hstype, precision in [ + ("integer", "Integer", 64), + ("rational", "Rational", 64), + ("complex64", "Complex Float", 32), + ("complex128", "Complex Double", 64), + ("int8", "Int8", 64), + ]: + a = matrix.from_list_checked(2, 2, [1, 2, 3, 4], dtype=dtype) + b = matrix.from_list_checked(2, 2, [2, 0, 0, 2], dtype=dtype) + owners.extend([a, b]) + ah = f"(case M.fromListChecked 2 2 [1,2,3,4] :: Either HMath.Error.MathError (M.Matrix ({hstype})) of Right x->x;Left e->error(show e))" + bh = f"(case M.fromListChecked 2 2 [2,0,0,2] :: Either HMath.Error.MathError (M.Matrix ({hstype})) of Right x->x;Left e->error(show e))" + for module, name, kinds, _out, mode, expression in S: + if module != "M": + continue + args, hsargs = [], [] + for index, kind in enumerate(kinds): + if kind == "m": + args.append(b if index and kinds == "mm" else a) + hsargs.append(bh if index and kinds == "mm" else ah) + elif kind == "v": + values = [1, 2, 3, 4] if name.startswith("fromList") else [1, 2] + args.append(values) + hsargs.append(str(values)) + elif kind == "f": + args.append(Fraction(3, 2) if dtype == "rational" else 3) + hsargs.append("(3%2)" if dtype == "rational" else "3") + else: + value = ( + [0, 0, 1, 2][index] + if name.startswith("sliceMatrix") + else [0, 0, 1][index] + if name.startswith("at") + else [1, 4][index] + if name.startswith("reshape") + else 2 + ) + args.append(value) + hsargs.append(str(value)) + code = expression or ( + "M." + name + " " + " ".join("a" + str(i) for i in range(len(args))) + ) + for index in reversed(range(len(args))): + code = code.replace("a" + str(index), hsargs[index]) + if "m" not in kinds: + resulttype = f"M.Matrix ({hstype})" + code += " :: " + ( + f"Maybe ({resulttype})" + if mode == "maybe" + else f"Either HMath.Error.MathError ({resulttype})" + ) + result.append( + ( + snake(name), + args, + {} if "m" in kinds else {"dtype": dtype}, + ("ok" if mode == "either" else "enc") + " (" + code + ")", + precision, + ) + ) + result.extend( + [ + ("shape", [a], {}, "enc (M.shape " + ah + ")", precision), + ("to_list", [a], {}, "enc (M.toList " + ah + ")", precision), + ("at", [a, -1, 0], {}, "enc (M.at " + ah + " (-1) 0)", precision), + ( + "at_checked", + [a, -1, 0], + {}, + "ok (M.atChecked " + ah + " (-1) 0)", + precision, + ), + ( + "from_list", + [-1, 2, []], + {"dtype": dtype}, + f"enc (M.fromList (-1) 2 [] :: Maybe (M.Matrix ({hstype})))", + precision, + ), + ( + "from_list_checked", + [2, 2, [1]], + {"dtype": dtype}, + f"ok (M.fromListChecked 2 2 [1] :: Either HMath.Error.MathError (M.Matrix ({hstype})))", + precision, + ), + ] + ) + return result, owners + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import matrix, polynomial + + cases, owners = fixtures(matrix) + try: + source = HASKELL.replace( + "import Data.Complex", "import Data.Int\nimport Data.Complex" + ).replace("class E a where", "class E a where") + source = source.replace( + "pR=P.polynomial", + 'instance E Int8 where enc x="I"++show x\npR=P.polynomial', + ) + source = source.replace( + "EXPRESSIONS", "\n , ".join(case[3] for case in cases) + ) + with tempfile.TemporaryDirectory( + prefix="hmath-matrix-value-oracle-" + ) as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + expected = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=True, + ).stdout.splitlines() + actual = [] + for name, arguments, kwargs, _expression, precision in cases: + try: + value = getattr(matrix, name)(*arguments, **kwargs) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(value, polynomial, precision)) + finally: + close(value) + errors = [ + (cases[i][0], expected[i], actual[i]) + for i in range(len(actual)) + if expected[i] != actual[i] + ] + if errors: + raise AssertionError(errors[:10]) + print( + f"Generic Matrix direct Haskell equivalence: {len(actual)} cases, Integer/Rational/ComplexFloat/ComplexDouble/Int8" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_numeric_equality.py b/tools/check_numeric_equality.py new file mode 100644 index 0000000..6fcc9dc --- /dev/null +++ b/tools/check_numeric_equality.py @@ -0,0 +1,384 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Direct-source Eq semantics for Geometry distances and opaque numeric records.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def bits(value): + return ( + "nan" + if math.isnan(value) + else str(struct.unpack("!Q", struct.pack("!d", value))[0]) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import _value as v + from _hmath_native import algebra_api as aa + from _hmath_native import autodiff as ad + from _hmath_native import geometry as g + from _hmath_native import numeric_types as n + + owners, fixtures = [], [] + + def own(value): + owners.append(value) + return value + + def fixture(label, first, second, hs_first, hs_second): + fixtures.append((label, first, second, hs_first, hs_second)) + + huge = 10**160 + fixture( + "hugeInteger", huge, huge + 1, f"({huge}::Integer)", f"({huge + 1}::Integer)" + ) + fixture( + "closeRational", + Fraction(1, huge), + Fraction(1, huge + 1), + f"1%{huge}", + f"1%{huge + 1}", + ) + fixture("Bool", False, True, "False", "True") + fixture("String/NUL/Unicode", "a\0가", "a\0나", '"a\\0가"', '"a\\0나"') + fixture( + "tuple labels", + (huge, "a"), + (huge + 1, "a"), + f'({huge}::Integer,"a")', + f'({huge + 1}::Integer,"a")', + ) + fixture( + "list labels", + [huge, 2], + [huge + 1, 2], + f"[{huge},2::Integer]", + f"[{huge + 1},2::Integer]", + ) + fixture("Maybe", None, 3, "Nothing::Maybe Integer", "Just 3") + for dtype, typ in [ + ("float32", "Float"), + ("float64", "Double"), + ("complex64", "Complex Float"), + ("complex128", "Complex Double"), + ("int64", "Int64"), + ("uint64", "Word64"), + ]: + complex_type = dtype.startswith("complex") + first, second = (complex(1, 2), complex(1, 3)) if complex_type else (1, 2) + fixture( + dtype, + own(v.scalar(first, dtype)), + own(v.scalar(second, dtype)), + "((1:+2)::" + typ + ")" if complex_type else "(1::" + typ + ")", + "((1:+3)::" + typ + ")" if complex_type else "(2::" + typ + ")", + ) + one = own(n.number(1, "integer")) + two = own(n.number(2, "integer")) + nd1, nd2 = own(n.dual(one, one)), own(n.dual(one, two)) + fixture( + "Numeric.Dual exact tangent equality", + nd1, + nd2, + "N.Dual (1::Integer) 1", + "N.Dual (1::Integer) 2", + ) + fixture( + "nested Numeric.Dual", + own(n.dual(nd1, nd2)), + own(n.dual(nd2, nd1)), + "N.Dual (N.Dual (1::Integer) 1)(N.Dual 1 2)", + "N.Dual (N.Dual (1::Integer) 2)(N.Dual 1 1)", + ) + for dtype, typ in [("float32", "Float"), ("float64", "Double")]: + x, y = own(n.number(1.0, dtype)), own(n.number(2.0, dtype)) + q1, q2 = own(n.quaternion(x, x, x, x)), own(n.quaternion(x, x, x, y)) + fixture( + "Numeric.Quaternion " + dtype, + q1, + q2, + "N.Quaternion(1::" + typ + ") 1 1 1", + "N.Quaternion(1::" + typ + ") 1 1 2", + ) + fixture( + "Numeric.DualQuaternion " + dtype, + own(n.dual_quaternion(q1, q1)), + own(n.dual_quaternion(q1, q2)), + "N.DualQuaternion(N.Quaternion(1::" + + typ + + ") 1 1 1)(N.Quaternion 1 1 1 1)", + "N.DualQuaternion(N.Quaternion(1::" + + typ + + ") 1 1 1)(N.Quaternion 1 1 1 2)", + ) + fixture( + "AD.Dual uses full Eq rather than primal Ord", + own(ad.Dual(1.0, 1.0)), + own(ad.Dual(1.0, 2.0)), + "A.Dual(1::Double) 1", + "A.Dual(1::Double) 2", + ) + fixture( + "AD.Dual Complex no Ord", + own(ad.Dual(1 + 2j, 3 + 4j)), + own(ad.Dual(1 + 2j, 3 + 5j)), + "A.Dual((1:+2)::Complex Double)(3:+4)", + "A.Dual((1:+2)::Complex Double)(3:+5)", + ) + fixture( + "Exact Ord/Eq", + own(aa.Exact(Fraction(1, 3))), + own(aa.Exact(Fraction(2, 3))), + "AA.Exact(1%3)", + "AA.Exact(2%3)", + ) + fixture( + "Point2 Eq", + own(g.p2(1.0, 2.0)), + own(g.p2(1.0, 3.0)), + "G.P2 1 2", + "G.P2 1 3", + ) + fixture( + "NaN Eq remains nonreflexive", + math.nan, + math.nan, + "(0/0::Double)", + "(0/0::Double)", + ) + half1, half2 = own(n.float16_from_bits(0x7E01)), own(n.float16_from_bits(0x7E02)) + fixture( + "Float16 original bit Eq including NaN", + half1, + half2, + "N.float16FromBits 32257", + "N.float16FromBits 32258", + ) + fixture( + "BFloat16 original bit Eq", + own(n.bfloat16_from_bits(0x7FC1)), + own(n.bfloat16_from_bits(0x7FC2)), + "N.bfloat16FromBits 32705", + "N.bfloat16FromBits 32706", + ) + nearest = n.RoundingMode.NEAREST_EVEN + for label, constructor, source in [ + ( + "BigFloat", + lambda precision: n.big_float(precision, nearest, Fraction(1, 2)), + "N.bigFloat", + ), + ( + "Fixed", + lambda precision: n.fixed(precision, nearest, Fraction(1, 2)), + "N.fixed", + ), + ( + "Decimal", + lambda precision: n.decimal(precision, nearest, Fraction(1, 2)), + "N.decimal", + ), + ]: + a = own(n.rounded_value(own(constructor(3)))) + b = own(n.rounded_value(own(constructor(4)))) + fixture( + label + " precision/scale participates in Eq", + a, + b, + "N.roundedValue(right(" + source + " 3 N.NearestEven(1%2)))", + "N.roundedValue(right(" + source + " 4 N.NearestEven(1%2)))", + ) + fixture( + "Interval", + own(n.interval(-0.0, 2.0)), + own(n.interval(0.0, 3.0)), + "right(N.interval (-0.0) 2)", + "right(N.interval 0 3)", + ) + fixture( + "Rounded flags and ordering", + own( + n.rounded( + half1, [n.NumericException.INEXACT, n.NumericException.NUMERIC_OVERFLOW] + ) + ), + own( + n.rounded( + half1, [n.NumericException.NUMERIC_OVERFLOW, n.NumericException.INEXACT] + ) + ), + "N.Rounded(N.float16FromBits 32257)[N.Inexact,N.NumericOverflow]", + "N.Rounded(N.float16FromBits 32257)[N.NumericOverflow,N.Inexact]", + ) + fixture( + "Limits every metadata field", + own(n.float16_limits()), + own( + n.numeric_limits_record( + 2.0**-14, + 2.0**-24, + 65504.0, + 2.0**-10, + 12, + -13, + 16, + ) + ), + "N.float16Limits", + "N.NumericLimits(2**(-14)::Double)(2**(-24)) 65504 (2**(-10)) 12 (-13) 16", + ) + fixture( + "Constant metadata and exact rationals", + own( + n.constant( + "x\0", + Fraction(1, 3), + Fraction(1, 10**100), + Fraction(1, 10**110), + "m", + "s", + ) + ), + own( + n.constant( + "x\0", + Fraction(1, 3), + Fraction(1, 10**100), + Fraction(1, 10**110), + "m", + "other", + ) + ), + 'K.Constant "x\\0"(1%3)(1%10^100)(1%10^110) "m" "s"', + 'K.Constant "x\\0"(1%3)(1%10^100)(1%10^110) "m" "other"', + ) + + tests = [] + for label, a, b, ha, hb in fixtures: + for name, py, encoder in [ + ("hammingDistance", g.hamming_distance, str), + ("jaccardDistance", g.jaccard_distance, bits), + ]: + for suffix, xs, ys, hxs, hys in [ + ("self", [a], [a], "[" + ha + "]", "[" + ha + "]"), + ("different", [a], [b], "[" + ha + "]", "[" + hb + "]"), + ( + "duplicates", + [a, a, b], + [b, a, b], + "[" + ha + "," + ha + "," + hb + "]", + "[" + hb + "," + ha + "," + hb + "]", + ), + ]: + tests.append( + ( + label + " " + name + " " + suffix, + "G." + name + "(" + hxs + ")(" + hys + ")", + "show" if name == "hammingDistance" else "fp64", + lambda py=py, xs=xs, ys=ys, encoder=encoder: encoder( + py(xs, ys, dtype="value") + ), + ) + ) + for name, py, encoder in [ + ("hammingDistance", g.hamming_distance, str), + ("jaccardDistance", g.jaccard_distance, bits), + ]: + tests.append( + ( + name + " empty", + "G." + name + "([]::[Integer]) []", + "show" if name == "hammingDistance" else "fp64", + lambda py=py, encoder=encoder: encoder(py([], [], dtype="value")), + ) + ) + tests.append( + ( + "hamming length error", + "G.hammingDistance([1]::[Integer]) []", + "show", + lambda: str(g.hamming_distance([1], [], dtype="value")), + ) + ) + lines = [ + "module Main where", + "import qualified HMath.Geometry as G", + "import qualified HMath.Numeric as N", + "import qualified HMath.Autodiff as A", + "import qualified HMath.Constants as K", + "import qualified HMath.API.Algebra as AA", + "import HMath.Error", + "import Data.Complex", + "import Data.Ratio", + "import Data.Int", + "import Data.Word", + "import GHC.Float", + "right(Right x)=x", + "right(Left e)=error(show e)", + 'fp64 x=if isNaN x then "nan" else show(castDoubleToWord64 x)', + "emit :: (a->String)->Either MathError a->IO ()", + 'emit e= either(putStrLn . ("ERR:"++) . show)(putStrLn . ("OK:"++) . e)', + "main=do", + ] + lines.extend( + " emit " + encoder + " (" + expression + ")" + for _, expression, encoder, _ in tests + ) + with tempfile.TemporaryDirectory(prefix="hmath-equality-oracle-") as directory: + path = Path(directory) + (path / "Main.hs").write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-Iinclude", + "-outputdir", + directory, + "-stubdir", + directory, + str(path / "Main.hs"), + "cbits/backend.c", + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(tests) + for (label, _, _, call), wanted in zip(tests, expected): + try: + actual = "OK:" + call() + except hmath.HMathError as error: + assert error.math_error is not None, (label, error) + actual = "ERR:" + str(error.math_error) + assert actual == wanted, (label, actual, wanted) + for owner in reversed(owners): + owner.close() + print( + f"Geometry Eq: {len(expected)} direct original-Haskell cases, exact/structural labels, distinct Dual semantics, NaN and all opaque NumericTypes Eq records passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_numeric_equivalence.py b/tools/check_numeric_equivalence.py new file mode 100644 index 0000000..e70a68f --- /dev/null +++ b/tools/check_numeric_equivalence.py @@ -0,0 +1,493 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare every numeric binding with independent direct Haskell evaluation. + +The oracle imports the original public modules, never the generated FFI. Float +and Double results are compared by IEEE bits (NaNs by class). Errors compare +the full MathError constructor/payload. Pure exceptions compare failure kind. +""" + +import argparse +import importlib +import json +import math +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from generate_numeric_bindings import namespace +from numeric_specializations import BOUNDED, binding_variants + +ROOT = Path(__file__).resolve().parent.parent + + +def variant_fixtures(entry, variant): + dtype = variant["dtype"] + if not entry.get("specializations") or dtype in ("float32", "float64"): + yield from fixtures(entry) + return + if dtype in BOUNDED: + _, _, bits, signed, _ = BOUNDED[dtype] + bits = bits or struct.calcsize("P") * 8 + low = -(1 << (bits - 1)) if signed else 0 + high = (1 << (bits - 1)) - 1 if signed else (1 << bits) - 1 + else: + low, high = -(10**100 + 123), 10**100 + 123 + for case in range(4): + arguments = [] + for index, argument in enumerate(variant["args"]): + kind = argument["type"] + if kind == "q": + value = [ + Fraction(10**100 + index + 1, 3 + 2 * index), + Fraction(-1, 7), + Fraction(0), + Fraction(1, 3 + 2 * index), + ][case] + elif kind == "qs": + value = [ + [Fraction(10**100 + 1, 3), Fraction(-1, 7)], + [], + [Fraction(0)], + [Fraction(1, 3), Fraction(1, 7)], + ][case] + elif kind == "c": + value = [ + complex(0.25 + index, 0.5), + complex(-1, 2), + complex(-0.0, -0.0), + complex(2, -3), + ][case] + elif kind == "cs": + value = [ + [complex(1, 2), complex(-3, 0.25)], + [], + [complex(-0.0, -0.0)], + [complex(2, -3)], + ][case] + elif kind.endswith("s"): + value = [[high, 1, low], [], [0], [low, low]][case] + else: + value = [ + high if index == 0 else 1, + low if index == 0 else (1 if low == 0 else -1), + 0, + low if index == 0 else high, + ][case] + arguments.append(value) + yield arguments + + +def result_type(result, real): + if result in BOUNDED: + return BOUNDED[result][1] + if result.endswith("d") and result[:-1] in BOUNDED: + return "[" + BOUNDED[result[:-1]][1] + "]" + return { + "f": real, + "fs": f"[{real}]", + "fd": f"[{real}]", + "z": "Integer", + "i": "Int", + "b": "Bool", + "q": "Rational", + "zd": "[Integer]", + "id": "[Int]", + "qd": "[Rational]", + "cd": f"[Complex {real}]", + "zz": "(Integer,Integer)", + "zzz": "(Integer,Integer,Integer)", + "zzzz": "(Integer,Integer,Integer,Integer)", + "ff": f"({real},{real})", + "c": f"(Complex {real})", + }[result] + + +def fixtures(entry): + # Domain-valid nontrivial inputs complement the generic boundary cases. + # These are test data, never replacement formulas or implementation code. + name, module = entry["name"], entry["module"] + valid = None + if module in ("HMath.Statistics.Advanced", "HMath.Signal", "HMath.Fourier"): + valid = [ + {"f": 0.1, "i": 1, "b": False, "fs": [0.1, 0.2, 0.3, 0.4]}[a["type"]] + for a in entry["args"] + ] + if module == "HMath.Special": + valid = [ + { + "f": 0.5, + "i": 0, + "b": True, + "fs": [0.5], + "is": [0] * 9, + "c": complex(0.5, 0.1), + }[a["type"]] + for a in entry["args"] + ] + overrides = { + "hypergeometric": [[0.5], [1.5], 0.5], + "complex1F1": [complex(0.5), complex(1.5), complex(0.5, 0.1)], + "hankel": [1, 0, 0.5], + "hurwitzZeta": [2.0, 0.5], + "debye": [1, 0.5], + "boseEinstein": [0.5, -0.5], + } + valid = overrides.get(name, valid) + valid = { + ("HMath.Combinatorics", "inclusionExclusion"): [2, [1, 2, 3]], + ("HMath.Combinatorics", "rankPermutation"): [[2, 0, 1]], + ("HMath.NumberTheory", "discreteLog"): [1000, 2, 3, 5], + ("HMath.NumberTheory", "multiplicativeOrder"): [1000, 2, 5], + ("HMath.NumberTheory", "pellFundamental"): [1000, 2], + ("HMath.Probability", "multinomialPMF"): [[0.25, 0.75], [1, 3]], + ("HMath.Probability", "dirichletDensity"): [[1.0, 2.0], [0.25, 0.75]], + ("HMath.Probability", "bayes"): [[0.25, 0.75], [0.5, 0.25]], + ("HMath.Statistics.Advanced", "normalSampleSize"): [0.05, 0.8, 0.5], + ("HMath.Signal", "savitzkyGolay"): [5, 2, 1, 1.0, [1, 2, 4, 8, 16, 32, 64]], + ("HMath.Signal", "downsample"): [2, 0, [1, 2, 3, 4]], + }.get((module, name), valid) + if valid is not None: + yield valid + for case in range(4 if entry["args"] else 1): + arguments = [] + for index, arg in enumerate(entry["args"]): + kind = arg["type"] + value = [0.25 + index * 0.5, -1.0, 0.0, float("nan")][case] + if kind == "f": + arguments.append(value) + elif kind in ("z", "i"): + arguments.append([5, -1, 0, 2][case]) + elif kind == "b": + arguments.append([True, False, False, True][case]) + elif kind == "q": + arguments.append( + [Fraction(5, 3), Fraction(-1, 2), Fraction(0), Fraction(2, 7)][case] + ) + elif kind in ("zs", "is"): + arguments.append([[1, 3, 2], [], [-1], [0, 2]][case]) + elif kind in ("p", "c"): + pair = (value, value / 2) + arguments.append(complex(*pair) if kind == "c" else pair) + elif kind == "fs": + arguments.append( + [[1.0, 3.0, 2.0], [], [-0.0], [1.0, float("nan")]][case] + ) + yield arguments + + +def hsreal(value): + return "(0/0)" if math.isnan(value) else "(" + repr(value) + ")" + + +def hsarg(kind, value, real): + if kind in BOUNDED: + return f"({value} :: {BOUNDED[kind][1]})" + if kind.endswith("s") and kind[:-1] in BOUNDED: + return f"({value!r} :: [{BOUNDED[kind[:-1]][1]}])" + if kind in ("i", "z"): + return f"({value})" + if kind == "f": + return f"({hsreal(value)} :: {real})" + if kind == "b": + return "True" if value else "False" + if kind == "q": + return f"({value.numerator} % {value.denominator})" + if kind == "qs": + return "([" + ",".join(hsarg("q", v, real) for v in value) + "] :: [Rational])" + if kind == "cs": + return ( + "([" + + ",".join(hsarg("c", v, real) for v in value) + + f"] :: [Complex {real}])" + ) + if kind in ("zs", "is"): + return ( + "([" + + ",".join(str(v) for v in value) + + "] :: [" + + ("Integer" if kind == "zs" else "Int") + + "])" + ) + if kind == "p": + return f"({hsarg('f', value[0], real)}, {hsarg('f', value[1], real)})" + if kind == "c": + return f"({hsarg('f', value.real, real)} :+ {hsarg('f', value.imag, real)})" + if kind == "fs": + return "([" + ",".join(map(hsreal, value)) + f"] :: [{real}])" + raise ValueError(kind) + + +def hsencode(result, precision): + encode = "fp32" if precision == "float32" else "fp64" + if result in BOUNDED: + return "show" + if result.endswith("d") and result[:-1] in BOUNDED: + return '(intercalate "," . map show)' + if result == "cd": + return f'(intercalate ";" . map (\\x -> {encode} (realPart x) ++ "," ++ {encode} (imagPart x)))' + if result == "f": + return encode + if result in ("z", "i", "b"): + return "show" + if result in ("fs", "fd"): + return f'(intercalate "," . map {encode})' + if result in ("zd", "id"): + return '(intercalate "," . map show)' + if result == "qd": + return '(intercalate "," . map (\\x -> show (numerator x) ++ "/" ++ show (denominator x)))' + sf = f'(\\x -> {encode} (HMath.Special.sfValue x) ++ "," ++ {encode} (HMath.Special.sfError x))' + if result == "sf": + return sf + if result in ("sf2", "sf4"): + vs = ["a", "b"] if result == "sf2" else ["a", "b", "c", "d"] + return ( + "(\\(" + + ",".join(vs) + + ') -> intercalate "," [' + + ",".join(sf + " " + v for v in vs) + + "])" + ) + if result == "fsf": + return f'(\\(a,b) -> {encode} a ++ "," ++ {sf} b)' + if result == "q": + return '(\\x -> show (numerator x) ++ "," ++ show (denominator x))' + if result == "c": + return f'(\\x -> {encode} (realPart x) ++ "," ++ {encode} (imagPart x))' + encoders = ["show" if t == "z" else encode for t in result] + variables = ["a", "b", "c", "d"][: len(encoders)] + return ( + "(\\(" + + ",".join(variables) + + ') -> intercalate "," [' + + ",".join(f"{enc} {var}" for enc, var in zip(encoders, variables)) + + "])" + ) + + +def pyencode(result, value, precision): + def fp(number): + if math.isnan(number): + return "NaN" + return str( + struct.unpack( + "!I" if precision == "float32" else "!Q", + struct.pack("!f" if precision == "float32" else "!d", number), + )[0] + ) + + if result in BOUNDED: + return str(value) + if result.endswith("d") and result[:-1] in BOUNDED: + return ",".join(map(str, value)) + if result == "cd": + return ";".join(fp(v.real) + "," + fp(v.imag) for v in value) + if result == "f": + return fp(value) + if result in ("z", "i", "b"): + return str(value) + if result in ("fs", "fd", "sf"): + return ",".join(map(fp, value)) + if result in ("zd", "id"): + return ",".join(map(str, value)) + if result == "qd": + return ",".join(f"{v.numerator}/{v.denominator}" for v in value) + if result in ("sf2", "sf4"): + return ",".join(fp(component) for sf in value for component in sf) + if result == "fsf": + return fp(value[0]) + "," + ",".join(map(fp, value[1])) + if result == "q": + return f"{value.numerator},{value.denominator}" + if result == "c": + return f"{fp(value.real)},{fp(value.imag)}" + return ",".join( + str(item) if kind == "z" else fp(item) for kind, item in zip(result, value) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + parser.add_argument( + "--oracle-builddir", + type=Path, + help="Optional GHC object cache for repeated local checks", + ) + parser.add_argument( + "--optimization", + choices=("0", "1", "2"), + default="2", + help="Match the source algorithms to the native library's GHC optimization level", + ) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + entries = json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + lines = [ + # The oracle's source algorithms use the library optimization level; + # its large fixture driver does not need optimization. + "{-# OPTIONS_GHC -O0 #-}", + "{-# LANGUAGE ScopedTypeVariables #-}", + "import Control.Exception", + "import Data.List (intercalate)", + "import Data.Complex", + "import Data.Ratio", + "import Data.Int", + "import Data.Word", + "import GHC.Float", + "import HMath.Error", + "import qualified HMath.Optimization.FirstOrder as O", + ] + lines += [f"import qualified {m}" for m in sorted({e["module"] for e in entries})] + lines += [ + 'fp32 x = if isNaN x then "NaN" else show (castFloatToWord32 x)', + 'fp64 x = if isNaN x then "NaN" else show (castDoubleToWord64 x)', + "{-# NOINLINE opaque #-}", + "opaque :: a -> a", + "opaque x = x", + 'emit encode value = (do let text = either (("ERR:" ++) . show) (("OK:" ++) . encode) value', + " evaluate (length text)", + ' putStrLn text) `catch` (\\(_ :: SomeException) -> putStrLn "EXCEPTION")', + "steps method k state point | k > 20 = Right []", + "steps method k state point = do", + " (next, nextState) <- O.optimizerStep method 0.01 state point [fromIntegral (k `mod` 3) - 1, fromIntegral k * 0.25, -0.5]", + " rest <- steps method (k+1) nextState next", + " Right (next ++ rest)", + "main = do", + ' if castFloatToWord32 (opaque ((-0.0) :: Float)) /= 2147483648 then error "oracle lost Float input sign bit" else pure ()', + ' if castDoubleToWord64 (opaque ((-0.0) :: Double)) /= 9223372036854775808 then error "oracle lost Double input sign bit" else pure ()', + ] + cases = [] + for entry in entries: + for variant in binding_variants(entry): + bits = variant["precision"] + precision = f"float{bits}" if bits else None + for arguments in variant_fixtures(entry, variant): + real = "Float" if precision == "float32" else "Double" + call = ( + entry["module"] + + "." + + entry["name"] + + " " + + " ".join( + "(opaque " + hsarg(arg["type"], value, real) + ")" + for arg, value in zip(variant["args"], arguments) + ) + ) + if not entry["args"]: + call = f"({call} :: {real})" + if not entry["checked"]: + call = ( + f"(Right ({call}) :: Either MathError " + + result_type(variant["result"], real) + + ")" + ) + lines.append( + f" emit {hsencode(variant['result'], precision)} ({call})" + ) + cases.append((entry, variant, arguments)) + lines.append( + ' mapM_ (\\method -> emit (intercalate "," . map fp64) (O.initializeOptimizer 3 >>= \\state -> steps method (1 :: Int) state [1,-2,3])) [minBound..maxBound]' + ) + with tempfile.TemporaryDirectory(prefix="hmath-numeric-oracle-") as directory: + path = Path(directory) + object_path = args.oracle_builddir or path + object_path.mkdir(parents=True, exist_ok=True) + (path / "Main.hs").write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O" + args.optimization, + "-i" + str(ROOT / "src"), + "-outputdir", + str(object_path), + str(path / "Main.hs"), + str(ROOT / "cbits/backend.c"), + "-I" + str(ROOT / "include"), + "-optc-std=c11", + *(["-ldl"] if sys.platform.startswith("linux") else []), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + 12, (len(expected), len(cases)) + for (entry, variant, arguments), oracle in zip(cases, expected): + precision = f"float{variant['precision']}" if variant["precision"] else None + function = getattr( + importlib.import_module("_hmath_native." + namespace(entry)), + entry["python"], + ) + try: + if entry.get("specializations") and variant["legacy"]: + from _hmath_native._numeric import _call + from generate_numeric_bindings import prefix + + value = _call( + prefix(entry), + [a["type"] for a in variant["args"]], + variant["result"], + arguments, + precision, + entry.get("result_extra", 0), + symbol_suffix=variant["suffix"], + ) + else: + dtype = variant["dtype"] + value = function(*arguments, **({"dtype": dtype} if dtype else {})) + actual = "OK:" + pyencode(variant["result"], value, precision) + except hmath.HMathError as error: + actual = "EXCEPTION" if error.status == 6 else "ERR:" + str(error) + assert actual == oracle, ( + entry["module"], + entry["name"], + variant["dtype"], + arguments, + actual, + oracle, + ) + from _hmath_native import algorithms + from hmath import optimization + + for precision in ("float32", "float64"): + # partialSort is an identity for a single element: this verifies that + # the common Python→C→Haskell→C→Python array transport retains -0 bits. + value = algorithms.partial_sort(1, [-0.0], dtype=precision) + expected_zero = ( + "2147483648" if precision == "float32" else "9223372036854775808" + ) + assert pyencode("fs", value, precision) == expected_zero + + for method, oracle in zip(optimization.GradientMethod, expected[len(cases) :]): + state = optimization.initialize_optimizer(3) + point, values = [1, -2, 3], [] + try: + for step in range(1, 21): + point, next_state = optimization.optimizer_step( + method, 0.01, state, point, [step % 3 - 1, step * 0.25, -0.5] + ) + state.close() + state = next_state + values.extend(point) + finally: + state.close() + actual = "OK:" + pyencode("fs", values, "float64") + assert actual == oracle, (method, actual, oracle) + print( + f"{len(cases)} direct Haskell ↔ C/Python equivalence cases passed ({len(entries)} functions), plus 20 steps of all 12 optimizers." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_numeric_objects_equivalence.py b/tools/check_numeric_objects_equivalence.py new file mode 100644 index 0000000..662190f --- /dev/null +++ b/tools/check_numeric_objects_equivalence.py @@ -0,0 +1,542 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Actual Haskell instances for generic numerical owner specializations.""" + +import argparse +import importlib +import json +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close + +ROOT = Path(__file__).resolve().parent.parent +REQUIRES = { + "clamp": {"Ord"}, + "minimumScalar": {"Ord"}, + "maximumScalar": {"Ord"}, + "lerp": {"Fractional"}, + "mean": {"Fractional"}, + "variance": {"Fractional"}, + "standardDeviation": {"Floating"}, + "magnitude": {"Floating"}, + "normalize": {"Floating", "Eq"}, + "median": {"Fractional", "Ord"}, + "positiveModulo": {"Integral"}, + **{ + name: {"Integral", "Bounded"} + for name in [ + "saturatingAdd", + "saturatingSubtract", + "saturatingMultiply", + "checkedAdd", + "checkedSubtract", + "checkedMultiply", + ] + }, +} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import _value as v + from _hmath_native import algebra_api, geometry + from _hmath_native import autodiff as ad + from _hmath_native import numeric_types as n + + entries = [ + entry + for entry in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + if entry.get("specializations") + ] + assert len(entries) == 31 + modules = { + name: importlib.import_module("_hmath_native." + name.lower()) + for name in ["Basic", "Scalar", "Linear", "Statistics"] + } + owners = [] + domains = [] + tests = [] + expressions = [] + denied = [] + covered = set() + + def own(value): + owners.append(value) + return value + + def primitive( + dtype, + hstype, + kind, + fractional=False, + floating=False, + ordered=True, + integral=False, + bounded=False, + ): + capabilities = ( + {"Num", "Eq"} + | ({"Fractional"} if fractional else set()) + | ({"Floating"} if floating else set()) + | ({"Ord"} if ordered else set()) + | ({"Integral"} if integral else set()) + | ({"Bounded"} if bounded else set()) + ) + + def factory(index): + raw = ( + Fraction(index + 2, 3) + if dtype == "rational" + else complex(index + 2, index / 4) + if kind == "complex" + else float(index + 2) + if kind == "float" + else index + 2 + ) + text = ( + f"(({index + 2}%3)::Rational)" + if dtype == "rational" + else f"({index + 2}:+({index}/4)::{hstype})" + if kind == "complex" + else f"({index + 2}::{hstype})" + ) + return own(n.number(raw, dtype)), text + + domain = { + "name": dtype, + "type": hstype, + "factory": factory, + "caps": capabilities, + "precision": 32 if dtype in ("float32", "complex64") else 64, + } + domains.append(domain) + return domain + + bases = {} + for arguments in [ + ("integer", "Integer", "int", False, False, True, True, False), + ("rational", "Rational", "rational", True, False, True, False, False), + ("float32", "Float", "float", True, True, True, False, False), + ("float64", "Double", "float", True, True, True, False, False), + ("complex64", "Complex Float", "complex", True, True, False, False, False), + ("complex128", "Complex Double", "complex", True, True, False, False, False), + ("int8", "Int8", "int", False, False, True, True, True), + ("uint64", "Word64", "int", False, False, True, True, True), + ]: + bases[arguments[0]] = primitive(*arguments) + + def dual_domain(base, family): + constructor = "N.Dual" if family == "numeric" else "AD.Dual" + + def factory(index): + a, hs_a = base["factory"](index) + b, hs_b = base["factory"](0) + value = ( + n.dual(a, b) + if family == "numeric" + else ad.Dual(a, b) + if isinstance(a, ad.Dual) + else ad.Dual(a, b, dtype=a) + ) + return own(value), "(" + constructor + "(" + hs_a + ")(" + hs_b + "))" + + caps = (base["caps"] & {"Fractional", "Floating", "Eq"}) | {"Num"} + if family == "ad" and "Ord" in base["caps"]: + caps.add("Ord") + domain = { + "name": family + ".Dual(" + base["name"] + ")", + "type": constructor + "(" + base["type"] + ")", + "factory": factory, + "caps": caps, + "precision": base["precision"], + } + domains.append(domain) + return domain + + numeric_duals = { + name: dual_domain(bases[name], "numeric") + for name in ["integer", "rational", "float32", "float64"] + } + dual_domain(numeric_duals["float64"], "numeric") + quaternions = {} + for name in ["float32", "float64"]: + base = bases[name] + + def factory(index, base=base): + values = [base["factory"](index + j) for j in range(4)] + return own( + n.quaternion(*(x for x, _ in values)) + ), "(N.Quaternion " + " ".join("(" + h + ")" for _, h in values) + ")" + + domain = { + "name": "Quaternion(" + name + ")", + "type": "N.Quaternion(" + base["type"] + ")", + "factory": factory, + "caps": {"Num", "Eq"}, + "precision": base["precision"], + } + domains.append(domain) + quaternions[name] = domain + dual_domain(quaternions["float64"], "numeric") + ad_duals = { + name: dual_domain(bases[name], "ad") + for name in ["integer", "rational", "float32", "float64"] + } + dual_domain(ad_duals["float64"], "ad") + dual_domain(numeric_duals["float64"], "ad") + dual_domain(quaternions["float64"], "ad") + dual_domain(bases["complex128"], "ad") + + def expression(index): + x = own(ad.variable(index % 2)) + constant = own(ad.constant(index + 2.0)) + return own(x + constant), "(AD.variable " + str( + index % 2 + ) + "+AD.constant " + str(index + 2) + ")" + + domains.append( + { + "name": "AD.Expr", + "type": "AD.Expr", + "factory": expression, + "caps": {"Num", "Fractional", "Floating"}, + "precision": 64, + } + ) + + def encode(value, precision=64): + if isinstance(value, ad.Expr): + observed = [] + for point in [[1.25, 2.5], [-1.0, 3.0]]: + try: + observed.append(encode(ad.value_and_gradient(value, point), 64)) + except hmath.HMathError as error: + if error.math_error is None: + raise + observed.append("E" + str(error.math_error)) + return "EXPR(L[" + ",".join(observed) + "])" + if isinstance(value, ad.Dual): + parts = [value.primal, value.tangent] + try: + return "AD(" + ",".join(encode(part, precision) for part in parts) + ")" + finally: + close(parts) + if isinstance(value, v.Value): + kind, dtype, _ = value.info + if kind == 1 and dtype == 20: + parts = [n.primal(value, boxed=True), n.tangent(value, boxed=True)] + try: + return ( + "ND(" + + ",".join(encode(part, precision) for part in parts) + + ")" + ) + finally: + close(parts) + if kind == 1 and dtype == 21: + parts = [ + n.quaternion_component(value, index, boxed=True) + for index in range(4) + ] + try: + return ( + "Q(" + ",".join(encode(part, precision) for part in parts) + ")" + ) + finally: + close(parts) + if kind == 1: + precision = 32 if dtype in (1, 5) else 64 + raw = v.decode(value.clone()) + return encode(raw, precision) + if kind == 400: + return "EXACT(" + encode(algebra_api.get_exact(value), precision) + ")" + if kind == 169: + return "POINT(" + encode(value.coordinates, 64) + ")" + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + return f"F{precision}:" + str(bits(value, precision)) + if isinstance(value, complex): + return ( + f"C{precision}:" + + str(bits(value.real, precision)) + + ":" + + str(bits(value.imag, precision)) + ) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(x)) for x in value) + "]" + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(x, precision) for x in value) + + "]" + ) + raise TypeError(type(value)) + + def add(entry, domain, values, hsargs, kwargs=None, name=None): + function = getattr(modules[entry["module"].split(".")[-1]], entry["python"]) + checked = entry.get("checked", False) + expression = ( + entry["module"].split(".")[-1] + + "." + + entry["name"] + + " " + + " ".join("(" + h + ")" for h in hsargs) + ) + expressions.append(("ok" if checked else "enc") + "(" + expression + ")") + tests.append( + ( + function, + values, + kwargs or {}, + domain["precision"], + name or domain["name"] + ":" + entry["name"], + ) + ) + covered.add(entry["module"] + "." + entry["name"]) + + for domain in domains: + samples = [domain["factory"](index) for index in range(3)] + for entry in entries: + required = REQUIRES.get(entry["name"], {"Num"}) + if not required <= domain["caps"]: + denied.append((entry, domain, samples)) + continue + values = [] + hsargs = [] + for index, argument in enumerate(entry["args"]): + if argument["type"] == "fs": + values.append([x for x, _ in samples]) + hsargs.append("[" + ",".join(h for _, h in samples) + "]") + else: + x, h = samples[index % 3] + values.append(x) + hsargs.append(h) + add(entry, domain, values, hsargs) + # Explicit prototypes on empties preserve the actual additive identity, + # nested zero tower and source empty-list exceptions. + for entry in entries: + name = entry["name"] + if name not in [ + "dot", + "dotChecked", + "add", + "addChecked", + "subtractChecked", + "magnitude", + "normalize", + "cumulativeSum", + "prefixSum", + "cumulativeProduct", + "mean", + "variance", + "standardDeviation", + "median", + ]: + continue + if not all(arg["type"] == "fs" for arg in entry["args"]): + continue + if not REQUIRES.get(name, {"Num"}) <= domain["caps"]: + continue + if entry["module"] == "HMath.Scalar" and name == "add": + continue + add( + entry, + domain, + [[] for _ in entry["args"]], + ["([]::[" + domain["type"] + "])" for _ in entry["args"]], + {"dtype": samples[0][0]}, + domain["name"] + ":empty:" + name, + ) + for name, low, high, value, hs_low, hs_high, hs_value in [ + ("Bool", False, True, True, "False", "True", "True"), + ("String", "α", "ω", "β", '"α"', '"ω"', '"β"'), + ( + "Tuple", + (1, "a"), + (4, "z"), + (2, "b"), + '(1::Integer,"a")', + '(4::Integer,"z")', + '(2::Integer,"b")', + ), + ( + "NestedList", + [[1]], + [[4]], + [[], [3]], + "[[1::Integer]]", + "[[4::Integer]]", + "[[],[3::Integer]]", + ), + ( + "Exact", + own(algebra_api.Exact(Fraction(1, 3))), + own(algebra_api.Exact(Fraction(4, 3))), + own(algebra_api.Exact(Fraction(2, 3))), + "API.Exact(1%3)", + "API.Exact(4%3)", + "API.Exact(2%3)", + ), + ( + "Point2", + own(geometry.point2(1.0, 2.0)), + own(geometry.point2(4.0, 5.0)), + own(geometry.point2(2.0, 3.0)), + "G.P2 1 2", + "G.P2 4 5", + "G.P2 2 3", + ), + ]: + for entry in entries: + if entry["name"] == "clamp": + add( + entry, + {"name": name, "precision": 64}, + [low, high, value], + [hs_low, hs_high, hs_value], + {"dtype": "value"}, + ) + elif entry["name"] in ("minimumScalar", "maximumScalar"): + add( + entry, + {"name": name, "precision": 64}, + [low, high], + [hs_low, hs_high], + {"dtype": "value"}, + ) + # Mixed raw literals are converted only when an explicit actual primitive + # prototype is selected; the original Float32 rounding remains observable. + entry = next( + e for e in entries if e["module"] == "HMath.Scalar" and e["name"] == "add" + ) + prototype = own(n.number(16777216.0, "float32")) + add( + entry, + {"name": "mixed-Float32", "precision": 32}, + [prototype, 1.0], + ["(16777216::Float)", "(1::Float)"], + ) + imports = """import qualified HMath.Basic as Basic +import qualified HMath.Scalar as Scalar +import qualified HMath.Linear as Linear +import qualified HMath.Statistics as Statistics +import qualified HMath.Numeric as N +import qualified HMath.Autodiff as AD +import qualified HMath.API.Algebra as API +import qualified HMath.Geometry.Internal as G +import Data.Int +import Data.Word +import Data.Char(ord) +import Control.Exception(SomeException,catch,evaluate,displayException) +""" + source = HASKELL.split("pR=")[0].replace( + "import qualified HMath.Polynomial as P", + imports + "\nimport qualified HMath.Polynomial as P", + ) + source += """instance E Char where enc c="I"++show(ord c) +instance E Int8 where enc x="I"++show x +instance E Word64 where enc x="I"++show x +instance E a=>E(N.Dual a)where enc(N.Dual a b)="ND("++enc a++","++enc b++")" +instance E a=>E(N.Quaternion a)where enc(N.Quaternion a b c d)="Q("++intercalate ","[enc a,enc b,enc c,enc d]++")" +instance E a=>E(AD.Dual a)where enc(AD.Dual a b)="AD("++enc a++","++enc b++")" +instance E API.Exact where enc x="EXACT("++enc(API.getExact x)++")" +instance E G.Point2 where enc(G.P2 x y)="POINT("++enc[x,y]++")" +instance E AD.Expr where enc expression="EXPR("++enc[observe [1.25,2.5],observe[-1,3]]++")" where observe point=either(("E"++).show)(\\(x,y)->enc(x,y))(AD.valueAndGradient(const expression)point) +emit :: String->IO() +emit text=(evaluate(length text)>>putStrLn text) `catch` (\\errorValue->putStrLn("EXCEPTION:"++takeWhile(/='\\n')(displayException(errorValue::SomeException)))) +main=mapM_ emit [EXPRESSIONS] +""".replace("EXPRESSIONS", ",\n ".join(expressions)) + # Expr observation above returns canonical sub-observations, not quoted + # strings: retain the same actual values+gradients tuple structure. + source = source.replace( + "enc[observe [1.25,2.5],observe[-1,3]]", + '"L["++intercalate ","[observe [1.25,2.5],observe[-1,3]]++"]"', + ) + with tempfile.TemporaryDirectory( + prefix="hmath-numeric-object-oracle-" + ) as directory: + path = Path(directory) / "Oracle.hs" + path.write_text(source) + result = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + if result.returncode: + raise SystemExit(result.stderr[:12000]) + lines = result.stdout.splitlines() + if len(lines) != len(tests): + raise AssertionError((len(lines), len(tests))) + try: + for (function, arguments, kwargs, precision, name), expected in zip( + tests, lines + ): + try: + result = function(*arguments, **kwargs) + actual = encode(result, precision) + close(result) + except hmath.HMathError as error: + actual = ( + "E" + str(error.math_error) + if error.math_error is not None + else "EXCEPTION:" + str(error).splitlines()[0] + ) + if actual != expected: + raise AssertionError((name, actual, expected)) + for entry, domain, samples in denied: + arguments = [ + [x for x, _ in samples] + if argument["type"] == "fs" + else samples[index % 3][0] + for index, argument in enumerate(entry["args"]) + ] + function = getattr(modules[entry["module"].split(".")[-1]], entry["python"]) + try: + result = function(*arguments) + close(result) + except hmath.HMathError as error: + if error.status != 10: + raise AssertionError( + ( + domain["name"], + entry["name"], + "expected Unsupported", + error.status, + str(error), + ) + ) from error + else: + raise AssertionError( + (domain["name"], entry["name"], "invented instance") + ) + finally: + for owner in owners: + owner.close() + assert len(covered) == 31 + print( + f"Generic numeric owners: {len(tests)} direct-source cases across31 operations/{len(domains)} actual domains;{len(denied)} absent-instance rejections" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_numeric_types_equivalence.py b/tools/check_numeric_types_equivalence.py new file mode 100644 index 0000000..8d368f8 --- /dev/null +++ b/tools/check_numeric_types_equivalence.py @@ -0,0 +1,730 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare typed Numeric/Constants bindings with the original Haskell modules. + +The independent oracle imports only HMath.Numeric and HMath.Constants. Floating +values compare by IEEE bits; exact values, precision, flags and metadata compare +without Double or text-evaluation conversions. +""" + +import argparse +import gc +import math +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def bits(value, width=64): + if math.isnan(value): + return "nan" + return str( + struct.unpack( + "!Q" if width == 64 else "!I", + struct.pack("!d" if width == 64 else "!f", value), + )[0] + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import numeric_types as n + from _hmath_native._value import Value + + def encode(kind, value): + if kind.startswith("r:"): + child = value.rounded_value + try: + return ( + encode(kind[2:], child) + + "!" + + ",".join(str(int(x)) for x in value.numerical_exceptions) + ) + finally: + child.close() + if ( + isinstance(value, n.NumericValue) + and value.info[0] == 1 + and value.info[1] < 20 + ): + value = value.value + if kind == "d": + return bits(value) + if kind == "f": + return bits(value, 32) + if kind in ("i", "enum"): + return str(int(value)) + if kind == "bool": + return str(value) + if kind == "q": + return str(value.numerator) + "/" + str(value.denominator) + if kind == "text": + return ",".join(str(ord(c)) for c in value) + if kind == "half": + return str(n.float16_bits(value)) + if kind == "bhalf": + return str(n.bfloat16_bits(value)) + if kind == "big": + return ( + str(n.big_precision(value)) + ":" + encode("q", n.big_rational(value)) + ) + if kind == "fixed": + return str(n.fixed_scale(value)) + ":" + str(n.fixed_coefficient(value)) + if kind == "decimal": + return encode("q", n.decimal_rational(value)) + if kind == "interval": + return ",".join(bits(x) for x in n.interval_bounds(value)) + if kind.startswith("dual:"): + a, b = value.primal, value.tangent + try: + return encode(kind[5:], a) + ";" + encode(kind[5:], b) + finally: + a.close() + b.close() + if kind.startswith("quat:"): + children = value.components + try: + return ";".join(encode(kind[5:], c) for c in children) + finally: + for child in children: + child.close() + if kind.startswith("dq:"): + children = value.components + try: + return "/".join(encode("quat:" + kind[3:], c) for c in children) + finally: + for child in children: + child.close() + if kind.startswith("triple:"): + return ",".join(encode(kind[7:], x) for x in value) + if kind.startswith("frexp:"): + return encode(kind[6:], value[0]) + ":" + str(value[1]) + if kind == "constant": + return "|".join( + encode(k, f(value)) + for k, f in [ + ("text", n.constant_name), + ("q", n.constant_value), + ("q", n.standard_uncertainty), + ("q", n.approximation_bound), + ("text", n.constant_unit), + ("text", n.constant_source), + ] + ) + if kind == "constants": + return "~".join(encode("constant", x) for x in value) + if kind.startswith("limits:"): + scalar = kind[7:] + values = [ + (scalar, f(value)) + for f in ( + n.minimum_normal, + n.minimum_subnormal, + n.maximum_finite, + n.machine_epsilon, + ) + ] + values += [ + ("i", f(value)) + for f in (n.significand_digits, n.minimum_exponent, n.maximum_exponent) + ] + return ";".join(encode(k, x) for k, x in values) + if kind == "ints": + return ",".join(str(x) for x in value) + raise AssertionError(kind) + + cases = [] + + def case(label, expression, kind, call, hs_encoder=None): + cases.append( + ( + label, + expression, + kind, + call, + hs_encoder + or { + "d": "d", + "f": "f", + "i": "show", + "q": "q", + "bool": "show", + "enum": "ieee", + "text": "text", + "half": "show . N.float16Bits", + "bhalf": "show . N.bfloat16Bits", + "big": "big", + "fixed": "fixed", + "decimal": "q . N.decimalRational", + "interval": "interval", + "constant": "constant", + "constants": 'intercalate "~" . map constant', + "ints": 'intercalate "," . map show', + }.get(kind), + ) + ) + + mode_names = ["NearestEven", "TowardZero", "TowardPositive", "TowardNegative"] + edge_values = [ + 0.0, + -0.0, + 1.1, + -1.1, + 65504.0, + 65520.0, + 1e-40, + -1e-40, + math.inf, + -math.inf, + math.nan, + ] + hs_values = [ + "0", + "castWord64ToDouble 9223372036854775808", + "1.1", + "-1.1", + "65504", + "65520", + "1e-40", + "-1e-40", + "1/0", + "-1/0", + "0/0", + ] + for mode, mode_name in enumerate(mode_names): + for index, (value, hsvalue) in enumerate(zip(edge_values, hs_values)): + for name, hsname, kind in [ + ("float16", "float16", "half"), + ("bfloat16", "bfloat16", "bhalf"), + ]: + case( + f"{name}-{mode}-{index}", + f"N.{hsname} N.{mode_name} (opaque ({hsvalue}) :: Double)", + "r:" + kind, + lambda name=name, mode=mode, value=value: getattr(n, name)( + mode, value + ), + f"rounded ({'show . N.float16Bits' if kind == 'half' else 'show . N.bfloat16Bits'})", + ) + for value in [ + Fraction(-7, 2), + Fraction(-1, 2), + Fraction(1, 2), + Fraction(7, 2), + Fraction(10**100 + 1, 3), + ]: + case( + f"round-{mode}-{value}", + f"N.roundRational N.{mode_name} ({value.numerator}%{value.denominator})", + "i", + lambda mode=mode, value=value: n.round_rational(mode, value), + ) + for width, dtype, haskell in [(64, "float64", "Double"), (32, "float32", "Float")]: + for index, (value, hsvalue) in enumerate(zip(edge_values, hs_values)): + if width == 32 and index == 1: + hsvalue = "castWord32ToFloat 2147483648" + case( + f"class-{width}-{index}", + f"N.classify (opaque ({hsvalue}) :: {haskell})", + "enum", + lambda value=value, dtype=dtype: n.classify(n.number(value, dtype)), + ) + if math.isfinite(value): + case( + f"frexp-{width}-{index}", + f"N.frexp (opaque ({hsvalue}) :: {haskell})", + "frexp:" + ("d" if width == 64 else "f"), + lambda value=value, dtype=dtype: n.frexp(n.number(value, dtype)), + f"pair {'d' if width == 64 else 'f'} show", + ) + case( + f"limits-{width}", + f"N.numericLimits (0 :: {haskell})", + "limits:" + ("d" if width == 64 else "f"), + lambda dtype=dtype: n.numeric_limits(n.number(0, dtype)), + f"limits {'d' if width == 64 else 'f'}", + ) + for factory, hsname in [ + ("float16_limits", "float16Limits"), + ("bfloat16_limits", "bfloat16Limits"), + ]: + case( + factory, + "N." + hsname, + "limits:d", + lambda factory=factory: getattr(n, factory)(), + "limits d", + ) + bounded = [ + ("int8", "Int8"), + ("int16", "Int16"), + ("int32", "Int32"), + ("int64", "Int64"), + ("uint8", "Word8"), + ("uint16", "Word16"), + ("uint32", "Word32"), + ("uint64", "Word64"), + ("intp", "Int"), + ("uintp", "Word"), + ] + for dtype, hs in bounded: + case( + "integer-limits-" + dtype, + f"let (a,b)=N.integerLimits (0::{hs}) in [a,b]", + "ints", + lambda dtype=dtype: n.integer_limits(n.number(0, dtype)), + ) + for source in [-(10**100), -1, 0, 1, 10**100]: + case( + f"saturate-{dtype}-{source}", + f"toInteger (N.saturatingCast ({source}::Integer) :: {hs})", + "i", + lambda dtype=dtype, source=source: n.saturating_cast(source, dtype), + ) + case( + "safe-cast-" + dtype, + f"toInteger (right (N.safeIntegralCast (1::Integer)) :: {hs})", + "i", + lambda dtype=dtype: n.safe_integral_cast(1, dtype), + ) + case( + "real-cast-" + dtype, + f"toInteger (right (N.realToIntegral N.NearestEven (1.5::Double)) :: {hs})", + "i", + lambda dtype=dtype: n.real_to_integral(0, 1.5, dtype), + ) + for factory, hs_factory, kind in [ + ("big_float", "bigFloat", "big"), + ("fixed", "fixed", "fixed"), + ("decimal", "decimal", "decimal"), + ]: + precisions = [2, 53, 200] if kind == "big" else [0, 4, 40] + for precision in precisions: + for mode, mode_name in enumerate(mode_names): + expression = f"right (N.{hs_factory} {precision} N.{mode_name} (1%3))" + case( + f"{factory}-{precision}-{mode}", + expression, + "r:" + kind, + lambda factory=factory, precision=precision, mode=mode: getattr( + n, factory + )(precision, mode, Fraction(1, 3)), + "rounded " + + { + "big": "big", + "fixed": "fixed", + "decimal": "(q . N.decimalRational)", + }[kind], + ) + owners = [] + + def own(value): + owners.append(value) + return value + + big_a = own(n.big_float(200, 0, Fraction(1, 3)).rounded_value) + big_b = own(n.big_float(80, 0, Fraction(7, 5)).rounded_value) + for py, hs in [ + ("big_add", "bigAdd"), + ("big_subtract", "bigSubtract"), + ("big_multiply", "bigMultiply"), + ("big_divide", "bigDivide"), + ]: + case( + py, + f"right (N.{hs} bigA bigB)", + "big", + lambda py=py: getattr(n, py)(big_a, big_b), + ) + for py, hs in [ + ("big_sqrt", "bigSqrt"), + ("big_exp", "bigExp"), + ("big_log", "bigLog"), + ]: + case(py, f"right (N.{hs} bigB)", "big", lambda py=py: getattr(n, py)(big_b)) + case( + "extended", + "right (N.extended (1%7))", + "big", + lambda: n.extended(Fraction(1, 7)), + ) + case("big-to-double", "N.bigToDouble bigA", "d", lambda: n.big_to_double(big_a)) + for py, hs in [("mixed_add", "mixedAdd"), ("mixed_multiply", "mixedMultiply")]: + case( + py, + f"right (N.{hs} bigA 1.1)", + "big", + lambda py=py: getattr(n, py)(big_a, 1.1), + ) + for prefix, kind, encoder in [ + ("fixed", "fixed", "fixed"), + ("decimal", "decimal", "(q . N.decimalRational)"), + ]: + a = own(getattr(n, prefix)(4, 0, Fraction(1, 3)).rounded_value) + b = own(getattr(n, prefix)(2, 0, Fraction(7, 5)).rounded_value) + for py, hs in [("add", "Add"), ("multiply", "Multiply"), ("divide", "Divide")]: + mode_arg = "N.TowardNegative " if py != "add" else "" + fn = prefix + "_" + py + case( + fn, + f"right (N.{prefix}{hs} {mode_arg}{prefix}A {prefix}B)", + "r:" + kind, + lambda fn=fn, py=py, a=a, b=b: getattr(n, fn)( + *([] if py == "add" else [3]), a, b + ), + "rounded " + encoder, + ) + a = own(n.interval(-1, 2)) + b = own(n.interval(3, 4)) + for py, hs in [ + ("interval_add", "intervalAdd"), + ("interval_subtract", "intervalSubtract"), + ("interval_multiply", "intervalMultiply"), + ("interval_divide", "intervalDivide"), + ]: + case( + py, + f"right (N.{hs} intervalA intervalB)", + "interval", + lambda py=py: getattr(n, py)(a, b), + ) + case( + "interval-contains", + "N.intervalContains intervalA 0", + "bool", + lambda: n.interval_contains(a, 0), + ) + for dtype, hs, enc, value in [ + ("integer", "Integer", "i", 10**100), + ("rational", "Rational", "q", Fraction(1, 3)), + ("float32", "Float", "f", -2.0), + ("float64", "Double", "d", -2.0), + ]: + hsvalue = ( + f"{value.numerator}%{value.denominator}" + if isinstance(value, Fraction) + else repr(value) + ) + x = own(n.number(value, dtype)) + case( + "dual-" + dtype, + f"N.Dual ({hsvalue}::{hs}) 3", + "dual:" + enc, + lambda x=x: n.dual(x, n.literal_integer(x, 3, boxed=True)), + f"dual {enc if enc in ('d', 'f') else 'show' if enc == 'i' else 'q'}", + ) + case( + "derivative-" + dtype, + f"N.derivative (\\x -> x*x*x+2*x) ({hsvalue}::{hs})", + enc, + lambda x=x: n.derivative(lambda y: y**3 + 2 * y, x), + ) + nested = own(n.dual(2.0, 1.0)) + case( + "nested-derivative", + "N.derivative (\\x -> x*x*x) (N.Dual 2 1::N.Dual Double)", + "dual:d", + lambda: n.derivative(lambda x: x**3, nested), + "dual d", + ) + case( + "floating-derivative", + "N.derivative (\\x -> sin x * exp x) (0.25::Double)", + "d", + lambda: n.derivative(lambda x: x.sin() * x.exp(), 0.25), + ) + for dtype, hs, enc in [ + ("float64", "Double", "d"), + ("float32", "Float", "f"), + ("integer", "Integer", "i"), + ("rational", "Rational", "q"), + ]: + parts = [own(n.number(v, dtype)) for v in [1, 2, 3, 4]] + quat = own(n.quaternion(*parts)) + encoder = enc if enc in ("d", "f") else "show" if enc == "i" else "q" + case( + "quat-" + dtype, + f"N.Quaternion 1 2 3 4::N.Quaternion {hs}", + "quat:" + enc, + lambda quat=quat: quat.clone().decode(), + "quat " + encoder, + ) + case( + "quat-conjugate-" + dtype, + f"N.quaternionConjugate (N.Quaternion 1 2 3 4::N.Quaternion {hs})", + "quat:" + enc, + lambda quat=quat: n.quaternion_conjugate(quat), + "quat " + encoder, + ) + if enc not in ("d", "f"): + continue + case( + "quat-norm-" + dtype, + f"N.quaternionNorm (N.Quaternion 1 2 3 4::N.Quaternion {hs})", + enc, + lambda quat=quat: n.quaternion_norm(quat), + ) + case( + "quat-inverse-" + dtype, + f"right (N.quaternionInverse (N.Quaternion 1 2 3 4::N.Quaternion {hs}))", + "quat:" + enc, + lambda quat=quat: n.quaternion_inverse(quat), + "quat " + encoder, + ) + quat = own(n.quaternion(1.0, 0.0, 0.0, 0.0)) + dq = own(n.rigid_transform(quat, 1.0, 2.0, 3.0)) + case( + "rotation", + "right (N.rotateVector identity (2,3,4))", + "triple:d", + lambda: n.rotate_vector(quat, 2.0, 3.0, 4.0), + "triple d", + ) + case( + "rigid-transform", + "right (N.rigidTransform identity (1,2,3))", + "dq:d", + lambda: n.rigid_transform(quat, 1.0, 2.0, 3.0), + "dq d", + ) + case( + "dq-inverse", + "right (N.dualQuaternionInverse transform)", + "dq:d", + lambda: n.dual_quaternion_inverse(dq), + "dq d", + ) + case( + "dq-multiply", + "N.dualQuaternionMultiply transform transform", + "dq:d", + lambda: n.dual_quaternion_multiply(dq, dq), + "dq d", + ) + case( + "transform-point", + "right (N.transformPoint transform (2,3,4))", + "triple:d", + lambda: n.transform_point(dq, 2.0, 3.0, 4.0), + "triple d", + ) + for py, hs in [ + ("speed_of_light", "speedOfLight"), + ("planck_constant", "planckConstant"), + ("elementary_charge", "elementaryCharge"), + ("boltzmann_constant", "boltzmannConstant"), + ("avogadro_constant", "avogadroConstant"), + ("gravitational_constant", "gravitationalConstant"), + ("electron_mass", "electronMass"), + ("astronomical_unit", "astronomicalUnit"), + ]: + case(py, "K." + hs, "constant", lambda py=py: getattr(n, py)()) + case( + "math-constants", + "K.mathematicalConstants", + "constants", + n.mathematical_constants, + ) + case("physical-constants", "K.physicalConstants", "constants", n.physical_constants) + c = own( + n.constant( + "name\x00λ\ud800", + Fraction(10**100 + 1, 7), + Fraction(-1, 3), + Fraction(1, 11), + "m\x00s", + "source\udfff", + ) + ) + case( + "custom-constant", + 'K.Constant (map toEnum [110,97,109,101,0,955,55296]) ((10^100+1)%7) (-1%3) (1%11) "m\\0s" ("source"++[toEnum 57343])', + "constant", + lambda: c.clone().decode(), + ) + case( + "constant-as-rational", + "K.constantAs K.speedOfLight::Rational", + "q", + lambda: n.constant_as(n.speed_of_light(), "rational"), + ) + case( + "constant-as-dual", + "K.constantAs K.speedOfLight::N.Dual Double", + "dual:d", + lambda: n.constant_as_like(n.speed_of_light(), nested), + "dual d", + ) + for bit in [ + 0, + 1, + 2, + 0x3C00, + 0x7BFF, + 0x7C00, + 0x7C01, + 0x7FFF, + 0x8000, + 0x8001, + 0xFC00, + 0xFFFF, + ]: + case( + f"half-bits-{bit}", + f"N.fromFloat16 (N.float16FromBits {bit})", + "d", + lambda bit=bit: n.from_float16(n.float16_from_bits(bit)), + ) + case( + f"bhalf-bits-{bit}", + f"N.fromBFloat16 (N.bfloat16FromBits {bit})", + "d", + lambda bit=bit: n.from_bfloat16(n.bfloat16_from_bits(bit)), + ) + lines = [ + "{-# LANGUAGE ScopedTypeVariables #-}", + "import qualified HMath.Numeric as N", + "import qualified HMath.Constants as K", + "import Data.Ratio", + "import Data.Int", + "import Data.Word", + "import Data.List (intercalate)", + "import GHC.Float", + "import System.Environment (getArgs)", + "{-# NOINLINE opaque #-}", + "opaque :: a -> a", + "opaque x=x", + 'd x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'f x=if isNaN x then "nan" else show (castFloatToWord32 x)', + 'q x=show (numerator x)++"/"++show (denominator x)', + 'text=intercalate "," . map (show . fromEnum)', + "right (Right x)=x", + "right (Left e)=error (show e)", + "flag x=case x of {N.InvalidOperation->0;N.DivisionByZero->1;N.NumericOverflow->2;N.NumericUnderflow->3;N.Inexact->4}", + "ieee x=show (case x of {N.NotANumber->0;N.PositiveInfinity->1;N.NegativeInfinity->2;N.PositiveZero->3;N.NegativeZero->4;N.Subnormal->5;N.Normal->6} :: Int)", + 'rounded encode x=encode (N.roundedValue x)++"!"++intercalate "," (map (show . flag) (N.numericalExceptions x))', + 'big x=show (N.bigPrecision x)++":"++q (N.bigRational x)', + 'fixed x=show (N.fixedScale x)++":"++show (N.fixedCoefficient x)', + 'interval x=let (a,b)=N.intervalBounds x in d a++","++d b', + 'pair a b (x,y)=a x++":"++b y', + 'dual e (N.Dual a b)=e a++";"++e b', + 'quat e (N.Quaternion a b c z)=intercalate ";" [e a,e b,e c,e z]', + 'dq e (N.DualQuaternion a b)=quat e a++"/"++quat e b', + 'triple e (a,b,c)=intercalate "," [e a,e b,e c]', + 'limits e x=intercalate ";" [e (N.minimumNormal x),e (N.minimumSubnormal x),e (N.maximumFinite x),e (N.machineEpsilon x),show (N.significandDigits x),show (N.minimumExponent x),show (N.maximumExponent x)]', + 'constant x=intercalate "|" [text (K.constantName x),q (K.constantValue x),q (K.standardUncertainty x),q (K.approximationBound x),text (K.constantUnit x),text (K.constantSource x)]', + "bigA=N.roundedValue (right (N.bigFloat 200 N.NearestEven (1%3)))", + "bigB=N.roundedValue (right (N.bigFloat 80 N.NearestEven (7%5)))", + "fixedA=N.roundedValue (right (N.fixed 4 N.NearestEven (1%3)))", + "fixedB=N.roundedValue (right (N.fixed 2 N.NearestEven (7%5)))", + "decimalA=N.roundedValue (right (N.decimal 4 N.NearestEven (1%3)))", + "decimalB=N.roundedValue (right (N.decimal 2 N.NearestEven (7%5)))", + "intervalA=right (N.interval (-1) 2)", + "intervalB=right (N.interval 3 4)", + "identity=N.Quaternion 1 0 0 0::N.Quaternion Double", + "transform=right (N.rigidTransform identity (1,2,3))", + "main=do", + ] + for index, (_, expression, _, _, encoder) in enumerate(cases): + if encoder is None: + raise AssertionError(cases[index][:3]) + lines.append( + f' putStrLn (show ({index}::Int)++"\\t"++({encoder}) ({expression}))' + ) + with tempfile.TemporaryDirectory(prefix="hmath-numeric-types-oracle-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + oracle = subprocess.check_output([str(path / "oracle")], text=True).splitlines() + assert len(oracle) == len(cases) + for index, line in enumerate(oracle): + expected_index, expected = line.split("\t", 1) + assert int(expected_index) == index + label, _, kind, call, _ = cases[index] + value = call() + try: + actual = encode(kind, value) + assert actual == expected, (label, actual, expected) + finally: + if isinstance(value, Value): + value.close() + elif isinstance(value, (list, tuple)): + for child in value: + if isinstance(child, Value): + child.close() + # Lifetime/representation contracts independent of numerical oracle cases. + flags = [ + n.NumericException.INEXACT, + n.NumericException.INVALID_OPERATION, + n.NumericException.INEXACT, + ] + record = n.rounded(n.number(Fraction(1, 3), "rational"), flags) + child = record.rounded_value + record.close() + assert child.value == Fraction(1, 3) + child.close() + assert n.numerical_exceptions(n.rounded(None, flags)) == flags + assert n.rounded_value(n.rounded([1, Fraction(1, 3)], flags)) == [1, Fraction(1, 3)] + for function in [lambda x: x**2, lambda x: x * x]: + assert n.derivative(function, -2.0) == -4.0 + assert n.derivative(lambda x: x * 3, 2.0) == 3.0 + captured = n.number(3.0) + assert n.derivative(lambda x: x * captured.value, captured) == 3.0 + captured.close() + + def failing(_): + raise LookupError("callback failure") + + try: + n.derivative(failing, 2.0) + raise AssertionError("callback exception swallowed") + except LookupError as error: + assert str(error) == "callback failure" + for call in [ + lambda: n.safe_integral_cast(256, "uint8"), + lambda: n.interval(2, 1), + lambda: n.interval_divide(a, n.interval(-1, 1)), + lambda: n.big_float(0, 0, Fraction(1, 3)), + ]: + try: + call() + raise AssertionError("original MathError accepted") + except hmath.HMathError as error: + assert error.status == 11 + for owner in owners: + owner.close() + owners.clear() + cases.clear() + gc.collect() + print( + f"Numeric types: {len(oracle)} independent Haskell cases plus callback, exact-data and ownership contracts passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_numerical_equivalence.py b/tools/check_numerical_equivalence.py new file mode 100644 index 0000000..5a01393 --- /dev/null +++ b/tools/check_numerical_equivalence.py @@ -0,0 +1,770 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-Haskell oracle for all numerical solver adapters.""" + +import argparse +import json +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL as POLYNOMIAL_HASKELL +from check_polynomial_equivalence import bits, close +from generate_graph_bindings import snake, split_top +from generate_numerical_bindings import TYPES, normalize, spec + +ROOT = Path(__file__).resolve().parent.parent +IMPORTS = """import qualified HMath.Calculus as C +import qualified HMath.Root as R +import qualified HMath.ODE as O +import qualified HMath.PDE as D +import qualified HMath.Sparse as S +""" +BASE = POLYNOMIAL_HASKELL.split("pR=")[0].replace("class E a", IMPORTS + "class E a") +FIXTURES = r""" +right(Right x)=x +right(Left e)=error(show e) +f x=x*x-2 +square x=x*x +vector x=map negate x +scalar x=sum(map (\v->v*v) x) +matrix xs=[[-1 * (if i==j then 1 else 0) | j<-[0..length xs-1]] | i<-[0..length xs-1]] +path t=[t,t*t] +tangent t=[1,2*t] +rhs _ y=map negate y +boundary a b=zipWith (+) a b +dae _ y dy=zipWith (+) y dy +event _ y=head y-0.5 +sensitivity parameters _ y=map ((-head parameters)*) y +surface xy=[head xy,last xy,0] +du _=[1,0,0] +dv _=[0,1,0] +forcing _=[0,0,0] +options=R.defaultRootOptions +tolerance=C.Tolerance 1e-6 1e-6 2000 +odeOptions=O.defaultODEOptions +bracket=right(R.bracket f 0 2) +trajectory=right(O.solveIVP O.RK4 odeOptions 10 rhs 0 1 [1]) +grid=right(D.grid [3] [(0,1)] [False]) +periodicGrid=right(D.grid [3] [(0,1)] [True]) +boundaries=[(D.Dirichlet 0,D.Dirichlet 0)] +operator=right(D.assemblePDE D.FiniteDifference grid boundaries [1,1,1] 0) +complexPoly=P.polynomial [(-2):+0,0:+0,1:+0] +rationalPoly=P.polynomial [-2,0,1] :: P.Polynomial Rational +main=mapM_ putStrLn [EXPRESSIONS] +""" + + +def enc(value, modules): + from _hmath_native._linear_base import LinearValue + from _hmath_native._matrix_base import Matrix + from _hmath_native._value import Value + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return "F64:" + str(bits(value, 64)) + if isinstance(value, complex): + return "C64:" + str(bits(value.real, 64)) + ":" + str(bits(value.imag, 64)) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(enc(x, modules) for x in value) + + "]" + ) + if isinstance(value, Matrix): + r, c = value.shape + return f"M{r}:{c}[" + ",".join(enc(x, modules) for x in value.to_list()) + "]" + if isinstance(value, LinearValue) and value.source_type == "HMath.Sparse.Sparse": + return "Sparse" + enc( + ( + modules["sparse"].sparse_shape(value), + modules["sparse"].sparse_entries(value), + ), + modules, + ) + if not isinstance(value, Value): + raise TypeError(type(value)) + kind = value.info[0] + if kind == 200: + c = modules["calculus"] + return enc( + (c.estimate_value(value), c.estimate_error(value), c.evaluations(value)), + modules, + ) + if kind == 206: + r = modules["root"] + with r.bisection() as method, r.default_root_options() as options: + result = r.solve_bracket(method, options, lambda x: x * x - 2, value) + try: + return "Bracket" + enc(result, modules) + finally: + close(result) + if kind == 218: + p = modules["pde"] + fields = [p.grid_shape(value), p.grid_spacing(value), p.grid_coordinates(value)] + elif kind == 221: + p = modules["pde"] + fields = [p.pde_stiffness(value), p.pde_mass(value), p.pde_boundary_load(value)] + else: + namespace, _typ, _kind, names = next( + item for item in TYPES.values() if item[2] == kind + ) + if not names: + return "K" + str(kind) + fields = [getattr(modules[namespace], snake(name))(value) for name in names] + try: + return ( + "O" + + str(kind) + + "[" + + ",".join(enc(field, modules) for field in fields) + + "]" + ) + finally: + close(fields) + + +def source_instances(): + result = [ + "instance E a => E(C.Estimate a) where enc x=enc(C.estimateValue x,C.estimateError x,C.evaluations x)" + ] + result.append( + 'instance E(S.Sparse Double) where enc x="Sparse"++enc(S.sparseShape x,S.sparseEntries x)' + ) + for name, (namespace, typ, tag, fields) in TYPES.items(): + if name == "EstimateValue": + continue + typ = typ.replace("P.", "D.") + q = {"calculus": "C", "root": "R", "ode": "O", "pde": "D"}[namespace] + if tag == 206: + body = '"Bracket"++ok(R.solveBracket R.Bisection R.defaultRootOptions f x)' + elif tag == 218: + fields = ["gridShape", "gridSpacing", "gridCoordinates"] + body = None + else: + body = None + if body is None: + body = ( + '"K' + str(tag) + '"' + if not fields + else '"O' + + str(tag) + + '["++intercalate "," [' + + ",".join("enc(" + q + "." + field + " x)" for field in fields) + + ']++"]"' + ) + result.append("instance E(" + typ + ") where enc x=" + body) + return "\n".join(result) + + +def cases(modules): + c, r, o, p = (modules[n] for n in ("calculus", "root", "ode", "pde")) + owners = [] + + def keep(value): + owners.append(value) + return value + + constructors = { + "Tolerance": (keep(c.tolerance(1e-6, 1e-6, 2000)), "tolerance"), + "Difference": (keep(c.central()), "C.Central"), + "Quadrature": (keep(c.simpson()), "C.Simpson"), + "RootOptions": (keep(r.default_root_options()), "options"), + "RootResult": ( + keep(r.root_result(1, 0, None, 2, 3)), + "R.RootResult 1 0 Nothing 2 3", + ), + "Bracket": (keep(r.bracket(lambda x: x * x - 2, 0, 2)), "bracket"), + "BracketMethod": (keep(r.brent()), "R.Brent"), + "DerivativeMethod": (keep(r.newton()), "R.Newton"), + "FixedPointMethod": (keep(r.picard()), "R.Picard"), + "SystemMethod": (keep(r.multivariate_newton()), "R.MultivariateNewton"), + "SystemRootResult": ( + keep(r.system_root_result([1], 0, 2, 3)), + "R.SystemRootResult [1] 0 2 3", + ), + "ODEMethod": (keep(o.rk4()), "O.RK4"), + "ODEOptions": (keep(o.default_ode_options()), "odeOptions"), + "EventDirection": (keep(o.any_direction()), "O.AnyDirection"), + "Event": (keep(o.event(0.5, [0.5])), "O.Event 0.5 [0.5]"), + "HamiltonianMethod": (keep(o.verlet()), "O.Verlet"), + "Grid": (keep(p.grid([3], [(0, 1)], [False])), "grid"), + "Boundary": (keep(p.dirichlet(0)), "D.Dirichlet 0"), + "Discretization": (keep(p.finite_difference()), "D.FiniteDifference"), + "PDEResult": (keep(p.pde_result([0, 0, 0], 0, 0)), "D.PDEResult [0,0,0] 0 0"), + "EstimateValue": ( + keep(c.estimate(2.0, 0.1, 4)), + "C.Estimate (2::Double) 0.1 4", + ), + } + options, ode_options = constructors["RootOptions"][0], constructors["ODEOptions"][0] + grid, boundary = constructors["Grid"][0], constructors["Boundary"][0] + boundaries = [(boundary, boundary)] + trajectory = keep( + o.solve_ivp( + constructors["ODEMethod"][0], + ode_options, + 10, + lambda t, y: [-v for v in y], + 0, + 1, + [1], + ) + ) + constructors["Trajectory"] = (trajectory, "trajectory") + constructors["PDEOperator"] = ( + keep( + p.assemble_pde( + constructors["Discretization"][0], grid, boundaries, [1, 1, 1], 0 + ) + ), + "operator", + ) + complex_poly = keep( + modules["polynomial"].polynomial([-2 + 0j, 0j, 1 + 0j], dtype="complex128") + ) + rational_poly = keep(modules["polynomial"].polynomial([-2, 0, 1], dtype="rational")) + functions = { + ("Double", "Double"): (lambda x: x * x, "square"), + ("ComplexDouble", "ComplexDouble"): (lambda z: z * z, "(\\z->z*z)"), + ("list:Double", "Double"): (lambda xs: sum(x * x for x in xs), "scalar"), + ("list:Double", "list:Double"): (lambda xs: [-x for x in xs], "vector"), + ("list:Double", "list:list:Double"): ( + lambda xs: [ + [-1.0 if i == j else 0.0 for j in range(len(xs))] + for i in range(len(xs)) + ], + "matrix", + ), + ("Double", "list:Double"): (lambda t: [t, t * t], "path"), + ("Double", "list:Double", "list:Double"): ( + lambda t, ys: [-y for y in ys], + "rhs", + ), + ("Double", "list:Double", "Double"): (lambda t, y: y[0] - 0.5, "event"), + ("list:Double", "list:Double", "list:Double"): ( + lambda a, b: [x + y for x, y in zip(a, b)], + "boundary", + ), + ("Double", "list:Double", "list:Double", "list:Double"): ( + lambda t, y, dy: [a + b for a, b in zip(y, dy)], + "dae", + ), + ("list:Double", "Double", "list:Double", "list:Double"): ( + lambda parameters, t, y: [-parameters[0] * v for v in y], + "sensitivity", + ), + } + + def key(type_): + return type_[0] + (":" + key(type_[1]) if type_[0] == "list" else "") + + def argument(type_, namespace): + kind = type_[0] + if kind == "function": + return functions[tuple(key(t) for t in type_[1:])] + if kind in constructors: + value, expression = constructors[kind] + return value, "(" + expression + ")" + defaults = { + "Double": (0.1, "0.1"), + "Int": (4, "4"), + "Integer": (13, "13"), + "Bool": (False, "False"), + "Rational": (Fraction(1, 100), "(1/100)"), + "Value": (2.0, "(2::Double)"), + "ComplexPolynomial": (complex_poly, "complexPoly"), + "RationalPolynomial": (rational_poly, "rationalPoly"), + "list:Double": ([1.0, 2.0], "[1,2]"), + "list:list:Double": ([[1.0]], "[[1]]"), + "list:Int": ([0], "[0]"), + "list:Bool": ([False], "[False]"), + } + if key(type_) in defaults: + return defaults[key(type_)] + if kind == "maybe": + return None, "Nothing" + if kind == "tuple": + items = [argument(item, namespace) for item in type_[1:]] + return tuple(v for v, _ in items), "(" + ",".join(e for _, e in items) + ")" + if kind == "list": + item, expression = argument(type_[1], namespace) + return [item], "[" + expression + "]" + raise ValueError(type_) + + overrides = {} + + def override(namespace, name, values, expressions): + overrides[(namespace, name)] = (values, expressions) + + # Common quadrature bounds and callback dimensions are explicit. + tol = constructors["Tolerance"][0] + for name in ("romberg", "adaptiveIntegrate", "tanhSinh"): + override( + "calculus", + name, + [tol, lambda x: x * x, 0, 1], + ["tolerance", "square", "0", "1"], + ) + for name in ("gaussLegendre", "clenshawCurtis"): + override( + "calculus", name, [4, lambda x: x * x, 0, 1], ["4", "square", "0", "1"] + ) + override( + "calculus", + "integrateComposite", + [constructors["Quadrature"][0], 4, lambda x: x * x, 0, 1], + ["C.Simpson", "4", "square", "0", "1"], + ) + override("calculus", "gaussKronrod", [lambda x: x * x, 0, 1], ["square", "0", "1"]) + override( + "calculus", + "integrateOscillatory", + [True, 2, tol, lambda x: x * x, 0, 1], + ["True", "2", "tolerance", "square", "0", "1"], + ) + for name in ("integrateND", "volumeIntegral"): + override( + "calculus", + name, + [2, 4, lambda xs: sum(x * x for x in xs), [(0, 1), (0, 1)]], + ["2", "4", "scalar", "[(0,1),(0,1)]"], + ) + override( + "calculus", + "monteCarlo", + [13, 10, lambda xs: sum(x * x for x in xs), [(0, 1), (0, 1)]], + ["13", "10", "scalar", "[(0,1),(0,1)]"], + ) + override( + "calculus", + "quasiMonteCarlo", + [10, lambda xs: sum(x * x for x in xs), [(0, 1), (0, 1)]], + ["10", "scalar", "[(0,1),(0,1)]"], + ) + override( + "calculus", + "pathIntegral", + [ + tol, + lambda t: [t, t * t], + lambda t: [1, 2 * t], + lambda xs: sum(x * x for x in xs), + 0, + 1, + ], + ["tolerance", "path", "tangent", "scalar", "0", "1"], + ) + override( + "calculus", + "lineIntegral", + [tol, lambda t: [t, t * t], lambda t: [1, 2 * t], lambda xs: xs, 0, 1], + ["tolerance", "path", "tangent", "id", "0", "1"], + ) + override( + "calculus", + "surfaceIntegral", + [ + 2, + 4, + lambda xy: [xy[0], xy[1], 0], + lambda _: [1, 0, 0], + lambda _: [0, 1, 0], + lambda xs: sum(x * x for x in xs), + [(0, 1), (0, 1)], + ], + ["2", "4", "surface", "du", "dv", "scalar", "[(0,1),(0,1)]"], + ) + override( + "calculus", + "curl", + [0.001, lambda xs: [-x for x in xs], [1, 2, 3]], + ["0.001", "vector", "[1,2,3]"], + ) + # Use the same scalar residual for each bracketing/derivative solver. + scalar_root = lambda x: x * x - 2 + for name in ("bracketScan", "isolateIntervals"): + override( + "root", + name, + [options, scalar_root, 0, 2, 8], + ["options", "f", "0", "2", "8"], + ) + override("root", "bracket", [scalar_root, 0, 2], ["f", "0", "2"]) + override( + "root", + "solveBracket", + [ + constructors["BracketMethod"][0], + options, + scalar_root, + constructors["Bracket"][0], + ], + ["R.Brent", "options", "f", "bracket"], + ) + override( + "root", + "solveDerivative", + [ + constructors["DerivativeMethod"][0], + options, + scalar_root, + [lambda x: 2 * x, lambda _: 2, lambda _: 0], + 1, + ], + ["R.Newton", "options", "f", "[(\\x->2*x),(const 2),(const 0)]", "1"], + ) + override("root", "secant", [options, scalar_root, 0, 2], ["options", "f", "0", "2"]) + override("root", "steffensen", [options, scalar_root, 1], ["options", "f", "1"]) + override( + "root", + "fixedPoint", + [constructors["FixedPointMethod"][0], options, lambda x: x / 2, 1], + ["R.Picard", "options", "(/2)", "1"], + ) + # ODE time intervals and dimensions remain valid for all methods. + rhs = lambda _, ys: [-y for y in ys] + override( + "ode", + "solveIVP", + [constructors["ODEMethod"][0], ode_options, 4, rhs, 0, 1, [1]], + ["O.RK4", "odeOptions", "4", "rhs", "0", "1", "[1]"], + ) + override( + "ode", + "solveAdaptive", + [constructors["ODEMethod"][0], ode_options, rhs, 0, 1, [1]], + ["O.RK4", "odeOptions", "rhs", "0", "1", "[1]"], + ) + override( + "ode", + "solveBoundary", + [ + constructors["ODEMethod"][0], + ode_options, + 4, + rhs, + lambda a, b: [a[0] + b[0]], + 0, + 1, + [1], + ], + ["O.RK4", "odeOptions", "4", "rhs", "boundary", "0", "1", "[1]"], + ) + override( + "ode", + "solveDAE", + [ode_options, 4, lambda t, y, dy: [y[0] + dy[0]], 0, 1, [1], [-1]], + ["odeOptions", "4", "dae", "0", "1", "[1]", "[-1]"], + ) + override( + "ode", + "sensitivities", + [ + constructors["ODEMethod"][0], + ode_options, + 4, + 0.001, + lambda params, t, y: [-params[0] * x for x in y], + [1], + 0, + 1, + [1], + ], + ["O.RK4", "odeOptions", "4", "0.001", "sensitivity", "[1]", "0", "1", "[1]"], + ) + override( + "ode", + "solveNystrom", + [4, lambda t, y: [-x for x in y], 0, 1, [1], [0]], + ["4", "rhs", "0", "1", "[1]", "[0]"], + ) + override( + "ode", + "solveHamiltonian", + [ + constructors["HamiltonianMethod"][0], + 4, + lambda x: x, + lambda x: x, + 0, + 1, + [1], + [0], + ], + ["O.Verlet", "4", "id", "id", "0", "1", "[1]", "[0]"], + ) + override( + "ode", + "phaseTrajectories", + [ + constructors["ODEMethod"][0], + ode_options, + 4, + lambda x: [-v for v in x], + 0, + 1, + [[1], [2]], + ], + ["O.RK4", "odeOptions", "4", "vector", "0", "1", "[[1],[2]]"], + ) + override( + "ode", + "lyapunovExponents", + [ode_options, 4, 0.001, rhs, 0, 1, [1]], + ["odeOptions", "4", "0.001", "rhs", "0", "1", "[1]"], + ) + override("pde", "grid", [[3], [(0, 1)], [False]], ["[3]", "[(0,1)]", "[False]"]) + entries = json.loads( + (ROOT / "bindings/schema/numerical-functions.json").read_text() + )["functions"] + fixtures = [] + for entry in entries: + namespace = entry["module"].removeprefix("HMath.").lower() + names = split_top(normalize(entry["signature"], namespace), "->") + prepared = [argument(spec(text), namespace) for text in names[:-1]] + arguments = [value for value, _ in prepared] + expressions = [expression for _, expression in prepared] + if (namespace, entry["name"]) in overrides: + arguments, expressions = overrides[(namespace, entry["name"])] + # PDE shape-sensitive lists: count3 values and one pair of faces. + if namespace == "pde" and entry["name"] != "grid": + for i, text in enumerate(names[:-1]): + if text == "[Double]": + arguments[i] = [1, 1, 1] + expressions[i] = "[1,1,1]" + elif text == "[(Boundary, Boundary)]": + arguments[i] = boundaries + expressions[i] = "boundaries" + elif text == "(Double -> [Double])": + arguments[i] = lambda _: [0, 0, 0] + expressions[i] = "forcing" + q = {"calculus": "C", "root": "R", "ode": "O", "pde": "D"}[namespace] + call = q + "." + entry["name"] + " " + " ".join(expressions) + checked = names[-1].startswith("Either MathError") + fixtures.append( + ( + namespace, + snake(entry["name"]), + arguments, + ("ok(" if checked else "enc(") + call + ")", + ) + ) + # Constructor results are also exercised in the mathematical algorithms. + for constructor in ("forward", "backward", "central"): + method = keep(getattr(c, constructor)()) + fixtures.append( + ( + "calculus", + "derivative", + [method, 0.001, lambda x: x * x, 2], + "ok(C.derivative C." + constructor.capitalize() + " 0.001 square 2)", + ) + ) + # Feed every public method constructor back into the original algorithm; + # merely comparing its opaque kind would not distinguish wrong variants. + for entry in entries: + if not entry["name"][0].isupper(): + continue + namespace = entry["module"].removeprefix("HMath.").lower() + normalized = split_top(normalize(entry["signature"], namespace), "->") + result_type = normalized[-1] + targets = { + "Quadrature", + "BracketMethod", + "DerivativeMethod", + "FixedPointMethod", + "SystemMethod", + "ODEMethod", + "HamiltonianMethod", + "Discretization", + } + if result_type not in targets: + continue + prepared = [argument(spec(text), namespace) for text in normalized[:-1]] + method = keep( + getattr(modules[namespace], snake(entry["name"]))(*[v for v, _ in prepared]) + ) + qualifier = {"calculus": "C", "root": "R", "ode": "O", "pde": "D"}[namespace] + expression = ( + "(" + + qualifier + + "." + + entry["name"] + + " " + + " ".join(e for _, e in prepared) + + ")" + ) + if result_type == "Quadrature": + call = ( + "calculus", + "integrate_composite", + [method, 6, lambda x: x * x, 0, 1], + "ok(C.integrateComposite " + expression + " 6 square 0 1)", + ) + elif result_type == "BracketMethod": + call = ( + "root", + "solve_bracket", + [method, options, scalar_root, constructors["Bracket"][0]], + "ok(R.solveBracket " + expression + " options f bracket)", + ) + elif result_type == "DerivativeMethod": + call = ( + "root", + "solve_derivative", + [ + method, + options, + scalar_root, + [lambda x: 2 * x, lambda _: 2, lambda _: 0], + 1, + ], + "ok(R.solveDerivative " + + expression + + " options f [(\\x->2*x),(const 2),(const 0)] 1)", + ) + elif result_type == "FixedPointMethod": + call = ( + "root", + "fixed_point", + [method, options, lambda x: x / 2, 1], + "ok(R.fixedPoint " + expression + " options (/2) 1)", + ) + elif result_type == "SystemMethod": + call = ( + "root", + "solve_system", + [ + method, + options, + lambda xs: [-x for x in xs], + lambda xs: [ + [-1.0 if i == j else 0.0 for j in range(len(xs))] + for i in range(len(xs)) + ], + [1, 2], + ], + "ok(R.solveSystem " + expression + " options vector matrix [1,2])", + ) + elif result_type == "ODEMethod": + call = ( + "ode", + "solve_ivp", + [method, ode_options, 4, rhs, 0, 1, [1]], + "ok(O.solveIVP " + expression + " odeOptions 4 rhs 0 1 [1])", + ) + elif result_type == "HamiltonianMethod": + call = ( + "ode", + "solve_hamiltonian", + [method, 4, lambda x: x, lambda x: x, 0, 1, [1], [0]], + "ok(O.solveHamiltonian " + expression + " 4 id id 0 1 [1] [0])", + ) + else: + call = ( + "pde", + "poisson", + [method, grid, boundaries, [1, 1, 1]], + "ok(D.poisson " + expression + " grid boundaries [1,1,1])", + ) + fixtures.append(call) + return fixtures, owners + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + modules = { + name: getattr(hmath, name) + for name in ("calculus", "root", "ode", "pde", "sparse", "polynomial") + } + fixtures, owners = cases(modules) + try: + source = ( + BASE + + source_instances() + + FIXTURES.replace( + "EXPRESSIONS", ",\n ".join(case[3] for case in fixtures) + ) + ) + with tempfile.TemporaryDirectory(prefix="hmath-numerical-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + shim = Path(directory) / "libhmath_oracle_backend.so" + subprocess.run( + [ + "cc", + "-shared", + "-fPIC", + "-std=c11", + "-Iinclude", + "cbits/backend.c", + "-ldl", + "-lm", + "-o", + str(shim), + ], + cwd=ROOT, + check=True, + capture_output=True, + ) + result = subprocess.run( + [ + "runghc", + "-isrc", + "-L" + directory, + "-lhmath_oracle_backend", + str(path), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if result.returncode: + Path("/tmp/hmath-numerical-oracle-failed.hs").write_text(source) + raise RuntimeError(result.stderr[-12000:]) + expected = result.stdout.splitlines() + actual = [] + for namespace, name, arguments, _ in fixtures: + try: + value = getattr(modules[namespace], name)(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(enc(value, modules)) + finally: + close(value) + failures = [ + (fixtures[i][:2], want, got) + for i, (want, got) in enumerate(zip(expected, actual)) + if want != got + ] + if failures or len(expected) != len(actual): + raise AssertionError(f"Numerical oracle mismatches: {failures[:10]}") + print( + f"Numerical solvers: {len(actual)} direct Haskell cases; all185 public operations/constructors" + ) + finally: + for owner in owners: + close(owner) + + +if __name__ == "__main__": + main() diff --git a/tools/check_optimization_equivalence.py b/tools/check_optimization_equivalence.py new file mode 100644 index 0000000..60775a7 --- /dev/null +++ b/tools/check_optimization_equivalence.py @@ -0,0 +1,462 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare optimization bindings with independent direct original Haskell calls.""" + +import argparse +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PRELUDE = r"""import qualified HMath.Optimization.Common as C +import HMath.Optimization.Common (LearningRate(..)) +import qualified HMath.Optimization.FirstOrder as F +import qualified HMath.Optimization.Local as L +import qualified HMath.Optimization.Constrained as K +import qualified HMath.Optimization.Global as G +import HMath.Error +import GHC.Float (castDoubleToWord64) +import Data.List (intercalate) +f x = Right (sum (map (\v -> v*v) x)) +g x = Right (map (2*) x) +h x = Right [[if i==j then 2 else 0 | j<-[1..length x]] | i<-[1..length x]] +o = C.OptimizeOptions 400 40000 1e-7 0.25 +short = C.OptimizeOptions 3 10000 1e-7 0.25 +r = fmap (\v -> C.optPoint v ++ [C.optValue v,C.optGradientNorm v,fromIntegral(C.optIterations v),fromIntegral(C.optEvaluations v),if C.optConverged v then 1 else 0]) +lp = fmap (\v -> K.lpPoint v ++ [K.lpValue v,fromIntegral(K.lpIterations v)] ++ map fromIntegral(K.lpBasis v)) +s = fmap (:[]) +u = fmap (const []) +stop = fmap (\v -> maybe [0,0] (\x -> [1,x]) (C.bestScore v) ++ [fromIntegral(C.staleSteps v),if C.stopped v then 1 else 0]) +ls = fmap (\(a,y,x,n) -> x++[y,a,fromIntegral n]) +stateStep method = do + (x,state)<-F.stochasticGradient method 0.1 [g,g] [1,-2] + (next,_)<-F.optimizerStep method 0.1 state x [0.3,-0.4] + Right (x++next) +emit :: Either MathError [Double] -> IO () +emit (Left e) = putStrLn ("E:"++show e) +emit (Right values) = putStrLn ("R:"++intercalate "," (map (show . castDoubleToWord64) values)) +main = sequence_ [ +""" + + +def cases(opt): + """Independent language expressions: no adapter-derived expected outputs.""" + o = opt.OptimizeOptions(400, 40000, 1e-7, 0.25) + short = opt.OptimizeOptions(3, 10000, 1e-7, 0.25) + f = lambda x: sum(v * v for v in x) + g = lambda x: [2 * v for v in x] + h = lambda x: [ + [2.0 if i == j else 0.0 for j in range(len(x))] for i in range(len(x)) + ] + result = [] + + def add(name, hs, function): + result.append((name, hs, function)) + + def state_step(method): + point, state = opt.stochastic_gradient(method, 0.1, [g, g], [1, -2]) + with state: + next_point, next_state = opt.optimizer_step( + method, 0.1, state, point, [0.3, -0.4] + ) + next_state.close() + return point + next_point + + def options(): + value = opt.default_optimize_options() + return [ + value.max_iterations, + value.max_evaluations, + value.tolerance, + value.learning_rate, + ] + + add( + "defaults", + "Right [fromIntegral(C.optMaxIterations C.defaultOptimizeOptions),fromIntegral(C.optMaxEvaluations C.defaultOptimizeOptions),C.optTolerance C.defaultOptimizeOptions,C.optLearningRate C.defaultOptimizeOptions]", + options, + ) + schedules = [ + ("ConstantRate 0.2", opt.ConstantRate(0.2)), + ("StepDecay 0.2 3 0.5", opt.StepDecay(0.2, 3, 0.5)), + ("ExponentialDecay 0.2 0.9", opt.ExponentialDecay(0.2, 0.9)), + ("CosineAnnealing 0.2 0.01 8", opt.CosineAnnealing(0.2, 0.01, 8)), + ("Warmup 4 (ConstantRate 0.2)", opt.Warmup(4, opt.ConstantRate(0.2))), + ] + for hs, schedule in schedules: + add( + "schedule " + hs, + "mapM (C.learningRate (" + hs + ")) [0,2,5,9]", + lambda schedule=schedule: [ + opt.learning_rate(schedule, k) for k in [0, 2, 5, 9] + ], + ) + add( + "early stop", + "stop (C.earlyStopping 2 0.01 2 (C.EarlyStopping (Just 1) 1 False))", + lambda: opt.early_stopping(2, 0.01, 2, opt.EarlyStopping(1, 1, False)), + ) + add( + "checked point", "u (C.checkedPoint [1,-2])", lambda: opt.checked_point([1, -2]) + ) + add("checked options", "u (C.checkedOptions o)", lambda: opt.checked_options(o)) + add( + "checked value", + "s (C.checkedValue f [2,-3])", + lambda: opt.checked_value(f, [2, -3]), + ) + add( + "checked gradient", + "C.checkedGradient g [2,-3]", + lambda: opt.checked_gradient(g, [2, -3]), + ) + add("budget", "u (C.checkBudget o 40000)", lambda: opt.check_budget(o, 40000)) + add( + "dense solve", + "C.solveDense [[2,1],[1,3]] [5,7]", + lambda: opt.solve_dense([[2, 1], [1, 3]], [5, 7]), + ) + add( + "ragged multiply", + "Right (concat (C.matMul [[1,2],[3]] [[4],[5,6]]))", + lambda: [v for row in opt.mat_mul([[1, 2], [3]], [[4], [5, 6]]) for v in row], + ) + add( + "result", + "r (C.result 3 8 False f g [2,-3])", + lambda: opt.result(3, 8, False, f, g, [2, -3]), + ) + for method in ["Armijo", "StrongWolfe"]: + add( + "line search " + method, + "ls (C.lineSearch C." + method + " 100 f g [1] [-2] 1 [2])", + lambda method=method: sum_line( + opt.line_search(getattr(opt, method), 100, f, g, [1], [-2], 1, [2]) + ), + ) + methods = [ + "GradientDescent", + "Momentum", + "Nesterov", + "AdaGrad", + "RMSProp", + "AdaDelta", + "Adam", + "AdamW", + "AMSGrad", + "AdaMax", + "Nadam", + "RAdam", + ] + for method, enum in zip(methods, opt.GradientMethod): + add( + "monitor " + method, + "r (F.minimizeGradientWithCallback (\\v -> Right (C.optIterations v < 2)) F." + + method + + " o f g [1,-2])", + lambda enum=enum: opt.minimize_gradient_with_callback( + lambda v: v.iterations < 2, enum, o, f, g, [1, -2] + ), + ) + add( + "stochastic " + method, + "stateStep F." + method, + lambda enum=enum: state_step(enum), + ) + add( + "gradient", + "r (F.minimizeGradient F.GradientDescent o f g [1,-2])", + lambda: opt.minimize_gradient( + opt.GradientMethod.GRADIENT_DESCENT, o, f, g, [1, -2] + ), + ) + add( + "mini batch", + "F.miniBatchGradient [g,Right . map (3*)] [1,-2]", + lambda: invoke_close( + opt.mini_batch_gradient([g, lambda x: [3 * v for v in x]]), [1, -2] + ), + ) + add( + "projected", + "r (F.projectedGradient o f g (Right . map (max 0)) [1,-2])", + lambda: opt.projected_gradient( + o, f, g, lambda x: [max(0, v) for v in x], [1, -2] + ), + ) + add( + "proximal", + "r (F.proximalGradient o f g (\\_ -> Right) [1,-2])", + lambda: opt.proximal_gradient(o, f, g, lambda rate, x: x, [1, -2]), + ) + add( + "fista", + "r (F.fista o f g (\\_ -> Right) [1,-2])", + lambda: opt.fista(o, f, g, lambda rate, x: x, [1, -2]), + ) + add( + "coordinate", + "r (F.coordinateDescent [[1],[0]] o f g [1,-2])", + lambda: opt.coordinate_descent([[1], [0]], o, f, g, [1, -2]), + ) + for method in ["GoldenSection", "TernarySearch", "BrentSearch"]: + add( + "scalar " + method, + "r (L.minimizeScalar L." + method + " o (\\x -> Right (x*x)) (-2) 3)", + lambda method=method: opt.minimize_scalar( + getattr(opt, method), o, lambda x: x * x, -2, 3 + ), + ) + for hs, method in [ + ("BFGS", opt.BFGS), + ("LBFGS 3", opt.LBFGS(3)), + ("DFP", opt.DFP), + ("SR1", opt.SR1), + ]: + add( + "quasi " + hs, + "r (L.minimizeQuasiNewton (L." + hs + ") o f g [1,-2])", + lambda method=method: opt.minimize_quasi_newton(method, o, f, g, [1, -2]), + ) + for hs, method in [ + ("Newton", opt.Newton), + ("NewtonCG", opt.NewtonCG), + ("TrustRegion 0.5", opt.TrustRegion(0.5)), + ("Dogleg 0.5", opt.Dogleg(0.5)), + ]: + add( + "newton " + hs, + "r (L.minimizeNewton (L." + hs + ") o f g h [1,-2])", + lambda method=method: opt.minimize_newton(method, o, f, g, h, [1, -2]), + ) + add( + "cg", + "r (L.nonlinearCG o f g [1,-2])", + lambda: opt.nonlinear_cg(o, f, g, [1, -2]), + ) + for hs, loss in [ + ("SquaredLoss", opt.SquaredLoss), + ("HuberLoss 0.5", opt.HuberLoss(0.5)), + ("CauchyLoss 0.5", opt.CauchyLoss(0.5)), + ("SoftL1 0.5", opt.SoftL1(0.5)), + ]: + add( + "least squares " + hs, + "r (L.leastSquares (L." + + hs + + ") 0.01 o Right (\\_ -> Right [[1,0],[0,1]]) [1,-2])", + lambda loss=loss: opt.least_squares( + loss, 0.01, o, lambda x: x, lambda x: [[1, 0], [0, 1]], [1, -2] + ), + ) + add( + "nelder mead", + "r (L.nelderMead o f [1,-2])", + lambda: opt.nelder_mead(o, f, [1, -2]), + ) + add("powell", "r (L.powell 0.5 o f [1,-2])", lambda: opt.powell(0.5, o, f, [1, -2])) + equality = opt.Equality(lambda x: x[0], lambda x: [1]) + inequality = opt.LessEqual(lambda x: x[0] - 2, lambda x: [1]) + add( + "feasibility", + "s (K.feasibility [K.Equality (Right . head) (const (Right [1])),K.LessEqual (\\x -> Right (head x-2)) (const (Right [1]))] [3])", + lambda: opt.feasibility([equality, inequality], [3]), + ) + for method in [ + "QuadraticPenalty", + "LogBarrier", + "InteriorPoint", + "AugmentedLagrangian", + ]: + add( + "constrained " + method, + "r (K.constrainedMinimize K." + method + " o f g [] [1])", + lambda method=method: opt.constrained_minimize( + getattr(opt, method), o, f, g, [], [1] + ), + ) + add( + "lp", + "lp (K.linearProgramming 100 1e-9 [-1] [[1]] [2])", + lambda: opt.linear_programming(100, 1e-9, [-1], [[1]], [2]), + ) + add( + "revised simplex", + "lp (K.revisedSimplex 100 1e-9 [-1,0] [[1,1]] [2] [1])", + lambda: opt.revised_simplex(100, 1e-9, [-1, 0], [[1, 1]], [2], [1]), + ) + add( + "qp", + "r (K.quadraticProgramming 100 1e-9 [[2]] [-4] [[1]] [1])", + lambda: opt.quadratic_programming(100, 1e-9, [[2]], [-4], [[1]], [1]), + ) + add("slsqp", "r (K.slsqp o f g h [] [1])", lambda: opt.slsqp(o, f, g, h, [], [1])) + add("cobyla", "r (K.cobyla 0.5 o f [] [1])", lambda: opt.cobyla(0.5, o, f, [], [1])) + add( + "weighted objective", + "s (K.weightedObjective [0.25,0.75] [f,Right . sum] [1,2])", + lambda: invoke_close(opt.weighted_objective([0.25, 0.75], [f, sum]), [1, 2]), + ) + add( + "pareto", + "fmap (map fromIntegral) (K.paretoFront [[1,2],[2,1],[3,3],[1,2]])", + lambda: opt.pareto_front([[1, 2], [2, 1], [3, 3], [1, 2]]), + ) + for method in [ + "SimulatedAnnealing", + "DifferentialEvolution", + "GeneticAlgorithm", + "ParticleSwarm", + "CMAES", + ]: + add( + "global " + method, + "r (G.globalMinimize G." + + method + + " 4 18446744073709551615 short [(-2,2),(-3,3)] f)", + lambda method=method: opt.global_minimize( + getattr(opt, method), 4, 2**64 - 1, short, [(-2, 2), (-3, 3)], f + ), + ) + add( + "basin hopping", + "r (G.basinHopping 91 1 2 o [(-2,2)] f [1])", + lambda: opt.basin_hopping(91, 1, 2, o, [(-2, 2)], f, [1]), + ) + invalid = [ + ( + "bad options", + "u (C.checkedOptions (o{C.optMaxIterations=0}))", + lambda: opt.checked_options(opt.OptimizeOptions(0, 100, 1e-7, 0.25)), + ), + ( + "budget error", + "u (C.checkBudget o 40001)", + lambda: opt.check_budget(o, 40001), + ), + ( + "bad gradient", + "C.checkedGradient (const (Right [])) [1]", + lambda: opt.checked_gradient(lambda x: [], [1]), + ), + ( + "bad point", + "u (C.checkedPoint [0/0])", + lambda: opt.checked_point([float("nan")]), + ), + ( + "invalid LBFGS", + "r (L.minimizeQuasiNewton (L.LBFGS 0) o f g [1])", + lambda: opt.minimize_quasi_newton(opt.LBFGS(0), o, f, g, [1]), + ), + ( + "empty batch", + "F.miniBatchGradient [] [1]", + lambda: invoke_close(opt.mini_batch_gradient([]), [1]), + ), + ( + "unbounded LP", + "lp (K.linearProgramming 100 1e-9 [-1] [[-1]] [0])", + lambda: opt.linear_programming(100, 1e-9, [-1], [[-1]], [0]), + ), + ] + for name, hs, fn in invalid: + add(name, hs, fn) + return result + + +def invoke_close(function, *args): + with function: + return function(*args) + + +def sum_line(value): + rate, y, point, count = value + return point + [y, rate, count] + + +def flatten(value): + from _hmath_native import optimization as opt + + if value is None: + return [] + if isinstance(value, opt.OptimizeResult): + return value.point + [ + value.value, + value.gradient_norm, + value.iterations, + value.evaluations, + value.converged, + ] + if isinstance(value, opt.LPResult): + return value.point + [value.value, value.iterations] + value.basis + if isinstance(value, opt.EarlyStopping): + return ([0, 0] if value.best_score is None else [1, value.best_score]) + [ + value.stale_steps, + value.stopped, + ] + if isinstance(value, (list, tuple)): + return list(value) + return [value] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + os.environ["HMATH_BACKEND"] = "pure" + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import optimization as opt + + selected = cases(opt) + with tempfile.TemporaryDirectory(prefix="hmath-opt-oracle-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text( + PRELUDE + ",\n".join(" emit (" + hs + ")" for _, hs, _ in selected) + "]\n" + ) + subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-i" + str(ROOT / "src"), + "-I" + str(ROOT / "include"), + "-outputdir", + temporary, + str(source), + str(ROOT / "cbits/backend.c"), + "-ldl", + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + for (name, _, call), reference in zip(selected, expected, strict=True): + try: + output = flatten(call()) + bits = [ + str(struct.unpack("=Q", struct.pack("=d", float(v)))[0]) for v in output + ] + actual = "R:" + ",".join(bits) + except hmath.HMathError as error: + if error.math_error is None: + raise + actual = "E:" + str(error.math_error) + if actual != reference: + raise AssertionError(f"{name}: binding {actual}, original {reference}") + print( + f"Optimization equivalence: {len(selected)} independent original Haskell operation sequences match (binary64 bits, complete diagnostics and errors)." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_polynomial_equivalence.py b/tools/check_polynomial_equivalence.py new file mode 100644 index 0000000..3bc0c7d --- /dev/null +++ b/tools/check_polynomial_equivalence.py @@ -0,0 +1,403 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-Haskell oracle for all public Polynomial operations.""" + +import argparse +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +F = Fraction + +HASKELL = r"""{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +import qualified HMath.Polynomial as P +import qualified HMath.Matrix as M +import Data.Complex +import Data.Ratio +import Data.List (intercalate) +import GHC.Float (castDoubleToWord64,castFloatToWord32) +class E a where enc :: a -> String +instance E Integer where enc x="I"++show x +instance E Int where enc x="I"++show x +instance E Bool where enc x=if x then "B1" else "B0" +instance E Double where enc x="F64:"++show(castDoubleToWord64 x) +instance E Float where enc x="F32:"++show(castFloatToWord32 x) +instance E Rational where enc x="R"++show(numerator x)++"/"++show(denominator x) +instance E (Complex Double) where enc (r:+i)="C64:"++show(castDoubleToWord64 r)++":"++show(castDoubleToWord64 i) +instance E (Complex Float) where enc (r:+i)="C32:"++show(castFloatToWord32 r)++":"++show(castFloatToWord32 i) +instance E a => E [a] where enc xs="L["++intercalate "," (map enc xs)++"]" +instance (E a,E b) => E (a,b) where enc(a,b)="T["++enc a++","++enc b++"]" +instance (E a,E b,E c) => E (a,b,c) where enc(a,b,c)="T["++enc a++","++enc b++","++enc c++"]" +instance E a => E (P.Polynomial a) where enc p="P["++intercalate "," (map enc(P.coefficients p))++"]" +instance E a => E (P.PowerSeries a) where enc p="S["++intercalate "," (map enc(P.seriesCoefficients p))++"]" +instance E P.RationalFunction where enc f="RF["++enc(P.rationalNumerator f)++","++enc(P.rationalDenominator f)++"]" +instance E a => E (M.Matrix a) where enc m=let(r,c)=M.shape m in "M"++show r++":"++show c++"["++intercalate "," (map enc(M.toList m))++"]" +instance E a => E(Maybe a) where enc Nothing="N"; enc(Just x)=enc x +ok :: E a => Either HMath.Error.MathError a -> String +ok=either (("E"++).show) enc +pR=P.polynomial [-1,0,1] :: P.Polynomial Rational +qR=P.polynomial [-1,1] :: P.Polynomial Rational +sR=P.powerSeries [1,2,3,0] :: P.PowerSeries Rational +tR=P.powerSeries [0,1,0,0] :: P.PowerSeries Rational +rf=case P.rationalFunction (P.polynomial [1]) pR of Right x->x; Left e->error(show e) +pointsR=[(0,1),(1,3),(2,7)] :: [(Rational,Rational)] +main=mapM_ putStrLn + [ EXPRESSIONS + ] +""".replace("import Data.Complex", "import qualified HMath.Error\nimport Data.Complex") + + +def bits(value, precision): + return struct.unpack( + "!I" if precision == 32 else "!Q", + struct.pack("!f" if precision == 32 else "!d", value), + )[0] + + +def encode(value, p, precision=64): + from _hmath_native import _matrix_base + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, F): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + return f"F{precision}:" + str(bits(value, precision)) + if isinstance(value, complex): + return ( + f"C{precision}:" + + str(bits(value.real, precision)) + + ":" + + str(bits(value.imag, precision)) + ) + if isinstance(value, p.Polynomial): + return ( + "P[" + ",".join(encode(x, p, precision) for x in value.coefficients) + "]" + ) + if isinstance(value, p.PowerSeries): + return ( + "S[" + ",".join(encode(x, p, precision) for x in value.coefficients) + "]" + ) + if isinstance(value, p.RationalFunction): + numerator = p.rational_numerator(value) + denominator = p.rational_denominator(value) + try: + return "RF[" + encode(numerator, p) + "," + encode(denominator, p) + "]" + finally: + numerator.close() + denominator.close() + if isinstance(value, _matrix_base.Matrix): + r, c = value.shape + return ( + f"M{r}:{c}[" + + ",".join(encode(x, p, precision) for x in value.to_list()) + + "]" + ) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(x, p, precision) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +def close(value): + if isinstance(value, (list, tuple)): + for item in value: + close(item) + elif hasattr(value, "close"): + value.close() + + +def cases(p): + owned = [] + + def poly(xs, dtype="rational"): + x = p.polynomial(xs, dtype=dtype) + owned.append(x) + return x + + def series(xs, dtype="rational"): + x = p.power_series(xs, dtype=dtype) + owned.append(x) + return x + + a = poly([-1, 0, 1]) + b = poly([-1, 1]) + s = series([1, 2, 3, 0]) + t = series([0, 1, 0, 0]) + z = poly([]) + rf = p.rational_function(poly([1]), a) + owned.append(rf) + points = [(F(0), F(1)), (F(1), F(3)), (F(2), F(7))] + result = [] + + def add(name, args, expression, checked=False, precision=64, kwargs=None): + result.append( + ( + name, + args, + kwargs or {}, + ("ok" if checked else "enc") + " (" + expression + ")", + precision, + ) + ) + + add( + "polynomial", + ([1, 0, 0],), + "P.polynomial [1,0,0] :: P.Polynomial Rational", + kwargs={"dtype": "rational"}, + ) + add("coefficients", (a,), "P.coefficients pR") + add("polynomial_degree", (a,), "P.polynomialDegree pR") + add( + "polynomial_degree", + (z,), + "P.polynomialDegree (P.polynomial [] :: P.Polynomial Rational)", + ) + add("evaluate_polynomial", (a, F(3, 2)), "P.evaluatePolynomial pR (3%2)") + for python, haskell in [ + ("add_polynomial", "addPolynomial"), + ("subtract_polynomial", "subtractPolynomial"), + ("multiply_polynomial", "multiplyPolynomial"), + ("compose_polynomial", "composePolynomial"), + ("divide_polynomial", "dividePolynomial"), + ("gcd_polynomial", "gcdPolynomial"), + ]: + add(python, (a, b), "P." + haskell + " pR qR", haskell == "dividePolynomial") + add("scale_polynomial", (F(3, 2), a), "P.scalePolynomial (3%2) pR") + add("monic_polynomial", (a,), "P.monicPolynomial pR") + add("differentiate_polynomial", (a,), "P.differentiatePolynomial pR") + add("integrate_polynomial", (F(7, 3), a), "P.integratePolynomial (7%3) pR") + add("square_free_factors", (a,), "P.squareFreeFactors pR") + add("rational_roots", (1000, a), "P.rationalRoots 1000 pR", True) + add( + "factor_rational_polynomial", + (1000, a), + "P.factorRationalPolynomial 1000 pR", + True, + ) + add("sturm_sequence", (a,), "P.sturmSequence pR", True) + add("count_real_roots", (a, F(-2), F(2)), "P.countRealRoots pR (-2) 2", True) + add( + "isolate_real_roots", + (20, F(1, 100), a), + "P.isolateRealRoots 20 (1%100) pR", + True, + ) + c = poly([-1, 0, 1], "complex128") + for py, hs in [ + ("durand_kerner", "durandKerner"), + ("aberth_ehrlich", "aberthEhrlich"), + ]: + add( + py, + (200, 1e-8, c), + "P." + + hs + + " 200 1e-8 (P.polynomial [-1,0,1] :: P.Polynomial (Complex Double))", + True, + ) + add("companion_matrix", (a,), "P.companionMatrix pR", True) + for py, hs in [ + ("lagrange_interpolation", "lagrangeInterpolation"), + ("newton_interpolation", "newtonInterpolation"), + ]: + add(py, (points,), "P." + hs + " pointsR", True, kwargs={"dtype": "rational"}) + for py, hs in [ + ("chebyshev_polynomial", "chebyshevPolynomial"), + ("legendre_polynomial", "legendrePolynomial"), + ("hermite_polynomial", "hermitePolynomial"), + ("laguerre_polynomial", "laguerrePolynomial"), + ]: + add( + py, + (3,), + "P." + hs + " 3 :: Either HMath.Error.MathError (P.Polynomial Rational)", + True, + kwargs={"dtype": "rational"}, + ) + add( + "bernstein_polynomial", + (4, 2), + "P.bernsteinPolynomial 4 2 :: Either HMath.Error.MathError (P.Polynomial Rational)", + True, + kwargs={"dtype": "rational"}, + ) + add( + "polynomial_regression", + (2, [(0.0, 1.0), (1.0, 3.0), (2.0, 7.0), (3.0, 13.0)]), + "P.polynomialRegression 2 [(0,1),(1,3),(2,7),(3,13)] :: Either HMath.Error.MathError (P.Polynomial Double)", + True, + ) + add( + "chebyshev_approximation", + (4, lambda x: x * x + 2 * x + 1), + "P.chebyshevApproximation 4 (\\x -> x*x+2*x+1)", + True, + ) + add( + "power_series", + ([1, 0, 0],), + "P.powerSeries [1,0,0] :: P.PowerSeries Rational", + kwargs={"dtype": "rational"}, + ) + add("series_coefficients", (s,), "P.seriesCoefficients sR") + for py, hs, args, hsargs, checked in [ + ("add_series", "addSeries", (s, t), "sR tR", False), + ("multiply_series", "multiplySeries", (s, t), "sR tR", False), + ("reciprocal_series", "reciprocalSeries", (s,), "sR", True), + ("divide_series", "divideSeries", (t, s), "tR sR", True), + ("compose_series", "composeSeries", (s, t), "sR tR", True), + ("differentiate_series", "differentiateSeries", (s,), "sR", False), + ("integrate_series", "integrateSeries", (F(2, 3), s), "(2%3) sR", False), + ]: + add(py, args, "P." + hs + " " + hsargs, checked) + sd = series([1.0, 2.0, 3.0, 0.0], "float64") + add( + "exp_series", + (sd,), + "P.expSeries (P.powerSeries [1,2,3,0] :: P.PowerSeries Double)", + ) + add( + "log_series", + (sd,), + "P.logSeries (P.powerSeries [1,2,3,0] :: P.PowerSeries Double)", + True, + ) + add( + "rational_function", + (poly([1]), a), + "P.rationalFunction (P.polynomial [1]) pR", + True, + ) + add("rational_numerator", (rf,), "P.rationalNumerator rf") + add("rational_denominator", (rf,), "P.rationalDenominator rf") + add( + "evaluate_rational_function", + (rf, F(3, 2)), + "P.evaluateRationalFunction rf (3%2)", + True, + ) + add("add_rational_function", (rf, rf), "P.addRationalFunction rf rf", True) + add( + "multiply_rational_function", (rf, rf), "P.multiplyRationalFunction rf rf", True + ) + add("partial_fractions", (1000, rf), "P.partialFractions 1000 rf", True) + # Original checked failures and both floating coefficient types. + add("divide_polynomial", (a, z), "P.dividePolynomial pR (P.polynomial [])", True) + add("rational_roots", (-1, a), "P.rationalRoots (-1) pR", True) + add("count_real_roots", (a, F(2), F(-2)), "P.countRealRoots pR 2 (-2)", True) + add("reciprocal_series", (t,), "P.reciprocalSeries tR", True) + add("compose_series", (s, s), "P.composeSeries sR sR", True) + add("rational_function", (a, z), "P.rationalFunction pR (P.polynomial [])", True) + add( + "chebyshev_approximation", + (-1, lambda x: x), + "P.chebyshevApproximation (-1) id", + True, + ) + for dtype, hsdtype, precision in [ + ("float32", "Float", 32), + ("float64", "Double", 64), + ("integer", "Integer", 64), + ("complex64", "Complex Float", 32), + ("complex128", "Complex Double", 64), + ]: + fp = poly([0.125, 2, -3] if dtype != "integer" else [10**80, 2, -3], dtype) + xs = "[0.125,2,-3]" if dtype != "integer" else "[" + str(10**80) + ",2,-3]" + if dtype.startswith("complex"): + xs = "[0.125 :+ 0,2 :+ 0,(-3) :+ 0]" + hp = "(P.polynomial " + xs + " :: P.Polynomial (" + hsdtype + "))" + add( + "multiply_polynomial", + (fp, fp), + "P.multiplyPolynomial " + hp + " " + hp, + precision=precision, + ) + add( + "differentiate_polynomial", + (fp,), + "P.differentiatePolynomial " + hp, + precision=precision, + ) + if dtype != "integer": + add( + "companion_matrix", + (fp,), + "P.companionMatrix " + hp, + True, + precision=precision, + ) + return result, owned + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + # Test modules may also be exposed through hmath.polynomial by integration. + from _hmath_native import _matrix_base + from _hmath_native import polynomial as p + + del _matrix_base + fixtures, owners = cases(p) + try: + source = HASKELL.replace( + "EXPRESSIONS", "\n , ".join(item[3] for item in fixtures) + ) + with tempfile.TemporaryDirectory(prefix="hmath-poly-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + expected = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=True, + ).stdout.splitlines() + actual = [] + for name, arguments, kwargs, _expression, precision in fixtures: + try: + result = getattr(p, name)(*arguments, **kwargs) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(result, p, precision)) + finally: + close(result) + failures = [ + (i, fixtures[i][0], want, got) + for i, (want, got) in enumerate(zip(expected, actual)) + if want != got + ] + if len(expected) != len(actual) or failures: + raise AssertionError( + f"{len(failures)} Polynomial oracle mismatches: {failures[:12]}" + ) + print( + f"Polynomial direct Haskell equivalence: {len(actual)} cases, all50 public functions" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_python_wheel.py b/tools/check_python_wheel.py index 1bf920b..746fdfd 100644 --- a/tools/check_python_wheel.py +++ b/tools/check_python_wheel.py @@ -37,5 +37,7 @@ ) if len(sys.argv) > 1: - runpy.run_path(sys.argv[1], run_name="__main__") + test_path = sys.argv[1] + sys.argv = [test_path] + runpy.run_path(test_path, run_name="__main__") print(f"Installed wheel verified on Python {sys.version.split()[0]}") diff --git a/tools/check_release_remote.py b/tools/check_release_remote.py new file mode 100644 index 0000000..4427659 --- /dev/null +++ b/tools/check_release_remote.py @@ -0,0 +1,101 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Refuse immutable-version collisions before uploading either package. + +Retries may skip an existing file only after its SHA-256 matches the prepared +artifact. Network/authentication failures are errors, never treated as absence. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +from urllib.error import HTTPError +from urllib.request import urlopen + +from release_version import release_version +from verify_release_candidate import verify_candidate + + +def fetch(url): + try: + with urlopen(url, timeout=30) as response: + return response.read() + except HTTPError as error: + if error.code == 404: + return None + raise + + +def python_status(files, body): + remote = ( + { + entry["filename"]: entry["digests"]["sha256"] + for entry in json.loads(body)["urls"] + } + if body + else {} + ) + matches = 0 + for path in files: + if path.name in remote: + if remote[path.name] != hashlib.sha256(path.read_bytes()).hexdigest(): + raise ValueError( + f"published Python file differs: {path.name}; choose a new version" + ) + matches += 1 + if remote and not matches: + raise ValueError( + "published version cannot be identified as this prepared release" + ) + return matches == len(files) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--python", type=Path, required=True) + parser.add_argument("--native", type=Path, required=True) + parser.add_argument("--index", choices=["pypi", "testpypi"], default="pypi") + parser.add_argument("--commit", help="Original source SHA of a verified candidate") + args = parser.parse_args() + version = ( + verify_candidate(args.python, args.commit)["version"] + if args.commit + else release_version() + ) + files = sorted(args.python.glob("*.whl")) + sorted( + args.python.glob("hmath_python-*.tar.gz") + ) + if not files: + raise ValueError("missing Python distributions") + host = "pypi.org" if args.index == "pypi" else "test.pypi.org" + python_complete = python_status( + files, fetch(f"https://{host}/pypi/hmath-python/{version}/json") + ) + haskell_complete = False + if args.index == "pypi": + source = args.native / f"hmath-{version}.tar.gz" + if not source.is_file(): + raise ValueError("missing Haskell source distribution") + remote = fetch( + f"https://hackage.haskell.org/package/hmath-{version}/hmath-{version}.tar.gz" + ) + if remote is not None: + if ( + hashlib.sha256(remote).digest() + != hashlib.sha256(source.read_bytes()).digest() + ): + raise ValueError( + "published Haskell source differs; choose a new version" + ) + haskell_complete = True + values = {"python_complete": python_complete, "haskell_complete": haskell_complete} + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + for name, value in values.items(): + print(f"{name}={str(value).lower()}", file=output) + print(json.dumps(values)) + + +if __name__ == "__main__": + main() diff --git a/tools/check_rotation_equivalence.py b/tools/check_rotation_equivalence.py new file mode 100644 index 0000000..d34e12e --- /dev/null +++ b/tools/check_rotation_equivalence.py @@ -0,0 +1,295 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare every Quaternion/Rotation adapter with independent original Haskell calls.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_rotation_bindings import SPECS + +ROOT = Path(__file__).resolve().parent.parent + + +def fp(value): + return ( + "nan" + if math.isnan(value) + else str(struct.unpack("!Q", struct.pack("!d", value))[0]) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", type=Path, required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import matrix as m + from _hmath_native import quaternion as q + from _hmath_native import rotation as r + + owners = [] + + def own(value): + owners.append(value) + return value + + qa = own(q.from_euler(0.1, 0.2, 0.3)) + qb = own(q.from_euler(-0.2, 0.4, -0.1)) + zero = own(q.quaternion(0, 0, 0, 0)) + ra, rb = own(r.so3(qa)), own(r.so3(qb)) + ta, tb = own(r.se3(ra, [1, 2, 3])), own(r.se3(rb, [-2, 0.5, 4])) + dqa, dqb = own(r.to_dual_quaternion(ta)), own(r.to_dual_quaternion(tb)) + qm, hm = own(q.to_matrix(qa)), own(r.to_homogeneous(ta)) + wrong_matrix = own(m.from_list_checked(2, 3, [1, 0, 0, 0, 1, 0])) + + def encode(kind, value): + if kind == "q": + return encode("v", q.components(value)) + if kind == "r": + with r.rotation_quaternion(value) as child: + return encode("q", child) + if kind == "t": + with r.rotation_part(value) as child: + return encode("r", child) + ";" + encode("v", r.translation_part(value)) + if kind == "dq": + children = r.dual_parts(value) + try: + return ";".join(encode("q", x) for x in children) + finally: + for child in children: + child.close() + if kind == "d": + return fp(value) + if kind in ("v", "triple"): + return ",".join(fp(x) for x in value) + if kind == "m": + return ( + str(value.shape[0]) + + "," + + str(value.shape[1]) + + ":" + + encode("v", value.to_list()) + ) + if kind == "axis": + return encode("v", value[0]) + ";" + fp(value[1]) + if kind == "twist": + return ";".join(encode("v", x) for x in value) + if kind == "qq": + return ";".join(encode("q", x) for x in value) + raise AssertionError(kind) + + def argument(item, name, kind, bad, index): + if kind == "q": + return ( + (zero, "zero") if bad else (qa, "qa") if index % 2 == 0 else (qb, "qb") + ) + if kind == "r": + return (ra, "ra") if index % 2 == 0 else (rb, "rb") + if kind == "t": + return (ta, "ta") if index % 2 == 0 else (tb, "tb") + if kind == "dq": + return (dqa, "dqa") if index % 2 == 0 else (dqb, "dqb") + if kind == "d": + if bad: + return math.inf, "(1/0)" + return 0.25, "(0.25)" + if kind == "v": + return ([], "[]") if bad else ([0.1, 0.2, 0.3], "[0.1,0.2,0.3]") + if kind == "twist": + return ( + (([], []), "([],[])") + if bad + else (([0.1, 0.2, 0.3], [1, 2, 3]), "([0.1,0.2,0.3],[1,2,3])") + ) + if kind == "m": + if bad: + return wrong_matrix, "wrongMatrix" + return (qm, "qm") if item["module"] == "Quaternion" else (hm, "hm") + raise AssertionError((name, kind)) + + hsenc = { + "q": "quat", + "r": "rotation", + "t": "transform", + "dq": "dualQuaternion", + "d": "fp", + "v": "vector", + "m": "matrix", + "axis": "axis", + "triple": "triple", + "qq": "quaternionPair", + "twist": "twist", + } + lines = [ + "import qualified HMath.Quaternion as Q", + "import HMath.Error (MathError)", + "import qualified HMath.Rotation as R", + "import qualified HMath.Matrix as M", + "import Data.List (intercalate)", + "import GHC.Float", + 'fp x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'vector=intercalate "," . map fp', + "quat=vector . Q.components", + "rotation=quat . R.rotationQuaternion", + 'transform t=rotation (R.rotationPart t)++";"++vector (R.translationPart t)', + "dualQuaternion t=quaternionPair (R.dualParts t)", + 'quaternionPair (a,b)=quat a++";"++quat b', + 'axis (a,b)=vector a++";"++fp b', + "triple (a,b,c)=vector [a,b,c]", + 'twist (a,b)=vector a++";"++vector b', + 'matrix m=let (a,b)=M.shape m in show a++","++show b++":"++vector (M.toList m)', + "right (Right x)=x", + "right (Left e)=error (show e)", + "emit :: (a -> String) -> Either MathError a -> IO ()", + 'emit e (Right x)=putStrLn ("OK:"++e x)', + 'emit _ (Left e)=putStrLn ("ERR:"++show e)', + "qa=right (Q.fromEuler 0.1 0.2 0.3)", + "qb=right (Q.fromEuler (-0.2) 0.4 (-0.1))", + "zero=right (Q.quaternion 0 0 0 0)", + "ra=right (R.so3 qa)", + "rb=right (R.so3 qb)", + "ta=right (R.se3 ra [1,2,3])", + "tb=right (R.se3 rb [-2,0.5,4])", + "dqa=right (R.toDualQuaternion ta)", + "dqb=right (R.toDualQuaternion tb)", + "qm=right (Q.toMatrix qa)", + "hm=right (R.toHomogeneous ta)", + "wrongMatrix=right (M.fromListChecked 2 3 [1,0,0,0,1,0]::Either a (M.Matrix Double))", + "main=do", + ] + # Remove the unconstrained diagnostic type from the concrete Matrix fixture. + lines[-2] = "wrongMatrix=right (M.fromListChecked 2 3 [1,0,0,0,1,0::Double])" + cases = [] + for item in SPECS: + for bad in [False, True]: + values = [ + argument(item, name, kind, bad, i) + for i, (name, kind) in enumerate(item["args"]) + ] + expression = ( + ("Q." if item["module"] == "Quaternion" else "R.") + + item["name"] + + "".join(" " + x[1] for x in values) + ) + if not item["checked"]: + expression = "Right (" + expression + ")" + lines.append(" emit " + hsenc[item["result"]] + " (" + expression + ")") + cases.append((item, [x[0] for x in values], bad)) + # Exercise identity series, pi branch, gimbal lock and sign-equivalent arcs. + extras = [ + ( + "log-so3-pi", + "R.logSO3 (right (R.expSO3 [pi,0,0]))", + "v", + lambda: r.log_so3(r.exp_so3([math.pi, 0, 0])), + ), + ( + "log-so3-zero", + "R.logSO3 R.identityRotation", + "v", + lambda: r.log_so3(r.identity_rotation()), + ), + ( + "pure-translation", + "R.expSE3 ([0,0,0],[1,2,3])", + "t", + lambda: r.exp_se3(([0, 0, 0], [1, 2, 3])), + ), + ( + "identity-log", + "R.logSE3 R.identityTransform", + "twist", + lambda: r.log_se3(r.identity_transform()), + ), + ( + "gimbal-lock", + "Q.toEuler (right (Q.fromEuler 0.2 (pi/2) 0.3))", + "triple", + lambda: q.to_euler(q.from_euler(0.2, math.pi / 2, 0.3)), + ), + ( + "negative-quaternion", + "Q.slerp 0.5 qa (right (Q.scale (-1) qa))", + "q", + lambda: q.slerp(0.5, qa, q.scale(-1, qa)), + ), + ] + for _, expression, kind, _ in extras: + lines.append(" emit " + hsenc[kind] + " (" + expression + ")") + with tempfile.TemporaryDirectory(prefix="hmath-rotation-oracle-") as directory: + path = Path(directory) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-outputdir", + directory, + str(source), + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + assert len(expected) == len(cases) + len(extras) + for index, (item, values, bad) in enumerate(cases): + result = None + try: + result = getattr( + q if item["module"] == "Quaternion" else r, item["python"] + )(*values) + actual = "OK:" + encode(item["result"], result) + except hmath.HMathError as error: + assert error.math_error is not None + actual = "ERR:" + str(error.math_error) + finally: + if isinstance(result, (list, tuple)): + for child in result: + if hasattr(child, "close"): + child.close() + elif hasattr(result, "close"): + result.close() + assert actual == expected[index], ( + item["module"], + item["name"], + bad, + actual, + expected[index], + ) + for index, (label, _, kind, function) in enumerate(extras, len(cases)): + result = function() + try: + actual = "OK:" + encode(kind, result) + assert actual == expected[index], (label, actual, expected[index]) + finally: + if hasattr(result, "close"): + result.close() + assert qa == qa.clone().decode() + assert qa != qb + child = r.rotation_part(ta) + ta.close() + assert r.rotate(child, [1, 2, 3]) == r.rotate(ra, [1, 2, 3]) + child.close() + for owner in owners: + owner.close() + print( + f"Quaternion/Rotation: {len(expected)} direct Haskell cases, complete source errors, matrix interop and ownership passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_scalar_extras.py b/tools/check_scalar_extras.py new file mode 100644 index 0000000..1863e73 --- /dev/null +++ b/tools/check_scalar_extras.py @@ -0,0 +1,371 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare completed scalar domains with direct source Haskell and IEEE/exact wire values.""" + +import argparse +import math +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_graph_bindings import snake +from generate_scalar_extras import COMPLEX_FUNCTION, ELEMENTARY + +ROOT = Path(__file__).resolve().parent.parent + + +def bits(value, width=64): + return ( + "nan" + if math.isnan(value) + else str( + struct.unpack( + "!Q" if width == 64 else "!I", + struct.pack("!d" if width == 64 else "!f", value), + )[0] + ) + ) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--library", type=Path, required=True) + a = p.parse_args() + os.environ["HMATH_LIBRARY"] = str(a.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import ( + complex_extras as c, + ) + from _hmath_native import ( + numbertheory_extras as n, + ) + from _hmath_native import ( + special_extras as s, + ) + from _hmath_native import ( + trigonometry_extras as t, + ) + from _hmath_native._value import Value + + cases = [] + owners = [] + + def case(label, hs, encode, call): + cases.append((label, hs, encode, call)) + + def own(x): + owners.append(x) + return x + + def encode(kind, value): + if kind == "selector": + return value.name + if kind in ("c64", "c32"): + width = 64 if kind == "c64" else 32 + return bits(value.real, width) + "," + bits(value.imag, width) + if kind == "d": + return bits(value) + if kind in ("i", "z"): + return str(value) + if kind == "sf": + return bits(value.sf_value) + "," + bits(value.sf_error) + if kind == "matrix": + return ( + str(value.shape[0]) + + "," + + str(value.shape[1]) + + ":" + + encode("list:c64", value.to_list()) + ) + if kind.startswith("list:"): + return "[" + ",".join(encode(kind[5:], x) for x in value) + "]" + if kind.startswith("pair:"): + ks = kind[5:].split(":") + return "(" + ";".join(encode(k, x) for k, x in zip(ks, value)) + ")" + if kind.startswith("maybe:"): + return ( + "Nothing" if value is None else "Just(" + encode(kind[6:], value) + ")" + ) + raise AssertionError(kind) + + def hse(kind): + if kind == "selector": + return "show" + if kind == "c64": + return "(complex fp64)" + if kind == "c32": + return "(complex fp32)" + if kind == "d": + return "fp64" + if kind in ("i", "z"): + return "show" + if kind == "sf": + return "sf" + if kind == "matrix": + return "matrix" + if kind.startswith("list:"): + return "(list " + hse(kind[5:]) + ")" + if kind.startswith("pair:"): + ks = kind[5:].split(":") + vs = ["v" + str(j) for j in range(len(ks))] + return ( + "(\\(" + + ",".join(vs) + + ') -> "("++intercalate ";" [' + + ",".join(hse(k) + " " + v for k, v in zip(ks, vs)) + + ']++")")' + ) + if kind.startswith("maybe:"): + return '(maybe "Nothing" (\\x -> "Just("++' + hse(kind[6:]) + ' x++")"))' + raise AssertionError(kind) + + input_values = [complex(0.25, 0.5), 0j, complex(-1, -0.0), complex(math.inf, 0.25)] + hs64 = [ + "(0.25:+0.5)", + "(0:+0)", + "((-1):+castWord64ToDouble 9223372036854775808)", + "((1/0):+0.25)", + ] + hs32 = [ + "(0.25:+0.5)", + "(0:+0)", + "((-1):+castWord32ToFloat 2147483648)", + "((1/0):+0.25)", + ] + for name in ELEMENTARY: + selector = own(getattr(c, snake(name))()) + case( + "Elementary." + name, + "Right C." + name, + "selector", + lambda selector=selector: selector.clone().decode(), + ) + for j, value in enumerate(input_values): + case( + name + str(j), + "C.elementary C." + name + " (opaque " + hs64[j] + ")", + "c64", + lambda selector=selector, value=value: c.elementary(selector, value), + ) + for name in COMPLEX_FUNCTION: + selector = own(getattr(t, snake(name))()) + case( + "ComplexFunction." + name, + "Right T." + name, + "selector", + lambda selector=selector: selector.clone().decode(), + ) + for width, values in [(32, hs32), (64, hs64)]: + for j, value in enumerate(input_values): + case( + name + str(width) + str(j), + "T.complexFunction T." + + name + + " (opaque " + + values[j] + + "::Complex " + + ("Float" if width == 32 else "Double") + + ")", + "c32" if width == 32 else "c64", + lambda selector=selector, value=value, width=width: ( + t.complex_function(selector, value, dtype="float" + str(width)) + ), + ) + ma = own( + c.complex_matrix( + 2, 2, [1 + 2j, complex(-0.5, 0.25), complex(-0.0, -0.0), 3 - 2j] + ) + ) + mb = own(c.complex_matrix(2, 1, [0.5 + 1j, -2 + 0.25j])) + case( + "complexMatrix", + "C.complexMatrix 2 2 matrixValues", + "matrix", + lambda: c.complex_matrix( + 2, 2, [1 + 2j, complex(-0.5, 0.25), complex(-0.0, -0.0), 3 - 2j] + ), + ) + case( + "multiplyMatrices", + "C.multiplyMatrices ma mb", + "matrix", + lambda: c.multiply_matrices(ma, mb), + ) + case( + "conjugateTranspose", + "C.conjugateTranspose ma", + "matrix", + lambda: c.conjugate_transpose(ma), + ) + case( + "matrixshapeerror", + "C.complexMatrix (-1) 2 []", + "matrix", + lambda: c.complex_matrix(-1, 2, []), + ) + for name, hs in [("complex_fft", "complexFFT"), ("complex_ifft", "complexIFFT")]: + for values, expression in [ + ([], "[]"), + ([1 + 2j, 0.5 - 1j, 3 + 4j], "[1:+2,0.5:+(-1),3:+4]"), + ]: + case( + name + expression, + "C." + hs + " " + expression, + "list:c64", + lambda name=name, values=values: getattr(c, name)(values), + ) + for pairs in [ + [(2, 3), (3, 5)], + [(-1, 6), (5, 8)], + [(1, 2), (0, 2)], + [(10**100 + 1, 97), (10**110 + 2, 101)], + ]: + hs = "[" + ",".join("(" + str(x) + "," + str(y) + ")" for x, y in pairs) + "]" + case( + "CRT" + hs, + "N.chineseRemainder " + hs, + "pair:z:z", + lambda pairs=pairs: n.chinese_remainder(pairs), + ) + for args in [(15, 21, 6), (-15, 21, 6), (0, 0, 0), (15, 21, 7), (10**90 + 1, 3, 1)]: + case( + "Diophantine" + str(args), + "N.linearDiophantine " + " ".join("(" + str(x) + ")" for x in args), + "pair:z:z:z:z", + lambda args=args: n.linear_diophantine(*args), + ) + for value in [0, 1, -1, 2, 4, 8, -8, -16, 10**100, 10**100 + 3]: + case( + "power" + str(value), + "Right (N.perfectPower (" + str(value) + "))", + "maybe:pair:z:i", + lambda value=value: n.perfect_power(value), + ) + for budget, value in [(1000, 360), (0, 97), (0, 1), (0, 360), (-1, 2), (10, 0)]: + case( + "factor" + str((budget, value)), + "N.primeFactorization (" + str(budget) + ") (" + str(value) + ")", + "list:pair:z:i", + lambda budget=budget, value=value: n.prime_factorization(budget, value), + ) + for value in [-1, 0, 1, 5]: + case( + "partitions" + str(value), + "N.partitions (" + str(value) + ")", + "list:list:i", + lambda value=value: n.partitions(value), + ) + for value, error, expression in [ + (1.25, -0.5, "S.SFResult 1.25 (-0.5)"), + (-0.0, math.nan, "S.SFResult (castWord64ToDouble 9223372036854775808) (0/0)"), + (math.inf, -0.0, "S.SFResult (1/0) (castWord64ToDouble 9223372036854775808)"), + ]: + case( + "SFResult" + expression, + "Right (" + expression + ")", + "sf", + lambda value=value, error=error: s.sf_result(value, error), + ) + case( + "sfValue" + expression, + "Right (S.sfValue (" + expression + "))", + "d", + lambda value=value, error=error: s.sf_value((value, error)), + ) + case( + "sfError" + expression, + "Right (S.sfError (" + expression + "))", + "d", + lambda value=value, error=error: s.sf_error((value, error)), + ) + lines = [ + "import qualified HMath.Complex as C", + "import qualified HMath.Trigonometry as T", + "import qualified HMath.NumberTheory as N", + "import qualified HMath.Special as S", + "import qualified HMath.Matrix as M", + "import HMath.Error (MathError)", + "import Data.Complex", + "import Data.List (intercalate)", + "import GHC.Float", + "{-# NOINLINE opaque #-}", + "opaque x=x", + 'fp64 x=if isNaN x then "nan" else show (castDoubleToWord64 x)', + 'fp32 x=if isNaN x then "nan" else show (castFloatToWord32 x)', + 'complex e x=e (realPart x)++","++e (imagPart x)', + 'list e xs="["++intercalate "," (map e xs)++"]"', + 'sf x=fp64 (S.sfValue x)++","++fp64 (S.sfError x)', + 'matrix x=let (a,b)=M.shape x in show a++","++show b++":"++list (complex fp64) (M.toList x)', + "right (Right x)=x", + "right (Left e)=error (show e)", + "emit :: (a->String)->Either MathError a->IO ()", + 'emit e (Right x)=putStrLn ("OK:"++e x)', + 'emit _ (Left e)=putStrLn ("ERR:"++show e)', + "matrixValues=[1:+2,(-0.5):+0.25,castWord64ToDouble 9223372036854775808:+castWord64ToDouble 9223372036854775808,3:+(-2)]", + "ma=right (C.complexMatrix 2 2 (opaque matrixValues))", + "mb=right (C.complexMatrix 2 1 [0.5:+1,(-2):+0.25])", + "main=do", + ] + for _, expression, kind, _ in cases: + lines.append(" emit " + hse(kind) + " (" + expression + ")") + with tempfile.TemporaryDirectory(prefix="hmath-scalar-extras-oracle-") as directory: + path = Path(directory) + source = path / "Main.hs" + source.write_text("\n".join(lines) + "\n") + subprocess.run( + [ + "ghc", + "-O0", + "-isrc", + "-Iinclude", + "-optc-std=c11", + "-outputdir", + directory, + "-stubdir", + directory, + str(source), + "cbits/backend.c", + "-o", + str(path / "oracle"), + ], + cwd=ROOT, + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + + def close(value): + if isinstance(value, Value) or hasattr(value, "close"): + value.close() + elif isinstance(value, (tuple, list)): + for child in value: + close(child) + + for (label, _, kind, call), wanted in zip(cases, expected): + result = None + try: + result = call() + actual = "OK:" + encode(kind, result) + except hmath.HMathError as error: + assert error.math_error is not None, (label, error) + actual = "ERR:" + str(error.math_error) + finally: + close(result) + assert actual == wanted, (label, actual, wanted) + assert len(cases) == len(expected) + with c.exp() as a, c.exp() as b, c.log() as other: + assert a == b and a != other + for owner in owners: + owner.close() + print( + f"Scalar extras: {len(expected)} direct Haskell cases, both complex precisions, signed-zero branches, exact integers and raw SFResult fields passed." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_shape_equivalence.py b/tools/check_shape_equivalence.py new file mode 100644 index 0000000..bb81718 --- /dev/null +++ b/tools/check_shape_equivalence.py @@ -0,0 +1,223 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Haskell KnownNat/KnownShape oracle, including huge type indices.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from fractions import Fraction as Q +from pathlib import Path + +from check_algebra_equivalence import normalized +from check_polynomial_equivalence import HASKELL, close + +ROOT = Path(__file__).resolve().parent.parent + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import algebra as a + from _hmath_native import algebra_api as p + from _hmath_native import shape_values as s + from _hmath_native._foundation_base import FoundationValue + + modules = {"HMath.Algebra": a, "HMath.API.Algebra": p} + owners = [] + tests = [] + expressions = [] + + def own(value): + owners.append(value) + return value + + matrix = own(p.matrix_construct(2, 2, [1, 2, 3, 4])) + tensor = own(p.tensor_construct([2], [1, 2])) + static = own(s.static_matrix(2, 2, matrix)) + stensor = own(s.static_tensor([2], tensor)) + coord = own(s.coordinates(2, [Q(1, 3), Q(2, 5)])) + shape = own(s.make_shape([2, 3])) + scalar = own(s.make_shape([])) + vector = own(s.make_shape([3])) + exact = own(p.Exact(Q(2, 3))) + + def add(function, values, expression, checked=False, kwargs=None): + tests.append((function, values, kwargs or {}, function.__name__)) + expressions.append(("ok" if checked else "enc") + "(" + expression + ")") + + add(s.shape_dimensions, [shape], "S.shapeDimensions shape") + add(s.shape_elements, [shape], "S.shapeElements shape") + for dims, hs in [ + ([], "[]"), + ([2, 3], "[2,3]"), + ([2, 0, 3], "[2,0,3]"), + ([-1], "[-1]"), + ([2**62, 4], "[4611686018427387904,4]"), + ]: + add(s.make_shape, [dims], "S.makeShape " + hs, True) + add(s.scalar_shape, [scalar], "case scalar of S.ScalarShape -> True;_ -> False") + add(s.scalar_shape, [shape], "case shape of S.ScalarShape -> True;_ -> False") + add( + s.vector_shape, + [vector], + "case vector of S.VectorShape n -> Just n;_ -> Nothing", + ) + add(s.vector_shape, [shape], "case shape of S.VectorShape n -> Just n;_ -> Nothing") + add( + s.matrix_shape, + [shape], + "case shape of S.MatrixShape r c -> Just(r,c);_ -> Nothing", + ) + add(s.static_matrix, [2, 2, matrix], "S.staticMatrix @2 @2 mat", True) + add(s.static_matrix, [1, 4, matrix], "S.staticMatrix @1 @4 mat", True) + add( + s.static_matrix, + [2**100, 2, matrix], + "S.staticMatrix @1267650600228229401496703205376 @2 mat", + True, + ) + add(s.dynamic_matrix, [static], "S.dynamicMatrix sm") + add(s.static_multiply, [static, static], "S.staticMultiply sm sm", True) + add(s.static_transpose, [static], "S.staticTranspose sm") + add(s.reflected_shape, [[2, 3]], "S.reflectedShape(Proxy::Proxy '[2,3])") + add( + s.reflected_shape, + [[2**100, 0]], + "S.reflectedShape(Proxy::Proxy '[1267650600228229401496703205376,0])", + ) + add(s.static_tensor, [[2], tensor], "S.staticTensor @'[2] ten", True) + add(s.static_tensor, [[1, 2], tensor], "S.staticTensor @'[1,2] ten", True) + add(s.dynamic_tensor, [stensor], "S.dynamicTensor st") + add( + s.coordinates, + [2, [Q(1, 3), Q(2, 5)]], + "S.coordinates @2 [1%3,2%5::Rational]", + True, + ) + add( + s.coordinates, + [3, [Q(1, 3), Q(2, 5)]], + "S.coordinates @3 [1%3,2%5::Rational]", + True, + ) + add(s.coordinate_values, [coord], "S.coordinateValues co") + add(s.coordinates_to_vector, [coord], "S.coordinatesToVector co", True) + for values, hs, dtype in [ + ([True, False], "[True,False]", "bool"), + (["α\0", "🙂"], '["α\\NUL","🙂"]', "string"), + ([exact, exact], "[P.Exact(2%3),P.Exact(2%3)]", exact), + ]: + add( + s.coordinates, [2, values], "S.coordinates @2 " + hs, True, {"dtype": dtype} + ) + value = own(s.coordinates(2, values, dtype=dtype)) + add( + s.coordinates_to_vector, + [value], + "S.coordinatesToVector(right(S.coordinates @2 " + hs + "))", + True, + ) + + def encode(value): + if isinstance(value, FoundationValue) and value.source_type.startswith( + "HMath.API.Shape." + ): + name = value.source_type.rsplit(".", 1)[-1] + if name == "Shape": + data = (value.dimensions, value.elements) + elif name == "StaticMatrix": + data = s.dynamic_matrix(value) + elif name == "StaticTensor": + data = s.dynamic_tensor(value) + elif name == "Coordinates": + data = s.coordinate_values(value) + else: + raise TypeError(name) + try: + return name + "(" + normalized(data, modules) + ")" + finally: + close(data) + return normalized(value, modules) + + imports = """import qualified HMath.API.Shape as S +import qualified HMath.API.Algebra as P +import qualified HMath.Polynomial as Poly +import qualified HMath.Tensor as T +import qualified HMath.Vector as V +import Data.Proxy(Proxy(..)) +import Data.Char(ord) +""" + source = ( + HASKELL.split("pR=")[0] + .replace("import qualified HMath.Polynomial as P", imports) + .replace("P.Polynomial", "Poly.Polynomial") + .replace("P.coefficients", "Poly.coefficients") + .replace("P.PowerSeries", "Poly.PowerSeries") + .replace("P.seriesCoefficients", "Poly.seriesCoefficients") + .replace("P.RationalFunction", "Poly.RationalFunction") + .replace("P.rationalNumerator", "Poly.rationalNumerator") + .replace("P.rationalDenominator", "Poly.rationalDenominator") + ) + source = ( + "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE PatternSynonyms #-}\n" + + source + + """instance E Char where enc c="I"++show(ord c) +instance E P.Exact where enc x="X("++enc(P.getExact x)++")" +instance E S.Shape where enc x="Shape("++enc(S.shapeDimensions x,S.shapeElements x)++")" +instance E a=>E(S.StaticMatrix m n a)where enc x="StaticMatrix("++enc(S.dynamicMatrix x)++")" +instance E a=>E(S.StaticTensor ds a)where enc x="StaticTensor("++enc(S.dynamicTensor x)++")" +instance E a=>E(S.Coordinates n a)where enc x="Coordinates("++enc(S.coordinateValues x)++")" +instance E a=>E(V.Vector a)where enc x="VECTOR("++enc(V.vectorValues x)++")" +instance E a=>E(T.Tensor a)where enc x="TENSOR("++enc(T.tensorShape x,T.tensorValues x)++")" +right=either(error.show)id +mat=right(P.matrixConstruct 2 2 [1,2,3,4])::M.Matrix Integer +ten=right(P.tensorConstruct [2] [1,2])::T.Tensor Integer +sm=right(S.staticMatrix @2 @2 mat) +st=right(S.staticTensor @'[2] ten) +co=right(S.coordinates @2 [1%3,2%5::Rational]) +shape=right(S.makeShape [2,3]) +scalar=right(S.makeShape []) +vector=right(S.makeShape [3]) +main=mapM_ putStrLn [EXPRESSIONS] +""".replace("EXPRESSIONS", ",\n ".join(expressions)) + ) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "Oracle.hs" + path.write_text(source) + result = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + if result.returncode: + raise SystemExit(result.stderr) + lines = result.stdout.splitlines() + if len(lines) != len(tests): + raise AssertionError((len(lines), len(tests))) + try: + for (function, values, kwargs, name), expected in zip(tests, lines): + try: + value = function(*values, **kwargs) + actual = encode(value) + close(value) + except hmath.HMathError as error: + actual = "E" + str(error.math_error) + if actual != expected: + raise AssertionError((name, actual, expected)) + finally: + for owner in owners: + owner.close() + print( + f"Shape direct Haskell equivalence: {len(tests)} cases;21 source symbols;genuine nominal indices/Int overflow/structural interop" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_spectral_equivalence.py b/tools/check_spectral_equivalence.py new file mode 100644 index 0000000..352d0cb --- /dev/null +++ b/tools/check_spectral_equivalence.py @@ -0,0 +1,430 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-Haskell oracle for Signal/Fourier/Interpolation.""" + +import argparse +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_graph_bindings import snake, split_top +from generate_numerical_bindings import normalize, spec +from generate_spectral_bindings import TYPES + +ROOT = Path(__file__).resolve().parent.parent +BASE = HASKELL.split("pR=")[0].replace( + "class E a", + """import Prelude hiding (filter) +import qualified HMath.Signal as S +import qualified HMath.Fourier as F +import qualified HMath.Interpolation as I +import qualified HMath.Calculus as C +import Data.Char(ord) +import Foreign.Marshal.Array(newArray,peekArray) +import Foreign.Marshal.Alloc(free) +class E a""", +) +FIXTURES = r""" +right(Right x)=x +right(Left e)=error(show e) +xs=[1,2,3,4,5,6,7,8] :: [Double] +cx=[fromIntegral i :+ (negate(fromIntegral i)/2) | i<-[1..8]] :: [Complex Double] +filter=right(S.fir [0.5,0.5]) +family=S.Butterworth +band=S.Lowpass 0.2 +window=S.Hann +peak=S.Peak 1 2 0.3 0.4 +wavelet=S.Haar +tree=right(S.dwt S.Haar 1 xs) +mother=S.MexicanHat +packet=right(S.waveletPackets S.Haar 2 xs) +extrapolation=I.Clamp +method=I.Linear +boundary=I.Natural +piecewise=right(I.piecewisePolynomial [0,1,2] [[1,2],[3,4]]) +spline=right(I.bSpline 1 [0,0,1,1] [[0,0],[1,1]] [1,1]) +kernel=I.Gaussian 1 +rbf=right(I.fitRBF kernel 0.1 [[0],[1]] [0,1]) +approximation=I.Approximation [1,2] 0 1 +direction=F.Forward +algorithm=F.Automatic +plan=right(F.planFFT direction algorithm 8) +transform=F.TypeII +stft=right(F.stft [1,1,1,1] 2 xs) +gaussian=right(S.gaussianState [0] [[1]]) +tolerance=C.Tolerance 1e-5 1e-5 2000 +square x=x*x +identity xs=xs +model x parameters=head parameters*x +main=do + mapM_ putStrLn [EXPRESSIONS] + pointer<-newArray cx + outcome<-F.fftInPlace plan pointer 8 + transformed<-peekArray 8 pointer + putStrLn(ok outcome++":"++enc transformed) + free pointer +""" + + +def encode(value, modules): + from _hmath_native._value import Value + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return "F64:" + str(bits(value, 64)) + if isinstance(value, complex): + return "C64:" + str(bits(value.real, 64)) + ":" + str(bits(value.imag, 64)) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(x, modules) for x in value) + + "]" + ) + if isinstance(value, Value): + if value.info[0] == 200: + c = modules["calculus"] + return encode( + ( + c.estimate_value(value), + c.estimate_error(value), + c.evaluations(value), + ), + modules, + ) + return "O" + encode(list(map(ord, modules["signal"].describe(value))), modules) + raise TypeError(type(value)) + + +def cases(modules): + s, f, i, c = ( + modules[n] for n in ("signal", "fourier", "interpolation", "calculus") + ) + owners = [] + + def keep(value): + owners.append(value) + return value + + xs = [float(k) for k in range(1, 9)] + cx = [complex(k, -k / 2) for k in range(1, 9)] + records = { + "Filter": (keep(s.fir([0.5, 0.5])), "filter"), + "FilterFamily": (keep(s.butterworth()), "family"), + "FilterBand": (keep(s.lowpass(0.2)), "band"), + "Window": (keep(s.hann()), "window"), + "Peak": (keep(s.peak(1, 2, 0.3, 0.4)), "peak"), + "Wavelet": (keep(s.haar()), "wavelet"), + "WaveletTree": (keep(s.dwt(s.haar(), 1, xs)), "tree"), + "MotherWavelet": (keep(s.mexican_hat()), "mother"), + "WaveletPacket": (keep(s.wavelet_packets(s.haar(), 2, xs)), "packet"), + "Extrapolation": (keep(i.clamp()), "extrapolation"), + "InterpolationMethod": (keep(i.linear()), "method"), + "SplineBoundary": (keep(i.natural()), "boundary"), + "PiecewisePolynomial": ( + keep(i.piecewise_polynomial([0, 1, 2], [[1, 2], [3, 4]])), + "piecewise", + ), + "BSpline": ( + keep(i.b_spline(1, [0, 0, 1, 1], [[0, 0], [1, 1]], [1, 1])), + "spline", + ), + "RadialKernel": (keep(i.gaussian(1)), "kernel"), + "RBF": (keep(i.fit_rbf(i.gaussian(1), 0.1, [[0], [1]], [0, 1])), "rbf"), + "Approximation": (keep(i.approximation([1, 2], 0, 1)), "approximation"), + "Direction": (keep(f.forward()), "direction"), + "FFTAlgorithm": (keep(f.automatic()), "algorithm"), + "FFTPlan": (keep(f.plan_fft(f.forward(), f.automatic(), 8)), "plan"), + "TransformType": (keep(f.type_ii()), "transform"), + "STFT": (keep(f.stft([1, 1, 1, 1], 2, xs)), "stft"), + "GaussianState": (keep(s.gaussian_state([0], [[1]])), "gaussian"), + "Tolerance": (keep(c.tolerance(1e-5, 1e-5, 2000)), "tolerance"), + } + + def arg(type_): + kind = type_[0] + if kind in records: + value, expression = records[kind] + return value, "(" + expression + ")" + if kind == "function": + if type_[1:] == [["Double"], ["Double"]]: + return lambda x: x * x, "square" + if type_[1:] == [["list", ["Double"]], ["list", ["Double"]]]: + return lambda x: x, "identity" + if type_[1:] == [["Double"], ["list", ["Double"]], ["Double"]]: + return lambda x, p: p[0] * x, "model" + raise ValueError(type_) + if kind == "Double": + return 0.5, "0.5" + if kind == "Int": + return 4, "4" + if kind == "ComplexDouble": + return 1 + 0j, "(1:+0)" + if kind == "Bool": + return False, "False" + if kind == "maybe": + return None, "Nothing" + if kind == "tuple": + items = [arg(t) for t in type_[1:]] + return tuple(v for v, _ in items), "(" + ",".join(e for _, e in items) + ")" + if kind == "list": + if type_[1] == ["Double"]: + return xs, "xs" + if type_[1] == ["ComplexDouble"]: + return cx, "cx" + if type_[1] == ["Value"]: + return [0.0, 1.0, 2.0, 3.0], "([0,1,2,3]::[Double])" + if type_[1] == ["Int"]: + return [8], "[8]" + if type_[1] == ["list", ["Double"]]: + return [[0], [1]], "[[0],[1]]" + item, expression = arg(type_[1]) + return [item], "[" + expression + "]" + raise ValueError(type_) + + overrides = {} + + def put(module, name, arguments, expressions): + overrides[(module, name)] = (arguments, expressions) + + put("signal", "dwt", [records["Wavelet"][0], 1, xs], ["wavelet", "1", "xs"]) + put( + "signal", + "waveletPackets", + [records["Wavelet"][0], 2, xs], + ["wavelet", "2", "xs"], + ) + put( + "signal", + "waveletDenoise", + [records["Wavelet"][0], 1, None, xs], + ["wavelet", "1", "Nothing", "xs"], + ) + put( + "signal", + "designIIR", + [records["FilterFamily"][0], records["FilterBand"][0], 2, 1], + ["family", "band", "2", "1"], + ) + put( + "signal", + "kalman", + [[[1]], [[1]], [[0.1]], [[0.2]], [1], records["GaussianState"][0]], + ["[[1]]", "[[1]]", "[[0.1]]", "[[0.2]]", "[1]", "gaussian"], + ) + put( + "signal", + "extendedKalman", + [lambda x: x, lambda x: x, [[0.1]], [[0.2]], [1], records["GaussianState"][0]], + ["identity", "identity", "[[0.1]]", "[[0.2]]", "[1]", "gaussian"], + ) + put( + "signal", + "unscentedKalman", + [ + 0.1, + 2, + 0, + lambda x: x, + lambda x: x, + [[0.1]], + [[0.2]], + [1], + records["GaussianState"][0], + ], + [ + "0.1", + "2", + "0", + "identity", + "identity", + "[[0.1]]", + "[[0.2]]", + "[1]", + "gaussian", + ], + ) + points = [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)] + hs_points = "[(0,0),(1,1),(2,4),(3,9),(4,16)]" + for name in ("pchip", "akima", "catmullRom"): + put("interpolation", name, [points], [hs_points]) + put( + "interpolation", + "interpolate", + [records["InterpolationMethod"][0], records["Extrapolation"][0], points, 0.5], + ["method", "extrapolation", hs_points, "0.5"], + ) + put( + "interpolation", + "cubicSpline", + [records["SplineBoundary"][0], points], + ["boundary", hs_points], + ) + put("interpolation", "smoothingSpline", [0.1, points], ["0.1", hs_points]) + put("interpolation", "cardinalSpline", [0.2, points], ["0.2", hs_points]) + put( + "interpolation", + "kochanekBartels", + [0.1, 0.2, 0.3, points], + ["0.1", "0.2", "0.3", hs_points], + ) + put( + "interpolation", + "bSpline", + [1, [0, 0, 1, 1], [[0, 0], [1, 1]], [1, 1]], + ["1", "[0,0,1,1]", "[[0,0],[1,1]]", "[1,1]"], + ) + put( + "interpolation", + "fitRBF", + [records["RadialKernel"][0], 0.1, [[0], [1]], [0, 1]], + ["kernel", "0.1", "[[0],[1]]", "[0,1]"], + ) + put("interpolation", "evaluateRBF", [records["RBF"][0], [0.5]], ["rbf", "[0.5]"]) + put("interpolation", "polynomialFit", [2, points], ["2", hs_points]) + put( + "interpolation", + "chebyshevApproximate", + [4, lambda x: x * x, 0, 1], + ["4", "square", "0", "1"], + ) + put( + "interpolation", + "remez", + [1, 64, 1e-4, 20, lambda x: x * x, 0, 1], + ["1", "64", "1e-4", "20", "square", "0", "1"], + ) + put( + "interpolation", + "nonlinearFit", + [20, 1e-6, lambda x, p: p[0] * x, [(1, 2), (2, 4), (3, 6)], [1]], + ["20", "1e-6", "model", "[(1,2),(2,4),(3,6)]", "[1]"], + ) + put("fourier", "stft", [[1, 1, 1, 1], 2, xs], ["[1,1,1,1]", "2", "xs"]) + entries = json.loads( + (ROOT / "bindings/schema/spectral-functions.json").read_text() + )["functions"] + fixtures = [] + for entry in entries: + if entry["name"] == "fftInPlace": + continue + module = entry["module"].removeprefix("HMath.").lower() + normalized = split_top(normalize(entry["signature"], module), "->") + prepared = [arg(spec(text, TYPES)) for text in normalized[:-1]] + arguments = [v for v, _ in prepared] + expressions = [e for _, e in prepared] + if (module, entry["name"]) in overrides: + arguments, expressions = overrides[(module, entry["name"])] + q = {"signal": "S", "fourier": "F", "interpolation": "I"}[module] + call = q + "." + entry["name"] + " " + " ".join(expressions) + expression = ( + ("ok(" if normalized[-1].startswith("Either MathError") else "enc(") + + call + + ")" + ) + fixtures.append((module, snake(entry["name"]), arguments, expression)) + return fixtures, owners, records["FFTPlan"][0], cx + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + import numpy as np + + modules = { + n: getattr(hmath, n) for n in ("signal", "fourier", "interpolation", "calculus") + } + fixtures, owners, plan, cx = cases(modules) + try: + instances = "\n".join( + "instance E(" + typ + ') where enc x="O"++enc(map ord(show x))' + for _, typ, _, _ in TYPES.values() + ) + instances += '\ninstance E S.GaussianState where enc x="O"++enc(map ord(show x))\ninstance E a=>E(C.Estimate a) where enc x=enc(C.estimateValue x,C.estimateError x,C.evaluations x)\ninstance E () where enc ()="T[]"\n' + source = ( + BASE + + instances + + FIXTURES.replace( + "EXPRESSIONS", ",\n ".join(case[3] for case in fixtures) + ) + ) + with tempfile.TemporaryDirectory(prefix="hmath-spectral-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + shim = Path(directory) / "libhmath_oracle_backend.so" + subprocess.run( + [ + "cc", + "-shared", + "-fPIC", + "-std=c11", + "-Iinclude", + "cbits/backend.c", + "-ldl", + "-lm", + "-o", + str(shim), + ], + cwd=ROOT, + check=True, + capture_output=True, + ) + result = subprocess.run( + [ + "runghc", + "-isrc", + "-L" + directory, + "-lhmath_oracle_backend", + str(path), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if result.returncode: + Path("/tmp/hmath-spectral-oracle-failed.hs").write_text(source) + raise RuntimeError(result.stderr[-12000:]) + expected = result.stdout.splitlines() + actual = [] + for module, name, arguments, _ in fixtures: + try: + output = getattr(modules[module], name)(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(output, modules)) + finally: + close(output) + buffer = np.array(cx, dtype=np.complex128) + modules["fourier"].fft_in_place(plan, buffer) + actual.append("T[]:" + encode(buffer.tolist(), modules)) + failures = [ + (i, fixtures[i][:2] if i < len(fixtures) else "fftInPlace", a, b) + for i, (a, b) in enumerate(zip(expected, actual)) + if a != b + ] + if failures or len(expected) != len(actual): + raise AssertionError(f"Spectral mismatches: {failures[:8]}") + print( + f"Spectral direct Haskell equivalence: {len(actual)} cases, all153 named adapters" + ) + finally: + for owner in owners: + close(owner) + + +if __name__ == "__main__": + main() diff --git a/tools/check_stochastic_equivalence.py b/tools/check_stochastic_equivalence.py new file mode 100644 index 0000000..1d0a834 --- /dev/null +++ b/tools/check_stochastic_equivalence.py @@ -0,0 +1,475 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original-source oracle: complete seeded streams, distributions and statistics.""" + +import argparse +import importlib +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, bits, close +from generate_stochastic_bindings import MODULES, hs_type, python_name, specification + +ROOT = Path(__file__).resolve().parent.parent + + +def normalize(value, modules): + import hmath + from _hmath_native._matrix_base import Matrix + from _hmath_native._stochastic_base import StochasticValue + + if isinstance(value, StochasticValue): + kind = value.info[0] + if kind == 240: + data = modules["HMath.Random"].serialize_rng(value) + elif kind == 242: + r = modules["HMath.Random"] + generator = r.pcg32() + state = r.seed_rng(generator, 42) + try: + data = r.alias_sample(value, state) + finally: + generator.close() + state.close() + elif kind == 244: + p = modules["HMath.Probability"] + data = (p.transition(value, [1, 0]), p.transition(value, [0, 1])) + elif kind == 245: + p = modules["HMath.Probability"] + data = (p.forward(value, [0, 1]), p.backward(value, [0, 1])) + elif kind == 246: + try: + data = modules["HMath.Statistics.Advanced"].streaming_result( + False, value + ) + except hmath.HMathError as error: + return "O246(E" + str(error.math_error) + ")" + else: + data = value.parts + try: + return "O" + str(kind) + "(" + normalize(data, modules) + ")" + finally: + close(data) + if isinstance(value, Matrix): + r, c = value.shape + return ( + f"M{r}:{c}[" + + ",".join(normalize(x, modules) for x in value.to_list()) + + "]" + ) + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return "F64:" + str(bits(value, 64)) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(c)) for c in value) + "]" + if isinstance(value, (tuple, list)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(normalize(x, modules) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +class Fixtures: + def __init__(self, modules): + self.modules = modules + self.owned = [] + + def own(self, value, expression): + if hasattr(value, "close"): + self.owned.append(value) + return value, expression + + def object(self, name): + r = self.modules["HMath.Random"] + p = self.modules["HMath.Probability"] + s = self.modules["HMath.Statistics.Advanced"] + if name == "Generator": + return self.own(r.pcg32(), "R.PCG32") + if name == "RNG": + g, _ = self.object("Generator") + return self.own(r.seed_rng(g, 42), "(R.seedRNG R.PCG32 42)") + if name == "AliasTable": + return self.own(r.alias_table([1, 2, 3]), "(right(R.aliasTable [1,2,3]))") + if name == "Distribution": + return self.own(p.normal(0, 1), "(P.Normal 0 1)") + if name == "Markov": + return self.own( + p.markov([[0.8, 0.2], [0.1, 0.9]]), + "(right(P.markov [[0.8,0.2],[0.1,0.9]]))", + ) + if name == "HMM": + return self.own( + p.hmm([0.5, 0.5], [[0.8, 0.2], [0.1, 0.9]], [[0.7, 0.3], [0.2, 0.8]]), + "(right(P.hmm [0.5,0.5] [[0.8,0.2],[0.1,0.9]] [[0.7,0.3],[0.2,0.8]]))", + ) + if name == "Streaming": + return self.own(s.empty_streaming(), "S.emptyStreaming") + if name == "TestResult": + return self.own( + s.TestResult(1.5, 0.25, [2.0]), "(S.TestResult 1.5 0.25 [2])" + ) + raise ValueError(name) + + def argument(self, spec, name, index): + r = self.modules["HMath.Random"] + head, *args = spec + if head in ( + "Generator", + "RNG", + "AliasTable", + "Distribution", + "Markov", + "HMM", + "Streaming", + "TestResult", + ): + return self.object(head) + if head == "a": + return 7, "(7::Integer)" + if head == "Int": + value = 3 if name not in ("uniformInt", "stationary", "baumWelch") else 2 + return value, str(value) + if head == "Integer": + return 10, "10" + if head == "Word64": + return 42, "42" + if head == "Double": + value = 0.25 + if name in ( + "normal", + "exponential", + "gamma", + "beta", + "poisson", + "binomial", + ): + value = 1.0 if index < 2 else 0.25 + if name in ("hamiltonianMonteCarlo", "metropolisHastings"): + value = 0.1 + return value, str(value) + if head == "Bool": + return False, "False" + if head == "String": + state, hs = self.object("RNG") + return r.serialize_rng(state), "R.serializeRNG " + hs + if head == "Matrix": + from _hmath_native import matrix as m + + return self.own( + m.from_list_checked(2, 2, [1, 0, 0, 1]), + "(right(M.fromListChecked 2 2 [1,0,0,1]))", + ) + if head == "list": + child = args[0] + if child == ["Double"]: + value = [1.0, 2.0, 3.0, 4.0] + if name in ( + "forward", + "backward", + "posteriorStates", + "viterbi", + "baumWelch", + ): + value = [0.0, 1.0] + if name in ( + "sampleMultivariateNormal", + "multivariateNormalLogDensity", + "gibbs", + "hamiltonianMonteCarlo", + ): + value = [0.0, 0.0] + return value, str(value) + if child == ["Int"]: + return [0, 1], "[0,1]" + if child == ["Bool"]: + return [True, False, True], "[True,False,True]" + if child == ["a"]: + return [10, 20, 30], "([10,20,30]::[Integer])" + value, expression = self.argument(child, name, index) + return [value], "[" + expression + "]" + if head == "tuple": + values = [] + expressions = [] + for i, s in enumerate(args): + v, h = self.argument(s, name, i) + values.append(v) + expressions.append(h) + return tuple(values), "(" + ",".join(expressions) + ")" + if head == "function": + result = args[-1] + if name == "sampleN": + + def sample(state): + word, next_state = r.next_word64(state) + return word, next_state + + return ( + sample, + "(\\state -> let(word,next)=R.nextWord64 state in Right(toInteger word,next))", + ) + if name == "rejection": + return ( + (lambda _x: 1.0, "(const 1)") + if result == ["Double"] + else (lambda state: r.uniform(state), "(Right . R.uniform)") + ) + if name == "inverseTransform": + return lambda x: x, "Right" + if name == "gibbs": + return lambda _point, state: r.normal( + 0.0, 1.0, state + ), "(\\_ state -> R.normal 0 1 state)" + if name == "hamiltonianMonteCarlo": + return ( + ( + lambda xs: -sum(x * x for x in xs) / 2.0, + "(\\xs -> -sum(map (\\x -> x*x) xs)/2)", + ) + if result == ["Double"] + else (lambda xs: [-x for x in xs], "(map negate)") + ) + if name == "metropolisHastings": + return lambda x: -x * x / 2.0, "(\\x -> -x*x/2)" + if name in ("monteCarlo", "expectation"): + return lambda x: x * x, "(\\x -> x*x)" + if name == "fitMAPGrid": + return lambda _distribution: 0.0, "(const 0)" + if name in ("bootstrap", "jackknife"): + return ( + lambda xs: sum(xs) / len(xs), + "(\\xs -> Right(sum xs/fromIntegral(length xs)))", + ) + if name == "permutationTest": + return ( + lambda xs, ys: sum(xs) / len(xs) - sum(ys) / len(ys), + "(\\xs ys -> Right(sum xs/fromIntegral(length xs)-sum ys/fromIntegral(length ys)))", + ) + raise ValueError((name, index, spec)) + + +def oracle_instances(entries, types): + out = [ + 'instance E Char where enc c="I"++show(ord c)\ninstance E Word64 where enc x="I"++show x\ninstance E () where enc ()="N"\nright=either(error.show) id\n' + ] + from generate_stochastic_bindings import TAGS + + for name, t in types.items(): + prefix = "O" + str(TAGS[name]) + "(" + out.append( + "instance E(" + + t["alias"] + + "." + + name + + ') where\n enc value="' + + prefix + + '"++(' + ) + if name == "RNG": + expr = "enc(R.serializeRNG value)" + elif name == "AliasTable": + expr = "ok(R.aliasSample value (R.seedRNG R.PCG32 42))" + elif name == "Markov": + expr = ( + "enc(right(P.transition value [1,0]),right(P.transition value [0,1]))" + ) + elif name == "HMM": + expr = "enc(right(P.forward value [0,1]),right(P.backward value [0,1]))" + elif name == "Streaming": + expr = "ok(S.streamingResult False value)" + else: + constructors = [ + e for e in entries if e["constructor"] and e["result"][0] == name + ] + parts = [] + for e in constructors: + args = ["p" + str(i) for i in range(len(e["args"]))] + result = ( + '"T["++enc("' + + e["name"] + + '")++",T["++intercalate "," [' + + ",".join("enc " + p for p in args) + + ']++"]]"' + ) + parts.append( + t["alias"] + + "." + + e["name"] + + " " + + " ".join(args) + + " -> " + + result + ) + expr = "case value of {" + ";".join(parts) + "}" + out.append(expr + ')++")"\n') + return "".join(out) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + entries, types, _fields = specification() + modules = { + m: importlib.import_module("_hmath_native." + ns) + for m, (_alias, ns, _public) in MODULES.items() + } + fixtures = [] + expressions = [] + owners = [] + for entry in entries: + if entry["name"] == "entropySeed": + continue + factory = Fixtures(modules) + values = [] + hsargs = [] + for index, spec in enumerate(entry["args"]): + value, expression = factory.argument(spec, entry["name"], index) + values.append(value) + hsargs.append(expression) + name = python_name(entry, entries, types) + function = getattr(modules[entry["module"]], name) + expression = ( + "(" + + MODULES[entry["module"]][0] + + "." + + entry["name"] + + " " + + " ".join("(" + x + ")" for x in hsargs) + + " :: " + + hs_type(entry["result"], types).replace("(X.Value)", "(Integer)") + + ")" + ) + expression = ( + "putStrLn (" + + ("ok" if entry["result"][0] == "Either" else "enc") + + " " + + expression + + ")" + ) + fixtures.append((function, values, entry["module"] + "." + entry["name"])) + expressions.append(expression) + owners.extend(factory.owned) + random_module = modules["HMath.Random"] + for entry in entries: + if ( + entry["module"] != "HMath.Random" + or not entry["constructor"] + or entry["result"] != ["Generator"] + ): + continue + generator = getattr(random_module, python_name(entry, entries, types))() + current = random_module.seed_rng(generator, 2**64 - 1) + owners.extend([generator, current]) + expression = "(R.seedRNG R." + entry["name"] + " 18446744073709551615)" + for step in range(3): + fixtures.append( + ( + random_module.next_word64, + [current], + "RNGcontinuation." + entry["name"] + "." + str(step), + ) + ) + expressions.append("putStrLn(enc(R.nextWord64 " + expression + "))") + _word, current = random_module.next_word64(current) + owners.append(current) + expression = "(snd(R.nextWord64 " + expression + "))" + try: + imports = ( + "import Data.Char(ord)\nimport Data.Word(Word64)\nimport qualified HMath.Error as E\n" + + "".join( + "import qualified " + m + " as " + alias + "\n" + for m, (alias, _ns, _public) in MODULES.items() + ) + ) + source = ( + HASKELL.replace( + "import Data.Complex", imports + "import Data.Complex" + ).split("main=mapM_ putStrLn")[0] + + oracle_instances(entries, types) + + "\nmain=sequence_\n [ " + + "\n , ".join(expressions) + + "\n ]\n" + ) + with tempfile.TemporaryDirectory( + prefix="hmath-stochastic-oracle-" + ) as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + shim = Path(directory) / "libhmath_oracle_backend.so" + subprocess.run( + [ + "cc", + "-shared", + "-fPIC", + "-std=c11", + "-Iinclude", + "cbits/backend.c", + "-ldl", + "-lm", + "-o", + str(shim), + ], + cwd=ROOT, + check=True, + capture_output=True, + ) + result = subprocess.run( + [ + "runghc", + "-isrc", + "-L" + directory, + "-lhmath_oracle_backend", + str(path), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if result.returncode: + Path("/tmp/hmath-stochastic-oracle-failed.hs").write_text(source) + raise RuntimeError(result.stderr[-8000:]) + expected = result.stdout.splitlines() + actual = [] + for function, arguments, name in fixtures: + try: + value = function(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(normalize(value, modules)) + finally: + close(value) + failures = [ + (fixtures[i][-1], expected[i], actual[i]) + for i in range(min(len(expected), len(actual))) + if expected[i] != actual[i] + ] + if failures or len(expected) != len(actual): + raise AssertionError(f"{len(failures)} mismatches: {failures[:12]}") + entropy = modules["HMath.Random"].entropy_seed() + assert isinstance(entropy, int) and 0 <= entropy < 2**64 + print( + f"Stochastic direct Haskell equivalence: {len(actual)} deterministic operations; entropySeed Word64 IO contract;152source symbols" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_structural_matrix_equivalence.py b/tools/check_structural_matrix_equivalence.py new file mode 100644 index 0000000..04c13dc --- /dev/null +++ b/tools/check_structural_matrix_equivalence.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Bool/String Matrix structure; no invented arithmetic instances.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, close +from generate_matrix_bindings import S, snake + +ROOT = Path(__file__).resolve().parent.parent +STRUCTURAL = { + "fromList", + "fromListChecked", + "at", + "atChecked", + "sliceMatrix", + "sliceMatrixChecked", + "reshape", + "reshapeChecked", + "transposeMatrix", +} + + +def normalize(value): + from _hmath_native._matrix_base import Matrix + + if isinstance(value, Matrix): + rows, cols = value.shape + return ( + f"M{rows}:{cols}[" + ",".join(normalize(x) for x in value.to_list()) + "]" + ) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(x)) for x in value) + "]" + if isinstance(value, bool): + return "B1" if value else "B0" + if value is None: + return "N" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(normalize(x) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import matrix as m + + fixtures = [] + owners = [] + for dtype, typ, data, hsdata in [ + ("bool", "Bool", [True, False, False, True], "[True,False,False,True]"), + ( + "string", + "String", + ["a\0α", "\ud800", "", "🙂"], + '["a\\NUL\\945","\\55296","","\\128578"]', + ), + ]: + matrix = m.from_list_checked(2, 2, data, dtype=dtype) + owners.append(matrix) + hsm = ( + "(case M.fromListChecked 2 2 " + + hsdata + + " :: Either HMath.Error.MathError(M.Matrix " + + typ + + ") of Right x->x;Left e->error(show e))" + ) + for module, name, kinds, _result, mode, expr in S: + if module != "M" or name not in STRUCTURAL: + continue + arguments = [] + hsargs = [] + for index, kind in enumerate(kinds): + if kind == "m": + arguments.append(matrix) + hsargs.append(hsm) + elif kind == "v": + arguments.append(data) + hsargs.append(hsdata) + else: + value = ( + [0, 0, 1, 2][index] + if name.startswith("slice") + else [0, 0, 1][index] + if name.startswith("at") + else [1, 4][index] + if name.startswith("reshape") + else 2 + ) + arguments.append(value) + hsargs.append(str(value)) + code = expr or "M." + name + " " + " ".join( + "a" + str(i) for i in range(len(arguments)) + ) + for index in reversed(range(len(arguments))): + code = code.replace("a" + str(index), hsargs[index]) + if "m" not in kinds: + code += ( + " :: " + + ("Either HMath.Error.MathError" if mode == "either" else "Maybe") + + "(M.Matrix " + + typ + + ")" + ) + fixtures.append( + ( + getattr(m, snake(name)), + arguments, + {"dtype": dtype} if "m" not in kinds else {}, + ("ok" if mode == "either" else "enc") + " (" + code + ")", + ) + ) + fixtures.extend( + [ + (m.to_list, [matrix], {}, "enc(M.toList " + hsm + ")"), + (m.shape, [matrix], {}, "enc(M.shape " + hsm + ")"), + (m.at, [matrix, -1, 0], {}, "enc(M.at " + hsm + " (-1) 0)"), + ( + m.at_checked, + [matrix, -1, 0], + {}, + "ok(M.atChecked " + hsm + " (-1) 0)", + ), + ] + ) + for name in [ + "zero_matrix", + "identity", + "diagonal", + "add_matrix", + "multiply_checked", + "scale_matrix", + ]: + arguments = ( + [2, 2] + if name == "zero_matrix" + else [2] + if name == "identity" + else [data] + if name == "diagonal" + else [1, matrix] + if name == "scale_matrix" + else [matrix, matrix] + ) + try: + getattr(m, name)( + *arguments, + **( + {"dtype": dtype} + if name in ["zero_matrix", "identity", "diagonal"] + else {} + ), + ) + except hmath.HMathError as error: + assert error.status == 10 + else: + raise AssertionError("invented Num instance: " + dtype + "/" + name) + try: + source = ( + HASKELL.replace( + "import Data.Complex", "import Data.Char(ord)\nimport Data.Complex" + ) + .replace( + "pR=P.polynomial", + 'instance E Char where enc x="I"++show(ord x)\npR=P.polynomial', + ) + .replace("EXPRESSIONS", "\n , ".join(row[3] for row in fixtures)) + ) + with tempfile.TemporaryDirectory( + prefix="hmath-structural-matrix-oracle-" + ) as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + expected = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=True, + ).stdout.splitlines() + actual = [] + for function, arguments, kwargs, _expr in fixtures: + try: + value = function(*arguments, **kwargs) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(normalize(value)) + finally: + close(value) + errors = [ + (i, expected[i], actual[i]) + for i in range(len(actual)) + if expected[i] != actual[i] + ] + if errors: + raise AssertionError(errors) + print( + f"Structural Matrix original Haskell equivalence:{len(actual)} Bool/String cases; Num-only APIs explicitly reject" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_tensor_equivalence.py b/tools/check_tensor_equivalence.py new file mode 100644 index 0000000..03bd42c --- /dev/null +++ b/tools/check_tensor_equivalence.py @@ -0,0 +1,485 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Compare full original tensor metadata/values and mutable results with Haskell.""" + +import argparse +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SOURCE = r"""{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +import qualified HMath.Tensor as T +import qualified HMath.Tensor.Mutable as M +import qualified HMath.Error as E +import Data.Complex +import Data.Int +import Data.Word +import Data.Typeable(Typeable) +import Data.List(intercalate) +import Data.Char(ord,toUpper) +import Data.Ratio +import Foreign.Storable +import GHC.Float(castFloatToWord32,castDoubleToWord64) +class Enc a where enc::a->String +instance Enc Int where enc x="I"++show x +instance Enc Integer where enc x="I"++show x +instance Enc Int8 where enc x="I"++show x +instance Enc Word64 where enc x="I"++show x +instance Enc Bool where enc x=if x then "B1" else "B0" +instance Enc Double where enc x="F64:"++show(castDoubleToWord64 x) +instance Enc Float where enc x="F32:"++show(castFloatToWord32 x) +instance Enc Rational where enc x="R"++show(numerator x)++"/"++show(denominator x) +instance Enc a=>Enc(Complex a) where enc(x:+y)="C["++enc x++","++enc y++"]" +instance {-# OVERLAPPING #-} Enc String where enc x="U["++intercalate ","(map(show.ord)x)++"]" +instance {-# OVERLAPPABLE #-} Enc a=>Enc[a] where enc x="L["++intercalate ","(map enc x)++"]" +instance(Enc a,Enc b)=>Enc(a,b) where enc(a,b)="T["++enc a++","++enc b++"]" +instance Enc a=>Enc(Either E.MathError a) where enc(Left e)="ERR"++show e;enc(Right x)=enc x +instance Enc () where enc ()="N" +instance(Typeable a,Enc a)=>Enc(T.Tensor a) where + enc t="Tensor["++enc(T.tensorDType t)++","++enc(T.tensorShape t)++","++enc(T.tensorStrides t)++","++enc(T.tensorOffset t)++","++show(T.tensorLayout t)++","++enc(T.tensorValues t)++"]" +checked=either(error.show)id +make dims xs=checked(T.tensor dims xs) +a=make[2,2][1.1,-2.3,3.7,4.2]::T.Tensor Double +b=make[2,1][10,20]::T.Tensor Double +x=make[3][1,2,3]::T.Tensor Double +u=make[2][4,5]::T.Tensor Double +mask=make[3][True,False,True] +f=make[1][1.0000001]::T.Tensor Float +q=make[2][1%3,2%7]::T.Tensor Rational +i=make[2][10^100,-3]::T.Tensor Integer +z=make[2][1:+2,(-3):+4]::T.Tensor(Complex Float) +text=make[2]["a","b"] +mu=do + result<-M.newMutable[2,2](0::Float) + case result of + Left e->pure(enc(Left e::Either E.MathError(T.Tensor Float))) + Right tensor->do + let view=checked(M.sliceMutable 1 1 2 (-1) tensor) + _<-M.writeMutable view[1,0]7 + _<-M.modifyMutable tensor[0,0](+2) + M.freezeTensor(M.transposeMutable view)>>=pure.enc +buffer=do + result<-M.newMutable[3](1::Float) + case result of + Left e->pure(enc(Left e::Either E.MathError(T.Tensor Float))) + Right tensor->do + let view=checked(M.sliceMutable 0 2 3 (-1)tensor) + M.withMutableBuffer view(\pointer _ strides->pokeElemOff pointer(strides!!0)7) + M.freezeTensor tensor>>=pure.enc +main=sequence_(map(>>=putStrLn)[CASES]) +""" + + +def close(value): + if isinstance(value, (list, tuple)): + for item in value: + close(item) + elif hasattr(value, "close"): + value.close() + + +def encode(value, t, dtype=None): + def enc(x, code=None): + return encode(x, t, code) + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, float): + single = dtype in (1, 5) + return ("F32:" if single else "F64:") + str( + struct.unpack( + "=I" if single else "=Q", struct.pack("=f" if single else "=d", value) + )[0] + ) + if isinstance(value, complex): + return "C[" + enc(value.real, dtype) + "," + enc(value.imag, dtype) + "]" + if isinstance(value, str): + return "U[" + ",".join(str(ord(c)) for c in value) + "]" + if isinstance(value, t.Tensor): + layout = {0: "RowMajor", 1: "ColumnMajor", 2: "Strided"}[value.layout] + return ( + "Tensor[" + + enc(value.type_name) + + "," + + enc(value.shape) + + "," + + enc(value.strides) + + "," + + enc(value.offset) + + "," + + layout + + "," + + enc(value.values, value.dtype_code) + + "]" + ) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(enc(x, dtype) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +def cases(t): + owned = [] + + def keep(x): + owned.append(x) + return x + + def make(dims, values, dtype="float64"): + return keep(t.tensor(dims, values, dtype=dtype)) + + a = make([2, 2], [1.1, -2.3, 3.7, 4.2]) + b = make([2, 1], [10, 20]) + x = make([3], [1, 2, 3]) + u = make([2], [4, 5]) + mask = make([3], [True, False, True], "bool") + f = make([1], [1.0000001], "float32") + q = make([2], [Fraction(1, 3), Fraction(2, 7)], "rational") + i = make([2], [10**100, -3], "integer") + z = make([2], [1 + 2j, -3 + 4j], "complex64") + text = make([2], ["a", "b"], "string") + selected = [] + + def add(name, hs, call, code=None): + selected.append((name, "pure(enc(" + hs + "))", call, code)) + + for hs, value in [ + ("a", a), + ("f", f), + ("q", q), + ("i", i), + ("z", z), + ("text", text), + ("mask", mask), + ]: + add("construct " + hs, hs, lambda value=value: value.clone().decode()) + add( + "column major", + "T.tensorColumnMajor[2,2][1,2,3,4::Float]", + lambda: t.tensor_column_major([2, 2], [1, 2, 3, 4], dtype="float32"), + ) + add("scalar", "T.tensor[][7::Integer]", lambda: t.tensor([], [7], dtype="integer")) + add( + "zero axis", + "T.tensor[0,2][]::Either E.MathError(T.Tensor Float)", + lambda: t.tensor([0, 2], [], dtype="float32"), + ) + add( + "zeros", + "T.tensorZeros[2,2]::Either E.MathError(T.Tensor Rational)", + lambda: t.tensor_zeros([2, 2], dtype="rational"), + ) + add( + "ones", + "T.tensorOnes[2]::Either E.MathError(T.Tensor Int8)", + lambda: t.tensor_ones([2], dtype="int8"), + ) + add( + "full", + "T.tensorFull[2](2%3::Rational)", + lambda: t.tensor_full([2], Fraction(2, 3), dtype="rational"), + ) + add( + "arange", + "T.tensorArange(0.1::Float)1 0.2", + lambda: t.tensor_arange(0.1, 1, 0.2, dtype="float32"), + ) + add( + "linspace", + "T.tensorLinspace(1%3::Rational)(2%3)4", + lambda: t.tensor_linspace(Fraction(1, 3), Fraction(2, 3), 4, dtype="rational"), + ) + add( + "logspace", + "T.tensorLogspace(2::Float)(-1)2 5", + lambda: t.tensor_logspace(2, -1, 2, 5, dtype="float32"), + ) + add( + "random", + "T.tensorRandom(10^100+7)[2,2]", + lambda: t.tensor_random(10**100 + 7, [2, 2]), + ) + for source, py in [ + ("tensorShape", "tensor_shape"), + ("tensorStrides", "tensor_strides"), + ("tensorOffset", "tensor_offset"), + ("tensorDType", "tensor_dtype"), + ("isContiguous", "is_contiguous"), + ("numel", "numel"), + ]: + add(source, "T." + source + " a", lambda py=py: getattr(t, py)(a)) + add("values", "T.tensorValues f", lambda: t.tensor_values(f), 1) + add("size", "T.shapeSize[2,3,0]", lambda: t.shape_size([2, 3, 0])) + add( + "broadcast shape", + "T.inferBroadcast[2,1][3]", + lambda: t.infer_broadcast([2, 1], [3]), + ) + add("index", "T.indexTensor a[1,0]", lambda: t.index_tensor(a, [1, 0])) + add("slice", "T.sliceTensor 1 1 2 (-1) a", lambda: t.slice_tensor(1, 1, 2, -1, a)) + sliced = keep(t.slice_tensor(1, 1, 2, -1, a)) + add( + "contiguous", + "T.sliceTensor 1 1 2 (-1) a >>= T.contiguous", + lambda: t.contiguous(sliced), + ) + for source, py in [("fancyIndex", "fancy_index"), ("gather", "gather")]: + add( + source, + "T." + source + " 0 [2,0,2] x", + lambda py=py: getattr(t, py)(0, [2, 0, 2], x), + ) + add("boolean index", "T.booleanIndex mask x", lambda: t.boolean_index(mask, x)) + for source, py in [("scatter", "scatter"), ("scatterAdd", "scatter_add")]: + add( + source, + "T." + source + " 0 [1,1] u x", + lambda py=py: getattr(t, py)(0, [1, 1], u, x), + ) + add("reshape", "T.reshapeTensor[4]a", lambda: t.reshape_tensor([4], a)) + add("flatten", "T.flattenTensor a", lambda: t.flatten_tensor(a)) + for source, py, hs, params in [ + ("squeeze", "squeeze", "b", [b]), + ("unsqueeze", "unsqueeze", "0 a", [0, a]), + ("expand", "expand", "[3,2,2]a", [[3, 2, 2], a]), + ("permute", "permute", "[1,0]a", [[1, 0], a]), + ("transposeTensor", "transpose_tensor", "a", [a]), + ("moveAxis", "move_axis", "0 1 a", [0, 1, a]), + ("swapAxes", "swap_axes", "0 1 a", [0, 1, a]), + ("broadcastTo", "broadcast_to", "[3,2,2]a", [[3, 2, 2], a]), + ("repeatTensor", "repeat_tensor", "1 2 a", [1, 2, a]), + ("tile", "tile", "[1,2]a", [[1, 2], a]), + ("roll", "roll", "1 1 a", [1, 1, a]), + ("flipTensor", "flip_tensor", "1 a", [1, a]), + ("rotate", "rotate", "0 1 1 a", [0, 1, 1, a]), + ]: + add( + source, + "T." + source + " " + hs, + lambda py=py, params=params: getattr(t, py)(*params), + ) + for source, py in [("concatenate", "concatenate"), ("stack", "stack")]: + add(source, "T." + source + " 0 [a,a]", lambda py=py: getattr(t, py)(0, [a, a])) + add("split", "T.splitTensor 1 [1,1] a", lambda: t.split_tensor(1, [1, 1], a)) + add("chunk", "T.chunkTensor 0 2 a", lambda: t.chunk_tensor(0, 2, a)) + add( + "padding", + "T.padTensor[(1,0),(0,1)]9 a", + lambda: t.pad_tensor([(1, 0), (0, 1)], 9, a), + ) + for source, py in [ + ("sortTensor", "sort_tensor"), + ("argsort", "argsort"), + ("unique", "unique"), + ("nonzero", "nonzero"), + ]: + add(source, "T." + source + " a", lambda py=py: getattr(t, py)(a)) + add("topk", "T.topk 2 a", lambda: t.topk(2, a)) + add( + "where", + "T.whereTensor mask x (make[3][7,8,9::Double])", + lambda: t.where_tensor(mask, x, make([3], [7, 8, 9])), + ) + add("masked fill", "T.maskedFill mask 7 x", lambda: t.masked_fill(mask, 7, x)) + add("masked select", "T.maskedSelect mask x", lambda: t.masked_select(mask, x)) + add( + "map float32", + r"T.mapTensor(\v->v*v*v)f", + lambda: t.map_tensor(lambda v: v * v * v, f), + ) + add( + "map string", + "T.mapTensor(map toUpper)text", + lambda: t.map_tensor(str.upper, text), + ) + add( + "zip cross type", + r"T.zipTensor(\v w->toRational v+w)f q", + lambda: t.zip_tensor( + lambda v, w: Fraction(v.value) + w.value, f, q, dtype="rational" + ), + ) + for source, py in [ + ("tensorAdd", "tensor_add"), + ("tensorSubtract", "tensor_subtract"), + ("tensorMultiply", "tensor_multiply"), + ("tensorDivide", "tensor_divide"), + ("tensorEqual", "tensor_equal"), + ("tensorLess", "tensor_less"), + ]: + add(source, "T." + source + " a b", lambda py=py: getattr(t, py)(a, b)) + for source, py in [("tensorAnd", "tensor_and"), ("tensorOr", "tensor_or")]: + add( + source, + "T." + source + " mask mask", + lambda py=py: getattr(t, py)(mask, mask), + ) + add("not", "T.tensorNot mask", lambda: t.tensor_not(mask)) + add( + "promote", + "T.promoteTensor f::T.Tensor Double", + lambda: t.promote_tensor("float64", f), + ) + for source, py in [ + ("sumAxes", "sum_axes"), + ("meanAxes", "mean_axes"), + ("productAxes", "product_axes"), + ("minAxes", "min_axes"), + ("maxAxes", "max_axes"), + ("varianceAxes", "variance_axes"), + ("normAxes", "norm_axes"), + ]: + add( + source, + "T." + source + "[0]True a", + lambda py=py: getattr(t, py)([0], True, a), + ) + for source, py in [("argmin", "argmin"), ("argmax", "argmax")]: + add(source, "T." + source + " a", lambda py=py: getattr(t, py)(a)) + for source, py in [ + ("cumulativeSum", "cumulative_sum"), + ("cumulativeProduct", "cumulative_product"), + ]: + add(source, "T." + source + " 1 a", lambda py=py: getattr(t, py)(1, a)) + add("tensordot", "T.tensordot[1][0]a a", lambda: t.tensordot([1], [0], a, a)) + add( + "einsum", + 'T.einsum["ab","bc"]"ac"[a,a]', + lambda: t.einsum(["ab", "bc"], "ac", [a, a]), + ) + add( + "einsum identity", + 'T.einsum[]""[]::Either E.MathError(T.Tensor Rational)', + lambda: t.einsum([], "", [], dtype="rational"), + ) + for source, py in [ + ("batchedMatmul", "batched_matmul"), + ("tensorKronecker", "tensor_kronecker"), + ]: + add(source, "T." + source + " a a", lambda py=py: getattr(t, py)(a, a)) + add("serialize", "T.serializeTensor q", lambda: t.serialize_tensor(q)) + add( + "deserialize", + "T.deserializeTensor(T.serializeTensor q)::Either E.MathError(T.Tensor Rational)", + lambda: t.deserialize_tensor(t.serialize_tensor(q), dtype="rational"), + ) + leaf = keep(t.input_graph(f)) + mapped = keep(t.map_graph(lambda v: v * v, leaf)) + add( + "graph map", + r"T.evaluateGraph(T.mapGraph(\v->v*v)(T.inputGraph f))", + lambda: t.evaluate_graph(mapped), + ) + zipped = keep(t.zip_graph(lambda v, w: v + w, mapped, mapped)) + add( + "graph zip", + r"T.zipGraph(+)(T.mapGraph(\v->v*v)(T.inputGraph f))(T.mapGraph(\v->v*v)(T.inputGraph f)) >>= T.evaluateGraph", + lambda: t.evaluate_graph(zipped), + ) + + def mutable(): + with ( + t.new_mutable([2, 2], 0, dtype="float32") as base, + t.slice_mutable(1, 1, 2, -1, base) as view, + ): + t.write_mutable(view, [1, 0], 7) + t.modify_mutable(base, [0, 0], lambda v: v + 2) + with t.transpose_mutable(view) as transposed: + return t.freeze_tensor(transposed) + + selected.append(("mutable view", "mu", mutable, None)) + + def buffer(): + with ( + t.new_mutable([3], 1, dtype="float32") as base, + t.slice_mutable(0, 2, 3, -1, base) as view, + ): + + def update(raw): + raw.pointer[raw.strides[0]] = 7 + + t.with_mutable_buffer(view, update) + return t.freeze_tensor(base) + + selected.append(("mutable buffer", "buffer", buffer, None)) + add("bad shape", "T.tensor[-1][1::Double]", lambda: t.tensor([-1], [1])) + add("bad count", "T.tensor[2][1::Double]", lambda: t.tensor([2], [1])) + add("bad slice", "T.sliceTensor 0 3 1 1 x", lambda: t.slice_tensor(0, 3, 1, 1, x)) + add("bad reshape", "T.reshapeTensor[5]a", lambda: t.reshape_tensor([5], a)) + add("bad axes", "T.sumAxes[0,0]False a", lambda: t.sum_axes([0, 0], False, a)) + return selected, owned + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(args.library.resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import _tensor_core as t + + selected, owned = cases(t) + try: + with tempfile.TemporaryDirectory(prefix="hmath-tensor-oracle-") as temporary: + path = Path(temporary) + source = path / "Main.hs" + source.write_text( + SOURCE.replace( + "CASES", ",\n ".join(expr for _, expr, _, _ in selected) + ) + ) + subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-i" + str(ROOT / "src"), + "-outputdir", + temporary, + str(source), + "-o", + str(path / "oracle"), + ], + check=True, + stdout=subprocess.DEVNULL, + ) + expected = subprocess.check_output( + [str(path / "oracle")], text=True + ).splitlines() + for (name, _, call, dtype), reference in zip(selected, expected, strict=True): + value = None + try: + value = call() + actual = encode(value, t, dtype) + except hmath.HMathError as error: + if error.math_error is None: + raise + actual = "ERR" + str(error.math_error) + finally: + close(value) + if actual != reference: + raise AssertionError(f"{name}: native {actual}, original {reference}") + print( + f"Tensor equivalence: {len(selected)} independent original Haskell sequences match dtype/shape/strides/offset/layout, exact data and IEEE bits, mutable views and errors." + ) + finally: + close(owned) + + +if __name__ == "__main__": + main() diff --git a/tools/check_timeseries_equivalence.py b/tools/check_timeseries_equivalence.py new file mode 100644 index 0000000..c17ad65 --- /dev/null +++ b/tools/check_timeseries_equivalence.py @@ -0,0 +1,289 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent original-Haskell oracle for the complete TimeSeries adapter.""" + +import argparse +import json +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from generate_graph_bindings import snake, split_top +from generate_timeseries_bindings import TYPES + +ROOT = Path(__file__).resolve().parent.parent +HASKELL = r"""{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +import qualified HMath.TimeSeries as T +import qualified HMath.Signal as S +import qualified HMath.Optimization.Common as O +import qualified HMath.Error as E +import Data.Char(ord) +import Data.List(intercalate) +import GHC.Float(castDoubleToWord64) +class Encode a where enc :: a -> String +instance Encode Int where enc x="I"++show x +instance Encode Double where enc x="F"++show(castDoubleToWord64 x) +instance Encode Bool where enc x=if x then "B1" else "B0" +instance {-# OVERLAPPING #-} Encode String where enc x="S"++show(map ord x) +instance {-# OVERLAPPABLE #-} Encode a => Encode [a] where enc xs="L["++intercalate "," (map enc xs)++"]" +instance Encode a => Encode (Maybe a) where enc Nothing="N"; enc(Just x)=enc x +instance(Encode a,Encode b) => Encode(a,b) where enc(a,b)="T["++enc a++","++enc b++"]" +instance(Encode a,Encode b,Encode c) => Encode(a,b,c) where enc(a,b,c)="T["++enc a++","++enc b++","++enc c++"]" +INSTANCES +ok :: Encode a => Either E.MathError a -> String +ok=either (("E"++).show) enc +right(Right x)=x +right(Left e)=error(show e) +xs=[2,1,4,3,6,5,8,7,10,9,12,11] :: [Double] +options=O.OptimizeOptions 100 300 1e-8 0.01 +series=right(T.series [(0,Just 1),(1,Nothing),(2,Just 3)]) +complete=right(T.regularSeries 0 1 (map Just xs)) +alignment=T.Outer +fill=T.LinearFill +resampling=T.BinMean +rolling=T.MovingMean +dtw=right(T.dynamicTimeWarping 2 xs xs) +deterministic=T.Level +metric=T.MAE +stationarity=T.Stationarity 3 [(0.05,2)] 12 "null" +arima=right(T.fitARIMA options 0 0 0 xs) +ar=right(T.fitAR 1 xs) +decomposition=right(T.decompose 2 xs) +order=T.SARIMAOrder 0 0 0 0 0 0 1 +config=T.defaultSTLConfig 2 +smoothing=T.Simple 0.5 +var=right(T.fitVAR 1 (map (:[]) xs)) +gaussian=right(S.gaussianState [0] [[1]]) +main=mapM_ putStrLn [EXPRESSIONS] +""" + + +def close(value): + if hasattr(value, "close"): + value.close() + elif isinstance(value, (tuple, list)): + for item in value: + close(item) + + +def encode(value, ts): + from _hmath_native._value import Value + + if value is None: + return "N" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, float): + return "F" + str(struct.unpack("!Q", struct.pack("!d", value))[0]) + if isinstance(value, str): + return "S" + json.dumps(list(map(ord, value)), separators=(",", ":")) + if isinstance(value, Value): + return "O" + encode(ts.describe(value), ts) + if isinstance(value, (tuple, list)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(item, ts) for item in value) + + "]" + ) + raise TypeError(type(value)) + + +def cases(ts, opt): + xs = [2.0, 1.0, 4.0, 3.0, 6.0, 5.0, 8.0, 7.0, 10.0, 9.0, 12.0, 11.0] + options = opt.OptimizeOptions(100, 300, 1e-8, 0.01) + owners = { + "series": ts.series([(0, 1), (1, None), (2, 3)]), + "complete": ts.regular_series(0, 1, xs), + "alignment": ts.outer(), + "fill": ts.linear_fill(), + "resampling": ts.bin_mean(), + "rolling": ts.moving_mean(), + "dtw": ts.dynamic_time_warping(2, xs, xs), + "deterministic": ts.level(), + "metric": ts.mae(), + "stationarity": ts.stationarity(3, [(0.05, 2)], 12, "null"), + "arima": ts.fit_arima(options, 0, 0, 0, xs), + "ar": ts.fit_ar(1, xs), + "decomposition": ts.decompose(2, xs), + "order": ts.sarima_order(0, 0, 0, 0, 0, 0, 1), + "config": ts.default_stl_config(2), + "smoothing": ts.simple(0.5), + "var": ts.fit_var(1, [[x] for x in xs]), + "gaussian": ts.gaussian_state([0], [[1]]), + } + keys = dict( + zip( + TYPES, + [ + "series", + "alignment", + "fill", + "resampling", + "rolling", + "dtw", + "deterministic", + "metric", + "stationarity", + "arima", + "ar", + "decomposition", + "order", + "config", + "smoothing", + "var", + "gaussian", + ], + ) + ) + defaults = { + "Int": (2, "2"), + "Double": (0.5, "0.5"), + "Bool": (False, "False"), + "String": ("null", '"null"'), + "[Double]": (xs, "xs"), + "[[Double]]": ([[1.0]], "[[1]]"), + "[Maybe Double]": ([1, None, 3], "[Just 1,Nothing,Just 3]"), + "[(Double, Maybe Double)]": ( + [(0, 1), (1, None), (2, 3)], + "[(0,Just 1),(1,Nothing),(2,Just 3)]", + ), + "[(Int, Int)]": ([(0, 0), (1, 1)], "[(0,0),(1,1)]"), + "[(Double, Double)]": ([(0.05, 2)], "[(0.05,2)]"), + "OptimizeOptions": (options, "options"), + } + overrides = { + "fitARIMA": ([options, 0, 0, 0, xs], ["options", "0", "0", "0", "xs"]), + "fitARMA": ([options, 0, 0, xs], ["options", "0", "0", "xs"]), + "fitMA": ([options, 0, xs], ["options", "0", "xs"]), + "fitAR": ([1, xs], ["1", "xs"]), + "fitVAR": ([1, [[x] for x in xs]], ["1", "(map (:[]) xs)"]), + "gaussianState": ([[0], [[1]]], ["[0]", "[[1]]"]), + "seriesValues": ([owners["complete"]], ["complete"]), + "regularSeries": ([0, 1, [1, None, 3]], ["0", "1", "[Just 1,Nothing,Just 3]"]), + } + entries = json.loads( + (ROOT / "bindings/schema/timeseries-functions.json").read_text() + )["functions"] + result = [] + for entry in entries: + name = entry["name"] + if name in overrides: + arguments, expressions = overrides[name] + else: + arguments, expressions = [], [] + for typ in split_top(entry["signature"], "->")[:-1]: + if typ in keys: + key = keys[typ] + arguments.append(owners[key]) + expressions.append(key) + else: + value, expression = defaults[typ] + arguments.append(value) + expressions.append(expression) + qualified = "S" if entry["module"] == "HMath.Signal" else "T" + call = qualified + "." + name + " " + " ".join(expressions) + checked = split_top(entry["signature"], "->")[-1].startswith("Either MathError") + result.append( + (snake(name), arguments, ("ok (" if checked else "enc (") + call + ")") + ) + result += [ + ("series_values", [owners["series"]], "ok(T.seriesValues series)"), + ("series", [[(1, 2), (0, 3)]], "ok(T.series [(1,Just 2),(0,Just 3)])"), + ("regular_series", [0, 0, []], "ok(T.regularSeries 0 0 [])"), + ("forecast_ar", [-1, owners["ar"]], "ok(T.forecastAR (-1) ar)"), + ( + "fit_sarima", + [options, owners["order"], [1, 2]], + "ok(T.fitSARIMA options order [1,2])", + ), + ("rolling", [owners["rolling"], 0, xs], "ok(T.rolling rolling 0 xs)"), + ("gaussian_state", [[0], [[-1]]], "ok(S.gaussianState [0] [[-1]])"), + ] + return result, owners + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + + ts = hmath.timeseries + fixtures, owners = cases(ts, hmath.optimization) + try: + instances = "\n".join( + "instance Encode " + + ("S." if module == "HMath.Signal" else "T.") + + name + + ' where enc x="O"++enc(show x)' + for name, (module, _) in TYPES.items() + ) + source = HASKELL.replace("INSTANCES", instances).replace( + "EXPRESSIONS", ",\n ".join(case[2] for case in fixtures) + ) + with tempfile.TemporaryDirectory( + prefix="hmath-timeseries-oracle-" + ) as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + executable = Path(directory) / "oracle" + process = subprocess.run( + [ + "ghc", + "-XHaskell2010", + "-O1", + "-isrc", + "-Iinclude", + "-outputdir", + directory, + str(path), + "cbits/backend.c", + *(["-ldl"] if sys.platform.startswith("linux") else []), + "-o", + str(executable), + ], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + if process.returncode: + raise RuntimeError(process.stderr) + expected = subprocess.check_output( + [str(executable)], text=True + ).splitlines() + actual = [] + for name, arguments, _ in fixtures: + try: + value = getattr(ts, name)(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(value, ts)) + finally: + close(value) + failures = [ + (i, fixtures[i][0], want, got) + for i, (want, got) in enumerate(zip(expected, actual)) + if want != got + ] + if len(actual) != len(expected) or failures: + raise AssertionError(f"TimeSeries oracle mismatches: {failures[:8]}") + print( + f"TimeSeries direct Haskell equivalence: {len(actual)} cases, all101 named adapters" + ) + finally: + for owner in owners.values(): + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/check_units_equivalence.py b/tools/check_units_equivalence.py new file mode 100644 index 0000000..6c749ba --- /dev/null +++ b/tools/check_units_equivalence.py @@ -0,0 +1,280 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exact original-Haskell oracle for Units catalogs, constructors and operations.""" + +import argparse +import os +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +from check_polynomial_equivalence import HASKELL, close +from generate_units_bindings import ops, snake + +ROOT = Path(__file__).resolve().parent.parent + + +def encode(value, u): + import hmath + + if isinstance(value, u.Dimension): + return "D" + encode(value.exponents, u) + if isinstance(value, u.Unit): + dimension = u.unit_dimension(value) + try: + return ( + "U[" + + ",".join( + encode(x, u) + for x in [value.name, dimension, value.scale, value.offset] + ) + + "]" + ) + finally: + dimension.close() + if isinstance(value, u.Quantity): + dimension = u.quantity_dimension(value) + with u.celsius() as c: + try: + temperature = u.in_unit(c, value) + except hmath.HMathError as error: + temperature = "E" + str(error.math_error) + try: + return ( + "Q[" + + ",".join(encode(x, u) for x in [dimension, value.si_value]) + + "," + + ( + temperature + if isinstance(temperature, str) + else encode(temperature, u) + ) + + "]" + ) + finally: + dimension.close() + if isinstance(value, u.SIPrefix): + return ( + "SIP[" + + ",".join(encode(x, u) for x in [value.name, value.symbol, value.exponent]) + + "]" + ) + if isinstance(value, str): + return "L[" + ",".join("I" + str(ord(x)) for x in value) + "]" + if isinstance(value, Fraction): + return f"R{value.numerator}/{value.denominator}" + if isinstance(value, bool): + return "B1" if value else "B0" + if isinstance(value, int): + return "I" + str(value) + if isinstance(value, (list, tuple)): + return ( + ("T[" if isinstance(value, tuple) else "L[") + + ",".join(encode(x, u) for x in value) + + "]" + ) + raise TypeError(type(value)) + + +EXTRA = r""" +instance E Char where enc x="I"++show(ord x) +instance E U.Dimension where enc x="D"++enc(U.dimensionExponents x) +instance E U.Unit where enc x="U["++enc(U.unitName x)++","++enc(U.unitDimension x)++","++enc(U.unitScale x)++","++enc(U.unitOffset x)++"]" +instance E U.Quantity where enc x="Q["++enc(U.quantityDimension x)++","++enc(U.siValue x)++","++ok(U.inUnit U.celsius x)++"]" +instance E U.SIPrefix where enc x="SIP["++enc(U.prefixName x)++","++enc(U.prefixSymbol x)++","++enc(U.prefixExponent x)++"]" +unitM=case U.unit "x\NUL\945" U.lengthDimension (3%7) 0 of Right x->x;Left e->error(show e) +prefix=U.SIPrefix "kilo" "k" 3 +leftQ=U.quantity U.metre (3%2) +rightQ=U.quantity U.metre 2 +""" + + +def fixtures(u): + owned = [] + + def own(value): + owned.append(value) + return value + + metre = own(u.metre()) + km = own(u.kilometre()) + c = own(u.celsius()) + f = own(u.fahrenheit()) + dim = own(u.length_dimension()) + unit = own(u.unit("x\0α", dim, Fraction(3, 7), 0)) + prefix = own(u.SIPrefix("kilo", "k", 3)) + left = own(u.quantity(metre, Fraction(3, 2))) + right = own(u.quantity(metre, 2)) + result = [] + + def add(name, args, hs, mode="pure"): + result.append( + (snake(name), args, ("ok" if mode == "either" else "enc") + " (" + hs + ")") + ) + + for name, args, _return, mode in ops(): + values = [] + hsargs = [] + for parameter, typ in args: + if typ == "Dimension": + value, h = dim, "U.lengthDimension" + elif typ == "[Integer]": + value, h = [1] + [0] * 8, "[1,0,0,0,0,0,0,0,0]" + elif typ == "Rational": + value, h = Fraction(3, 7), "(3%7)" + elif typ == "Integer": + value, h = -2, "(-2)" + elif typ == "Int": + value, h = 3, "3" + elif typ == "String": + value, h = ( + ("x\0α", '"x\\NUL\\945"') if parameter == "name" else ("k", '"k"') + ) + elif typ == "SIPrefix": + value, h = prefix, "prefix" + elif typ == "Quantity": + value, h = ( + (right, "rightQ") + if parameter in ("right", "denominator") + else (left, "leftQ") + ) + elif typ == "Unit": + if name == "temperatureDifference": + value, h = c, "U.celsius" + elif name == "convert": + value, h = ( + (km, "U.kilometre") + if parameter == "source" + else (metre, "U.metre") + ) + elif name in ("unitName", "unitDimension", "unitScale", "unitOffset"): + value, h = unit, "unitM" + else: + value, h = metre, "U.metre" + else: + raise AssertionError(typ) + if name == "unit" and parameter == "offset": + value, h = 0, "0" + values.append(value) + hsargs.append(h) + add(name, values, "U." + name + " " + " ".join(hsargs), mode) + # Invalid and affine/temperature branches use original source checks. + add("dimension", [[0] * 8], "U.dimension [0,0,0,0,0,0,0,0]", "either") + add("unit", ["bad", dim, 0, 0], 'U.unit "bad" U.lengthDimension 0 0', "either") + add("unit", ["bad", dim, 1, 1], 'U.unit "bad" U.lengthDimension 1 1', "either") + add("unitProduct", [c, metre], "U.unitProduct U.celsius U.metre", "either") + add("unitQuotient", [metre, c], "U.unitQuotient U.metre U.celsius", "either") + add("unitPower", [c, 2], "U.unitPower U.celsius 2", "either") + add( + "temperatureDifference", + [metre, 1], + "U.temperatureDifference U.metre 1", + "either", + ) + add("convert", [metre, c, 1], "U.convert U.metre U.celsius 1", "either") + absA = own(u.quantity(c, 20)) + absB = own(u.quantity(c, 10)) + delta = own(u.temperature_difference(c, 10)) + for name, arguments, hargs in [ + ( + "addQuantity", + [absA, absB], + "(U.quantity U.celsius 20) (U.quantity U.celsius 10)", + ), + ( + "addQuantity", + [absA, delta], + "(U.quantity U.celsius 20) (case U.temperatureDifference U.celsius 10 of Right x->x;Left e->error(show e))", + ), + ( + "subtractQuantity", + [absA, absB], + "(U.quantity U.celsius 20) (U.quantity U.celsius 10)", + ), + ( + "subtractQuantity", + [delta, absA], + "(case U.temperatureDifference U.celsius 10 of Right x->x;Left e->error(show e)) (U.quantity U.celsius 20)", + ), + ("multiplyQuantity", [absA, left], "(U.quantity U.celsius 20) leftQ"), + ("divideQuantity", [left, absA], "leftQ (U.quantity U.celsius 20)"), + ]: + add(name, arguments, "U." + name + " " + hargs, "either") + add( + "inUnit", + [f, delta], + "U.inUnit U.fahrenheit (case U.temperatureDifference U.celsius 10 of Right x->x;Left e->error(show e))", + "either", + ) + add( + "inUnit", [f, absA], "U.inUnit U.fahrenheit (U.quantity U.celsius 20)", "either" + ) + add("prefixed", [prefix, c], "U.prefixed prefix U.celsius", "either") + huge = own(u.SIPrefix("huge", "H", 10001)) + add( + "prefixed", + [huge, metre], + 'U.prefixed (U.SIPrefix "huge" "H" 10001) U.metre', + "either", + ) + return result, owned + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", required=True) + args = parser.parse_args() + os.environ["HMATH_LIBRARY"] = str(Path(args.library).resolve()) + sys.path.insert(0, str(ROOT / "bindings/python")) + import hmath + from _hmath_native import units_values as u + + cases, owners = fixtures(u) + try: + source = ( + HASKELL.replace( + "import Data.Complex", + "import qualified HMath.Units as U\nimport Data.Char (ord)\nimport Data.Complex", + ) + .replace("pR=P.polynomial", EXTRA + "\npR=P.polynomial") + .replace("EXPRESSIONS", "\n , ".join(case[2] for case in cases)) + ) + with tempfile.TemporaryDirectory(prefix="hmath-units-oracle-") as directory: + path = Path(directory) / "Main.hs" + path.write_text(source) + expected = subprocess.run( + ["runghc", "-isrc", str(path)], + cwd=ROOT, + text=True, + capture_output=True, + check=True, + ).stdout.splitlines() + actual = [] + for name, arguments, _expression in cases: + try: + value = getattr(u, name)(*arguments) + except hmath.HMathError as error: + actual.append("E" + str(error.math_error or error)) + else: + try: + actual.append(encode(value, u)) + finally: + close(value) + errors = [ + (cases[i][0], expected[i], actual[i]) + for i in range(len(actual)) + if expected[i] != actual[i] + ] + if len(expected) != len(actual) or errors: + raise AssertionError(errors[:10]) + print( + f"Units direct Haskell equivalence: {len(actual)} cases, all80remaining symbols" + ) + finally: + for owner in owners: + owner.close() + + +if __name__ == "__main__": + main() diff --git a/tools/generate_algebra_bindings.py b/tools/generate_algebra_bindings.py new file mode 100644 index 0000000..10e120e --- /dev/null +++ b/tools/generate_algebra_bindings.py @@ -0,0 +1,638 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Expose both original algebra interfaces without inventing typeclass instances.""" + +import argparse +import json +import re +from pathlib import Path + +import generate_foundation_bindings as F +import generate_linear_bindings as G +from generate_stochastic_bindings import fmt + +ROOT = Path(__file__).resolve().parent.parent +MODULES = {"HMath.Algebra": ("A", "algebra"), "HMath.API.Algebra": ("P", "algebra_api")} +CLASSES = { + "HMath.Algebra": { + "Semiring": ["zero", "one", "plus", "times"], + "Ring": ["negateRing"], + "Field": ["inverseField"], + "Group": ["groupIdentity", "groupCombine", "groupInverse"], + "Module": ["moduleScale", "moduleAdd"], + "VectorSpace": [], + }, + "HMath.API.Algebra": { + "Ring": ["zero", "one", "plus", "times", "negative", "integer"], + "Field": ["invert"], + "Scalar": ["conjugateScalar"], + "FloatingPoint": ["machineEpsilon", "finiteScalar"], + "Numeric": ["rational"], + "MatrixLike": ["matrixDimensions", "matrixElements", "matrixConstruct"], + "TensorLike": ["tensorDimensions", "tensorElements", "tensorConstruct"], + "VectorSpace": ["vectorPlus", "vectorScale"], + "Differentiable": ["differential"], + "Differential": [], + }, +} +METHODS = { + "zero": "a", + "one": "a", + "plus": "a -> a -> a", + "times": "a -> a -> a", + "negateRing": "a -> a", + "inverseField": "a -> Either MathError a", + "groupIdentity": "Additive a", + "groupCombine": "Additive a -> Additive a -> Additive a", + "groupInverse": "Additive a -> Additive a", + "moduleScale": "a -> [a] -> [a]", + "moduleAdd": "[a] -> [a] -> Either MathError [a]", + "negative": "a -> a", + "integer": "Integer -> a", + "invert": "a -> Either MathError a", + "conjugateScalar": "a -> a", + "machineEpsilon": "Double", + "finiteScalar": "a -> Bool", + "rational": "Rational -> Either MathError a", + "matrixDimensions": "Matrix a -> (Int,Int)", + "matrixElements": "Matrix a -> [a]", + "matrixConstruct": "Int -> Int -> [a] -> Either MathError (Matrix a)", + "tensorDimensions": "Tensor a -> [Int]", + "tensorElements": "Tensor a -> [a]", + "tensorConstruct": "[Int] -> [a] -> Either MathError (Tensor a)", + "vectorPlus": "Vector a -> Vector a -> Either MathError (Vector a)", + "vectorScale": "a -> Vector a -> Vector a", + "differential": "Dual a -> a", +} + + +def specification(): + old = G.MODULES + G.MODULES = MODULES + try: + entries, types, _fields, _missing = G.signatures() + finally: + G.MODULES = old + for module, classes in CLASSES.items(): + for cls, names in classes.items(): + for name in names: + signature = METHODS[name] + parts = G.split_top(signature, "->") + raw = (ROOT / "src" / (module.replace(".", "/") + ".hs")).read_text() + original = re.search( + r"^[ \t]+" + re.escape(name) + r"[ \t]*::[ \t]*([^\n]+)", + raw, + re.MULTILINE, + ) + entries.append( + { + "module": module, + "name": name, + "args": [G.parse_type(s) for s in parts[:-1]], + "result": G.parse_type(parts[-1]), + "constraints": cls + " (original instances only)", + "signature": original[1].strip() if original else signature, + "wire_signature": signature, + "constructor": False, + } + ) + return entries, types + + +def mode(e): + name = e["name"] + if e["module"] == "HMath.Algebra": + if name in ("moduleScale", "moduleAdd", "moduleLaws", "linearCombination"): + return "module" + if name in ( + "zero", + "one", + "plus", + "times", + "negateRing", + "inverseField", + "semiringLaws", + "ringLaws", + "fieldLaws", + "Additive", + "getAdditive", + "groupIdentity", + "groupCombine", + "groupInverse", + "groupLaws", + ): + return "old" + else: + if name in ("matrixConstruct", "tensorConstruct", "vectorPlus", "vectorScale"): + return "typed" + if name in ( + "zero", + "one", + "plus", + "times", + "negative", + "integer", + "invert", + "conjugateScalar", + "machineEpsilon", + "finiteScalar", + "rational", + "horner", + "innerProduct", + ): + return "api" + return "value" + + +def sym(e): + return ( + "hmath_algebra_" + + ("core_" if e["module"] == "HMath.Algebra" else "api_") + + ("new_" if e["constructor"] else "") + + G.snake(e["name"]) + ) + + +def decode(spec, value, wire=None): + head, *args = spec + if head in ("a", "s"): + return "readWire " + wire + " " + value + if head == "v": + return "readList(readWire " + wire + ") " + value + if head == "Additive": + return "asAdditiveWire " + wire + " " + value + if head == "list": + return "readList(\\x -> " + decode(args[0], "x", wire) + ") " + value + if head == "tuple": + variables = [G.fresh("part") for _ in args] + return ( + "(V.asTuple " + + str(len(args)) + + " " + + value + + " >>= \\parts -> case parts of {[" + + ",".join(variables) + + "] -> (" + + "," * (len(args) - 1) + + ") <$> " + + " <*> ".join( + "(" + decode(s, v, wire) + ")" for s, v in zip(args, variables) + ) + + ';_ -> V.invalid "tuple arity differs"})' + ) + if head in ("Modular", "FiniteField", "FieldElement"): + return "as" + head + " " + value + if head == "Exact": + return 'unbox "HMath.API.Algebra.Exact" ' + value + if head == "Rational": + return "V.asScalar " + value + if head == "MathError": + raise ValueError(spec) + return F.decode(spec, value, {}).replace("X.", "V.") + + +def encode(spec, value, wire=None, domain=None): + head, *args = spec + if head in ("a", "s"): + return "writeWire " + wire + " " + value + if head == "v": + return "list(writeWire " + wire + ") " + value + if head == "Additive": + return "pure(additive " + domain + " " + value + ")" + if head == "Either": + return ( + "source " + + value + + " >>= \\result -> " + + encode(args[1], "result", wire, domain) + ) + if head == "list": + return "list(\\x -> " + encode(args[0], "x", wire, domain) + ") " + value + if head == "tuple": + vs = [G.fresh("field") for _ in args] + return ( + "(\\(" + + ",".join(vs) + + ") -> V.Tuple <$> sequence [" + + ",".join(encode(s, v, wire, domain) for s, v in zip(args, vs)) + + "]) " + + value + ) + if head in ("Modular", "FiniteField", "FieldElement", "Exact"): + return ( + "pure(" + + G.snake(head) + .replace("finite_field", "finiteField") + .replace("field_element", "fieldElement") + + " " + + value + + ")" + ) + return F.encode(spec, value, {}).replace("X.", "V.") + + +def native_body(e): + name = e["name"] + selected = mode(e) + alias = MODULES[e["module"]][0] + if selected == "module": + return "withModule prototype $ \\wire -> do\n" + module_body(e) + if selected in ("old", "api"): + domain = "Old" if selected == "old" else "API" + lines = ["with" + domain + " prototype $ \\domain -> do"] + if name not in ("groupIdentity", "machineEpsilon"): + lines.append( + " let wire=" + selected.lower() + "Wire domain" + if selected == "old" + else " let wire=apiWire domain" + ) + specs = e["args"] + if name == "groupLaws": + specs = [["list", ["Additive", ["a"]]]] + for i, s in enumerate(specs): + lines.append(" x" + str(i) + " <- " + decode(s, "a" + str(i), "wire")) + result = e["result"] + call = ( + "(" + + alias + + "." + + name + + (" " + " ".join("x" + str(i) for i in range(len(specs))) if specs else "") + + ")" + ) + if name == "machineEpsilon": + call = "(apiEpsilon domain)" + out = encode(result, call, "wire", "domain") + if selected == "old" and name in ("inverseField", "fieldLaws"): + out = "oldField domain $ " + out + if selected == "api" and name == "invert": + out = "apiField domain $ " + out + if selected == "api" and name in ("machineEpsilon", "finiteScalar"): + out = "apiFloating domain $ " + out + # General Group a signatures are represented by the original Additive + # instance. No other Group instances exist in the source tree. + if name == "getAdditive": + out = "writeWire wire (A.getAdditive x0)" + if name == "groupIdentity": + out = "pure(additive domain A.groupIdentity)" + if name == "groupLaws": + out = "pairs(A.groupLaws x0)" + lines.append(" " + out) + return "\n".join(lines) + specials = { + "matrixDimensions": "withMatrix a0 $ \\_ matrixValue -> pure(\\(r,c) -> V.Tuple[V.Index r,V.Index c]) <*> pure(P.matrixDimensions matrixValue)", + "matrixElements": "withMatrix a0 $ \\wire matrixValue -> list(writeWire wire)(P.matrixElements matrixValue)", + "matrixConstruct": "do {r <- V.asIndex a0;c <- V.asIndex a1;xs <- V.asList a2;matrixConstruct prototype r c xs}", + "tensorDimensions": "tensorDimensions a0", + "tensorElements": "tensorElements a0", + "tensorConstruct": "do {ds <- V.asList a0 >>= mapM V.asIndex;xs <- V.asList a1;tensorConstruct prototype ds xs}", + "vectorPlus": "vectorPlus prototype a0 a1", + "vectorScale": "vectorScale prototype a0 a1", + "differential": "differential a0", + } + if e["module"] == "HMath.API.Algebra" and name in specials: + return specials[name] + lines = ["do"] + for i, s in enumerate(e["args"]): + lines.append(" x" + str(i) + " <- " + decode(s, "a" + str(i))) + call = ( + "(" + + alias + + "." + + name + + " " + + " ".join("x" + str(i) for i in range(len(e["args"]))) + + ")" + ) + lines.append(" " + encode(e["result"], call)) + return "\n".join(lines) + + +def module_body(e): + name = e["name"] + bodies = { + "moduleScale": "x <- readWire wire a0;xs <- readList(readWire wire)a1;list(writeWire wire)(A.moduleScale x xs)", + "moduleAdd": "xs <- readList(readWire wire)a0;ys <- readList(readWire wire)a1;source(A.moduleAdd xs ys) >>= list(writeWire wire)", + "moduleLaws": "xs <- readList(readWire wire)a0;ys <- readList(readList(readWire wire))a1;pairs(A.moduleLaws xs ys)", + "linearCombination": 'zeroVector <- readList(readWire wire)a0;terms <- readList(\\v -> V.asTuple 2 v >>= \\parts -> case parts of {[s,x] -> (,) <$>readWire wire s <*>readList(readWire wire)x;_ -> V.invalid "module term arity differs"})a1;source(A.linearCombination zeroVector terms) >>= list(writeWire wire)', + } + return " " + bodies[name] + + +def outputs(): + G._COUNTER = 0 + entries, types = specification() + numeric_sources = { + entry["module"] + "." + entry["name"] + for entry in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + } + hs = [ + """{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated direct calls into the two distinct original algebra interfaces. +module HMath.FFI.AlgebraAll where +import Prelude hiding(readList) +import Foreign +import Foreign.C +import qualified HMath.Algebra as A +import qualified HMath.API.Algebra as P +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec +import HMath.FFI.AlgebraCodec +import qualified HMath.FFI.TensorCodec as TensorCodec +apply :: Int -> [V.Value] -> IO V.Value +apply operation args=case(operation,args) of +""" + ] + header = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated original algebra typeclass instances and checked field APIs. */ +#ifndef HMATH_ALGEBRA_H +#define HMATH_ALGEBRA_H +#include "hmath_foundation.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Explicit prototype parameters select actual source instances. They are not + * conversions. Old Algebra: Integer/Rational/Polynomial, Additive groups and + * Integer/Rational list modules. API.Algebra: Integer/Rational/Float/Double/ + * Complex Double/Exact; unsupported original instances return Unsupported. + * Exact has no Num instance. Inputs borrow; outputs own an independent Value. + * Failure leaves *out untouched; release outputs using hmath_value_release. */ +""" + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n#include "hmath_algebra.h"\n#include "value_internal.h"\nextern int hm_algebra_apply(int,void *const *,size_t,void **);\n' + ] + py = { + m: [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated original algebra interface.\nfrom ._algebra_base import invoke,initialize\nfrom ._foundation_base import FoundationValue,register\n" + ] + for m in MODULES + } + exports = {m: [] for m in MODULES} + mappings = [] + docs = [ + "# Original algebra interfaces\n\nThe two source modules define different classes and instances. Their functions remain separate. Prototypes select the actual original type, without adding arithmetic instances or converting through Double. `Exact` wraps Rational and deliberately has no Num instance. Old Algebra supports Integer/Rational/Polynomial rings, Rational fields, Additive groups and Integer/Rational list modules. API.Algebra supports Integer/Rational/Float/Double/Complex Double/Exact; Field excludes Integer and FloatingPoint is Float/Double/Complex Double. Source errors, modular ring identity, finite-field proof budgets and checked inversion are unchanged. Values own references and support close/context management.\n\n" + ] + for name, t in types.items(): + m = t["module"] + source = m + "." + name + exports[m].append(name) + ctor = next( + ( + e + for e in entries + if e["constructor"] and e["name"] == name and e["module"] == m + ), + None, + ) + py[m].append( + "\nclass " + + name + + '(FoundationValue):\n """Original ' + + source + + ' owner."""\n _source_type=' + + repr(source) + + "\n" + ) + if ctor: + params = ["argument" + str(i + 1) for i in range(len(ctor["args"]))] + py[m].append( + " def __init__(self" + + (", " + ",".join(params) if params else "") + + ", *, dtype=None):\n initialize(self," + + repr(sym(ctor)) + + "," + + repr(ctor["args"]) + + ",[" + + ",".join(params) + + "]," + + repr(mode(ctor)) + + ",dtype)\n" + ) + if name == "Exact": + py[m].append( + " @property\n def value(self):\n return get_exact(self)\n" + " @property\n def element_type(self):\n return exact_element_type()\n" + ) + if name == "Additive": + py[m].append( + " @property\n def value(self):\n return get_additive(self)\n" + ) + py[m].append("register(" + repr(source) + "," + name + ")\n") + for opcode, e in enumerate(entries): + args = ["a" + str(i) for i in range(len(e["args"]))] + if mode(e) != "value": + args = ["prototype"] + args + hs.append( + " (" + + str(opcode) + + ",[" + + ",".join(args) + + "]) -> " + + native_body(e).replace("\n", "\n ") + + "\n" + ) + parameters = ( + ["hmath_context *context"] + + ["const hmath_value *" + a for a in args] + + ["hmath_value **out"] + ) + prototype = "hmath_status " + sym(e) + "(" + ",".join(parameters) + ")" + header.append( + "/* " + + e["module"] + + "." + + e["name"] + + " */\nHMATH_API " + + prototype + + ";\n" + ) + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + a for a in args) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL algebra argument");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n' + ) + if args: + c.append( + " void *args[]={" + + ",".join("hm_value_stable(" + a + ")" for a in args) + + "};\n" + ) + c.append( + " return hm_value_finish(result,hm_algebra_apply(" + + str(opcode) + + "," + + ("args" if args else "NULL") + + "," + + str(len(args)) + + ",&result->stable),out);\n}\n" + ) + name = e["name"] if e["constructor"] else G.snake(e["name"]) + m = e["module"] + exports[m].append(name) + if not e["constructor"]: + params = ["argument" + str(i + 1) for i in range(len(e["args"]))] + typed = mode(e) != "value" + py[m].append( + "\ndef " + + name + + "(" + + ",".join(params) + + (", " if params and typed else "") + + ("*, dtype=None" if typed else "") + + "):\n " + + repr(G.source_prose(e)) + + "\n return invoke(" + + repr(sym(e)) + + "," + + repr(e["args"]) + + ",[" + + ",".join(params) + + "]," + + repr(mode(e)) + + ("," + "dtype" if typed else "") + + ")\n" + ) + if e["module"] + "." + e["name"] not in numeric_sources: + mappings.append( + { + "symbol": e["module"] + "." + e["name"], + "c": [sym(e)], + "python": "hmath." + MODULES[m][1] + "." + name, + "specializations": [ + "actual original instances; exact domain/dictionary retained; no invented typeclass instances" + ], + } + ) + docs.append( + "## `" + + MODULES[m][1] + + "." + + name + + "`\n\n" + + G.source_prose(e) + + "\n\nOriginal signature: `" + + e["signature"] + + "`. " + + ( + "The first C Value is a prototype; Python accepts `dtype=` or infers a typed argument. " + if mode(e) != "value" + else "" + ) + + "Borrowed source-order arguments; owned successful output; failure leaves the output untouched.\n\n" + ) + for m, classes in CLASSES.items(): + for name, methods in classes.items(): + exports[m].append(name) + py[m].append( + "\nclass " + + name + + ':\n """Original ' + + m + + "." + + name + + ' interface; methods select supported source instances."""\n' + ) + if methods: + for method in methods: + py[m].append( + " " + + G.snake(method) + + "=staticmethod(" + + G.snake(method) + + ")\n" + ) + else: + py[m].append(" pass\n") + mappings.append( + { + "symbol": m + "." + name, + "c": [ + sym(e) + for e in entries + if e["module"] == m and e["name"] in methods + ] + or ["hmath_value", "hmath_value_release"], + "python": "hmath." + MODULES[m][1] + "." + name, + "specializations": [ + "original open class/associated type; adapter exposes documented existing concrete instances" + ], + } + ) + covered = {m["symbol"] for m in mappings} + for name, t in types.items(): + if t["module"] + "." + name not in covered: + mappings.append( + { + "symbol": t["module"] + "." + name, + "c": ["hmath_value", "hmath_value_release"], + "python": "hmath." + MODULES[t["module"]][1] + "." + name, + "specializations": ["original opaque owned type"], + } + ) + py["HMath.API.Algebra"].append( + '\ndef exact_element_type():\n """Typed structural Exact element prototype for ordinary Tensor/Vector APIs."""\n from ._value import decode,invoke as native_invoke\n return decode(native_invoke("hmath_algebra_api_exact_element_type"))\n' + ) + exports["HMath.API.Algebra"].append("exact_element_type") + header.append( + "HMATH_API hmath_status hmath_algebra_api_exact_element_type(hmath_context *context,hmath_value **out);\n" + ) + c.append( + 'hmath_status hmath_algebra_api_exact_element_type(hmath_context *context,hmath_value **out) {\n if(!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL element type output");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n return hm_value_finish(result,hm_algebra_apply(-1,NULL,0,&result->stable),out);\n}\n' + ) + hs.append(""" (-1,[]) -> pure(TensorCodec.prototype exactElement) + _ -> V.invalid "invalid algebra operation/arity" +foreign export ccall "hm_algebra_apply" ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(V.publish value out)) +""") + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + result = { + "src/HMath/FFI/AlgebraAll.hs": "".join(hs), + "include/hmath_algebra.h": "".join(header), + "cbits/algebra.c": "".join(c), + "bindings/schema/algebra-functions.json": json.dumps( + {"functions": entries, "types": types}, indent=2 + ) + + "\n", + "bindings/schema/algebra-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mappings, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "docs/reference/algebra-values.md": "".join(docs), + } + for m, data in py.items(): + data.append("\n__all__=" + repr(sorted(set(exports[m]))) + "\n") + result["bindings/python/_hmath_native/" + MODULES[m][1] + ".py"] = fmt( + "".join(data), MODULES[m][1] + ".py" + ) + return { + name: F.format_c(data) if name.endswith((".c", ".h")) else data + for name, data in result.items() + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_buffer_bindings.py b/tools/generate_buffer_bindings.py new file mode 100644 index 0000000..56013e0 --- /dev/null +++ b/tools/generate_buffer_bindings.py @@ -0,0 +1,273 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named adapters and source documentation for all API.Buffer exports.""" + +import argparse +import json +from pathlib import Path + +from generate_graph_bindings import snake, source_prose + +ROOT = Path(__file__).resolve().parent.parent +# Native operation order is the explicit dispatcher in HMath.FFI.Buffer. +SPECS = [ + ( + "lazyBoxed", + ["values"], + "[a] -> Boxed a", + "return _boxed('lazy_boxed', values, dtype)", + ", *, dtype=None", + ), + ( + "strictBoxed", + ["values"], + "[a] -> Boxed a", + "return _boxed('strict_boxed', values, dtype)", + ", *, dtype=None", + ), + ("boxedValues", ["value"], "Boxed a -> [a]", None, ""), + ("boxedLength", ["value"], "Boxed a -> Int", None, ""), + ( + "mapStrict", + ["function", "value"], + "(a -> b) -> Boxed a -> Boxed b", + "return _call('map_strict', [function, value], 0)", + "", + ), + ( + "unboxedDouble", + ["values"], + "[Double] -> UnboxedDouble", + "return UnboxedDouble(values)", + "", + ), + ("unboxedValues", ["value"], "UnboxedDouble -> [Double]", None, ""), + ( + "runSTBuffer", + ["value", "callback"], + "Boxed a -> (forall s. STBuffer s a -> ST s b) -> b", + "return _call('run_st_buffer', [value, callback], 1)", + "", + ), + ("thawSTBuffer", ["region", "value"], "Boxed a -> ST s (STBuffer s a)", None, ""), + ("freezeSTBuffer", ["value"], "STBuffer s a -> ST s (Boxed a)", None, ""), + ( + "readSTBuffer", + ["value", "index"], + "STBuffer s a -> Int -> ST s (Either MathError a)", + None, + "", + ), + ( + "writeSTBuffer", + ["value", "index", "element"], + "STBuffer s a -> Int -> a -> ST s (Either MathError ())", + None, + "", + ), + ( + "newIOBuffer", + ["count", "initial"], + "Storable a => Int -> a -> IO (Either MathError (IOBuffer a))", + "return _new_io(count, initial, dtype)", + ", *, dtype=None", + ), + ( + "thawIOBuffer", + ["prototype", "value"], + "Storable a => Boxed a -> IO (Either MathError (IOBuffer a))", + "return _thaw_io(value, dtype, prototype)", + ", *, dtype=None", + ), + ("freezeIOBuffer", ["value"], "Storable a => IOBuffer a -> IO (Boxed a)", None, ""), + ("ioBufferLength", ["value"], "IOBuffer a -> Int", None, ""), + ( + "readIOBuffer", + ["value", "index"], + "Storable a => IOBuffer a -> Int -> IO (Either MathError a)", + None, + "", + ), + ( + "writeIOBuffer", + ["value", "index", "element"], + "Storable a => IOBuffer a -> Int -> a -> IO (Either MathError ())", + "return value.write(index, element)", + "", + ), + ( + "withIOBuffer", + ["value", "callback"], + "Storable a => IOBuffer a -> (Ptr a -> Int -> IO b) -> IO b", + "return _call('with_io_buffer', [value, callback], 1)", + "", + ), + ("unboxedToBoxed", ["value"], "UnboxedDouble -> Boxed Double", None, ""), + ("boxedToUnboxed", ["value"], "Boxed Double -> UnboxedDouble", None, ""), +] +HELPERS = [ + ("storage_info", ["value"]), + ("pointer_info", ["value"]), + ("pointer_read", ["value", "index"]), + ("pointer_write", ["value", "index", "element"]), + ("pointer_address", ["value"]), + ("st_active", ["value"]), + ("pointer_active", ["value"]), +] +TYPES = ["Boxed", "UnboxedDouble", "STBuffer", "IOBuffer"] + + +def generate(): + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_buffer_bindings.py. */\n#ifndef HMATH_BUFFER_H\n#define HMATH_BUFFER_H\n#include "hmath_value.h"\n#include "hmath_linear.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Actual API.Buffer containers, Foundation-kind400. Borrowed input handles;\n * successful outputs own one reference and errors leave outputs untouched.\n * Boxed generic values preserve exact elements; strictBoxed/mapStrict force\n * original WHNF, not deep normal form. Unboxed uses original Double without\n * added finite checks. ST region handles may execute only on the callback\n * thread inside runSTBuffer; thawSTBuffer takes an explicit region handle.\n * IO storage supports actual Storable Float/Double/Complex and bounded/native\n * Int/Word, Bool(dtype16), Char(dtype17). Integer/Rational/Dual have no original\n * Storable instance. storage_info returns(dtype,size,alignment,length).\n * Freeze/thaw copy; aliases share one ForeignPtr and original IO lock. Callback\n * args use callback101 Tuple(STBuffer) or Tuple(BorrowedPointer,count). Pointers\n * are valid only for the synchronous callback; never retain a raw address or\n * reenter locking operations on the same buffer (same-thread reentry is BUSY).\n * Scoped operations from another thread/after return are INVALID_ARGUMENT.\n * Independent IO operations synchronize using the original lock. Original\n * MathError uses status11; allocation/OS/callback exceptions propagate. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_buffer_bindings.py. */\n#include "hmath_buffer.h"\n#include "value_internal.h"\nextern int hm_buffer_apply(int,void *const *,size_t,void **);\nstatic _Thread_local unsigned char buffer_thread_token;\nvoid *hm_buffer_thread_token(void) { return &buffer_thread_token; }\n' + ] + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_buffer_bindings.py.\nfrom ._buffer_base import (\n BorrowedPointer,\n Boxed,\n IOBuffer,\n STBuffer,\n UnboxedDouble,\n _boxed,\n _call,\n _new_io,\n _thaw_io,\n)\n" + ] + docs = [ + "# Buffer API\n\n`from hmath import buffer` exposes the actual `HMath.API.Buffer` containers and operations. C includes `hmath_buffer.h`; all objects use the shared [Value ownership contract](values.md). Outputs own one reference and remain untouched on failure. Release every owner with `close()`/`hmath_value_release`.\n\n", + "Boxed elements remain exact generic values. The distinction between original lazy and WHNF-strict constructors is preserved; foreign values themselves are already materialized, so these constructors do not synthesize Haskell bottoms. Unboxed storage is Double, with no added NaN/Inf checks. Every freeze/thaw conversion copies.\n\n", + "## Mutable scopes and storage\n\n`run_st_buffer(boxed, callback)` lends an actual STBuffer to a synchronous callback. Use `thaw_st_buffer(region, boxed)` to select that same ST state region explicitly. Scoped handles cannot execute on another thread or after the callback; immutable frozen values and ordinary callback results remain owned.\n\n", + "`IOBuffer(n, initial, dtype=...)` / `new_io_buffer` allocate original pinned, synchronized IO storage. Standard Float/Double, Complex Float/Double, signed/unsigned bounded and native integers, Bool and Char have original Storable instances. Exact Integer/Rational and Dual do not. Python integer initial values default to native `intp`; use explicit dtype to select width. Boxed constructors accept dtype to preserve that element witness, and `thaw_io_buffer(boxed, dtype=...)` performs the explicit marshal conversion before the original copying thaw. Empty storage requires dtype or a typed prototype.\n\n", + "`with_io_buffer(io, callback)` lends `(BorrowedPointer, count)` while holding the original lock and ForeignPtr. `pointer.read/write`, `.layout` and `.address` are valid only in that callback and thread. Never retain the raw address or reenter locking operations on the same IOBuffer; same-thread reentry returns BUSY. Other threads use the original synchronized operations. Callback errors release the pointer borrow and lock before propagating the original exception. Bool/Char layouts are queried from their actual Storable instance, not assumed to match C bool/char. `.layout` is `(dtype, size, alignment, length)`; Bool uses dtype16 and Char17.\n\n", + '```python\nfrom hmath import buffer\n\nwith buffer.Boxed([1, 2, 3]) as source:\n def change(region):\n region.write(1, 8)\n return region.freeze()\n with buffer.run_st_buffer(source, change) as frozen:\n assert frozen.values == [1, 8, 3]\n\nwith buffer.IOBuffer(3, 0.0, dtype="float32") as storage:\n storage.with_pointer(lambda pointer, count: pointer.write(count - 1, 2.0))\n assert storage.read(2) == 2.0\n```\n\n', + ] + mappings = [] + for name in TYPES: + alias = "hmath_buffer_" + snake(name) + "_object" + header.append("typedef hmath_value " + alias + ";\n") + mappings.append( + { + "symbol": "HMath.API.Buffer." + name, + "c": [alias], + "python": "hmath.buffer." + name, + "specializations": [ + "actual original container; generic owned elements or actual standard Storable witnesses" + ], + } + ) + exports = TYPES + ["BorrowedPointer"] + symbols = [] + for operation, entry in enumerate( + SPECS + [(name, args, "", None, "") for name, args in HELPERS] + ): + source_name, params, signature, body, extra = entry + name = snake(source_name) if operation < len(SPECS) else source_name + symbol = "hmath_buffer_" + name + parameters = ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + p for p in params] + + ["hmath_value **out"] + ) + header.append( + "/* " + + ( + "HMath.API.Buffer." + source_name + " :: " + signature + if signature + else "Scoped representation helper" + ) + + " */\nHMATH_API hmath_status " + + symbol + + "(" + + parameters + + ");\n" + ) + c.append( + "hmath_status " + + symbol + + "(" + + parameters + + ") {\n if(!out" + + "".join("||!" + p for p in params) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL Buffer argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n void *arguments[]={' + + ",".join("hm_value_stable(" + p + ")" for p in params) + + "};\n return hm_value_finish(result,hm_buffer_apply(" + + str(operation) + + ",arguments," + + str(len(params)) + + ",&result->stable),out);\n}\n" + ) + symbols.append(symbol) + if operation >= len(SPECS): + continue + pyparams = params + if source_name == "thawIOBuffer": + pyparams = ["value"] + extra = ", *, dtype=None, prototype=None" + py.append( + "\n\ndef " + + name + + "(" + + ", ".join(pyparams) + + extra + + '):\n """' + + source_prose({"module": "HMath.API.Buffer", "name": source_name}).replace( + '"', '"' + ) + + '"""\n ' + + (body or "return _call(" + repr(name) + ", [" + ", ".join(params) + "])") + + "\n" + ) + exports.append(name) + mappings.append( + { + "symbol": "HMath.API.Buffer." + source_name, + "c": [symbol], + "python": "hmath.buffer." + name, + "specializations": [ + "original source structure and scope; exact generic values / standard original Storable instances where constrained" + ], + } + ) + docs.append( + "## `buffer." + + name + + "`\n\n" + + source_prose({"module": "HMath.API.Buffer", "name": source_name}) + + "\n\n```haskell\n" + + signature + + "\n```\n\n```text\n" + + name + + "(" + + ", ".join(pyparams) + + extra + + ")\n```\n\n```c\nhmath_status " + + symbol + + "(" + + parameters + + ");\n```\n\n" + ) + py.append("\n\n__all__ = " + json.dumps(sorted(exports), indent=4) + "\n") + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_buffer.h": "".join(header), + "cbits/buffer.c": "".join(c), + "bindings/python/_hmath_native/buffer_values.py": "".join(py), + "bindings/schema/buffer-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "bindings/schema/buffer-symbols.txt": "\n".join(symbols) + "\n", + "docs/reference/buffer-bindings.md": "".join(docs), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale Buffer binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_deeplearning_bindings.py b/tools/generate_deeplearning_bindings.py new file mode 100644 index 0000000..292cb19 --- /dev/null +++ b/tools/generate_deeplearning_bindings.py @@ -0,0 +1,802 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate direct named adapters for every original DeepLearning public symbol.""" + +import argparse +import ast +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +S = [] + + +def snake(name): + special = { + "ReLU": "relu", + "LeakyReLU": "leaky_relu", + "PReLU": "prelu", + "SiLU": "silu", + } + return special.get( + name, + re.sub( + r"([a-z0-9])([A-Z])", + r"\1_\2", + re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name), + ).lower(), + ) + + +def add(module, name, args, result): + S.append( + { + "module": "HMath.DeepLearning." + module, + "name": name, + "arguments": args, + "result": result, + "python": snake(name), + "c": "hmath_neural_" + + module.lower() + + "_" + + snake(name) + + ("_create" if name[0].isupper() else ""), + "expression": { + "Core": "C", + "Layers": "L", + "Precision": "P", + "Metrics": "M", + }[module] + + "." + + name, + } + ) + + +for name in [ + "Sigmoid", + "Tanh", + "ReLU", + "SELU", + "GELU", + "SiLU", + "Mish", + "Softplus", + "Softsign", + "HardSigmoid", + "HardSwish", +]: + add("Core", name, [], "Activation") +for name in ["LeakyReLU", "PReLU", "ELU"]: + add("Core", name, [("parameter", "Double")], "Activation") +for name in ["Sum", "Mean"]: + add("Core", name, [], "Reduction") +for name in [ + "MeanSquaredError", + "MeanAbsoluteError", + "BinaryCrossEntropy", + "CategoricalCrossEntropy", + "NegativeLogLikelihood", + "KLDivergence", + "CosineLoss", +]: + add("Core", name, [], "Loss") +for name in ["Huber", "SmoothL1", "Hinge"]: + add("Core", name, [("parameter", "Double")], "Loss") +for name in ["activation", "activationDerivative"]: + add("Core", name, [("method", "Activation"), ("value", "Double")], "Double") +add("Core", "activationExpr", [("method", "Activation"), ("value", "ADExpr")], "ADExpr") +for name in ["softmax", "logSoftmax", "sparsemax"]: + add("Core", name, [("values", "[Double]")], "[Double]") +add( + "Core", + "gatedLinearUnit", + [("values", "[Double]"), ("gate", "[Double]")], + "[Double]", +) +for name in ["softmaxExpr", "logSoftmaxExpr", "sparsemaxExpr"]: + add("Core", name, [("values", "[ADExpr]")], "[ADExpr]") +for name, result in [("loss", "Double"), ("lossGradient", "[Double]")]: + add( + "Core", + name, + [ + ("method", "Loss"), + ("reduction", "Reduction"), + ("target", "[Double]"), + ("prediction", "[Double]"), + ], + result, + ) +add( + "Core", + "lossExpr", + [ + ("method", "Loss"), + ("reduction", "Reduction"), + ("target", "[Double]"), + ("prediction", "[ADExpr]"), + ], + "ADExpr", +) +add( + "Core", + "binaryCrossEntropyLogits", + [("reduction", "Reduction"), ("target", "[Double]"), ("logits", "[Double]")], + "Double", +) +add( + "Core", + "categoricalCrossEntropyLogits", + [("target", "[Double]"), ("logits", "[Double]")], + "Double", +) +add( + "Core", + "regularization", + [("l1", "Double"), ("l2", "Double"), ("weights", "[Double]")], + "Double", +) +add( + "Core", + "contrastiveLoss", + [ + ("margin", "Double"), + ("similar", "Bool"), + ("left", "[Double]"), + ("right", "[Double]"), + ], + "Double", +) +add( + "Core", + "tripletLoss", + [ + ("margin", "Double"), + ("anchor", "[Double]"), + ("positive", "[Double]"), + ("negative", "[Double]"), + ], + "Double", +) +add( + "Core", + "focalLoss", + [ + ("alpha", "Double"), + ("gamma", "Double"), + ("target", "[Double]"), + ("prediction", "[Double]"), + ], + "Double", +) +for name in ["diceLoss", "iouLoss"]: + add( + "Core", + name, + [("smooth", "Double"), ("target", "[Double]"), ("prediction", "[Double]")], + "Double", + ) +for name, result, values in [ + ("ctcLoss", "Double", "[[Double]]"), + ("ctcLossGradient", "(Double,[[Double]])", "[[Double]]"), + ("ctcLossExpr", "ADExpr", "[[ADExpr]]"), +]: + add( + "Core", + name, + [("blank", "Int"), ("labels", "[Int]"), ("log_probabilities", values)], + result, + ) +for name in ["Training", "Inference"]: + add("Layers", name, [], "Training") +for name in ["dropout", "spatialDropout"]: + add( + "Layers", + name, + [ + ("mode", "Training"), + ("probability", "Double"), + ("rng", "RNG"), + ("input", "Tensor"), + ], + "(Tensor,Tensor,RNG)", + ) +add( + "Layers", + "BatchNormState", + [ + ("running_mean", "[Double]"), + ("running_variance", "[Double]"), + ("batches_seen", "Int"), + ], + "BatchNormState", +) +for name, result in [ + ("runningMean", "[Double]"), + ("runningVariance", "[Double]"), + ("batchesSeen", "Int"), +]: + add("Layers", name, [("state", "BatchNormState")], result) +add( + "Layers", + "batchNorm", + [ + ("mode", "Training"), + ("momentum", "Double"), + ("epsilon", "Double"), + ("gamma", "[Double]"), + ("beta", "[Double]"), + ("state", "BatchNormState"), + ("input", "Tensor"), + ], + "(Tensor,BatchNormState)", +) +for name in ["layerNorm", "rmsNorm"]: + add( + "Layers", + name, + [("axes", "Int"), ("epsilon", "Double"), ("input", "Tensor")], + "Tensor", + ) +add("Layers", "instanceNorm", [("epsilon", "Double"), ("input", "Tensor")], "Tensor") +add( + "Layers", + "groupNorm", + [("groups", "Int"), ("epsilon", "Double"), ("input", "Tensor")], + "Tensor", +) +add( + "Layers", + "weightNorm", + [("axis", "Int"), ("scales", "[Double]"), ("input", "Tensor")], + "Tensor", +) +for name in ["XavierUniform", "XavierNormal", "KaimingUniform", "KaimingNormal"]: + add("Layers", name, [], "Initializer") +add("Layers", "Orthogonal", [("scale", "Double")], "Initializer") +add( + "Layers", + "TruncatedNormal", + [("mean", "Double"), ("standard_deviation", "Double"), ("bound", "Double")], + "Initializer", +) +add( + "Layers", + "initializeWeights", + [ + ("method", "Initializer"), + ("fan_in", "Int"), + ("fan_out", "Int"), + ("shape", "[Int]"), + ("rng", "RNG"), + ], + "(Tensor,RNG)", +) +add("Layers", "embedding", [("weights", "Tensor"), ("indices", "[Int]")], "Tensor") +for suffix, hint in [("", "Tensor"), ("AD", "ADTensor")]: + add( + "Layers", + "dense" + suffix, + [ + ("input", hint), + ("weights", hint), + ("bias", "[ADExpr]" if suffix else "[Double]"), + ], + hint, + ) +add( + "Layers", + "ConvOptions", + [ + ("stride", "[Int]"), + ("padding", "[Int]"), + ("dilation", "[Int]"), + ("groups", "Int"), + ], + "ConvOptions", +) +for name, result in [ + ("convolutionStride", "[Int]"), + ("convolutionPadding", "[Int]"), + ("convolutionDilation", "[Int]"), + ("convolutionGroups", "Int"), +]: + add("Layers", name, [("options", "ConvOptions")], result) +for name in ["convolution", "depthwiseConvolution", "convolutionAD"]: + hint = "ADTensor" if name.endswith("AD") else "Tensor" + add( + "Layers", + name, + [ + ("options", "ConvOptions"), + ("input", hint), + ("weights", hint), + ("bias", "[ADExpr]" if hint == "ADTensor" else "[Double]"), + ], + hint, + ) +add( + "Layers", + "transposedConvolution", + [ + ("output_padding", "[Int]"), + ("options", "ConvOptions"), + ("input", "Tensor"), + ("weights", "Tensor"), + ("bias", "[Double]"), + ], + "Tensor", +) +for name in ["MaxPool", "AveragePool"]: + add("Layers", name, [], "PoolMode") +add( + "Layers", + "pooling", + [ + ("mode", "PoolMode"), + ("kernel", "[Int]"), + ("stride", "[Int]"), + ("padding", "[Int]"), + ("input", "Tensor"), + ], + "Tensor", +) +add( + "Layers", + "adaptivePooling", + [("mode", "PoolMode"), ("shape", "[Int]"), ("input", "Tensor")], + "Tensor", +) +add("Layers", "globalPooling", [("mode", "PoolMode"), ("input", "Tensor")], "Tensor") +add( + "Layers", + "scaledDotProductAttention", + [ + ("query", "Tensor"), + ("key", "Tensor"), + ("value", "Tensor"), + ("mask", "Maybe[[Bool]]"), + ("bias", "Maybe[[Double]]"), + ], + "(Tensor,Tensor)", +) +add( + "Layers", + "multiheadAttention", + [ + ("heads", "Int"), + ("query", "Tensor"), + ("key", "Tensor"), + ("value", "Tensor"), + ("mask", "Maybe[[Bool]]"), + ], + "Tensor", +) +add( + "Layers", + "causalMask", + [("queries", "Int"), ("keys", "Int"), ("offset", "Int")], + "[[Bool]]", +) +add( + "Layers", + "rotaryEmbedding", + [("base", "Double"), ("offset", "Int"), ("input", "Tensor")], + "Tensor", +) +add( + "Layers", + "sinusoidalEncoding", + [("length", "Int"), ("dimensions", "Int"), ("offset", "Int")], + "Tensor", +) +add( + "Layers", + "alibiBias", + [("slope", "Double"), ("queries", "Int"), ("keys", "Int"), ("offset", "Int")], + "[[Double]]", +) +add( + "Layers", + "emptyCache", + [("capacity", "Int"), ("key_dimensions", "Int"), ("value_dimensions", "Int")], + "KVCache", +) +add( + "Layers", + "appendCache", + [("cache", "KVCache"), ("key", "Tensor"), ("value", "Tensor")], + "KVCache", +) +add("Layers", "cacheValues", [("cache", "KVCache")], "(Tensor,Tensor)") +add( + "Layers", + "transformerFeedForward", + [ + ("activation", "Activation"), + ("input", "Tensor"), + ("first_weights", "Tensor"), + ("first_bias", "[Double]"), + ("second_weights", "Tensor"), + ("second_bias", "[Double]"), + ], + "Tensor", +) +for name in ["layerNormAD", "rmsNormAD"]: + add( + "Layers", + name, + [("axes", "Int"), ("epsilon", "Double"), ("input", "ADTensor")], + "ADTensor", + ) +add( + "Layers", + "scaledDotProductAttentionAD", + [ + ("query", "ADTensor"), + ("key", "ADTensor"), + ("value", "ADTensor"), + ("mask", "Maybe[[Bool]]"), + ], + "ADTensor", +) +for name in ["Symmetric", "Asymmetric"]: + add("Precision", name, [], "Quantization") +add( + "Precision", + "quantize", + [("scheme", "Quantization"), ("axis", "MaybeInt"), ("input", "Tensor")], + "QuantizedTensor", +) +add("Precision", "dequantize", [("quantized", "QuantizedTensor")], "Tensor") +for name, result in [ + ("quantizedValues", "[Int8]"), + ("quantizationScales", "[Double]"), + ("quantizationZeroPoints", "[Int]"), +]: + add("Precision", name, [("quantized", "QuantizedTensor")], result) +add( + "Precision", + "int8Gemm", + [("left", "QuantizedTensor"), ("right", "QuantizedTensor")], + "Tensor", +) +for name in ["FP16", "BF16"]: + add("Precision", name, [], "Precision") +add( + "Precision", + "reducedGemm", + [("precision", "Precision"), ("left", "Tensor"), ("right", "Tensor")], + "Tensor", +) +add( + "Precision", + "LossScaler", + [("scale", "Double"), ("growth_interval", "Int"), ("finite_steps", "Int")], + "LossScaler", +) +for name, result in [ + ("lossScale", "Double"), + ("scaleGrowthInterval", "Int"), + ("finiteSteps", "Int"), +]: + add("Precision", name, [("state", "LossScaler")], result) +add( + "Precision", + "initialLossScaler", + [("scale", "Double"), ("growth_interval", "Int")], + "LossScaler", +) +add("Precision", "scaleLoss", [("state", "LossScaler"), ("loss", "Double")], "Double") +add( + "Precision", + "unscaleGradients", + [("state", "LossScaler"), ("gradients", "[Double]")], + "(Bool,[Double])", +) +add( + "Precision", + "updateLossScaler", + [("finite", "Bool"), ("state", "LossScaler")], + "LossScaler", +) +add("Precision", "gradientNorm", [("gradient", "[Double]")], "Double") +add( + "Precision", + "clipGradients", + [("maximum", "Double"), ("gradient", "[Double]")], + "[Double]", +) +add( + "Metrics", + "ClassificationMetrics", + [ + ("accuracy", "Double"), + ("precision", "[Double]"), + ("recall", "[Double]"), + ("f1", "[Double]"), + ], + "ClassificationMetrics", +) +for name, result in [ + ("accuracy", "Double"), + ("precisionByClass", "[Double]"), + ("recallByClass", "[Double]"), + ("f1ByClass", "[Double]"), +]: + add("Metrics", name, [("metrics", "ClassificationMetrics")], result) +for name, result in [ + ("confusionMatrix", "[[Int]]"), + ("classificationMetrics", "ClassificationMetrics"), +]: + add( + "Metrics", + name, + [("classes", "Int"), ("truth", "[Int]"), ("prediction", "[Int]")], + result, + ) +add( + "Metrics", + "topKAccuracy", + [("k", "Int"), ("truth", "[Int]"), ("scores", "[[Double]]")], + "Double", +) +for name in ["rocAUC", "prAUC"]: + add("Metrics", name, [("truth", "[Bool]"), ("scores", "[Double]")], "Double") +add("Metrics", "perplexity", [("negative_log_probabilities", "[Double]")], "Double") +add( + "Metrics", + "cosineSimilarityMatrix", + [("left", "Tensor"), ("right", "Tensor")], + "Tensor", +) +add( + "Metrics", + "marginRankingLoss", + [ + ("margin", "Double"), + ("left", "[Double]"), + ("right", "[Double]"), + ("labels", "[Double]"), + ], + "Double", +) + + +def outputs(): + files = { + ROOT / "bindings/schema/deeplearning.json": json.dumps( + {"schema": 1, "functions": S}, indent=2 + ) + + "\n", + ROOT + / "bindings/python/_hmath_native/_neural_catalog.py": "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_deeplearning_bindings.py.\nimport json\nCATALOG=json.loads(" + + repr(json.dumps(S, separators=(",", ":"))) + + ")\n", + } + headers = [] + native = [] + dispatch = [] + for item in S: + parameters = ( + ["hmath_context *context"] + + ["const hmath_value *" + name for name, _ in item["arguments"]] + + ["hmath_value **out"] + ) + signature = ( + "hmath_status " + item["c"] + "(\n " + ",\n ".join(parameters) + ")" + ) + headers.append( + "/* " + + item["module"] + + "." + + item["name"] + + " -> " + + item["result"] + + ". */\nHMATH_API " + + signature + + ";\n" + ) + names = [name for name, _ in item["arguments"]] + native.append( + signature + + " {\n" + + ( + " const hmath_value *hm_arguments[]={" + ", ".join(names) + "};\n" + if names + else "" + ) + + ' return invoke(context, "' + + item["module"] + + "." + + item["name"] + + '", ' + + ("hm_arguments" if names else "NULL") + + ", " + + str(len(names)) + + ", out);\n}\n" + ) + dispatch.append( + ' "' + + item["module"] + + "." + + item["name"] + + '" -> apply ' + + item["expression"] + + " arguments\n" + ) + for path, mark, end, body in [ + ( + ROOT / "include/hmath_deeplearning.h", + "/* BEGIN GENERATED */", + "/* END GENERATED */", + "\n".join(headers), + ), + ( + ROOT / "cbits/deeplearning.c", + "/* BEGIN GENERATED */", + "/* END GENERATED */", + "\n".join(native), + ), + ( + ROOT / "src/HMath/FFI/DeepLearning.hs", + "-- BEGIN GENERATED", + "-- END GENERATED", + "".join(dispatch), + ), + ]: + text = path.read_text() + a = text.index(mark) + len(mark) + b = text.index(end) + files[path] = text[:a] + "\n" + body + text[b:] + enum_names = {"Reduction", "Training", "PoolMode", "Quantization", "Precision"} + record_names = { + "BatchNormState", + "ConvOptions", + "LossScaler", + "ClassificationMetrics", + } + descriptors = {"Activation", "Loss", "Initializer"} + tails = [] + exports = {module: set() for module in ["Core", "Layers", "Precision", "Metrics"]} + for module, names in { + "Core": ["Activation", "Loss", "Reduction"], + "Layers": [ + "Training", + "BatchNormState", + "Initializer", + "ConvOptions", + "PoolMode", + "KVCache", + ], + "Precision": ["Quantization", "Precision", "QuantizedTensor", "LossScaler"], + "Metrics": ["ClassificationMetrics"], + }.items(): + exports[module].update(names) + for entry in S: + name = entry["name"] + module = entry["module"].split(".")[-1] + hint = entry["result"] + public = name if name[0].isupper() else entry["python"] + exports[module].add(public) + if name in record_names or name == "Training": + continue + if name[0].isupper() and hint in enum_names: + tails.append(name + " = " + hint + "." + snake(name).upper() + "\n") + continue + parameters = ", ".join(param for param, _ in entry["arguments"]) + if name[0].isupper() and hint in descriptors: + expression = ( + hint + + "(" + + repr(entry["module"] + "." + name) + + ( + ", (" + + parameters + + ("," if len(entry["arguments"]) == 1 else "") + + "))" + if parameters + else ")" + ) + ) + if not parameters: + tails.append(name + " = " + expression + "\n") + else: + tails.append( + "def " + + name + + "(" + + parameters + + "):\n return " + + expression + + "\n" + ) + tails.append( + hint + + "." + + snake(name).upper() + + " = " + + ("staticmethod(" + name + ")" if parameters else name) + + "\n" + ) + continue + tails.append( + "def " + + public + + "(" + + parameters + + '):\n """' + + entry["module"] + + "." + + name + + ': original defaults, errors, state and graph rules."""\n return _invoke(' + + repr(entry["module"] + "." + name) + + (", " + parameters if parameters else "") + + ")\n" + ) + path = ROOT / "bindings/python/_hmath_native/_neural_base.py" + text = path.read_text() + a = text.index("# BEGIN GENERATED") + len("# BEGIN GENERATED") + b = text.index("# END GENERATED") + files[path] = text[:a] + "\n" + "\n".join(tails) + text[b:] + numeric = json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + for module, public in exports.items(): + excluded = { + entry["python"] + for entry in numeric + if entry["module"] == "HMath.DeepLearning." + module + } + path = ROOT / ( + "bindings/python/_hmath_native/" + + ( + "deeplearning_layers" + if module == "Layers" + else "_neural_" + module.lower() + ) + + ".py" + ) + files[path] = ( + '# SPDX-License-Identifier: MPL-2.0\n"""Original HMath.DeepLearning.' + + module + + ' complete typed adapters."""\nfrom ._neural_base import (\n' + + "".join( + " " + name + ",\n" + for name in sorted( + public - excluded, + key=lambda name: (not name.isupper(), name[0].islower(), name.casefold()), + ) + ) + + ")\n\n__all__ = " + + repr( + sorted(public - excluded, key=lambda name: (not name.isupper(), name)) + ) + + "\n" + ) + return files + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for path, text in outputs().items(): + if args.check: + same = ( + ast.dump(ast.parse(path.read_text())) == ast.dump(ast.parse(text)) + if path.suffix == ".py" + else path.read_text() == text + ) + if not same: + raise SystemExit(str(path.relative_to(ROOT)) + " is stale") + else: + path.write_text(text) + print( + f"DeepLearning: {len(S)} direct original constructor/function/selector dispatches." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_expression_bindings.py b/tools/generate_expression_bindings.py new file mode 100644 index 0000000..181be60 --- /dev/null +++ b/tools/generate_expression_bindings.py @@ -0,0 +1,747 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named adapters for the original Expression and Symbolic APIs.""" + +import argparse +import ast +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +S = [] + + +def snake(name): + return re.sub( + r"([a-z0-9])([A-Z])", r"\1_\2", re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + ).lower() + + +def add(module, name, arguments, result, expression=None): + S.append( + { + "module": "HMath." + module, + "name": name, + "arguments": arguments, + "result": result, + "expression": expression + or ("E." if module == "Expression" else "S.") + name, + "python": snake(name), + "c": "hmath_" + + snake(module) + + "_" + + snake(name) + + ("_create" if name[0].isupper() else ""), + } + ) + + +def e(name, args, result, expression=None): + add("Expression", name, args, result, expression) + + +def s(name, args, result, expression=None): + add("Symbolic", name, args, result, expression) + + +e("SourcePos", [("offset", "Int"), ("line", "Int"), ("column", "Int")], "SourcePos") +e("unknownPosition", [], "SourcePos") +for n in ["sourceOffset", "sourceLine", "sourceColumn"]: + e(n, [("position", "SourcePos")], "Int") +for typ, names in { + "UnaryOp": ["Negate"], + "BinaryOp": ["Add", "Subtract", "Multiply", "Divide", "Power"], + "NamedConstant": ["Pi", "Euler", "Tau"], + "Precision": ["ExactRational", "Float64"], + "ErrorKind": [ + "SyntaxError", + "UnknownName", + "TypeMismatch", + "DomainFailure", + "NonFinite", + "StepLimit", + "DepthLimit", + "MemoryLimit", + "InvalidLimits", + "Unsupported", + ], + "Builtin": [ + "Sin", + "Cos", + "Tan", + "Exp", + "Log", + "Sqrt", + "Abs", + "Signum", + "Floor", + "Ceiling", + "Min", + "Max", + "Asin", + "Acos", + "Atan", + "Sinh", + "Cosh", + "Tanh", + ], +}.items(): + for name in names: + e(name, [], typ) +e("Expr", [("position", "SourcePos"), ("node", "ExprNode")], "Expr") +e("expressionPosition", [("expression", "Expr")], "SourcePos") +e("expressionNode", [("expression", "Expr")], "ExprNode") +for name, args in [ + ("Literal", [("value", "Rational")]), + ("Variable", [("name", "String")]), + ("Constant", [("constant", "NamedConstant")]), + ("Unary", [("operator", "UnaryOp"), ("child", "Expr")]), + ("Binary", [("operator", "BinaryOp"), ("left", "Expr"), ("right", "Expr")]), + ("Call", [("name", "String"), ("arguments", "[Expr]")]), + ("Let", [("name", "String"), ("value", "Expr"), ("body", "Expr")]), +]: + e(name, args, "ExprNode") +for name in ["literal", "variable", "constant", "unary", "binary", "call", "letIn"]: + upper = { + "literal": "Literal", + "variable": "Variable", + "constant": "Constant", + "unary": "Unary", + "binary": "Binary", + "call": "Call", + "letIn": "Let", + }[name] + spec = next(item for item in S if item["name"] == upper) + e(name, spec["arguments"], "Expr") +limits = [ + ("maximum_steps", "Int"), + ("maximum_depth", "Int"), + ("maximum_nodes", "Int"), + ("maximum_input_chars", "Int"), + ("maximum_integer_bits", "Int"), + ("maximum_cache_entries", "Int"), +] +e("Limits", limits, "Limits") +e("defaultLimits", [], "Limits") +for name in [ + "maximumSteps", + "maximumDepth", + "maximumNodes", + "maximumInputChars", + "maximumIntegerBits", + "maximumCacheEntries", +]: + e(name, [("limits", "Limits")], "Int") +e( + "ExprError", + [("kind", "ErrorKind"), ("position", "SourcePos"), ("message", "String")], + "ExprError", +) +for name, out in [ + ("errorKind", "ErrorKind"), + ("errorPosition", "SourcePos"), + ("errorMessage", "String"), +]: + e(name, [("error", "ExprError")], out) +e("validateLimits", [("limits", "Limits")], "Unit") +e("validateExpression", [("limits", "Limits"), ("expression", "Expr")], "Unit") +e("parseExpression", [("limits", "Limits"), ("source", "String")], "Expr") +e("prettyExpression", [("expression", "Expr")], "String") +e("freeVariables", [("expression", "Expr")], "[String]") +e("ExactValue", [("value", "Rational")], "ExpressionValue") +e("FloatValue", [("value", "Double")], "ExpressionValue") +e("defaultRegistry", [], "Registry") +e("emptyRegistry", [], "Registry") +e( + "registerFunction", + [("name", "String"), ("builtin", "Builtin"), ("registry", "Registry")], + "Registry", +) +e("allowedFunctions", [("registry", "Registry")], "[String]") +for name, last, out in [ + ("typeCheckExpression", ("expression", "Expr"), "Precision"), + ("evaluateExpression", ("expression", "Expr"), "ExpressionValue"), + ("evaluateText", ("source", "String"), "ExpressionValue"), + ("evaluateCompiled", ("compiled", "Compiled"), "ExpressionValue"), +]: + e( + name, + [ + ("limits", "Limits"), + ("precision", "Precision"), + ("registry", "Registry"), + ("bindings", "Bindings"), + last, + ], + out, + ) +e("compileExpression", [("limits", "Limits"), ("expression", "Expr")], "Compiled") +e("compiledNodeCount", [("compiled", "Compiled")], "Int") +e( + "optimizeExpression", + [("limits", "Limits"), ("precision", "Precision"), ("expression", "Expr")], + "Expr", +) +e("emptyExpressionCache", [], "ExpressionCache") +e("cacheSize", [("cache", "ExpressionCache")], "Int") +e( + "cachedExpression", + [("limits", "Limits"), ("source", "String"), ("cache", "ExpressionCache")], + "(Compiled,ExpressionCache)", +) +e("formatScientific", [("digits", "Int"), ("value", "ExpressionValue")], "String") +e("formatRadix", [("radix", "Int"), ("value", "ExpressionValue")], "String") +e("serializeExpression", [("limits", "Limits"), ("expression", "Expr")], "String") +e("deserializeExpression", [("limits", "Limits"), ("serialized", "String")], "Expr") +e("expressionHash", [("limits", "Limits"), ("expression", "Expr")], "Word64") +for typ, names in { + "Property": [ + "Real", + "NonZero", + "Positive", + "NonNegative", + "Integral", + "Negative", + "NonPositive", + ], + "Direction": ["FromLeft", "FromRight", "TwoSided"], + "RelationOp": ["Equal", "NotEqual", "Less", "LessEqual", "Greater", "GreaterEqual"], +}.items(): + for name in names: + s(name, [], typ) +s("assumptions", [("entries", "[(String,[Property])]")], "Assumptions") +s("noAssumptions", [], "Assumptions") +s( + "proves", + [("assumptions", "Assumptions"), ("property", "Property"), ("expression", "Expr")], + "Bool", +) +s( + "SymbolicOptions", + [("limits", "Limits"), ("assumptions", "Assumptions")], + "SymbolicOptions", +) +s("defaultSymbolicOptions", [], "SymbolicOptions") +s("symbolicLimits", [("options", "SymbolicOptions")], "Limits") +s("symbolicAssumptions", [("options", "SymbolicOptions")], "Assumptions") +for name in [ + "normalize", + "simplify", + "expand", + "collectTerms", + "trigonometricSimplify", + "logarithmicSimplify", +]: + s(name, [("options", "SymbolicOptions"), ("expression", "Expr")], "Expr") +for name, out in [ + ("factorPolynomial", "PolynomialFactorization"), + ("rationalSimplify", "Expr"), + ("differentiate", "Expr"), + ("integrateBasic", "Expr"), + ("toPolynomial", "Polynomial"), + ("exactPolynomialRoots", "([(Rational,Int)],Expr)"), + ("numericalPolynomialRoots", "[Complex]"), +]: + s( + name, + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("expression", "Expr"), + ], + out, + ) +s( + "PolynomialFactorization", + [("leading", "Rational"), ("terms", "[(Expr,Int)]")], + "PolynomialFactorization", +) +s("factorLeading", [("factorization", "PolynomialFactorization")], "Rational") +s("factorTerms", [("factorization", "PolynomialFactorization")], "[(Expr,Int)]") +s( + "substitute", + [("limits", "Limits"), ("bindings", "[(String,Expr)]"), ("expression", "Expr")], + "Expr", +) +for name, args in [ + ("Any", [("name", "String")]), + ("Exactly", [("expression", "Expr")]), + ("UnaryPattern", [("operator", "UnaryOp"), ("child", "Pattern")]), + ( + "BinaryPattern", + [("operator", "BinaryOp"), ("left", "Pattern"), ("right", "Pattern")], + ), + ("CallPattern", [("name", "String"), ("arguments", "[Pattern]")]), +]: + s(name, args, "Pattern") +s( + "matchPattern", + [("limits", "Limits"), ("pattern", "Pattern"), ("expression", "Expr")], + "Maybe[(String,Expr)]", +) +s( + "RewriteRule", + [ + ("pattern", "Pattern"), + ("replacement", "Expr"), + ("requirements", "[(String,Property)]"), + ], + "RewriteRule", +) +for name, out in [ + ("rewritePattern", "Pattern"), + ("rewriteReplacement", "Expr"), + ("rewriteRequirements", "[(String,Property)]"), +]: + s(name, [("rule", "RewriteRule")], out) +s( + "applyRewrite", + [("options", "SymbolicOptions"), ("rule", "RewriteRule"), ("expression", "Expr")], + "Expr", +) +for name, last, out in [ + ("gradient", "Expr", "[Expr]"), + ("hessian", "Expr", "[[Expr]]"), + ("jacobian", "[Expr]", "[[Expr]]"), +]: + s( + name, + [ + ("options", "SymbolicOptions"), + ("variables", "[String]"), + ("expression" if last == "Expr" else "expressions", last), + ], + out, + ) +s( + "integrateByParts", + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("u", "Expr"), + ("dv", "Expr"), + ], + "Expr", +) +s( + "integrateSubstitution", + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("temporary", "String"), + ("inner", "Expr"), + ("outer", "Expr"), + ("integrand", "Expr"), + ], + "Expr", +) +s( + "integrateRational", + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("numerator", "Expr"), + ("denominator", "Expr"), + ], + "Expr", +) +s("FiniteLimit", [("value", "Rational")], "LimitResult") +for name in ["PositiveInfinity", "NegativeInfinity", "DoesNotExist"]: + s(name, [], "LimitResult") +s( + "symbolicLimit", + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("center", "Rational"), + ("direction", "Direction"), + ("expression", "Expr"), + ], + "LimitResult", +) +s( + "Series", + [("center", "Rational"), ("minimum_power", "Int"), ("terms", "[Expr]")], + "Series", +) +for name, out in [ + ("seriesCenter", "Rational"), + ("seriesMinimumPower", "Int"), + ("seriesTerms", "[Expr]"), +]: + s(name, [("series", "Series")], out) +for name in ["taylorSeries", "laurentSeries"]: + s( + name, + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("center", "Rational"), + ("order", "Int"), + ("expression", "Expr"), + ], + "Series", + ) +s( + "maclaurinSeries", + [ + ("options", "SymbolicOptions"), + ("variable", "String"), + ("order", "Int"), + ("expression", "Expr"), + ], + "Series", +) +s( + "formalPowerSeries", + [("options", "SymbolicOptions"), ("coefficients", "[Rational]")], + "PowerSeries", +) +s( + "multiplyFormalSeries", + [("options", "SymbolicOptions"), ("left", "PowerSeries"), ("right", "PowerSeries")], + "PowerSeries", +) +s( + "reciprocalFormalSeries", + [("options", "SymbolicOptions"), ("series", "PowerSeries")], + "PowerSeries", +) +s("fromPolynomial", [("variable", "String"), ("polynomial", "Polynomial")], "Expr") +s( + "Relation", + [("operator", "RelationOp"), ("left", "Expr"), ("right", "Expr")], + "Relation", +) +s("Truth", [("value", "Bool")], "RelationResult") +s("Unresolved", [("relation", "Relation")], "RelationResult") +s( + "simplifyRelation", + [("options", "SymbolicOptions"), ("relation", "Relation")], + "RelationResult", +) +s( + "solveLinearInequality", + [("options", "SymbolicOptions"), ("variable", "String"), ("relation", "Relation")], + "RelationResult", +) +s("Inconsistent", [], "LinearSolution") +s( + "ParametricSolution", + [("bindings", "[(String,Expr)]"), ("free_variables", "[String]")], + "LinearSolution", +) +s( + "solveLinearEquations", + [ + ("options", "SymbolicOptions"), + ("variables", "[String]"), + ("equations", "[(Expr,Expr)]"), + ], + "LinearSolution", +) +s( + "symbolicMatrix", + [("options", "SymbolicOptions"), ("rows", "[[Expr]]")], + "SymbolicMatrix", +) +s("matrixExpressions", [("matrix", "SymbolicMatrix")], "[[Expr]]") +for name in ["matrixAdd", "matrixMultiply"]: + s( + name, + [ + ("options", "SymbolicOptions"), + ("left", "SymbolicMatrix"), + ("right", "SymbolicMatrix"), + ], + "SymbolicMatrix", + ) +s( + "symbolicDeterminant", + [("options", "SymbolicOptions"), ("matrix", "SymbolicMatrix")], + "Expr", +) +s( + "Guarded", + [("value", "Generic"), ("conditions", "[(Expr,Property)]")], + "Guarded", + "(S.Guarded :: Value -> [(E.Expr,S.Property)] -> S.Guarded Value)", +) +s( + "guardedValue", + [("guarded", "Guarded")], + "Generic", + "(S.guardedValue :: S.Guarded Value -> Value)", +) +s( + "requiredConditions", + [("guarded", "Guarded")], + "[(Expr,Property)]", + "(S.requiredConditions :: S.Guarded Value -> [(E.Expr,S.Property)])", +) +s( + "symbolicEigenvalues", + [("options", "SymbolicOptions"), ("matrix", "SymbolicMatrix")], + "Guarded[Expr]", +) +s( + "numericalSubstitution", + [ + ("options", "SymbolicOptions"), + ("precision", "Precision"), + ("bindings", "[(String,ExpressionValue)]"), + ("expression", "Expr"), + ], + "ExpressionValue", +) +for name in ["toLaTeX", "toMathML"]: + s(name, [("limits", "Limits"), ("expression", "Expr")], "String") + + +for _entry in S: + if _entry["name"] == "errorKind": + _entry["c"] += "_get" + + +def outputs(): + catalog = json.dumps({"schema": 1, "functions": S}, indent=2) + "\n" + python = ( + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_expression_bindings.py.\nimport json\nCATALOG = json.loads(" + + repr(json.dumps(S, separators=(",", ":"))) + + ")\n" + ) + native = [] + header = [] + dispatch = [] + for entry in S: + arguments = ( + ["hmath_context *context"] + + [ + "const hmath_value *" + (p + "_" if p == "operator" else p) + for p, _ in entry["arguments"] + ] + + ["hmath_value **out"] + ) + signature = "hmath_status " + entry["c"] + "(" + ", ".join(arguments) + ")" + header.append( + "/* " + + entry["module"] + + "." + + entry["name"] + + " -> " + + entry["result"] + + ". */\nHMATH_API " + + signature + + ";\n" + ) + names = [p + "_" if p == "operator" else p for p, _ in entry["arguments"]] + native.append( + signature + + " {\n" + + ( + " const hmath_value *hm_arguments[] = {" + ", ".join(names) + "};\n" + if names + else "" + ) + + ' return invoke(context, "' + + entry["module"] + + "." + + entry["name"] + + '", ' + + ("hm_arguments" if names else "NULL") + + ", " + + str(len(names)) + + ", out);\n}\n" + ) + dispatch.append( + ' "' + + entry["module"] + + "." + + entry["name"] + + '" -> apply ' + + entry["expression"] + + " arguments\n" + ) + files = { + ROOT / "bindings/schema/expression.json": catalog, + ROOT / "bindings/python/_hmath_native/_expression_catalog.py": python, + } + for path, mark, end, section in [ + ( + ROOT / "cbits/expression.c", + "/* BEGIN GENERATED */", + "/* END GENERATED */", + "\n".join(native), + ), + ( + ROOT / "include/hmath_expression.h", + "/* BEGIN GENERATED */", + "/* END GENERATED */", + "\n".join(header), + ), + ( + ROOT / "src/HMath/FFI/Expression.hs", + "-- BEGIN GENERATED", + "-- END GENERATED", + "".join(dispatch), + ), + ]: + text = path.read_text() + a = text.index(mark) + len(mark) + b = text.index(end) + files[path] = text[:a] + "\n" + section + text[b:] + enums = { + "UnaryOp", + "BinaryOp", + "NamedConstant", + "Precision", + "Builtin", + "ErrorKind", + "Property", + "Direction", + "RelationOp", + } + records = { + "SourcePos", + "Expr", + "Limits", + "ExprError", + "ExactValue", + "FloatValue", + "SymbolicOptions", + "PolynomialFactorization", + "RewriteRule", + "Series", + "Relation", + "Guarded", + } + tails = [] + exports = { + "Expression": { + "ExprNode", + "Bindings", + "Value", + "Registry", + "Compiled", + "ExpressionCache", + *enums.intersection( + { + "UnaryOp", + "BinaryOp", + "NamedConstant", + "Precision", + "Builtin", + "ErrorKind", + } + ), + }, + "Symbolic": { + "Pattern", + "Assumptions", + "SymbolicMatrix", + "LimitResult", + "RelationResult", + "LinearSolution", + "Property", + "Direction", + "RelationOp", + }, + } + for entry in S: + name = entry["name"] + module = entry["module"].split(".")[-1] + public = name if name[0].isupper() else entry["python"] + exports[module].add(public) + if name in records: + continue + if name[0].isupper() and entry["result"] in enums: + tails.append( + public + " = " + entry["result"] + "." + snake(name).upper() + "\n" + ) + continue + if name in [ + "PositiveInfinity", + "NegativeInfinity", + "DoesNotExist", + "Inconsistent", + ]: + tails.append(public + " = " + entry["result"] + "(" + repr(name) + ")\n") + continue + params = ", ".join(param for param, _ in entry["arguments"]) + if name in ["FiniteLimit", "Truth", "Unresolved", "ParametricSolution"]: + tupleargs = ( + "(" + params + ("," if len(entry["arguments"]) == 1 else "") + ")" + ) + body = entry["result"] + "(" + repr(name) + "," + tupleargs + ")" + else: + body = ( + "_invoke(" + + repr(entry["module"] + "." + name) + + (", " + params if params else "") + + ")" + ) + tails.append( + "def " + + public + + "(" + + params + + '):\n """' + + entry["module"] + + "." + + name + + ': original semantics and checked errors."""\n return ' + + body + + "\n" + ) + path = ROOT / "bindings/python/_hmath_native/_expression_base.py" + text = path.read_text() + a = text.index("# BEGIN GENERATED") + len("# BEGIN GENERATED") + b = text.index("# END GENERATED") + files[path] = text[:a] + "\n" + "\n".join(tails) + text[b:] + for module, public in exports.items(): + extra = "from .expression import *\n" if module == "Symbolic" else "" + files[ROOT / ("bindings/python/_hmath_native/" + module.lower() + ".py")] = ( + '# SPDX-License-Identifier: MPL-2.0\n"""Original HMath.' + + module + + ' public API."""\n' + + "from ._expression_base import (\n" + + "".join( + " " + name + ",\n" + for name in sorted( + public, key=lambda name: (name[0].islower(), name.casefold()) + ) + ) + + ")\n" + + extra + + "\n__all__ = " + + repr( + sorted( + public | (exports["Expression"] if module == "Symbolic" else set()), + ) + ) + + "\n" + ) + return files + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for path, text in outputs().items(): + if args.check: + if ( + (ast.dump(ast.parse(path.read_text())) != ast.dump(ast.parse(text))) + if path.suffix == ".py" + else (path.read_text() != text) + ): + raise SystemExit(str(path.relative_to(ROOT)) + " is stale") + else: + path.write_text(text) + print( + f"Expression/Symbolic: {len(S)} named original constructor/function/selector dispatches." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_foundation_bindings.py b/tools/generate_foundation_bindings.py new file mode 100644 index 0000000..c6cc4d1 --- /dev/null +++ b/tools/generate_foundation_bindings.py @@ -0,0 +1,888 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Direct persistent data, discrete, combinatorial and convergence adapters.""" + +import argparse +import json +import keyword +import subprocess +from pathlib import Path + +import generate_linear_bindings as G +from generate_stochastic_bindings import fmt + +ROOT = Path(__file__).resolve().parent.parent +MODULES = { + "HMath.DataStructure": ("D", "data_structures", "datastructure"), + "HMath.Discrete": ("S", "discrete_values", "discrete"), + "HMath.Algorithms": ("A", "algorithm_values", "algorithms"), + "HMath.Combinatorics": ("C", "combinatorics_values", "combinatorics"), + "HMath.API.Convergence": ("V", "convergence_values", "convergence"), +} + + +def format_c(source): + return subprocess.run( + ["clang-format"], input=source, text=True, capture_output=True, check=True + ).stdout + + +def normalized(spec): + return [spec[0].lstrip("!"), *[normalized(s) for s in spec[1:]]] + + +def specification(): + old, aliases = G.MODULES, G.ALIASES + G.MODULES = {m: (a, n) for m, (a, n, _public) in MODULES.items()} + try: + entries, types, fields, missing = G.signatures() + finally: + G.MODULES, G.ALIASES = old, aliases + missing = [m for m in missing if m != "HMath.API.Convergence.Converged"] + if missing: + raise ValueError(missing) + oldbindings = { + x["module"] + "." + x["name"] + for x in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + } + entries = [e for e in entries if e["module"] + "." + e["name"] not in oldbindings] + for e in entries: + e["args"] = [normalized(s) for s in e["args"]] + e["result"] = normalized(e["result"]) + fields = {name: [(f, normalized(s)) for f, s in fs] for name, fs in fields.items()} + entries.append( + { + "module": "HMath.API.Convergence", + "name": "Converged", + "args": [["Convergence", ["a"]]], + "result": ["Maybe", ["a"]], + "constraints": "", + "signature": "Convergence a -> Maybe a (read-only source pattern)", + "constructor": False, + } + ) + return entries, types, fields + + +def mode(entry): + if ( + entry["module"] == "HMath.Combinatorics" + and entry["name"] == "finiteDifferences" + ): + return "numeric" + if "Eq a" in entry["constraints"]: + return "equality" + if entry["module"] == "HMath.DataStructure" and entry["name"] in ( + "reservoir", + "reservoirAdd", + "reservoirValues", + ): + return "equality" + if entry["module"] == "HMath.API.Convergence" and entry["name"] not in ( + "fromMaybeError", + "resultMaybe", + ): + return "equality" + if "Ord a" in entry["constraints"] and not any( + s[0] in ("Heap", "MultiSet") for s in entry["args"] + [entry["result"]] + ): + return "ordered" + return "value" + + +def hstype(spec, types, element="X.Value"): + head, *args = spec + if head == "Heap": + return "HeapState" + if head == "MultiSet": + return "MultiState" + if head == "a": + return element + if head == "e": + return "X.Value" + if head == "list": + return "[" + hstype(args[0], types, element) + "]" + if head == "tuple": + return "(" + ",".join(hstype(s, types, element) for s in args) + ")" + if head == "function": + return "(" + " -> ".join(hstype(s, types, element) for s in args) + ")" + if head == "unit": + return "()" + name = ( + types[head]["alias"] + "." + head + if head in types + else "E.MathError" + if head == "MathError" + else head + ) + return ( + "(" + + name + + (" " + " ".join(hstype(s, types, element) for s in args) if args else "") + + ")" + ) + + +def decode(spec, value, types, flavor="value"): + head, *args = spec + if head == "a": + return { + "value": "pure " + value, + "ordered": "readOrdered witness " + value, + "equality": "readEquality " + value, + "numeric": "X.asScalar " + value, + }[flavor] + if head == "e": + return "pure " + value + if head == "Maybe": + v = G.fresh("optional") + return ( + "(asMaybeValue " + + value + + " >>= \\" + + v + + " -> case " + + v + + " of {Nothing -> pure Nothing;Just item -> Just <$> (" + + decode(args[0], "item", types, flavor) + + ")})" + ) + if head == "Either": + return "asEitherValue " + value + if head == "function": + variables = [G.fresh("callbackArg") for _ in args[:-1]] + vals = [encode(s, v, types, flavor) for s, v in zip(args[:-1], variables)] + statement = ( + "inputs <- sequence [" + ",".join(vals) + "];let { input=X.Tuple inputs }" + ) + result = args[-1] + call = ( + "checkedCallback " + + value + + " input (\\reply -> " + + decode(result[2], "reply", types, flavor) + + ")" + if result[0] == "Either" and result[1] == ["MathError"] + else "LC.callbackValue " + + value + + " input >>= \\reply -> " + + decode(result, "reply", types, flavor) + ) + return ( + "pure(\\" + + " ".join(variables) + + " -> unsafePerformIO $ do {" + + statement + + ";" + + call + + "})" + ) + if head == "list": + item = G.fresh("item") + return ( + "X.asList " + + value + + " >>= mapM(\\" + + item + + " -> " + + decode(args[0], item, types, flavor) + + ")" + ) + if head == "tuple": + variables = [G.fresh("part") for _ in args] + ls = G.fresh("parts") + return ( + "(X.asTuple " + + str(len(args)) + + " " + + value + + " >>= \\" + + ls + + " -> case " + + ls + + " of { [" + + ",".join(variables) + + "] -> (" + + "," * (len(args) - 1) + + ") <$> " + + " <*> ".join( + "(" + decode(s, v, types, flavor) + ")" for s, v in zip(args, variables) + ) + + ';_ -> X.invalid "tuple arity differs"})' + ) + if head in types: + return 'unbox "' + types[head]["module"] + "." + head + '" ' + value + if head == "Int": + return "X.asIndex " + value + if head in ("Integer", "Double", "Word64", "Rational"): + return "X.asScalar " + value + if head == "Bool": + return "X.asBoolean " + value + if head == "String": + return "X.asText " + value + raise ValueError(("decode", spec)) + + +def encode(spec, value, types, flavor="value"): + head, *args = spec + if head == "a": + return { + "value": "pure " + value, + "ordered": "writeOrdered " + value, + "equality": "writeEquality " + value, + "numeric": "pure(X.Scalar w " + value + ")", + }[flavor] + if head == "e": + return "pure " + value + if head == "Either": + if args[0] != ["MathError"]: + return "eitherValue " + value + item = G.fresh("_result") + return ( + "source " + + value + + " >>= \\" + + item + + " -> " + + encode(args[1], item, types, flavor) + ) + if head == "Maybe": + item = G.fresh("item") + return ( + "(case " + + value + + " of {Nothing -> pure X.None;Just " + + item + + " -> " + + encode(args[0], item, types, flavor) + + " >>= maybeValue . Just})" + ) + if head == "list": + item = G.fresh("item") + return ( + "X.List <$>mapM(\\" + + item + + " -> " + + encode(args[0], item, types, flavor) + + ") " + + value + ) + if head == "tuple": + variables = [G.fresh("part") for _ in args] + return ( + "(\\(" + + ",".join(variables) + + ") -> X.Tuple <$> sequence [" + + ",".join(encode(s, v, types, flavor) for s, v in zip(args, variables)) + + "]) " + + value + ) + if head in types: + return "encode" + head + " " + value + if head == "Int": + return "pure(X.Index " + value + ")" + if head in ("Integer", "Double", "Word64", "Rational"): + return ( + "pure(X.Scalar " + + { + "Integer": "SInteger", + "Double": "SDouble", + "Word64": "SWord64", + "Rational": "SRational", + }[head] + + " " + + value + + ")" + ) + if head == "Bool": + return "pure(X.Boolean " + value + ")" + if head == "String": + return "pure(X.Text " + value + ")" + if head == "unit": + return "pure X.None" + raise ValueError(("encode", spec)) + + +def sym(entry): + return ( + "hmath_foundation_" + + MODULES[entry["module"]][2] + + "_" + + ("new_" if entry["constructor"] else "") + + G.snake(entry["name"]) + + ("_typed" if entry.get("typed_order") else "") + ) + + +def native(entries, types, fields): + entries = [ + *entries, + *[ + {**entry, "typed_order": True} + for entry in entries + if mode(entry) == "ordered" + ], + ] + hs = [ + """{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated original-operation adapters. No algorithm implementation here. +module HMath.FFI.Foundation where +import Control.Exception (evaluate) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import HMath.FFI.Coefficient +import HMath.FFI.FoundationCodec +import HMath.FFI.Ordering +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +""" + ] + for m, (alias, _ns, _public) in MODULES.items(): + hs.append("import qualified " + m + " as " + alias + "\n") + for name, t in types.items(): + typ = hstype( + [name, *[[p] for p in t["params"]]], + types, + "EqualityValue" if name in ("Reservoir", "Convergence") else "X.Value", + ) + hs.append( + "\nencode" + + name + + " :: " + + typ + + " -> IO X.Value\nencode" + + name + + ' value=pure(opaqueEq "' + + t["module"] + + "." + + name + + '" (-1) value force view)\n where\n force=' + ) + if fields[name]: + hs.append( + "forceFields [" + + ",".join( + encode( + s, + "(" + t["alias"] + "." + f + " value)", + types, + "equality" if name in ("Reservoir", "Convergence") else "value", + ) + for f, s in fields[name] + ) + + "]\n" + ) + elif name == "MultiSet": + hs.append( + "multisetEntries value >>= \\xs -> forceFields [" + + encode(["list", ["tuple", ["a"], ["Integer"]]], "xs", types) + + "]\n" + ) + else: + hs.append("evaluate value >> pure()\n") + constructors = [ + e for e in entries if e["constructor"] and e["result"][0] == name + ] + if constructors: + hs.append(" view=case value of\n") + for e in constructors: + variables = [G.fresh("field") for _ in e["args"]] + hs.append( + " " + + t["alias"] + + "." + + e["name"] + + " " + + " ".join(variables) + + " -> do\n values <- sequence [" + + ",".join( + encode( + s, + v, + types, + "equality" + if name in ("Reservoir", "Convergence") + else "value", + ) + for s, v in zip(e["args"], variables) + ) + + ']\n pure(X.Tuple[X.Text "' + + e["name"] + + '",X.Tuple values])\n' + ) + else: + hs.append( + ' view=X.unsupported "original abstract type has no public constructor fields"\n' + ) + hs.append( + "\napply :: Int -> [X.Value] -> IO X.Value\napply operation args=case(operation,args) of\n" + ) + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_foundation_bindings.py. */ +#ifndef HMATH_FOUNDATION_H +#define HMATH_FOUNDATION_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original persistent data/discrete/combinatorial/convergence operations. + * Opaque kind400 records own independent references; inputs borrow for the call. + * Value callback101 transports original argument tuples; checked status11 + * becomes genuine Left, pure callback failures abort. Generic Either results + * retain explicit Left/Right; optional Just(None) retains its distinction. + * No arbitrary precision integer, original budget, order, callback or error + * contract is replaced. Release each owned output with hmath_value_release. */ +HMATH_API hmath_status hmath_foundation_object_type(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_foundation_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_foundation_left(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_foundation_right(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_foundation_just(hmath_context *context,const hmath_value *value,hmath_value **out); +""" + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; original operation dispatch only. */\n#include "hmath_foundation.h"\n#include "value_internal.h"\nextern int hm_foundation_apply(int,void *const *,size_t,void **);\n' + ] + heap_calls = { + "emptyHeap": "pure heapEmpty", + "heapFromList": "heapFromList a0Value", + "heapInsert": "heapInsert a0Value a1Value", + "heapPop": "heapPop a0Value", + } + multis = { + "multiset": "multiset a0Value", + "multiplicity": "multiplicity a0Value a1Value", + "multisetEntries": "multisetEntries a0Value", + "multisetInsert": "multisetInsert a0Value a1Value", + "multisetDelete": "multisetDelete a0Value a1Value", + "multisetUnion": "multisetBinary S.multisetUnion a0Value a1Value", + "multisetIntersection": "multisetBinary S.multisetIntersection a0Value a1Value", + "multisetDifference": "multisetBinary S.multisetDifference a0Value a1Value", + } + for opcode, e in enumerate(entries): + flavor = mode(e) + variables = ["a" + str(i) for i in range(len(e["args"]))] + if flavor == "numeric" or e.get("typed_order"): + variables = ["prototype"] + variables + hs.append( + " (" + + str(opcode) + + ",[" + + ",".join(variables) + + "]) -> " + + ( + "LC.withWitness prototype $ \\(w::ScalarType a) -> " + if flavor == "numeric" + else "" + ) + + "do\n" + ) + if flavor == "ordered": + # Only nonpersistent arrays use this branch; every order operation's + # polymorphic elements are collected before selecting one real Ord. + examples = [] + for i, spec in enumerate(e["args"]): + if spec == ["a"]: + examples.append("pure [a" + str(i) + "]") + elif spec == ["list", ["a"]]: + examples.append("X.asList a" + str(i)) + if e.get("typed_order"): + hs.append( + " witness <- orderedWith [foundationOrdering][prototype]\n" + ) + else: + hs.append( + " examples <- concat <$> sequence [" + + ",".join(examples) + + "]\n witness <- if null examples then orderedFromPrototype(X.Scalar SInteger 0) else orderedWith [foundationOrdering] examples\n" + ) + element = { + "value": "X.Value", + "ordered": "OrderedValue", + "equality": "EqualityValue", + "numeric": "a", + }[flavor] + for i, spec in enumerate(e["args"]): + hs.append( + " a" + + str(i) + + "Value <- (" + + decode(spec, "a" + str(i), types, flavor) + + " :: IO " + + hstype(spec, types, element) + + ")\n" + ) + call = ( + "(" + + MODULES[e["module"]][0] + + "." + + e["name"] + + " " + + " ".join("a" + str(i) + "Value" for i in range(len(e["args"]))) + + ")" + ) + extra_io = False + if e["module"] == "HMath.DataStructure" and e["name"] in heap_calls: + call = "(" + heap_calls[e["name"]] + ")" + extra_io = True + if e["module"] == "HMath.Discrete" and e["name"] in multis: + call = "(" + multis[e["name"]] + ")" + extra_io = True + if e["name"] == "Converged": + call = "(case a0Value of V.Converged x -> Just x;_ -> Nothing)" + result = e["result"] + if extra_io: + hs.append( + " " + + call + + " >>= \\result -> " + + encode(result, "result", types, flavor) + + "\n" + ) + else: + call = "(" + call + " :: " + hstype(result, types, element) + ")" + hs.append(" " + encode(result, call, types, flavor) + "\n") + parameters = ( + ["hmath_context *context"] + + ["const hmath_value *" + v for v in variables] + + ["hmath_value **out"] + ) + proto = "hmath_status " + sym(e) + "(" + ", ".join(parameters) + ")" + h.append( + "/* " + e["module"] + "." + e["name"] + " */\nHMATH_API " + proto + ";\n" + ) + c.append( + proto + + " {\n if(!out" + + "".join(" || !" + v for v in variables) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL foundation argument");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n' + ) + ptr = "NULL" + if variables: + c.append( + " void *args[]={" + + ",".join("hm_value_stable(" + v + ")" for v in variables) + + "};\n" + ) + ptr = "args" + c.append( + " return hm_value_finish(result,hm_foundation_apply(" + + str(opcode) + + "," + + ptr + + "," + + str(len(variables)) + + ",&result->stable),out);\n}\n" + ) + hs.append(""" (-1,[value]) -> X.Text <$> objectName value + (-2,[value]) -> objectParts value + (-3,[value]) -> eitherValue(Left value) + (-4,[value]) -> eitherValue(Right value) + (-5,[value]) -> maybeValue(Just value) + (-6,[value]) -> orderedType value + (-7,[value]) -> optionalType value + (-8,[prototype,values]) -> X.asList values >>= heapFromListTyped prototype >>= encodeHeap + (-9,[prototype,values]) -> X.asList values >>= multisetTyped prototype >>= encodeMultiSet + _ -> X.invalid "invalid foundation operation/arity" +foreign export ccall "hm_foundation_apply" ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(X.publish value out)) +""") + for name, opcode in [ + ("object_type", -1), + ("object_parts", -2), + ("left", -3), + ("right", -4), + ("just", -5), + ("ordered_type", -6), + ("optional_type", -7), + ]: + if opcode in (-6, -7): + h.append( + "HMATH_API hmath_status hmath_foundation_" + + name + + "(hmath_context *context,const hmath_value *value,hmath_value **out);\n" + ) + c.append( + "hmath_status hmath_foundation_" + + name + + '(hmath_context *context,const hmath_value *value,hmath_value **out) {\n if(!value || !out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL foundation query");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n void *args[]={hm_value_stable(value)};\n return hm_value_finish(result,hm_foundation_apply(' + + str(opcode) + + ",args,1,&result->stable),out);\n}\n" + ) + for name, opcode in [("heap_from_list_typed", -8), ("multiset_typed", -9)]: + prototype = ( + "hmath_status hmath_foundation_" + + name + + "(hmath_context *context,const hmath_value *prototype,const hmath_value *values,hmath_value **out)" + ) + h.append("HMATH_API " + prototype + ";\n") + c.append( + prototype + + ' {\n if(!prototype || !values || !out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed container argument");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n void *args[]={hm_value_stable(prototype),hm_value_stable(values)};\n return hm_value_finish(result,hm_foundation_apply(' + + str(opcode) + + ",args,2,&result->stable),out);\n}\n" + ) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "src/HMath/FFI/Foundation.hs": "".join(hs), + "include/hmath_foundation.h": "".join(h), + "cbits/foundation.c": "".join(c), + } + + +def outputs(): + G._COUNTER = 0 + entries, types, fields = specification() + result = native(entries, types, fields) + result.update(frontend(entries, types, fields)) + result["bindings/schema/foundation-functions.json"] = ( + json.dumps({"functions": entries, "types": types, "fields": fields}, indent=2) + + "\n" + ) + return { + name: format_c(data) if name.endswith((".c", ".h")) else data + for name, data in result.items() + } + + +def pyname(entry, types): + if entry["constructor"] and entry["name"] in types: + return entry["name"] + name = G.snake(entry["name"]) + return {"and": "logical_and", "or": "logical_or", "not": "logical_not"}.get( + name, name + "_op" if keyword.iskeyword(name) else name + ) + + +def frontend(entries, types, fields): + py = { + m: [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_foundation_bindings.py.\n"""Original ' + + m + + ' public functions and immutable values."""\nfrom ._foundation_base import FoundationValue,_invoke,register\n' + ] + for m in MODULES + } + public = {m: [] for m in MODULES} + mappings = [] + covered = set() + docs = [ + "# Foundation, discrete structures and convergence\n\nThese functions call the original Haskell algorithms. Persistent heaps/multisets retain the actual original element ordering dictionary; exact integers, coefficient dtypes, strings, tuples and registered mathematical values are not converted through FP64. Sampling/combinatorial output limits, bit widths, logic depth/input caps, resource defaults and source error conventions remain unchanged. Objects own independent immutable references and support `close()`/context management.\n\nGeneric checked callbacks use plain successful return values and raise a `MathError` to return source Left. Pure callbacks abort on failure. Unexpected Python exceptions are rethrown after native cleanup. Callback owners are retained transitively. Convergence reports retain their estimate even when iteration/stagnation limits stop execution; inspect `stop_reason` or use `require_convergence`. Generic Either results use explicit Left/Right owners; optional Just(None) is preserved as a Just owner.\n\n" + ] + docs.append( + "## Ordered element prototypes\n\nOrd operations infer an actual Haskell dictionary from the supplied values. For all-None or recursively empty inputs, supply an explicit `prototype=`; it selects a type without adding data to the source algorithm. C uses the corresponding `_typed` overload. `ordered_type(example)` retains a representative original Ord dictionary and `optional_type(prototype)` constructs the original `Ord (Maybe a)` dictionary, including nesting. Empty heaps/multisets normally defer their dictionary until the first element arrives.\n\n```python\nfrom hmath import convergence, datastructure\n\nwith convergence.optional_type(0) as optional_integer:\n with datastructure.heap_from_list([None, None], prototype=optional_integer) as heap:\n first, remaining = datastructure.heap_pop(heap)\n assert first is None\n remaining.close()\n```\n\n`None` represents Nothing; `convergence.just(None)` distinguishes Just Nothing when optional layers nest. Generic Either values retain explicit Left/Right via `left`, `right`, and `.parts`. Prototypes and every returned owner support `close()`/context management. Equality-dependent grouping uses original dictionaries for supported scalar/recursive values, Foundation records, Polynomial/PowerSeries/RationalFunction, numeric/Bool/String/Exact Matrix and Tensor, and original AD.Dual full-field equality. NaNs and tensor views retain their source equality behavior. This finite transport does not invent Eq/Ord for arbitrary custom Haskell types.\n\n" + ) + constructors = { + e["name"]: e for e in entries if e["constructor"] and e["name"] in types + } + lower = { + "Fenwick": "fenwick", + "SegmentTree": "segmentTree", + "SparseTable": "sparseTable", + "DisjointSparseTable": "disjointSparseTable", + "Heap": "heapFromList", + "BinaryHeap": "binaryHeap", + "IndexedHeap": "indexedHeap", + "UnionFind": "unionFind", + "Bloom": "bloom", + "CountMin": "countMin", + "HyperLogLog": "hyperLogLog", + "Reservoir": "reservoir", + "OnlineQuantiles": "onlineQuantiles", + "MultiSet": "multiset", + "BitSet": "bitSet", + } + for name, t in types.items(): + m = t["module"] + source = m + "." + name + public[m].append(name) + py[m].append( + "\nclass " + + name + + '(FoundationValue):\n """Original ' + + source + + ' immutable owner."""\n _source_type=' + + repr(source) + + "\n" + ) + constructor = constructors.get(name) + if name in lower: + constructor = next( + e for e in entries if e["module"] == m and e["name"] == lower[name] + ) + if constructor: + typed_container = name in ("Heap", "MultiSet") + specs = constructor["args"] + params = ( + [G.snake(f) for f, _ in fields[name]] + if fields[name] + else ["argument" + str(i + 1) for i in range(len(specs))] + ) + py[m].append( + " def __init__(self" + + (", " + ", ".join(params) if params else "") + + (", *, prototype=None" if typed_container else "") + + "):\n self._initialize(" + + repr(sym(constructor)) + + ", " + + repr(specs) + + ", [" + + ", ".join(params) + + "], " + + repr(mode(constructor)) + + (", prototype=prototype" if typed_container else "") + + ")\n" + ) + for field, _spec in fields[name]: + entry = next(e for e in entries if e["module"] == m and e["name"] == field) + py[m].append( + " @property\n def " + + G.snake(field) + + "(self):\n return _invoke(" + + repr(sym(entry)) + + ", " + + repr(entry["args"]) + + ", [self], " + + repr(mode(entry)) + + ")\n" + ) + py[m].append("register(" + repr(source) + ", " + name + ")\n") + for entry in entries: + m = entry["module"] + name = pyname(entry, types) + record = entry["constructor"] and entry["name"] in types + if not record: + typed_order = mode(entry) == "ordered" or entry["name"] in ( + "heapFromList", + "multiset", + ) + params = ["argument" + str(i + 1) for i in range(len(entry["args"]))] + public[m].append(name) + signature = ", ".join(params) + ( + ", *, dtype=None" + if mode(entry) == "numeric" + else ", *, prototype=None" + if typed_order + else "" + ) + py[m].append( + "\ndef " + + name + + "(" + + signature + + "):\n " + + repr(G.source_prose(entry)) + + "\n return _invoke(" + + repr(sym(entry)) + + ", " + + repr(entry["args"]) + + ", [" + + ", ".join(params) + + "], " + + repr(mode(entry)) + + (", dtype" if mode(entry) == "numeric" else "") + + (", prototype=prototype" if typed_order else "") + + ")\n" + ) + source = m + "." + entry["name"] + covered.add(source) + mappings.append( + { + "symbol": source, + "c": [sym(entry)] + + ( + [sym(entry) + "_typed"] + if mode(entry) == "ordered" + else ["hmath_foundation_heap_from_list_typed"] + if entry["name"] == "heapFromList" + else ["hmath_foundation_multiset_typed"] + if entry["name"] == "multiset" + else [] + ), + "python": "hmath." + MODULES[m][2] + "." + name, + "specializations": [ + "original algorithms; actual supported Ord/Eq dictionaries; no numeric conversion; complete public variants/fields" + ], + } + ) + docs.append( + "## `" + + MODULES[m][2] + + "." + + name + + "`\n\n" + + G.source_prose(entry) + + "\n\nOriginal signature: `" + + entry["signature"] + + "`. Constraints: `" + + (entry["constraints"] or "none") + + "`. C arguments are borrowed Values in source order; a successful output owns one reference and failure leaves it untouched.\n\n" + ) + for name, t in types.items(): + source = t["module"] + "." + name + if source not in covered: + mappings.append( + { + "symbol": source, + "c": ["hmath_value", "hmath_value_release"], + "python": "hmath." + MODULES[t["module"]][2] + "." + name, + "specializations": [ + "original immutable persistent container; kind400 source subtype" + ], + } + ) + py["HMath.API.Convergence"].append( + "\nfrom ._foundation_base import Either,Just,OrderedType,left,right,just,ordered_type,optional_type\n" + ) + public["HMath.API.Convergence"].extend( + [ + "Either", + "Just", + "OrderedType", + "left", + "right", + "just", + "ordered_type", + "optional_type", + ] + ) + result = { + "bindings/schema/foundation-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mappings, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "docs/reference/foundation.md": "".join(docs), + } + for m, parts in py.items(): + parts.append("\n__all__=" + repr(sorted(set(public[m]))) + "\n") + result["bindings/python/_hmath_native/" + MODULES[m][1] + ".py"] = fmt( + "".join(parts), MODULES[m][1] + ".py" + ) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_geometry_bindings.py b/tools/generate_geometry_bindings.py new file mode 100644 index 0000000..b102aab --- /dev/null +++ b/tools/generate_geometry_bindings.py @@ -0,0 +1,494 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate typed direct adapters for the complete concrete public Geometry API.""" + +import argparse +import json +import keyword +from pathlib import Path + +from generate_graph_bindings import snake, source_prose, split_top, type_spec + +ROOT = Path(__file__).resolve().parent.parent +TYPE_NAMES = [ + "Point2", + "Point3", + "PointND", + "Line", + "Ray", + "Segment", + "Plane", + "Triangle", + "Rectangle", + "Circle", + "Ellipse", + "Polygon", + "Sphere", + "AABB", + "OBB", + "Capsule", + "Cylinder", + "Cone", + "Frustum", + "Orientation", + "Location", + "Penetration", + "HullAlgorithm", + "BooleanOperation", + "Metric", + "Intersection2", + "CircleIntersection", + "SpatialKind", + "PointCloud", + "SpatialIndex", + "NeighborQuery", +] +TYPES = {name: 169 + index for index, name in enumerate(TYPE_NAMES)} +KNOWN = {*TYPES, "Matrix Double", "IndexedTriangle", "Ordering"} +SKIP = {"hammingDistance", "jaccardDistance"} + + +def entries(): + data = json.loads((ROOT / "bindings/schema/geometry-functions.json").read_text())[ + "functions" + ] + return [e for e in data if e["name"] not in SKIP] + + +def arguments(entry): + types = split_top(entry["signature"], "->")[:-1] + result = [] + used = set() + for typ in types: + name = { + "Double": "number", + "Int": "count", + "Bool": "flag", + "Matrix Double": "matrix", + }.get( + typ, + "values" + if typ.startswith("[") + else "tuple_value" + if typ.startswith("(") + else snake(typ), + ) + if keyword.iskeyword(name) or name in { + "operator", + "union", + "struct", + "class", + "template", + }: + name += "Value" + original = name + index = 2 + while name in used: + name = original + str(index) + index += 1 + used.add(name) + result.append(name) + return result + + +def public_name(entry): + # The public raw PointND constructor and checked pointND function are distinct. + return "point_nd_raw" if entry["name"] == "PointND" else snake(entry["name"]) + + +def result_type(signature): + result = split_top(signature, "->")[-1] + checked = result.startswith("Either MathError ") + result = result.removeprefix("Either MathError ") + while result.startswith("(") and result.endswith(")"): + inner = result[1:-1].strip() + if len(split_top(inner, ",")) != 1: + break + result = inner + return result, checked + + +def native_type(typ): + if typ.startswith("["): + return "[" + native_type(typ[1:-1]) + "]" + if typ.startswith("("): + return "(" + ",".join(native_type(x) for x in split_top(typ[1:-1], ",")) + ")" + if typ.startswith("Maybe "): + return "(Maybe " + native_type(typ[6:].strip()) + ")" + if typ == "Matrix Double": + return "(M.Matrix Double)" + return "G." + typ if typ in KNOWN else typ + + +HS_PREFIX = """{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_geometry_bindings.py. +module HMath.FFI.Geometry where +import Foreign +import Foreign.C +import Data.Typeable (cast) +import HMath.FFI.Boundary +import HMath.FFI.Coefficient (ScalarType (SDouble)) +import HMath.FFI.GraphCodec (Wire(..),boxed,unboxed) +import HMath.FFI.Value +import qualified HMath.Geometry as G +import qualified HMath.Matrix as M + +matrixValue :: M.Matrix Double -> Value +matrixValue = Dense . SomeMatrix SDouble +matrixInput :: Value -> IO (M.Matrix Double) +matrixInput (Dense (SomeMatrix _ value)) = maybe (invalid "Matrix Double required") pure (cast value) +matrixInput _ = invalid "dense Matrix Double required" +orderingValue :: Ordering -> Value +orderingValue value = Index (case value of LT -> -1;EQ -> 0;GT -> 1) +-- Outer presence must remain explicit: Nothing and Just Nothing are distinct. +nestedMaybeValue :: Wire a => Maybe (Maybe a) -> Value +nestedMaybeValue Nothing = Tuple [Boolean False,None] +nestedMaybeValue (Just value) = Tuple [Boolean True,wire value] +""" + + +def generate(): + data = entries() + known = { + e["symbol"] + for e in json.loads((ROOT / "bindings/schema/public-api.json").read_text())[ + "symbols" + ] + } + for e in data: + assert e["module"] + "." + e["name"] in known, e + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_geometry_bindings.py. */\n#ifndef HMATH_GEOMETRY_H\n#define HMATH_GEOMETRY_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Actual immutable Geometry objects use kinds169..199. Inputs are borrowed;\n * successful outputs transfer one owned Value, unchanged on failure. Release\n * with hmath_value_release; each live owner pins the runtime. Source shape,\n * coordinate1e50, work/iteration budgets, exact Rational predicates and original\n * Double results are preserved. Raw public constructors remain unchecked;\n * checked operations retain their original validation and MathError/status11.\n * Matrices are shared Dense Matrix Double values. IndexedTriangle is an Int\n * triple. Ordering is a Haskell Int value -1(LT),0(EQ),1(GT). Other lists, tuples\n * and optional values retain source structure; nested Maybe results explicitly\n * return Tuple(Bool outer_present, inner_optional), distinguishing coincidence\n * from no intersection. Readers retain independent references per thread. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_geometry_bindings.py. */\n#include "hmath_geometry.h"\n#include "value_internal.h"\nextern int hm_geometry_apply(int,void *const *,size_t,void **);\n' + ] + hs = [HS_PREFIX] + for typ, tag in TYPES.items(): + hs.append( + "instance Wire G." + + typ + + " where\n wire = boxed " + + str(tag) + + "\n unwire = unboxed " + + str(tag) + + "\n" + ) + hs.insert(0, "{-# OPTIONS_GHC -Wno-orphans #-}\n") + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_geometry_bindings.py; do not edit.\n"""Original checked geometry, topology, intersections and spatial search."""\nfrom ._geometry_base import GeometryValue, Ordering, _invoke\nfrom ._value import register\nfrom .geometry_primitives import hamming_distance, jaccard_distance\n\nIndexedTriangle = tuple\n' + ] + exports = [ + "IndexedTriangle", + "Ordering", + "hamming_distance", + "jaccard_distance", + "parts", + "describe", + ] + docs = [ + "# Geometry bindings\n\n`from hmath import geometry` calls the original checked geometry algorithms. C includes `hmath_geometry.h`. Coordinates retain their finite1e50 cap, ND dimension1..16 bounds, exact Rational orientation/incircle predicates, source algorithm budgets, tie order and Double outputs. Raw public constructors retain their unchecked behavior; checked operations validate them without adapter changes.\n\nObjects are immutable owned [structured values](values.md); inputs are borrowed for a synchronous call and success transfers one output reference. Outputs stay untouched on failure. Each live owner pins the runtime. Independent readers retain their own references; original MathError/status11 includes its complete constructor and payload. Cancellation is checked before entry.\n\nUse `parts(value)` or `value.parts` for a public data constructor: it returns `(constructor_name, tuple_of_fields)` with typed child owners. A child remains valid after its parent closes. `value.coordinates` returns coordinates for Point2/Point3/PointND. Abstract PointCloud/SpatialIndex remain abstract; their original query functions are available. `describe(value)` exposes the original Show representation for inspection, without parsing or dispatching mathematics through text.\n\n`line_plane_intersection` and `plane_intersection` return `(outer_present, inner_optional)`: `(False, None)` is no intersection, `(True, None)` is coincidence, `(True, value)` is one intersection. This preserves all three source `Maybe (Maybe a)` states. `incircle` returns `Ordering.LT/EQ/GT` (C Haskell-Int values -1/0/1). Indexed triangles remain tuples of three zero-based original input indices. Matrix operations exchange actual shared `Matrix Double` objects.\n\nPolygon Boolean rings retain exterior/hole orientation. Constraints in Delaunay triangulation do not become a polygon/hole specification. Nearest-neighbor results keep original IDs, distance/ID tie order and explicit budget/exhaustive fields. Collision/penetration error estimates retain their source meaning; transforms retain the documented OpenGL depth conventions.\n\nThe existing hamming/jaccard compatibility functions expose Float/Double numeric variants; they do not claim arbitrary user-defined Haskell Eq instances.\n\n" + ] + mappings = [] + symbols = [] + names = {e["name"] for e in data} + for typ, tag in TYPES.items(): + py.append( + "\n\nclass " + + typ + + '(GeometryValue):\n """Actual immutable HMath.Geometry.' + + typ + + ' native owner."""\n\n\nregister(' + + str(tag) + + ", " + + typ + + ")\n" + ) + exports.append(typ) + header.append( + "typedef hmath_value hmath_geometry_" + + snake(typ) + + "_object; /* kind" + + str(tag) + + " */\n" + ) + if typ not in names: + source = next( + e["symbol"] + for e in json.loads( + (ROOT / "bindings/schema/public-api.json").read_text() + )["symbols"] + if e["symbol"].startswith("HMath.Geometry.") + and e["symbol"].rsplit(".", 1)[-1] == typ + ) + mappings.append( + { + "symbol": source, + "c": ["hmath_geometry_" + snake(typ) + "_object"], + "python": "hmath.geometry." + typ, + "specializations": ["original opaque type"], + } + ) + header.append( + "typedef hmath_value hmath_geometry_indexed_triangle_object; /* tuple(Int,Int,Int) */\n" + ) + mappings.append( + { + "symbol": "HMath.Geometry.Triangulation.IndexedTriangle", + "c": ["hmath_geometry_indexed_triangle_object"], + "python": "hmath.geometry.IndexedTriangle", + "specializations": ["exact original Int triple"], + } + ) + for helper in ["parts", "describe", "equal"]: + arity = 2 if helper == "equal" else 1 + prototype = ( + "hmath_status hmath_geometry_" + + helper + + "(hmath_context *context" + + "".join(",const hmath_value *value" + str(k) for k in range(arity)) + + ",hmath_value **out)" + ) + header.append("HMATH_API " + prototype + ";\n") + c.append( + "extern int hm_geometry_" + + helper + + "(" + + ",".join(["void *"] * arity + ["void **"]) + + ");\n" + + prototype + + " {\n if(!out" + + "".join(" || !value" + str(k) for k in range(arity)) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL geometry helper argument");\n hmath_value *temporary=NULL;\n hmath_status status=hm_value_begin(context,&temporary);\n if(status)return status;\n return hm_value_finish(temporary,hm_geometry_' + + helper + + "(" + + ",".join("hm_value_stable(value" + str(k) + ")" for k in range(arity)) + + ",&temporary->stable),out);\n}\n" + ) + symbols.append("hmath_geometry_" + helper) + hs.append( + 'foreign export ccall "hm_geometry_describe" describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\ndescribe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\ndescribe input out = boundary $ do\n value <- deRefStablePtr input\n text <- case valueInfo value of\n' + ) + for typ, tag in TYPES.items(): + hs.append( + " (" + + str(tag) + + ",_,_) -> show <$> (unwire value :: IO G." + + typ + + ")\n" + ) + hs.append( + ' _ -> invalid "expected Geometry object"\n checked (Right (Text text)) (`publish` out)\n' + ) + hs.append( + 'foreign export ccall "hm_geometry_equal" equal :: StablePtr Value -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\nequal :: StablePtr Value -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\nequal first second out = boundary $ do\n a <- deRefStablePtr first\n b <- deRefStablePtr second\n result <- case (valueInfo a,valueInfo b) of\n' + ) + for typ, tag in TYPES.items(): + hs.append( + " ((" + + str(tag) + + ",_,_),(" + + str(tag) + + ",_,_)) -> (==) <$> (unwire a :: IO G." + + typ + + ") <*> unwire b\n" + ) + hs.append( + " _ -> pure False\n checked (Right (Boolean result)) (`publish` out)\n" + ) + hs.append( + 'foreign export ccall "hm_geometry_parts" parts :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\nparts :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\nparts input out = boundary $ do\n value <- deRefStablePtr input\n result <- case valueInfo value of\n' + ) + for typ, tag in TYPES.items(): + constructors = [ + e + for e in data + if e["name"][0].isupper() and e["signature"].split(" -> ")[-1] == typ + ] + if not constructors: + continue + hs.append( + " (" + + str(tag) + + ",_,_) -> do\n object <- unwire value :: IO G." + + typ + + "\n pure $ case object of\n" + ) + for e in constructors: + args = split_top(e["signature"], "->")[:-1] + variables = ["field" + str(k) for k in range(len(args))] + hs.append( + " G." + + e["name"] + + "".join(" " + v for v in variables) + + " -> Tuple [Text " + + json.dumps(e["name"]) + + ",Tuple [" + + ",".join("wire " + v for v in variables) + + "]]\n" + ) + hs.append( + ' _ -> unsupported "public constructor fields unavailable for this abstract Geometry type"\n checked (Right result) (`publish` out)\n' + ) + hs.append( + 'foreign export ccall "hm_geometry_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt\napply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt\napply operation inputs arity out = boundary $ do\n values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr\n case (operation,values) of\n' + ) + py.append( + '\n\ndef parts(value):\n """Return the actual public constructor and typed fields."""\n return _invoke("hmath_geometry_parts", [["GeometryObject"]], [value])\n\n\ndef describe(value):\n """Return the original Show representation, never evaluated as code."""\n return _invoke("hmath_geometry_describe", [["GeometryObject"]], [value])\n' + ) + for op, e in enumerate(data): + types = split_top(e["signature"], "->") + args = types[:-1] + result, checked = result_type(e["signature"]) + names = arguments(e) + symbol = "hmath_geometry_" + public_name(e) + declaration = ( + ["hmath_context *context"] + + ["const hmath_value *" + n for n in names] + + ["hmath_value **out"] + ) + prototype = "hmath_status " + symbol + "(" + ", ".join(declaration) + ")" + header.append( + "/* " + + e["module"] + + "." + + e["name"] + + " :: " + + e["signature"] + + " */\nHMATH_API " + + prototype + + ";\n" + ) + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + n for n in names) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL Geometry argument");\n hmath_value *temporary=NULL;\n hmath_status status=hm_value_begin(context,&temporary);\n if(status)return status;\n void *arguments[]={' + + (",".join("hm_value_stable(" + n + ")" for n in names) or "NULL") + + "};\n return hm_value_finish(temporary,hm_geometry_apply(" + + str(op) + + ",arguments," + + str(len(args)) + + ",&temporary->stable),out);\n}\n" + ) + hs.append( + " (" + + str(op) + + ",[" + + ",".join("v" + str(k) for k in range(len(args))) + + "]) -> do\n" + ) + for k, typ in enumerate(args): + hs.append( + " arg" + + str(k) + + " <- " + + ( + "matrixInput v" + str(k) + if typ == "Matrix Double" + else "(unwire v" + str(k) + " :: IO (" + native_type(typ) + "))" + ) + + "\n" + ) + call = "G." + e["name"] + "".join(" arg" + str(k) for k in range(len(args))) + encoder = ( + "matrixValue" + if result == "Matrix Double" + else "orderingValue" + if result == "Ordering" + else "nestedMaybeValue" + if result in ("Maybe (Maybe Point3)", "Maybe (Maybe Line)") + else "wire" + ) + hs.append( + " checked (" + + (call if checked else "Right (" + call + ")") + + ") (\\result -> publish (" + + encoder + + " result) out)\n" + ) + specs = [type_spec(t, KNOWN) for t in args] + py.append( + "\n\ndef " + + public_name(e) + + "(" + + ", ".join(names) + + '):\n """' + + e["module"] + + "." + + e["name"] + + " :: " + + e["signature"] + + '."""\n result = _invoke(' + + repr(symbol) + + ", " + + repr(specs) + + ", [" + + ", ".join(names) + + "])\n return " + + ("Ordering(result)" if result == "Ordering" else "result") + + "\n" + ) + docs.append( + "## `" + + public_name(e) + + "`\n\n`geometry." + + snake(e["name"]) + + "(" + + ", ".join(names) + + ")`\n\n" + + source_prose(e) + + "\n\n```haskell\n" + + e["signature"] + + "\n```\n\n```c\n" + + prototype + + ";\n```\n\n" + ) + mappings.append( + { + "symbol": e["module"] + "." + e["name"], + "c": [symbol], + "python": "hmath.geometry." + public_name(e), + "specializations": ["original concrete types"], + } + ) + symbols.append(symbol) + exports.append(public_name(e)) + hs.append(' _ -> invalid "Geometry operation identifier or arity differs"\n') + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + py.append( + "\n\n__all__ = " + + json.dumps(sorted(exports, key=lambda n: (not n.isupper(), n)), indent=4) + + "\n" + ) + return { + "include/hmath_geometry.h": "".join(header), + "cbits/geometry.c": "".join(c), + "src/HMath/FFI/Geometry.hs": "".join(hs), + "bindings/python/_hmath_native/geometry.py": "".join(py), + "bindings/schema/geometry-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "bindings/schema/geometry-symbols.txt": "\n".join(symbols) + "\n", + "docs/reference/geometry-bindings.md": "".join(docs), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale Geometry binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_graph_bindings.py b/tools/generate_graph_bindings.py new file mode 100644 index 0000000..43010d9 --- /dev/null +++ b/tools/generate_graph_bindings.py @@ -0,0 +1,395 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named adapters for the concrete public Graph API, without algorithms.""" + +import argparse +import json +import keyword +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TYPES = { + "Graph": ("HMath.Graph.Core", 60), + "Edge": ("HMath.Graph.Core", 61), + "CSR": ("HMath.Graph.Core", 62), + "BipartiteGraph": ("HMath.Graph.Core", 63), + "Hypergraph": ("HMath.Graph.Core", 64), + "Network": ("HMath.Graph.Flow", 65), + "NetworkEdge": ("HMath.Graph.Flow", 66), + "FlowResult": ("HMath.Graph.Flow", 67), +} + + +def snake(name): + name = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name) + return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower() + + +def split_top(text, separator): + depth, start, result, index = 0, 0, [], 0 + while index < len(text): + char = text[index] + if char in "([": + depth += 1 + elif char in ")]": + depth -= 1 + if depth == 0 and text.startswith(separator, index): + result.append(text[start:index].strip()) + start = index + len(separator) + index += len(separator) + else: + index += 1 + return result + [text[start:].strip()] + + +def type_spec(text, known=None): + known = TYPES if known is None else known + text = text.strip() + if text.startswith("Maybe "): + return ["maybe", type_spec(text[6:], known)] + if text.startswith("[") and text.endswith("]"): + return ["list", type_spec(text[1:-1], known)] + if text.startswith("(") and text.endswith(")"): + inner = text[1:-1] + if not inner: + return ["unit"] + fields = split_top(inner, ",") + if len(fields) > 1: + return ["tuple", *[type_spec(field, known) for field in fields]] + arrows = split_top(inner, "->") + if len(arrows) > 1: + return ["function", *[type_spec(arrow, known) for arrow in arrows]] + return type_spec(inner, known) + if text not in {*known, "Bool", "Int", "Double", "Integer", "String", "Word64"}: + raise ValueError("unsupported structured type: " + text) + return [text] + + +def argument_names(entry, count): + """Use readable public names without altering the source argument order.""" + overrides = { + "Edge": "edge_id source target weight", + "CSR": "directed vertex_count offsets targets weights edge_ids orientations", + "NetworkEdge": "edge_id source target capacity cost", + "FlowResult": "value edge_flows cost", + "graph": "directed vertex_count edges", + "bipartiteGraph": "left_vertices right_vertices edges", + "hypergraph": "vertex_count hyperedges", + "network": "vertex_count edges", + "fromAdjacencyList": "directed rows orientations", + "fromLabeledAdjacencyMatrix": "directed cells orientations", + "fromAdjacencyMatrix": "directed cells", + "pageRank": "iterations tolerance damping graph", + "katzCentrality": "iterations tolerance alpha beta graph", + "eigenvectorCentrality": "iterations tolerance graph", + "laplacianSpectrum": "iterations tolerance normalized graph", + "randomWalk": "count seed graph start", + "kShortestPaths": "budget count graph source target", + "aStar": "graph heuristic source target", + "graphEditDistance": "budget left right", + "graphSimilarity": "left right", + "hungarian": "costs", + } + if entry["name"] in overrides: + names = overrides[entry["name"]].split() + else: + source = ( + ROOT / "src" / (entry["module"].replace(".", "/") + ".hs") + ).read_text() + match = re.search( + r"^" + re.escape(entry["name"]) + r"\s+([^\n=|]+)(?:=|\n\s*\|)", + source, + re.MULTILINE, + ) + parameters = match[1].strip().split() if match else [] + rename = { + "g": "graph", + "v": "vertex", + "b": "budget", + "net": "network", + "s": "source", + "t": "target", + "steps": "iterations", + "tol": "tolerance", + "fs": "flows", + "n": "vertex_count", + "es": "edges", + "bip": "bipartite", + "h": "hypergraph", + } + names = [ + rename.get(p, p) if entry["module"].startswith("HMath.Graph") else snake(p) + for p in parameters + ] + if len(names) != count or any(not name.isidentifier() for name in names): + types = split_top(entry["signature"], "->")[:-1] + names = [] + for index, typ in enumerate(types): + candidate = ( + snake(typ) + if typ in TYPES + else ("text" if typ == "String" else "value") + ) + names.append( + candidate if candidate not in names else candidate + str(index + 1) + ) + if len(names) != count: + raise ValueError("Graph argument names differ: " + entry["name"]) + used = set() + for index, name in enumerate(names): + if keyword.iskeyword(name) or name in { + "alignas", + "alignof", + "auto", + "bool", + "break", + "case", + "char", + "class", + "const", + "constexpr", + "continue", + "default", + "delete", + "do", + "double", + "else", + "enum", + "extern", + "float", + "for", + "friend", + "goto", + "inline", + "int", + "long", + "namespace", + "new", + "nullptr", + "operator", + "private", + "protected", + "public", + "register", + "return", + "short", + "signed", + "sizeof", + "static", + "struct", + "switch", + "template", + "this", + "throw", + "typedef", + "typename", + "union", + "unsigned", + "using", + "virtual", + "void", + "volatile", + "while", + }: + name += "_" + while name in used: + name += str(index + 1) + names[index] = name + used.add(name) + return names + + +def source_prose(entry): + source = (ROOT / "src" / (entry["module"].replace(".", "/") + ".hs")).read_text() + signature = re.search( + r"^" + re.escape(entry["name"]) + r"\s*::", source, re.MULTILINE + ) + if not signature: + return "Construct or inspect the original immutable record; field order follows the source signature." + before = source[: signature.start()].rstrip() + if before.endswith("-}"): + start = before.rfind("{- |") + if start >= 0: + return re.sub(r"\s+", " ", before[start + 4 : -2]).replace("\\<=", "<=") + lines = [] + for line in reversed(before.splitlines()): + if not line.startswith("--"): + break + lines.insert(0, line.removeprefix("--").removeprefix(" | ").strip()) + return ( + " ".join(lines) + or "Return the original field or query result without changing its value." + ) + + +def generate(): + entries = json.loads((ROOT / "bindings/schema/graph-functions.json").read_text())[ + "functions" + ] + numeric = { + e["module"] + "." + e["name"] + for e in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + } + header = [ + "/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_graph_bindings.py. */\n", + '#ifndef HMATH_GRAPH_H\n#define HMATH_GRAPH_H\n#include "hmath_value.h"\n', + '#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original Graph types are owned hmath_value objects (kinds 60..67).\n", + " * Pass Boolean, Haskell Int, binary64, exact Integer, String, list and\n", + " * tuple values matching each source signature. No algorithms or source\n", + " * limits are replaced. Every output owns one reference; release with\n", + " * hmath_value_release. Error outputs are untouched. MathError payloads\n", + " * are available through hmath_last_math_error. Cancellation is checked\n", + " * before entry; original per-algorithm budgets still apply. */\n", + "typedef hmath_status (*hmath_graph_heuristic)(ptrdiff_t vertex, void *userdata, double *out);\n", + ] + c = [ + "/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; do not edit. */\n", + '#include "hmath_graph.h"\n#include "value_internal.h"\n', + "extern int hm_graph_apply(int, void *const *, size_t, hmath_graph_heuristic, void *, void **);\n", + ] + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated; do not edit.\nmodule HMath.FFI.Graph where\n", + "import Foreign\nimport Foreign.C\nimport HMath.FFI.Boundary\nimport HMath.FFI.Value\nimport HMath.FFI.GraphCodec\nimport qualified HMath.Graph as G\n", + 'foreign export ccall "hm_graph_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr Heuristic -> Ptr () -> Ptr (StablePtr Value) -> IO CInt\n', + "apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr Heuristic -> Ptr () -> Ptr (StablePtr Value) -> IO CInt\n", + "apply operation input arity callback userdata out = boundary $ do\n values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr\n case (operation, values) of\n", + ] + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_graph_bindings.py.\n", + "from ._graph_base import _invoke, _astar\nfrom ._value import Value, register\n", + ] + docs = [ + "# Graph bindings\n\nThese adapters call the original Graph functions. Vertex/edge limits, tie order, loops, parallel edges, exact flow capacities and original algorithm budgets are preserved.\n\n", + "C uses `hmath_graph.h` with owned [structured values](values.md). Python uses `from hmath import graph`. Opaque graph objects support `close()` and context managers. Returned lists, tuples, Booleans, strings, integers, optional values and binary64 values use ordinary Python representations.\n\n", + "C output handles are owned and remain untouched on failure. Inputs are borrowed throughout a call; callers retain references. Independent calls may share immutable objects and must use independent output addresses. Source `Left MathError` uses status 11 with a lossless structured error. `Maybe` uses `None`/value kind 0. Checked cancellation occurs before entry; source algorithm budgets are not changed.\n\n", + ] + mappings = [] + names = {e["name"] for e in entries} + for name, (module, tag) in TYPES.items(): + py.append( + f'\n\nclass {name}(Value):\n """Owned immutable original {module}.{name}."""\n\n\nregister({tag}, {name})\n' + ) + header.append(f"typedef hmath_value hmath_graph_{snake(name)}_object;\n") + if name not in names: + mappings.append( + { + "symbol": module + "." + name, + "c": [f"hmath_graph_{snake(name)}_object"], + "python": "hmath.graph." + name, + "specializations": ["original concrete type"], + } + ) + for operation, entry in enumerate(entries): + pieces = split_top(entry["signature"], "->") + arguments, result = pieces[:-1], pieces[-1] + checked = result.startswith("Either MathError ") + result = result.removeprefix("Either MathError ") + specs = [type_spec(a) for a in arguments] + type_spec(result) + name = snake(entry["name"]) + symbol = "hmath_graph_" + name + source = entry["module"] + "." + entry["name"] + args = argument_names(entry, len(arguments)) + heuristic = entry["name"] == "aStar" + declaration = ["hmath_context *context"] + for i in range(len(args)): + if heuristic and i == 1: + declaration += ["hmath_graph_heuristic heuristic", "void *userdata"] + else: + declaration.append("const hmath_value *" + args[i]) + declaration.append("hmath_value **out") + prototype = f"hmath_status {symbol}(\n " + ",\n ".join(declaration) + ")" + header.append( + f"/* {source} :: {entry['signature']} */\nHMATH_API {prototype};\n" + ) + vals = [a for i, a in enumerate(args) if not (heuristic and i == 1)] + c.append(prototype + " {\n") + c.append( + " if (!out" + + "".join(" || !" + a for a in vals) + + (" || !heuristic" if heuristic else "") + + ')\n return hm_error(HMATH_INVALID_ARGUMENT, "NULL Graph argument");\n' + ) + c.append( + " hmath_value *temporary = NULL;\n hmath_status status = hm_value_begin(context, &temporary);\n if (status)\n return status;\n" + ) + c.append( + " void *arguments[] = {" + + ", ".join("hm_value_stable(" + a + ")" for a in vals) + + "};\n" + ) + c.append( + f" int code = hm_graph_apply({operation}, arguments, {len(vals)}, " + + ("heuristic, userdata" if heuristic else "NULL, NULL") + + ", &temporary->stable);\n return hm_value_finish(temporary, code, out);\n}\n" + ) + pattern = ", ".join("v" + a for a in vals) + hs.append(f" ({operation}, [{pattern}]) -> do\n") + for i, a in enumerate(args): + if heuristic and i == 1: + hs.append( + f" let {a} = heuristicFunction callback userdata\n" + ) + else: + hs.append(f" {a} <- unwire v{a}\n") + call = f"G.{entry['name']} " + " ".join(args) + hs.append( + " checked (" + + (call if checked else "Right (" + call + ")") + + ") (\\result_value -> publish (wire result_value) out)\n" + ) + py.append( + f'\n\ndef {name}({", ".join(args)}):\n """{source} :: {entry["signature"]}."""\n' + ) + if heuristic: + py.append(" return _astar(" + ", ".join(args) + ")\n") + else: + py.append( + f" return _invoke({symbol!r}, {specs!r}, [{', '.join(args)}])\n" + ) + docs.append( + f"## `{name}`\n\n`graph.{name}({', '.join(args)})`\n\n{source_prose(entry)}\n\nOriginal: [`{source}`](haskell/{entry['module'].replace('.', '-')}.md#v:{entry['name']}). Argument order and the full contract are defined there; the original type is:\n\n```haskell\n{entry['signature']}\n```\n\n```c\n{prototype};\n```\n\n" + ) + if source not in numeric: + mappings.append( + { + "symbol": source, + "c": [symbol], + "python": "hmath.graph." + name, + "specializations": ["original concrete types"], + } + ) + hs.append(' _ -> invalid "Graph operation arity or identifier differs"\n') + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_graph.h": "".join(header), + "cbits/graph_bindings.c": "".join(c), + "src/HMath/FFI/Graph.hs": "".join(hs), + "bindings/python/_hmath_native/graph.py": "".join(py), + "docs/reference/graph-bindings.md": "".join(docs), + "bindings/schema/graph-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, text in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != text: + parser.exit(1, "Stale Graph binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_image_bindings.py b/tools/generate_image_bindings.py new file mode 100644 index 0000000..324283b --- /dev/null +++ b/tools/generate_image_bindings.py @@ -0,0 +1,679 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate direct Haskell Image bindings and a lossless Tensor Double bridge.""" + +import argparse +import json +import re +from pathlib import Path + +from generate_graph_bindings import snake, source_prose, type_spec + +ROOT = Path(__file__).resolve().parent.parent +TYPES = { + "Image": ("HMath.Image.Core", "C", 160, "Image"), + "Tensor Double": ("HMath.Tensor", "T", 161, "TensorDouble"), + "Boundary": ("HMath.Image.Core", "C", 162, "Boundary"), + "GradientOperator": ("HMath.Image.Filter", "F", 163, "GradientOperator"), + "Morphology": ("HMath.Image.Filter", "F", 164, "Morphology"), + "TemplateMetric": ("HMath.Image.Measure", "M", 165, "TemplateMetric"), + "Interpolation": ("HMath.Image.Spatial", "S", 166, "Interpolation"), + "Connectivity": ("HMath.Image.Spatial", "S", 167, "Connectivity"), + "ColorSpace": ("HMath.Image.Color", "K", 168, "ColorSpace"), +} +SPECS = [] + + +def add(module, name, args, result, checked=True): + SPECS.append( + { + "module": module, + "name": name, + "args": args, + "result": result, + "checked": checked, + "signature": " -> ".join( + [typ for _, typ in args] + + [("Either MathError " if checked else "") + result] + ), + } + ) + + +for name, args, result, checked in [ + ( + "image", + [("shape", "[Int]"), ("channels", "Int"), ("values", "[Double]")], + "Image", + True, + ), + ("fromTensor", [("tensor", "Tensor Double")], "Image", True), + ("toTensor", [("image", "Image")], "Tensor Double", True), + ("imageShape", [("image", "Image")], "[Int]", False), + ("imageChannels", [("image", "Image")], "Int", False), + ("imageValues", [("image", "Image")], "[Double]", False), + ("pixel", [("image", "Image"), ("coordinates", "[Int]")], "[Double]", True), + ("channel", [("index", "Int"), ("image", "Image")], "Image", True), + ("combineChannels", [("images", "[Image]")], "Image", True), + ( + "mapImage", + [("function", "(Double -> Double)"), ("image", "Image")], + "Image", + True, + ), + ( + "zipImage", + [("function", "(Double -> Double -> Double)"), ("a", "Image"), ("b", "Image")], + "Image", + True, + ), + ( + "normalize", + [("low", "Double"), ("high", "Double"), ("image", "Image")], + "Image", + True, + ), + ("brightness", [("offset", "Double"), ("image", "Image")], "Image", True), + ( + "contrast", + [("factor", "Double"), ("pivot", "Double"), ("image", "Image")], + "Image", + True, + ), + ("gamma", [("power", "Double"), ("image", "Image")], "Image", True), + ("Constant", [("fill", "Double")], "Boundary", False), + ("Clamp", [], "Boundary", False), + ("Reflect", [], "Boundary", False), + ("Wrap", [], "Boundary", False), +]: + add("HMath.Image.Core", name, args, result, checked) +for name, args, result, checked in [ + ( + "convolve", + [ + ("boundary", "Boundary"), + ("shape", "[Int]"), + ("weights", "[Double]"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "correlate", + [ + ("boundary", "Boundary"), + ("shape", "[Int]"), + ("weights", "[Double]"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "gaussianBlur", + [ + ("boundary", "Boundary"), + ("sigma", "Double"), + ("radius", "Int"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "boxBlur", + [("boundary", "Boundary"), ("radius", "Int"), ("image", "Image")], + "Image", + True, + ), + ( + "medianBlur", + [("boundary", "Boundary"), ("radius", "Int"), ("image", "Image")], + "Image", + True, + ), + ( + "bilateralBlur", + [ + ("boundary", "Boundary"), + ("sigma_space", "Double"), + ("sigma_range", "Double"), + ("radius", "Int"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "sharpen", + [ + ("boundary", "Boundary"), + ("amount", "Double"), + ("sigma", "Double"), + ("radius", "Int"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "gradient", + [ + ("method", "GradientOperator"), + ("boundary", "Boundary"), + ("image", "Image"), + ], + "(Image, Image, Image, Image)", + True, + ), + ("laplacian", [("boundary", "Boundary"), ("image", "Image")], "Image", True), + ( + "canny", + [ + ("boundary", "Boundary"), + ("sigma", "Double"), + ("radius", "Int"), + ("low", "Double"), + ("high", "Double"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "morphology", + [ + ("operation", "Morphology"), + ("boundary", "Boundary"), + ("shape", "[Int]"), + ("mask", "[Bool]"), + ("image", "Image"), + ], + "Image", + True, + ), + ( + "morphologicalGradient", + [ + ("boundary", "Boundary"), + ("shape", "[Int]"), + ("mask", "[Bool]"), + ("image", "Image"), + ], + "Image", + True, + ), + ("validateBoundary", [("boundary", "Boundary")], "()", True), + ("scalar2D", [("image", "Image")], "(Int, Int)", True), + ("windowOffsets", [("radius", "Int"), ("image", "Image")], "[[Int]]", True), +]: + add("HMath.Image.Filter", name, args, result, checked) +for name in ["Sobel", "Prewitt", "Scharr"]: + add("HMath.Image.Filter", name, [], "GradientOperator", False) +for name in ["Erosion", "Dilation", "Opening", "Closing"]: + add("HMath.Image.Filter", name, [], "Morphology", False) +for name, args, result in [ + ("histogram", [("bins", "Int"), ("image", "Image")], "[[Int]]"), + ("equalizeHistogram", [("bins", "Int"), ("image", "Image")], "Image"), + ( + "clahe", + [ + ("bins", "Int"), + ("tiles", "(Int, Int)"), + ("clip_limit", "Double"), + ("image", "Image"), + ], + "Image", + ), + ("threshold", [("level", "Double"), ("image", "Image")], "Image"), + ("otsu", [("bins", "Int"), ("image", "Image")], "([Double], Image)"), + ( + "adaptiveThreshold", + [ + ("gaussian", "Bool"), + ("boundary", "Boundary"), + ("radius", "Int"), + ("offset", "Double"), + ("image", "Image"), + ], + "Image", + ), +]: + add("HMath.Image.Histogram", name, args, result) +for name, args, result in [ + ( + "templateMatch", + [("metric", "TemplateMetric"), ("needle", "Image"), ("haystack", "Image")], + "Image", + ), + ( + "rawMoment", + [("row_order", "Int"), ("column_order", "Int"), ("image", "Image")], + "Double", + ), + ( + "centralMoment", + [("row_order", "Int"), ("column_order", "Int"), ("image", "Image")], + "Double", + ), + ("imageCentroid", [("image", "Image")], "(Double, Double)"), + ("integralImage", [("image", "Image")], "Image"), + ( + "rectangleSum", + [("origin", "(Int, Int)"), ("extent", "(Int, Int)"), ("image", "Image")], + "[Double]", + ), + ("meanSquaredError", [("a", "Image"), ("b", "Image")], "Double"), + ( + "peakSignalToNoise", + [("data_range", "Double"), ("a", "Image"), ("b", "Image")], + "Double", + ), + ( + "structuralSimilarity", + [("data_range", "Double"), ("window", "Int"), ("a", "Image"), ("b", "Image")], + "Double", + ), +]: + add("HMath.Image.Measure", name, args, result) +for name in ["SquaredDifference", "NormalizedCorrelation"]: + add("HMath.Image.Measure", name, [], "TemplateMetric", False) +for name, args, result in [ + ( + "resize", + [ + ("interpolation", "Interpolation"), + ("boundary", "Boundary"), + ("shape", "(Int, Int)"), + ("image", "Image"), + ], + "Image", + ), + ( + "warp", + [ + ("interpolation", "Interpolation"), + ("boundary", "Boundary"), + ("shape", "(Int, Int)"), + ("matrix", "[[Double]]"), + ("image", "Image"), + ], + "Image", + ), + ( + "translate", + [ + ("interpolation", "Interpolation"), + ("boundary", "Boundary"), + ("row_shift", "Double"), + ("column_shift", "Double"), + ("image", "Image"), + ], + "Image", + ), + ( + "rotate", + [ + ("interpolation", "Interpolation"), + ("boundary", "Boundary"), + ("angle", "Double"), + ("image", "Image"), + ], + "Image", + ), + ( + "connectedComponents", + [("connectivity", "Connectivity"), ("image", "Image")], + "(Image, [Int])", + ), + ("distanceTransform", [("spacing", "[Double]"), ("image", "Image")], "Image"), +]: + add("HMath.Image.Spatial", name, args, result) +for name in ["Nearest", "Bilinear", "Bicubic", "Lanczos"]: + add("HMath.Image.Spatial", name, [], "Interpolation", False) +for name in ["AxisConnected", "FullyConnected"]: + add("HMath.Image.Spatial", name, [], "Connectivity", False) +for name, args, result in [ + ( + "convertColor", + [("source", "ColorSpace"), ("destination", "ColorSpace"), ("image", "Image")], + "Image", + ), + ("grayscale", [("source", "ColorSpace"), ("image", "Image")], "Image"), +]: + add("HMath.Image.Color", name, args, result) +for name in ["SRGB", "LinearRGB", "HSV", "HSL", "XYZ", "Lab", "YCbCr"]: + add("HMath.Image.Color", name, [], "ColorSpace", False) +add( + "HMath.Tensor", + "tensor", + [("shape", "[Int]"), ("values", "[Double]")], + "Tensor Double", +) +add("HMath.Tensor", "tensorShape", [("tensor", "Tensor Double")], "[Int]", False) +add("HMath.Tensor", "tensorValues", [("tensor", "Tensor Double")], "[Double]", False) + +HS_PREFIX = """{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE FlexibleInstances #-} +{-# OPTIONS_GHC -Wno-orphans #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_image_bindings.py. +module HMath.FFI.Image where +import Control.Exception (Exception,bracket,catch,evaluate,throwIO) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.FFI.GraphCodec (Wire(..),boxed,unboxed) +import HMath.FFI.Value +import qualified HMath.Image.Core as C +import qualified HMath.Image.Filter as F +import qualified HMath.Image.Histogram as H +import qualified HMath.Image.Measure as M +import qualified HMath.Image.Spatial as S +import qualified HMath.Image.Color as K +import qualified HMath.Tensor as T +import System.IO.Unsafe (unsafePerformIO) + +instance Wire C.Image where + wire image = Opaque 160 0 (length (C.imageValues image)) (mapM_ evaluate (C.imageValues image)) image + unwire = unboxed 160 +instance Wire (T.Tensor Double) where + wire tensor = Opaque 161 0 (length (T.tensorValues tensor)) (mapM_ evaluate (T.tensorValues tensor)) tensor + unwire = unboxed 161 + +data CallbackStatus = CallbackStatus CInt deriving Show +instance Exception CallbackStatus +imageBoundary :: IO CInt -> IO CInt +imageBoundary action = boundary (action `catch` (\\(CallbackStatus status) -> pure status)) +type ImageCallback = Ptr () -> Ptr () -> Ptr (Ptr ()) -> IO CInt +foreign import ccall safe "hm_image_invoke" invokeCallback :: FunPtr ImageCallback -> Ptr () -> StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +{-# NOINLINE callbackFunction #-} +callbackFunction :: FunPtr ImageCallback -> Ptr () -> [Double] -> Double +callbackFunction callback userdata arguments = unsafePerformIO $ do + let input=Tuple (map wire arguments) + forceValue input + pointer <- newStablePtr input + alloca $ \\out -> do + status <- invokeCallback callback userdata pointer out + if status /= 0 then throwIO (CallbackStatus status) else pure () + result <- peek out + bracket (pure result) freeStablePtr (\\value -> deRefStablePtr value >>= unwire) +foreign export ccall "hm_image_clone" clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt +clone input out = imageBoundary $ do + value <- deRefStablePtr input + checked (Right value) (`publish` out) +""" + + +def generate(): + known = { + e["symbol"] + for e in json.loads((ROOT / "bindings/schema/public-api.json").read_text())[ + "symbols" + ] + } + for item in SPECS: + assert item["module"] + "." + item["name"] in known, item + qualifiers = {module: qualifier for _, (module, qualifier, _, _) in TYPES.items()} + qualifiers["HMath.Image.Histogram"] = "H" + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_image_bindings.py. */\n#ifndef HMATH_IMAGE_H\n#define HMATH_IMAGE_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original finite interleaved ND Image algorithms; all coefficients are Double.\n * Inputs are borrowed; successful outputs transfer one immutable Value owner.\n * Outputs stay untouched on failure. Release with hmath_value_release. Live\n * owners pin the runtime. Source MathError/status11 retains its full payload.\n * Source shape/sample/work budgets, boundary policies, color ranges, tie order\n * and unchecked-helper errors remain unchanged. Callbacks are synchronous and\n * deterministic: input is a borrowed tuple of Double values; output transfers\n * one owned Double scalar. Retain input children if keeping them after return.\n * Callbacks may reenter checked APIs and must not unwind through C. */\n", + "typedef hmath_status (*hmath_image_callback)(const hmath_value *arguments,void *userdata,hmath_value **out);\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_image_bindings.py. */\n#include "hmath_image.h"\n#include "value_internal.h"\nextern int hm_image_apply(int,void *const *,size_t,hmath_image_callback,void *,void **);\n', + """extern int hm_image_clone(void *,void **); +int hm_image_invoke(hmath_image_callback callback,void *userdata,void *stable,void **out) { + hmath_value *temporary=NULL,*input=NULL,*output=NULL; + hmath_status status=hm_value_begin(NULL,&temporary); + if(status) { extern void hm_value_free(void *);hm_value_free(stable);return status; } + temporary->stable=stable; + status=hm_value_finish(temporary,0,&input); + if(status)return status; + status=callback(input,userdata,&output); + if(!status && !output)status=hm_error(HMATH_INVALID_ARGUMENT,"NULL Image callback output"); + if(!status)status=(hmath_status)hm_image_clone(output->stable,out); + if(output)hmath_value_release(output); + hmath_value_release(input); + return status; +} +""", + ] + hs = [HS_PREFIX] + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_image_bindings.py; do not edit.\n"""Original Image operations and typed Tensor Double interchange."""\nfrom ._image_base import _invoke\nfrom ._tensor_object import TensorDouble\nfrom ._value import Value, register\nfrom .image_color import linear_to_srgb, srgb_to_linear\n' + ] + docs = [ + "# Image bindings\n\n`from hmath import image` exposes the original ND CPU image algorithms. Storage is spatial row-major with interleaved channels. Intensities have no implicit range; color/histogram functions retain their source restrictions. Haskell algorithms, limits, normalization and errors are unchanged.\n\nC includes `hmath_image.h` and uses [owned structured values](values.md). Inputs are borrowed, outputs transfer one owner and stay untouched on failure. Immutable values support independent readers with their own references. All real values are Double; Python uses floats, lists and tuples matching each signature. Original MathError constructors/payloads remain available. Callbacks are synchronous and deterministic; Python exceptions rethrow after native cleanup. The Image result is fully evaluated before callbacks are released.\n\nImages retain the source rank1..8, channels1..16 and262144-sample limits. Filtering/interpolation retain per-algorithm budgets. No intensity clipping, dtype promotion, coordinate normalization or substituted boundary policy is added. The TensorDouble bridge retains the actual `HMath.Tensor.Tensor Double`; helpers construct it and expose shape/logical values without claiming the remaining Tensor operations.\n\n" + ] + mappings = [] + symbols = [] + exports = ["linear_to_srgb", "srgb_to_linear"] + for typ, (module, qualifier, tag, python) in TYPES.items(): + qualified = ( + qualifier + "." + ("Tensor Double" if typ == "Tensor Double" else typ) + ) + if typ not in ("Image", "Tensor Double"): + hs.append( + "instance Wire " + + qualified + + " where\n wire = boxed " + + str(tag) + + "\n unwire = unboxed " + + str(tag) + + "\n" + ) + header.append( + "typedef hmath_value hmath_image_" + + snake(python) + + "_object; /* kind" + + str(tag) + + " */\n" + ) + if typ != "Tensor Double": + py.append( + "\n\nclass " + + python + + '(Value):\n """Actual immutable ' + + module + + "." + + typ + + ' native owner."""\n\n\nregister(' + + str(tag) + + ", " + + python + + ")\n" + ) + exports.append(python) + source = module + "." + ("Tensor" if typ == "Tensor Double" else typ) + mappings.append( + { + "symbol": source, + "c": ["hmath_image_" + snake(python) + "_object"], + "python": "hmath.image." + python, + "specializations": [ + "Double only" + if typ == "Tensor Double" + else "original concrete type" + ], + } + ) + hs.append( + 'foreign export ccall "hm_image_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr ImageCallback -> Ptr () -> Ptr (StablePtr Value) -> IO CInt\napply :: CInt -> Ptr (StablePtr Value) -> CSize -> FunPtr ImageCallback -> Ptr () -> Ptr (StablePtr Value) -> IO CInt\napply operation inputs arity callback userdata out = imageBoundary $ do\n values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr\n case (operation,values) of\n' + ) + for op, item in enumerate(SPECS): + args = item["args"] + plain = [(name, typ) for name, typ in args if "->" not in typ] + callback = any("->" in typ for _, typ in args) + name = snake(item["name"]) + symbol = "hmath_image_" + name + decl = ["hmath_context *context"] + for arg, typ in args: + decl += ( + ["hmath_image_callback " + arg, "void *userdata"] + if "->" in typ + else ["const hmath_value *" + arg] + ) + prototype = ( + "hmath_status " + + symbol + + "(" + + ", ".join(decl + ["hmath_value **out"]) + + ")" + ) + header.append( + "/* " + + item["module"] + + "." + + item["name"] + + " :: " + + item["signature"] + + " */\nHMATH_API " + + prototype + + ";\n" + ) + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + arg for arg, _ in args) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL Image argument");\n hmath_value *temporary=NULL;\n hmath_status status=hm_value_begin(context,&temporary);\n if(status)return status;\n void *arguments[]={' + + (", ".join("hm_value_stable(" + arg + ")" for arg, _ in plain) or "NULL") + + "};\n return hm_value_finish(temporary,hm_image_apply(" + + str(op) + + ",arguments," + + str(len(plain)) + + "," + + ("function,userdata" if callback else "NULL,NULL") + + ",&temporary->stable),out);\n}\n" + ) + hs.append( + " (" + + str(op) + + ",[" + + ",".join("v" + arg for arg, _ in plain) + + "]) -> do\n" + ) + for arg, typ in plain: + native_type = typ + for token, (_, qualifier, _, _) in sorted( + TYPES.items(), key=lambda item: -len(item[0]) + ): + native_type = re.sub( + r"(? publish (wire result) out)\n" + ) + specs = [type_spec(t, TYPES) for _, t in args] + py.append( + "\n\ndef " + + name + + "(" + + ", ".join(arg for arg, _ in args) + + '):\n """' + + item["module"] + + "." + + item["name"] + + " :: " + + item["signature"] + + '."""\n return _invoke(' + + repr(symbol) + + ", " + + repr(specs) + + ", [" + + ", ".join(arg for arg, _ in args) + + "])\n" + ) + docs.append( + "## `" + + name + + "`\n\n`image." + + name + + "(" + + ", ".join(arg for arg, _ in args) + + ")`\n\n" + + source_prose(item) + + "\n\n```haskell\n" + + item["signature"] + + "\n```\n\n```c\n" + + prototype + + ";\n```\n\n" + ) + mappings.append( + { + "symbol": item["module"] + "." + item["name"], + "c": [symbol], + "python": "hmath.image." + name, + "specializations": [ + "Double only" + if item["module"] == "HMath.Tensor" + else "original concrete types" + ], + } + ) + symbols.append(symbol) + exports.append(name) + hs.append(' _ -> invalid "Image operation identifier or arity differs"\n') + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + py.append("\n\n__all__ = " + json.dumps(sorted(exports), indent=4) + "\n") + return { + "include/hmath_image.h": "".join(header), + "cbits/image.c": "".join(c), + "src/HMath/FFI/Image.hs": "".join(hs), + "bindings/python/_hmath_native/image.py": "".join(py), + "bindings/schema/image-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "bindings/schema/image-symbols.txt": "\n".join(symbols) + "\n", + "docs/reference/image-bindings.md": "".join(docs), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale Image binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_interchange_bindings.py b/tools/generate_interchange_bindings.py new file mode 100644 index 0000000..f1e0f1e --- /dev/null +++ b/tools/generate_interchange_bindings.py @@ -0,0 +1,334 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named adapters for every original public Interchange operation.""" + +import argparse +import json +import re +from pathlib import Path + +from generate_graph_bindings import argument_names, snake, source_prose, split_top + +ROOT = Path(__file__).resolve().parent.parent +TYPES = { + "Array": ("HMath.Interchange.Array", 451), + "InterchangeError": ("HMath.Interchange.Array", 453), + "Limits": ("HMath.Interchange.Array", 457), + "DType": ("HMath.Interchange.Array", 458), + "Endian": ("HMath.Interchange.Array", 459), + "Order": ("HMath.Interchange.Array", 460), + "Compression": ("HMath.Interchange.Compression", 461), + "RawSpec": ("HMath.Interchange.IO", 462), + "MappedArray": ("HMath.Interchange.IO", 465), +} +SPECIAL = { + "elementType", + "getElement", + "putElement", + "fromValues", + "toValues", + "fromMatrix", + "toMatrix", + "fromTensor", + "toTensor", + "mappedValue", + "mappedShape", + "mappedReadBytes", + "withMappedArray", + "runDecoder", +} +OVERRIDES = { + "elementType": (["prototype"], ["Value"]), + "getElement": (["prototype", "endian"], ["Value", "Endian"]), + "putElement": (["prototype", "endian", "value"], ["Value", "Endian", "Value"]), + "fromValues": ( + ["prototype", "limits", "endian", "shape", "values"], + ["Value", "Limits", "Endian", "[Int]", "Value"], + ), + "toValues": (["prototype", "array"], ["Value", "Array"]), + "toMatrix": (["prototype", "array"], ["Value", "Array"]), + "toTensor": (["prototype", "array"], ["Value", "Array"]), + "mappedValue": ( + ["prototype", "mapping", "indices"], + ["Value", "MappedArray", "[Int]"], + ), + "mappedShape": (["mapping"], ["MappedArray"]), + "mappedReadBytes": (["mapping", "offset", "count"], ["MappedArray", "Int", "Int"]), + "withMappedArray": ( + ["limits", "specification", "path", "callback"], + ["Limits", "RawSpec", "String", "(MappedArray -> IO Value)"], + ), + "runDecoder": (["parser", "data"], ["GetProgram", "ByteString"]), +} +AUX = { + "dtype_code": ("__dtype_code", ["dtype"]), + "error_fields": ("__error_fields", ["error"]), + "put_bytes": ("__put_bytes", ["program"]), + "open_handle": ("__open_handle", ["path", "mode"]), + "close_handle": ("__close_handle", ["handle"]), + "seek_handle": ("__seek_handle", ["handle", "whence", "offset"]), + "tell_handle": ("__tell_handle", ["handle"]), + "flush_handle": ("__flush_handle", ["handle"]), + "equal_array": ("__equal_array", ["left", "right"]), +} + + +def normalize(text): + text = re.sub(r"^forall\b.*?\.\s*", "", text) + text = re.sub(r"^Element a\s*=>\s*", "", text) + return ( + text.replace("HMath.Matrix.Matrix a", "Value") + .replace("HMath.Tensor.Tensor a", "Value") + .replace("FilePath", "String") + .replace("MappedArray s", "MappedArray") + ) + + +def spec(text): + text = text.strip() + arrows = split_top(text, "->") + if len(arrows) > 1: + return ["function", *[spec(a) for a in arrows]] + if text.startswith("IO "): + return ["io", spec(text[3:])] + if text.startswith("Either InterchangeError "): + return ["either", spec(text.removeprefix("Either InterchangeError "))] + if text.startswith("Maybe "): + return ["maybe", spec(text[6:])] + if text.startswith("[") and text.endswith("]"): + return ["list", spec(text[1:-1])] + if text.startswith("(") and text.endswith(")"): + fields = split_top(text[1:-1], ",") + if len(fields) > 1: + return ["tuple", *[spec(field) for field in fields]] + return ["unit"] if not fields[0] else spec(text[1:-1]) + if text not in { + *TYPES, + "Value", + "Int", + "Integer", + "Bool", + "String", + "Char", + "ByteString", + "Word32", + "Handle", + "GetProgram", + }: + raise ValueError("unsupported interchange representation: " + text) + return [text] + + +def wrapper(symbol, operation, names): + declaration = ", ".join( + [ + "hmath_context *context", + *["const hmath_value *" + n for n in names], + "hmath_value **out", + ] + ) + prototype = "hmath_status " + symbol + "(" + declaration + ")" + c = ( + prototype + + " {\n const hmath_value *arguments[]={" + + (",".join(names) or "NULL") + + "};\n return invoke(context," + + json.dumps(operation) + + f",arguments,{len(names)},out);\n}}\n" + ) + return prototype, c + + +def generate(): + entries = json.loads( + (ROOT / "bindings/schema/interchange-functions.json").read_text() + )["functions"] + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_interchange_bindings.py. */\n#ifndef HMATH_INTERCHANGE_H\n#define HMATH_INTERCHANGE_H\n#include "hmath_bytes.h"\n#include "hmath_callback.h"\n#include "hmath_interchange_error.h"\n#include "hmath_linear.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original fixed-width array formats, Element dictionaries, IO and scoped\n * mappings. All inputs are borrowed Value handles; each successful output owns\n * one reference. Failure leaves output pointers untouched. Source Left errors\n * return13 with hmath_last_interchange_error, not MathError. Callbacks use the\n * common kind101 tuple-argument protocol and may reenter checked APIs. Mapping\n * reads are valid only during withMappedArray; original retired-capability\n * checks reject reads after exit. Bytes copies can survive that scope.\n * File writes retain original partial-write/encoding-before-write semantics.\n * Typed Element operations take a scalar/Boolean prototype first, selecting\n * exactly one of the original13 fixed-width dictionaries. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; do not edit. */\n#include "hmath_interchange.h"\n#include "value_internal.h"\n#include \nextern int hm_interchange_apply(const char *,void *const *,size_t,void **);\nstatic hmath_status invoke(hmath_context *context,const char *operation,const hmath_value *const *arguments,size_t count,hmath_value **out) {\n if(!out || (count && !arguments))return hm_error(HMATH_INVALID_ARGUMENT,"NULL interchange arguments/output");\n for(size_t i=0;i(size_t)PTRDIFF_MAX/sizeof(void *))return hm_error(HMATH_OVERFLOW,"interchange argument span overflow");\n void **stable=malloc((count?count:1)*sizeof *stable);\n if(!stable)return hm_error(HMATH_ALLOCATION_FAILED,"interchange arguments allocation failed");\n for(size_t i=0;istable);\n free(stable);\n return hm_value_finish(result,code,out);\n}\n' + ] + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_interchange_bindings.py.\nfrom ._interchange_base import (Array,InterchangeError,Limits,DType,Endian,Order,Compression,RawSpec,MappedArray,GetProgram,PutProgram,BinaryHandle,Bytes,_invoke,_element_type,_get_element,_put_element,_from_values,_to_values,_mapped_value)\n" + ] + hs = [] + docs = [ + "# Array interchange\n\nPython uses `from hmath import interchange`; C includes `hmath_interchange.h`. These adapters call the original Haskell array, binary/text/NumPy, compression, streaming and mapped-file functions. Source byte/shape/archive budgets, checksums, metadata, byte order, stride/offset semantics and errors remain unchanged.\n\n", + "Each successful C output owns one [structured value](values.md); inputs are borrowed during the call and failure leaves output pointers untouched. `InterchangeError` uses status13 with its original four-way constructor and full message available through `hmath_last_interchange_error`. Python raises `HMathError` with `interchange_error`. Callbacks may supply the original checked Left by raising `InterchangeError`. Unexpected exceptions abort and are re-raised after cleanup.\n\n", + "ByteString results are owned `Bytes` objects. `bytes(result)` copies; `result.view()` borrows a read-only span retaining an independent reference. C uses `hmath_bytes_data` while retaining the owner. No terminator is implied. Binary/raw preserve IEEE bits; text follows the source policy and does not promise NaN payload preservation. `boxed=True` on scalar/list decoders retains native typed values when Python scalar conversion is undesirable.\n\n", + "Element-polymorphic operations select one original fixed-width instance using a scalar/Boolean prototype in C or `dtype=` in Python. Supported types are Bool8, signed/unsigned8/16/32/64, Float32/64 and Complex64/128. Array dtype and requested result type must match as in Haskell. Matrix/Tensor conversions preserve actual element types; they do not route FP32 through FP64. `get_element` returns the original parser program; `run_decoder` executes the original strict decoder, including trailing-byte checks. `put_element` returns the original Put program and `put_bytes` runs it.\n\n", + "Mapped array access is callback-scoped. A retained mapping capability rejects data reads after scope exit through the original closed-state checks; copied Bytes remain valid. File writes retain the source's IO effects and partial-write behavior. `open_handle`/`close_handle` and seek/tell/flush expose real binary Haskell handles for the original chunked APIs. Handles are shared resources; close them explicitly before releasing their owners.\n\n", + ] + mappings = [] + source_names = {e["module"] + "." + e["name"] for e in entries} + for name, (module, tag) in TYPES.items(): + symbol = "hmath_interchange_" + snake(name) + "_object" + header.append(f"typedef hmath_value {symbol}; /* kind{tag} */\n") + if module + "." + name not in source_names: + mappings.append( + { + "symbol": module + "." + name, + "c": [symbol], + "python": "hmath.interchange." + name, + "specializations": ["original structured type and scoped lifetime"], + } + ) + mappings.append( + { + "symbol": "HMath.Interchange.Array.Element", + "c": [ + "hmath_interchange_value_element_type", + "hmath_interchange_value_get_element", + "hmath_interchange_value_put_element", + ], + "python": "hmath.interchange.Element", + "specializations": ["all13 original fixed-width Element dictionaries"], + } + ) + custom = { + "elementType": 'def element_type(*, dtype="float64"):\n return _element_type(dtype)\n', + "getElement": 'def get_element(endian, *, dtype="float64"):\n return _get_element(endian,dtype)\n', + "putElement": 'def put_element(endian,value, *, dtype="float64"):\n return _put_element(endian,value,dtype)\n', + "fromValues": 'def from_values(limits,endian,shape,values, *, dtype="float64"):\n return _from_values(limits,endian,shape,values,dtype)\n', + "toValues": 'def to_values(array, *, dtype=None, boxed=False):\n return _to_values("to_values",array,dtype,boxed)\n', + "toMatrix": 'def to_matrix(array, *, dtype=None):\n return _to_values("to_matrix",array,dtype,False)\n', + "toTensor": 'def to_tensor(array, *, dtype=None):\n return _to_values("to_tensor",array,dtype,False)\n', + "mappedValue": 'def mapped_value(mapping,indices, *, dtype="float64",boxed=False):\n return _mapped_value(mapping,indices,dtype,boxed)\n', + } + for entry in entries: + normalized = normalize(entry["signature"]) + parts = split_top(normalized, "->") + if entry["name"] in OVERRIDES: + names, types = OVERRIDES[entry["name"]] + else: + names, types = argument_names(entry, len(parts) - 1), parts[:-1] + if entry["name"] == "Limits": + names = [ + "max_bytes", + "max_elements", + "max_rank", + "max_metadata", + "max_archive_entries", + ] + elif entry["name"] == "RawSpec": + names = ["dtype", "endian", "order", "shape"] + elif entry["name"] in ( + "InvalidData", + "Unsupported", + "LimitExceeded", + "InterchangeIOError", + ): + names = ["message"] + specifications = [spec(t) for t in types] + name = snake(entry["name"]) + source = entry["module"] + "." + entry["name"] + symbol = "hmath_interchange_value_" + name + prototype, body = wrapper(symbol, source, names) + header.append( + f"/* {source} :: {entry['signature']} */\nHMATH_API {prototype};\n" + ) + c.append(body) + if entry["name"] not in SPECIAL: + q = { + "Array": "A", + "Binary": "B", + "Compression": "C", + "IO": "I", + "Numpy": "N", + "Text": "T", + }[entry["module"].rsplit(".", 1)[1]] + hs.append(f' "{source}"->apply {q}.{entry["name"]} arguments\n') + if entry["name"] in custom: + py.append("\n\n" + custom[entry["name"]]) + else: + boxed = ", *, boxed=False" if entry["name"] == "runDecoder" else "" + py.append( + f'\n\ndef {name}({", ".join(names)}{boxed}):\n """{source} :: {entry["signature"]}."""\n return _invoke({symbol!r},{specifications!r},[{", ".join(names)}]' + + (",boxed=boxed" if boxed else "") + + ")\n" + ) + mappings.append( + { + "symbol": source, + "c": [symbol], + "python": "hmath.interchange." + name, + "specializations": [ + "all original fixed-width dictionaries where Element-polymorphic; original IO effects and error variants" + ], + } + ) + if entry["name"] in custom: + python_arguments = custom[entry["name"]].split("(", 1)[1].split("):", 1)[0] + else: + python_arguments = ", ".join(names) + if entry["name"] == "runDecoder": + python_arguments += ", *, boxed=False" + docs.append( + f"## `{name}`\n\n`interchange.{name}({python_arguments})`\n\n{source_prose(entry)}\n\nOriginal: [`{source}`](haskell/{entry['module'].replace('.', '-')}.md#v:{entry['name']}). Python keeps the source argument order; Element-polymorphic helpers use `dtype=` instead of a type annotation.\n\n```haskell\n{entry['signature']}\n```\n\n```c\n{prototype};\n```\n\n" + ) + auxiliary_docs = { + "dtype_code": "Return the original DType enumeration code as an integer (Bool8=0 through C128=12).", + "error_fields": "Return an InterchangeError's original constructor code and full message; embedded NUL and Unicode are retained.", + "put_bytes": "Execute the original Put program and return owned Bytes. This does not perform file IO.", + "open_handle": "Open a real binary handle. Modes are rb, wb, ab or r+b; wb truncates and ab appends. IO failures raise the original InterchangeIOError. Close the shared resource explicitly before releasing its value owner.", + "close_handle": "Close the shared Haskell handle. Other retained owners refer to that same closed resource. Python BinaryHandle.close() closes the resource and releases its own value reference.", + "seek_handle": "Seek the binary handle with whence 0 (absolute), 1 (relative) or 2 (from end) and an exact integer byte offset. Original handle IO errors become InterchangeIOError.", + "tell_handle": "Return the handle's current byte position as an exact integer.", + "flush_handle": "Flush the original Haskell handle. This has the source hFlush contract and does not promise a filesystem durability barrier.", + "equal_array": "Compare the original Array values, including dtype, endian, layout, metadata and backing bytes. This is structural equality, not a converted numerical comparison.", + } + for name, (operation, names) in AUX.items(): + symbol = "hmath_interchange_value_" + name + prototype, body = wrapper(symbol, operation, names) + header.append(f"HMATH_API {prototype};\n") + c.append(body) + python_specs = ( + [["String"], ["String"]] + if name == "open_handle" + else [["Value"] for _ in names] + ) + py.append( + f"\n\ndef {name}({', '.join(names)}):\n return _invoke({symbol!r},{python_specs!r},[{', '.join(names)}])\n" + ) + docs.append( + f"## `{name}`\n\n`interchange.{name}({', '.join(names)})`\n\n{auxiliary_docs[name]}\n\n```c\n{prototype};\n```\n\n" + ) + py.append("\n\nElement = DType\n") + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + path = ROOT / "src/HMath/FFI/InterchangeAll.hs" + haskell = re.sub( + r"(?<=-- BEGIN GENERATED\n).*?(?=-- END GENERATED)", + "".join(hs), + path.read_text(), + flags=re.DOTALL, + ) + return { + "include/hmath_interchange.h": "".join(header), + "cbits/interchange.c": "".join(c), + "bindings/python/_hmath_native/interchange.py": "".join(py), + "bindings/schema/interchange-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "docs/reference/interchange-bindings.md": "".join(docs), + "src/HMath/FFI/InterchangeAll.hs": haskell, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, text in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != text: + parser.exit(1, "Stale interchange binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_linear_bindings.py b/tools/generate_linear_bindings.py new file mode 100644 index 0000000..d2c549b --- /dev/null +++ b/tools/generate_linear_bindings.py @@ -0,0 +1,1362 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate original-operation adapters for the public linear algebra domains.""" + +import argparse +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +MODULES = { + "HMath.Vector": ("V", "vector"), + "HMath.Matrix.Advanced": ("A", "matrix_advanced"), + "HMath.Matrix.Decomposition": ("D", "decomposition"), + "HMath.Matrix.Iterative": ("I", "iterative"), + "HMath.Matrix.LAPACK": ("L", "lapack"), + "HMath.Sparse": ("S", "sparse"), + "HMath.Sparse.Spectral": ("P", "sparse_spectral"), + "HMath.Backend": ("B", "backend"), +} +ALIASES = { + "M.Matrix": "Matrix", + "LU.LU": "LU", + "QR.QR": "QR", + "L.SVD": "SVD", + "L.Eigen": "Eigen", + "FilePath": "String", +} + + +def snake(name): + return re.sub( + r"([a-z0-9])([A-Z])", r"\1_\2", re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + ).lower() + + +def split_top(text, sep): + depth = 0 + start = 0 + out = [] + i = 0 + while i < len(text): + if text[i] in "([": + depth += 1 + elif text[i] in ")]": + depth -= 1 + if depth == 0 and text.startswith(sep, i): + out.append(text[start:i].strip()) + i += len(sep) + start = i + else: + i += 1 + return out + [text[start:].strip()] + + +def parse_type(text): + text = " ".join(text.split()) + for old, new in ALIASES.items(): + text = re.sub(r"\b" + re.escape(old) + r"\b", new, text) + if text.startswith("[") and text.endswith("]"): + return ["list", parse_type(text[1:-1])] + if text.startswith("(") and text.endswith(")"): + inner = text[1:-1] + if not inner: + return ["unit"] + parts = split_top(inner, ",") + if len(parts) > 1: + return ["tuple", *[parse_type(x) for x in parts]] + parts = split_top(inner, "->") + if len(parts) > 1: + return ["function", *[parse_type(x) for x in parts]] + return parse_type(inner) + parts = [x for x in split_top(text, " ") if x] + if len(parts) > 1: + return [parts[0], *[parse_type(x) for x in parts[1:]]] + if not text: + raise ValueError("empty type") + return [text] + + +def signatures(): + known = { + x["symbol"] + for x in json.loads((ROOT / "bindings/schema/public-api.json").read_text())[ + "symbols" + ] + } + entries = [] + types = {} + fields_by_type = {} + for module, (alias, namespace) in MODULES.items(): + raw = (ROOT / "src" / (module.replace(".", "/") + ".hs")).read_text() + source = re.sub(r"\{-.*?-\}", "", raw, flags=re.DOTALL) + source = re.sub(r"--[^\n]*", "", source) + # Ordinary and shared signatures stop before a new top-level declaration. + for match in re.finditer( + r"^(\w+(?:\s*,\s*\w+)*)\s*::\s*([^\n]*(?:\n[ \t]+[^\n]*)*)", + source, + re.MULTILINE, + ): + names = re.findall(r"\w+", match[1]) + signature = " ".join(match[2].split()) + if not signature: + continue + constraints = "" + signature = re.sub(r"^forall\s+[^.]+\.\s*", "", signature) + if "=>" in signature: + constraints, signature = signature.split("=>", 1) + parts = split_top(signature.strip(), "->") + for name in names: + if module + "." + name not in known: + continue + entries.append( + { + "module": module, + "name": name, + "args": [parse_type(p) for p in parts[:-1]], + "result": parse_type(parts[-1]), + "constraints": constraints.strip(), + "signature": signature.strip(), + "constructor": False, + } + ) + for match in re.finditer( + r"^(?:data|newtype)\s+(\w+)([^=\n]*)(?:\n[ \t]+)?=\s*([^\n]*(?:\n[ \t]+[^\n]*)*)", + source, + re.MULTILINE, + ): + name = match[1] + if module + "." + name not in known: + continue + params = re.findall(r"\b[a-z]\b", match[2]) + if name == "FixedVector": + params = ["n", "a"] + types[name] = { + "module": module, + "alias": alias, + "namespace": namespace, + "name": name, + "params": params, + } + body = re.sub(r"\s+deriving\s*\(.*", "", match[3], flags=re.DOTALL).strip() + fields = [] + if "{" in body: + constructor = body.split("{", 1)[0].strip() + data = body.split("{", 1)[1].rsplit("}", 1)[0] + for field in split_top(data, ","): + fname, ftype = field.split("::", 1) + fields.append((fname.strip(), parse_type(ftype))) + constructors = [(constructor, [typ for _, typ in fields])] + for fname, ftype in fields: + entries.append( + { + "module": module, + "name": fname, + "args": [[name, *[[p] for p in params]]], + "result": ftype, + "constraints": "", + "signature": name + " -> field", + "constructor": False, + } + ) + else: + constructors = [] + for part in split_top(body, "|"): + tokens = [x for x in split_top(part, " ") if x] + if tokens: + constructors.append( + (tokens[0], [parse_type(x) for x in tokens[1:]]) + ) + fields_by_type[name] = fields + for cname, args in constructors: + if module + "." + cname not in known: + continue + header = raw.split(") where", 1)[0] + if not re.search(r"\b" + re.escape(name) + r"\s*\(\.\.\)", header): + continue + entries.append( + { + "module": module, + "name": cname, + "args": args, + "result": [name, *[[p] for p in params]], + "constraints": "", + "signature": "constructor", + "constructor": True, + } + ) + keys = [x["module"] + "." + x["name"] for x in entries] + if len(keys) != len(set(keys)): + raise ValueError( + "duplicate source function/field/constructor: " + + str([x for x in set(keys) if keys.count(x) > 1]) + ) + hidden = [ + key + for key in known + if key.rsplit(".", 1)[0] in MODULES + and key not in keys + and key.rsplit(".", 1)[-1] not in types + ] + return entries, types, fields_by_type, sorted(hidden) + + +# A representation compiler; it never emits arithmetic/algorithm loops. +_COUNTER = 0 + + +def fresh(stem): + global _COUNTER + _COUNTER += 1 + return stem + str(_COUNTER) + + +def hs_type(spec, types): + head, *args = spec + if head == "list": + return "[" + hs_type(args[0], types) + "]" + if head == "tuple": + return "(" + ",".join(hs_type(x, types) for x in args) + ")" + if head == "unit": + return "()" + if head == "function": + return "(" + " -> ".join(hs_type(x, types) for x in args) + ")" + prefix = { + "Matrix": "M.Matrix", + "LU": "LU.LU", + "QR": "QR.QR", + "MathError": "E.MathError", + }.get(head) + if head in types: + prefix = types[head]["alias"] + "." + head + return ( + "(" + + (prefix or head) + + (" " + " ".join(hs_type(x, types) for x in args) if args else "") + + ")" + ) + + +def witness(spec): + if spec == ["a"]: + return "w" + if spec == ["Complex", ["a"]]: + return "cw" + return { + ("Double",): "SDouble", + ("Float",): "SFloat", + ("Rational",): "SRational", + ("Integer",): "SInteger", + ("Complex", ("Double",)): "SComplexDouble", + ("Complex", ("Float",)): "SComplexFloat", + }.get(tuple(tuple(x) if isinstance(x, list) else x for x in spec)) + + +def decode_expr(spec, value, types): + head, *args = spec + if head == "list": + item = fresh("item") + return ( + "X.asList " + + value + + " >>= mapM (\\" + + item + + " -> " + + decode_expr(args[0], item, types) + + ")" + ) + if head == "tuple": + items = fresh("items") + names = [fresh("part") for _ in args] + ctor = "(" + "," * (len(args) - 1) + ")" + expr = ( + ctor + + " <$> " + + ( + " <*> ".join( + "(" + decode_expr(s, n, types) + ")" for s, n in zip(args, names) + ) + ) + ) + return ( + "(X.asTuple " + + str(len(args)) + + " " + + value + + " >>= \\" + + items + + " -> case " + + items + + " of { [" + + ",".join(names) + + "] -> " + + expr + + '; _ -> X.invalid "tuple arity differs" })' + ) + if head == "Maybe": + return ( + "(case " + + value + + " of { X.None -> pure Nothing; _ -> Just <$> (" + + decode_expr(args[0], value, types) + + ") })" + ) + if head == "Matrix": + return "asMatrix " + value + if head in types: + return ( + "unbox " + + repr(types[head]["module"] + "." + head).replace("'", '"') + + " " + + value + ) + if head == "a" or head in ("Double", "Float", "Integer", "Rational", "Complex"): + return "X.asScalar " + value + if head == "Int": + return "X.asIndex " + value + if head == "Bool": + return "X.asBoolean " + value + if head == "String": + return "X.asText " + value + raise ValueError("no decoder " + repr(spec)) + + +def encode_expr(spec, value, types): + head, *args = spec + if head == "Either": + result = fresh("_result") + return ( + "source " + + value + + " >>= \\" + + result + + " -> " + + encode_expr(args[1], result, types) + ) + if head == "IO": + result = fresh("_result") + return value + " >>= \\" + result + " -> " + encode_expr(args[0], result, types) + if head == "list": + item = fresh("item") + return ( + "X.List <$> mapM (\\" + + item + + " -> " + + encode_expr(args[0], item, types) + + ") " + + value + ) + if head == "tuple": + names = [fresh("part") for _ in args] + return ( + "(\\(" + + ",".join(names) + + ") -> X.Tuple <$> sequence [" + + ",".join(encode_expr(s, n, types) for s, n in zip(args, names)) + + "]) " + + value + ) + if head == "Maybe": + item = fresh("item") + return ( + "(case " + + value + + " of {Nothing -> pure X.None;Just " + + item + + " -> " + + encode_expr(args[0], item, types) + + "})" + ) + if head == "Matrix": + w = witness(args[0]) + if not w: + raise ValueError("matrix witness " + repr(spec)) + return "pure (X.Dense (X.SomeMatrix " + w + " " + value + "))" + if head in types: + t = types[head] + return "encode" + head + (" w" if "a" in t["params"] else "") + " " + value + if head in ("LU", "QR"): + return "encodeLegacy" + head + " " + value + w = witness(spec) + if w: + return "pure (X.Scalar " + w + " " + value + ")" + if head == "Int": + return "pure (X.Index " + value + ")" + if head == "Bool": + return "pure (X.Boolean " + value + ")" + if head == "String": + return "pure (X.Text " + value + ")" + if head == "unit": + return "pure X.None" + raise ValueError("no encoder " + repr(spec)) + + +def source_prose(entry): + source = (ROOT / "src" / (entry["module"].replace(".", "/") + ".hs")).read_text() + match = re.search(r"^[ \t]*(?:pattern[ \t]+)?" + re.escape(entry["name"]) + r"\s*::", source, re.MULTILINE) + if match: + before = source[: match.start()].rstrip() + if before.endswith("-}"): + start = before.rfind("{- |") + if start >= 0: + return " ".join(before[start + 4 : -2].replace("@", "`").split()) + lines = [] + for line in reversed(before.splitlines()): + line = line.lstrip() + if not line.startswith("--"): + break + lines.insert(0, line.removeprefix("--").removeprefix(" | ").strip()) + if lines: + return " ".join(lines).replace("@", "`") + if entry["constructor"]: + return "Construct the original public variant; positional fields retain their exact source types and order." + return "Read the original immutable public field; no numerical conversion is performed." + + +def generic_entry(entry): + def variable(spec): + return spec in (["a"], ["b"], ["c"]) or any( + variable(x) for x in spec[1:] if isinstance(x, list) + ) + + return any(variable(x) for x in entry["args"] + [entry["result"]]) + + +def c_symbol(entry): + namespace = MODULES[entry["module"]][1] + return ( + "hmath_linear_" + + namespace + + "_" + + ("new_" if entry["constructor"] else "") + + snake(entry["name"]) + ) + + +def codec_haskell(types, fields, entries): + out = [ + """{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_linear_bindings.py. Representation/lifetime only. +module HMath.FFI.LinearCodec where +import Control.Exception (bracket,evaluate,throwIO) +import Data.Dynamic (Dynamic,toDyn,fromDynamic) +import Data.Typeable (Typeable,cast) +import Data.Proxy (Proxy(..)) +import Data.Complex (Complex) +import Foreign +import Foreign.C +import GHC.TypeLits (KnownNat,SomeNat(..),someNatVal) +import qualified HMath.Error as E +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as LU +import qualified HMath.Matrix.QR as QR +import qualified HMath.FFI.Matrix as Legacy +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.Coefficient +import HMath.FFI.MathError +import qualified HMath.FFI.TensorCodec as TensorCodec +""" + ] + for module, (alias, _namespace) in MODULES.items(): + if any(t["module"] == module for t in types.values()): + out.append("import qualified " + module + " as " + alias + "\n") + out.append(""" +data Envelope=Envelope String Dynamic (IO X.Value) +opaque :: Typeable a => String -> Int -> a -> IO () -> IO X.Value -> X.Value +opaque name dtype payload force view=X.Opaque 100 dtype 0 force (Envelope name (toDyn payload) view) +unbox :: forall a. Typeable a => String -> X.Value -> IO a +unbox expected (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope actual value _) | actual==expected -> maybe (X.invalid "linear object coefficient/type differs") pure (fromDynamic value) + _ -> X.invalid "linear object subtype differs" +unbox _ _=X.invalid "expected linear object" +objectName :: X.Value -> IO String +objectName (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope name _ _) -> pure name + _ -> X.invalid "invalid linear envelope" +objectName _=X.invalid "expected linear object" +objectParts :: X.Value -> IO X.Value +objectParts (X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope _ _ view) -> view + _ -> X.invalid "invalid linear envelope" +objectParts _=X.invalid "expected linear object" +asMatrix :: forall a. Coefficient a => X.Value -> IO(M.Matrix a) +asMatrix (X.Dense(X.SomeMatrix _ matrix))=maybe (X.invalid "matrix coefficient types differ") pure (cast matrix) +asMatrix _=X.invalid "expected Matrix" +withWitness :: X.Value -> (forall a. Coefficient a => ScalarType a -> IO X.Value) -> IO X.Value +withWitness (X.Scalar witness _) action=action witness +withWitness _ _=X.invalid "expected scalar coefficient prototype" +source :: Either E.MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +forceFields :: [IO X.Value] -> IO () +forceFields fields=sequence fields >>= mapM_ X.forceValue +fractional :: forall a. Coefficient a => ScalarType a -> (Fractional a => IO X.Value) -> IO X.Value +fractional _ action=case fractionalDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires Fractional coefficients" +realFloat :: forall a. Coefficient a => ScalarType a -> (RealFloat a => IO X.Value) -> IO X.Value +realFloat _ action=case realFloatDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires RealFloat coefficients" +ordered :: forall a. Coefficient a => ScalarType a -> (Ord a => IO X.Value) -> IO X.Value +ordered _ action=case orderingDict(Proxy::Proxy a) of + Just Dict -> action + Nothing -> X.unsupported "original operation requires ordered coefficients" +withComplex :: forall a. Coefficient a => ScalarType a -> (Coefficient(Complex a) => ScalarType(Complex a) -> IO X.Value) -> IO X.Value +withComplex SFloat action=action SComplexFloat +withComplex SDouble action=action SComplexDouble +withComplex _ _=X.unsupported "complex component must retain original Float/Double RealFloat type" +linearBoundary :: IO CInt -> IO CInt +linearBoundary action=Boundary.boundary $ callbackBoundary (\\e -> Boundary.checked(Left e)(const(pure ()))) action + +data SomeFixed a where + SomeFixed :: KnownNat n => V.FixedVector n a -> SomeFixed a +fixedFrom :: forall a. Coefficient a => ScalarType a -> Int -> [a] -> IO X.Value +fixedFrom w count values=case someNatVal(toInteger count) of + Nothing -> X.invalid "fixed dimension cannot be a negative type-level natural" + Just(SomeNat(_::Proxy n)) -> do + result <- source(V.fixedVector values :: Either E.MathError(V.FixedVector n a)) + encodeFixedVector w (SomeFixed result) +""") + for name, t in types.items(): + generic = "a" in t["params"] + objtype = ( + "SomeFixed a" + if name == "FixedVector" + else t["alias"] + "." + name + (" a" if generic else "") + ) + out.append( + "\nencode" + + name + + " :: " + + ("Coefficient a => ScalarType a -> " if generic else "") + + "(" + + objtype + + ") -> IO X.Value\n" + ) + out.append( + "encode" + + name + + (" w" if generic else "") + + ' value=pure(opaque "' + + t["module"] + + "." + + name + + '" ' + + ("(scalarTypeCode w)" if generic else "(-1)") + + " value force view)\n where\n force=" + ) + specs = [] + if fields[name]: + specs = [ + (s, "(" + t["alias"] + "." + f + " value)") for f, s in fields[name] + ] + elif name == "Vector": + specs = [(["list", ["a"]], "(V.vectorValues value)")] + elif name == "Sparse": + specs = [ + ( + ["list", ["tuple", ["Int"], ["Int"], ["a"]]], + "(S.sparseEntries value)", + ) + ] + elif name == "SparseTensor": + specs = [ + ( + ["list", ["tuple", ["list", ["Int"]], ["a"]]], + "(S.sparseTensorEntries value)", + ) + ] + elif name == "SparseLU": + specs = [ + (["Sparse", ["a"]], "(S.sparseLULower value)"), + (["Sparse", ["a"]], "(S.sparseLUUpper value)"), + (["list", ["Int"]], "(S.sparseLUPermutation value)"), + ] + elif name == "SparseQR": + specs = [(["Sparse", ["a"]], "(S.sparseQRUpper value)")] + elif name == "Backend": + specs = [(["BackendInfo"], "(B.backendInfo value)")] + if specs: + out.append( + "forceFields [" + + ",".join(encode_expr(s, v, types) for s, v in specs) + + "]\n" + ) + elif name == "FixedVector": + out.append( + "case value of SomeFixed fixed -> forceFields [" + + encode_expr(["list", ["a"]], "(V.fixedValues fixed)", types) + + "]\n" + ) + elif name == "SparseFormat": + out.append("case value of\n") + for entry in entries: + if entry["constructor"] and entry["result"][0] == "SparseFormat": + variables = [fresh("field") for _ in entry["args"]] + out.append( + " S." + + entry["name"] + + " " + + " ".join(variables) + + " -> forceFields [" + + ",".join( + encode_expr(s, v, types) + for s, v in zip(entry["args"], variables) + ) + + "]\n" + ) + else: + out.append("evaluate value >> pure ()\n") + constructors = [ + e for e in entries if e["constructor"] and e["result"][0] == name + ] + if constructors: + out.append(" view=case value of\n") + for entry in constructors: + variables = [fresh("field") for _ in entry["args"]] + out.append( + " " + + t["alias"] + + "." + + entry["name"] + + " " + + " ".join(variables) + + " -> do\n" + ) + out.append( + " values <- sequence [" + + ",".join( + encode_expr(spec, v, types) + for spec, v in zip(entry["args"], variables) + ) + + "]\n" + ) + out.append( + ' pure(X.Tuple[X.Text "' + + entry["name"] + + '",X.Tuple values])\n' + ) + else: + out.append( + ' view=X.unsupported "original abstract type has no public constructor fields"\n' + ) + + out.append(""" +encodeLegacyLU :: LU.LU Double -> IO X.Value +encodeLegacyLU value=pure(opaque "HMath.Matrix.LU.LU" 0 value (forceFields [pure(X.Dense(X.SomeMatrix SDouble(LU.luLower value))),pure(X.Dense(X.SomeMatrix SDouble(LU.luUpper value)))]) (X.unsupported "abstract LU constructor")) +encodeLegacyQR :: QR.QR Double -> IO X.Value +encodeLegacyQR value=pure(opaque "HMath.Matrix.QR.QR" 0 value (forceFields [pure(X.Dense(X.SomeMatrix SDouble(QR.qrR value)))]) (X.unsupported "abstract QR constructor")) +foreign export ccall "hm_linear_legacy" legacy :: StablePtr X.Value -> Ptr CInt -> Ptr(StablePtr Legacy.Object) -> IO CInt +legacy :: StablePtr X.Value -> Ptr CInt -> Ptr(StablePtr Legacy.Object) -> IO CInt +legacy pointer kind out=linearBoundary $ do + value <- deRefStablePtr pointer + name <- objectName value + case name of + "HMath.Matrix.LU.LU" -> do + result <- unbox name value + Boundary.checked(Right())(const(Legacy.publish(Legacy.L64 result) out >> poke kind 2)) + "HMath.Matrix.QR.QR" -> do + result <- unbox name value + Boundary.checked(Right())(const(Legacy.publish(Legacy.Q64 result) out >> poke kind 3)) + _ -> X.invalid "expected original LU/QR result" +foreign export ccall "hm_linear_clone" clone :: StablePtr X.Value -> Ptr(StablePtr X.Value) -> IO CInt +clone :: StablePtr X.Value -> Ptr(StablePtr X.Value) -> IO CInt +clone pointer out=linearBoundary $ do + value <- deRefStablePtr pointer + Boundary.checked(Right())(const(X.publish value out)) +""") + structural = STRUCTURAL_VECTOR_HS + for index, entry in enumerate(entries): + if entry["module"] == "HMath.Vector": + structural = structural.replace("OP_" + entry["name"] + "_", str(index)) + return "".join(out) + CALLBACK_HS + structural + + +def dispatch_haskell(entries, types): + out = [ + """{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; every operation calls the original Haskell public function. +module HMath.FFI.LinearAll where +import Foreign +import Foreign.C +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as LU +import qualified HMath.Matrix.QR as QR +import Data.Complex (Complex) +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import HMath.FFI.Coefficient +import HMath.FFI.LinearCodec +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +""" + ] + for module, (alias, _ns) in MODULES.items(): + out.append("import qualified " + module + " as " + alias + "\n") + special = {"fixedVector", "fixedValues", "generateMatrix", "zipMatrixWith"} + out.append( + "\ngeneric :: forall a. Coefficient a => ScalarType a -> Int -> [X.Value] -> IO X.Value\ngeneric w operation args=case(operation,args) of\n" + ) + for opcode, entry in enumerate(entries): + if not generic_entry(entry) or entry["name"] in special: + continue + out.append(operation_haskell(opcode, entry, types, generic=True)) + out.append( + ' _ -> X.invalid "unsupported generic linear operation/arity"\n\nconcrete :: Int -> [X.Value] -> IO X.Value\nconcrete operation args=case(operation,args) of\n' + ) + for opcode, entry in enumerate(entries): + if generic_entry(entry) or entry["name"] in special: + continue + out.append(operation_haskell(opcode, entry, types, generic=False)) + out.append( + ' (-1,[value]) -> X.Text <$> objectName value\n (-2,[value]) -> objectParts value\n _ -> X.invalid "unsupported concrete linear operation/arity"\n' + ) + return "".join(out) + special_haskell(entries, types) + + +def operation_haskell(opcode, entry, types, generic): + variables = ["a" + str(i) for i in range(len(entry["args"]))] + wrappers = [] + if "RealFloat" in entry["constraints"]: + wrappers.append("realFloat w $ ") + elif "Fractional" in entry["constraints"]: + wrappers.append("fractional w $ ") + if "Ord " in entry["constraints"] or "Ord a" in entry["constraints"]: + wrappers.append("ordered w $ ") + if entry["name"] in ("hermitianMatrix", "conjugateTranspose"): + wrappers.append("withComplex w $ \\cw -> ") + lines = [ + " (" + + str(opcode) + + ",[" + + ",".join(variables) + + "]) -> " + + "".join(wrappers) + + "do\n" + ] + for variable, spec in zip(variables, entry["args"]): + lines.append( + " " + + variable + + "Value <- (" + + decode_expr(spec, variable, types) + + " :: IO " + + hs_type(spec, types) + + ")\n" + ) + call = ( + "(" + + MODULES[entry["module"]][0] + + "." + + entry["name"] + + " " + + " ".join(x + "Value" for x in variables) + + ")" + ) + # Result annotations fix constructor/result-only generic type variables. + call = "(" + call + " :: " + hs_type(entry["result"], types) + ")" + lines.append(" " + encode_expr(entry["result"], call, types) + "\n") + return "".join(lines) + + +CALLBACK_HS = """ +data Callback=Callback (FunPtr ()) (Ptr ()) +foreign import ccall safe "hm_linear_invoke_callback" + invokeCallback :: FunPtr () -> Ptr () -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> Ptr () -> IO CInt +callbackValue :: X.Value -> X.Value -> IO X.Value +callbackValue (X.Opaque 101 _ _ _ payload) argument=case cast payload of + Just(Callback function userdata) -> do + X.forceValue argument + bracket (newStablePtr argument) freeStablePtr $ \\input -> alloca $ \\out -> withMathErrorWire $ \\wire -> do + status <- invokeCallback function userdata input out wire + if status/=0 then readCallbackFailure status wire >>= throwIO + else peek out >>= \\pointer -> bracket(pure pointer) freeStablePtr deRefStablePtr + Nothing -> X.invalid "invalid linear callback payload" +callbackValue _ _=X.invalid "expected linear callback" +foreign export ccall "hm_linear_callback" createCallback :: FunPtr () -> Ptr () -> Ptr(StablePtr X.Value) -> IO CInt +createCallback :: FunPtr () -> Ptr () -> Ptr(StablePtr X.Value) -> IO CInt +createCallback pointer userdata out=linearBoundary $ Boundary.checked(Right()) $ const $ X.publish (X.Opaque 101 (-1) 0 (pure()) (Callback pointer userdata)) out +""" + + +def special_haskell(entries, types): + opcode = {e["name"]: i for i, e in enumerate(entries)} + return ( + """ +{-# NOINLINE generateCallback #-} +generateCallback :: Coefficient a => X.Value -> Int -> Int -> a +generateCallback callback row column=unsafePerformIO $ callbackValue callback (X.Tuple[X.Index row,X.Index column]) >>= X.asScalar +{-# NOINLINE zipCallback #-} +zipCallback :: (Coefficient a,Coefficient b,Coefficient c) => ScalarType a -> ScalarType b -> X.Value -> a -> b -> c +zipCallback wa wb callback left right=unsafePerformIO $ callbackValue callback (X.Tuple[X.Scalar wa left,X.Scalar wb right]) >>= X.asScalar +special :: Int -> X.Value -> [X.Value] -> IO X.Value +special operation prototype args=case(operation,args) of + (""" + + str(opcode["fixedVector"]) + + """,[dimension,values]) -> withWitness prototype $ \\(w::ScalarType a) -> do + count <- X.asIndex dimension + xs <- X.asList values >>= mapM X.asScalar + fixedFrom w count xs + (""" + + str(opcode["fixedValues"]) + + """,[value]) -> withWitness prototype $ \\(w::ScalarType a) -> do + fixed <- (unbox "HMath.Vector.FixedVector" value :: IO(SomeFixed a)) + case fixed of SomeFixed f -> X.List . map (X.Scalar w) <$> pure(V.fixedValues f) + (""" + + str(opcode["generateMatrix"]) + + """,[rows,columns,callback]) -> withWitness prototype $ \\(w::ScalarType a) -> do + r <- X.asIndex rows; c <- X.asIndex columns + matrix <- source(A.generateMatrix r c (generateCallback callback) :: Either E.MathError(M.Matrix a)) + pure(X.Dense(X.SomeMatrix w matrix)) + (""" + + str(opcode["zipMatrixWith"]) + + """,[callback,left,right]) -> do + prototypes <- X.asTuple 3 prototype + case prototypes of + [pa,pb,pc] -> withWitness pa $ \\(wa::ScalarType a) -> withWitness pb $ \\(wb::ScalarType b) -> withWitness pc $ \\(wc::ScalarType c) -> do + a <- (asMatrix left :: IO(M.Matrix a)); b <- (asMatrix right :: IO(M.Matrix b)) + matrix <- source(A.zipMatrixWith (zipCallback wa wb callback) a b :: Either E.MathError(M.Matrix c)) + pure(X.Dense(X.SomeMatrix wc matrix)) + _ -> X.invalid "zipMatrixWith requires three coefficient prototypes" + _ -> X.invalid "invalid special linear operation/arity" +foreign export ccall "hm_linear_apply" ffiApply :: CInt -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> StablePtr X.Value -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation prototype pointers count out=linearBoundary $ do + values <- peekArray(fromIntegral count) pointers >>= mapM deRefStablePtr + let op=fromIntegral operation + value <- if op `elem` """ + + repr( + [ + opcode[n] + for n in [ + "fixedVector", + "fixedValues", + "generateMatrix", + "zipMatrixWith", + ] + ] + ) + + """ then do + p <- deRefStablePtr prototype + if structuralVectorInput p values then structuralVectors op p values else special op p values + else if op `elem` """ + + repr([i for i, e in enumerate(entries) if generic_entry(e)]) + + """ then do + p <- deRefStablePtr prototype + if structuralVectorInput p values then structuralVectors op p values else withWitness p (\\w -> generic w op values) + else concrete op values + Boundary.checked(Right())(const(X.publish value out)) +""" + ) + + +def frontend(entries, types, fields): + import keyword + import subprocess + + def fmt(source, name): + fixed = subprocess.run( + [ + "ruff", + "check", + "--select", + "I,RUF022,F401", + "--fix", + "--stdin-filename", + name, + "-", + ], + input=source, + text=True, + capture_output=True, + check=True, + ).stdout + return subprocess.run( + ["ruff", "format", "--stdin-filename", name, "-"], + input=fixed, + text=True, + capture_output=True, + check=True, + ).stdout + + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_linear_bindings.py. */ +#ifndef HMATH_LINEAR_H +#define HMATH_LINEAR_H +#include "hmath_value.h" +#include "hmath_matrix.h" +#include "hmath_error.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Direct original Vector, Matrix advanced/decomposition/iterative/LAPACK, + * Sparse, Sparse.Spectral and Backend API. Values are immutable owned handles; + * Matrix uses Dense kind9, linear records use kind100 plus object_type query, + * and typed callback closures use kind101. Retain inputs for the call and + * release every owned result with hmath_value_release. Outputs remain untouched + * on failure. Generic functions take a typed scalar prototype before original + * arguments, even for empty lists. zip_matrix_with takes a tuple of prototypes + * (inputA,inputB,output). fixed_vector adds a runtime natural dimension that + * reifies the original KnownNat witness. Num/Fractional/Ord/RealFloat instance + * availability, defaults, resource limits, finite checks, ordering and errors + * remain the original Haskell operations. No mandatory native provider. + * Callback inputs borrow a Value; output transfers one owned reference. Source + * pure callbacks abort on nonzero status, preserving status11 MathError wire. + * Callback/userdata must outlive every function/derived object using them. */ +typedef hmath_status (*hmath_linear_callback_fn)(const hmath_value *input,void *userdata,hmath_value **out,hmath_math_error *error); +HMATH_API hmath_status hmath_linear_callback(hmath_context *context,hmath_linear_callback_fn callback,void *userdata,hmath_value **out); +HMATH_API hmath_status hmath_linear_object_type(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_linear_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +/* Convert original Backend LU/QR outputs to existing typed dense owners. */ +HMATH_API hmath_status hmath_linear_export_legacy(hmath_context *context,const hmath_value *value,void **out); +""" + ] + c = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_linear_bindings.py. */ +#include "hmath_linear.h" +#include "value_internal.h" +#include "matrix_internal.h" +#include +extern int hm_linear_apply(int opcode,void *prototype,void *const *args,size_t count,void **out); +extern int hm_linear_callback(hmath_linear_callback_fn callback,void *userdata,void **out); +extern int hm_linear_clone(void *value,void **out); +extern int hm_linear_legacy(void *value,int *kind,void **out); +extern void hm_dense_free(void *value); +""" + ] + py = { + namespace: [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_linear_bindings.py.\n"""Original ' + + module + + ' public operations and owned records."""\nfrom ._linear_base import LinearValue,_invoke,register\n' + ] + for module, (_alias, namespace) in MODULES.items() + } + allnames = {ns: [] for ns in py} + constructor_by_type = { + e["name"]: e for e in entries if e["constructor"] and e["name"] in types + } + for name, t in types.items(): + ns = t["namespace"] + typename = t["module"] + "." + name + allnames[ns].append(name) + h.append( + "typedef hmath_value hmath_linear_" + ns + "_" + snake(name) + "_object;\n" + ) + py[ns].append( + "\nclass " + + name + + '(LinearValue):\n """Original ' + + typename + + ' immutable owner."""\n _source_type=' + + repr(typename) + + "\n" + ) + constructor = constructor_by_type.get(name) + lower = { + "Vector": "vector", + "FixedVector": "fixedVector", + "SparseVector": "sparseVector", + "Sparse": "sparse", + "SparseTensor": "sparseTensor", + }.get(name) + if lower: + constructor = next( + e for e in entries if e["module"] == t["module"] and e["name"] == lower + ) + if constructor: + specs = constructor["args"] + if name == "FixedVector": + specs = [["Int"], ["list", ["a"]]] + names = ( + [snake(f[0]) for f in fields[name]] + if fields[name] + else ["dimension", "values"] + if name == "FixedVector" + else ["values"] + if name == "Vector" + else ["dimension", "entries"] + if name == "SparseVector" + else ["rows", "columns", "entries"] + if name == "Sparse" + else ["shape", "entries"] + if name == "SparseTensor" + else ["value" + str(i) for i in range(len(specs))] + ) + signature = ", ".join(names) + generic = generic_entry(constructor) + py[ns].append( + " def __init__(self, " + + signature + + (", *, dtype=None" if generic else "") + + "):\n" + ) + py[ns].append( + " self._initialize(" + + repr(c_symbol(constructor)) + + ", " + + repr(generic) + + ", " + + repr(specs) + + ", [" + + ", ".join(names) + + "]" + + (", dtype" if generic else "") + + ")\n" + ) + for field, spec in fields[name]: + entry = next( + e for e in entries if e["module"] == t["module"] and e["name"] == field + ) + py[ns].append( + " @property\n def " + + snake(field) + + "(self):\n return _invoke(" + + repr(c_symbol(entry)) + + ", " + + repr(generic_entry(entry)) + + ", " + + repr(entry["args"]) + + ", [self])\n" + ) + py[ns].append("register(" + repr(typename) + ", " + name + ")\n") + mappings = [] + docs = [ + "# Linear algebra bindings\n\nAll operations below call the original Haskell functions. Generic coefficients support standard Float/Double/Integer/Rational/Complex and bounded integral instances where the source constraints permit. No automatic dtype promotion occurs. RealFloat-only operations retain Float/Double; optional native LAPACK routines retain their original Double/ComplexDouble types and explicit unavailable-provider failures.\n\n" + ] + for opcode, entry in enumerate(entries): + generic = generic_entry(entry) + args = entry["args"] + ns = MODULES[entry["module"]][1] + if entry["name"] == "fixedVector": + args = [["Int"], ["list", ["a"]]] + names = [] + for i, spec in enumerate(args): + base = { + "Matrix": "matrix", + "Int": "index", + "Integer": "integer", + "Bool": "flag", + "String": "text", + "function": "function", + "list": "values", + }.get( + spec[0], snake(spec[0]) if spec[0] not in ("a", "b", "c") else "scalar" + ) + if keyword.iskeyword(base): + base += "_" + names.append(base + str(i + 1)) + symbol = c_symbol(entry) + params = ( + ["hmath_context *context"] + + (["const hmath_value *prototype"] if generic else []) + + ["const hmath_value *" + n for n in names] + + ["hmath_value **out"] + ) + proto = "hmath_status " + symbol + "(" + ", ".join(params) + ")" + h.append( + "/* " + + entry["module"] + + "." + + entry["name"] + + " :: " + + entry["signature"] + + " */\nHMATH_API " + + proto + + ";\n" + ) + c.append( + proto + + " {\n if (!out" + + (" || !prototype" if generic else "") + + "".join(" || !" + n for n in names) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear argument");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status;\n' + ) + cargs = "NULL" + if names: + c.append( + " void *args[]={" + + ",".join("hm_value_stable(" + n + ")" for n in names) + + "};\n" + ) + cargs = "args" + c.append( + " return hm_value_finish(result,hm_linear_apply(" + + str(opcode) + + "," + + ("hm_value_stable(prototype)" if generic else "NULL") + + "," + + cargs + + "," + + str(len(names)) + + ",&result->stable),out);\n}\n" + ) + is_record = entry["constructor"] and entry["name"] in types + pname = entry["name"] if is_record else snake(entry["name"]) + if not is_record: + allnames[ns].append(pname) + signature = ", ".join(names) + ( + ", *, dtype=None" + if generic and names + else "*, dtype=None" + if generic + else "" + ) + py[ns].append( + "\ndef " + + pname + + "(" + + signature + + "):\n " + + repr( + source_prose(entry) + + " Call original " + + entry["module"] + + "." + + entry["name"] + + " :: " + + entry["signature"] + ) + + "\n return _invoke(" + + repr(symbol) + + ", " + + repr(generic) + + ", " + + repr(args) + + ", [" + + ", ".join(names) + + "]" + + (", dtype=dtype" if generic else "") + + ")\n" + ) + mappings.append( + { + "symbol": entry["module"] + "." + entry["name"], + "c": [symbol], + "python": "hmath." + ns + "." + pname, + "specializations": [ + "original source type/constraints; standard coefficient witnesses; full public fields/constructors" + ], + } + ) + docs.append( + "## `" + + ns + + "." + + pname + + "`\n\n" + + source_prose(entry) + + "\n\nOriginal signature: `" + + entry["signature"] + + "`. Original constraints: `" + + (entry["constraints"] or "none") + + "`. " + + ( + "Construct the original public record/variant without inventing validation." + if entry["constructor"] + else "Return the original function result and original Either/Maybe failure convention." + ) + + "\n\n```c\n" + + proto + + ";\n```\n\n" + ) + covered = {m["symbol"] for m in mappings} + for name, t in types.items(): + symbol = t["module"] + "." + name + if symbol not in covered: + mappings.append( + { + "symbol": symbol, + "c": [ + "hmath_linear_" + t["namespace"] + "_" + snake(name) + "_object" + ], + "python": "hmath." + t["namespace"] + "." + name, + "specializations": [ + "original owned opaque type with source coefficient type" + ], + } + ) + for name, opcode in [("object_type", -1), ("object_parts", -2)]: + c.append( + "hmath_status hmath_linear_" + + name + + '(hmath_context *context,const hmath_value *value,hmath_value **out) {\n if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear object query");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status;\n void *args[]={hm_value_stable(value)};\n return hm_value_finish(result,hm_linear_apply(' + + str(opcode) + + ",NULL,args,1,&result->stable),out);\n}\n" + ) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + c.append(CALLBACK_C) + result = { + "include/hmath_linear.h": "".join(h), + "cbits/linear.c": "".join(c), + "bindings/schema/linear-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mappings, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "docs/reference/linear-bindings.md": "".join(docs), + } + for ns, parts in py.items(): + parts.append("\n__all__=" + repr(sorted(set(allnames[ns]))) + "\n") + result["bindings/python/_hmath_native/" + ns + ".py"] = fmt( + "".join(parts), ns + ".py" + ) + return result + + +CALLBACK_C = """ +hmath_status hmath_linear_callback(hmath_context *context,hmath_linear_callback_fn callback,void *userdata,hmath_value **out) { + if(!callback || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL linear callback/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_linear_callback(callback,userdata,&result->stable),out); +} +int hm_linear_invoke_callback(hmath_linear_callback_fn callback,void *userdata,void *argument,void **out,hmath_math_error *error) { + hmath_value *input=NULL,*borrowed=NULL,*result=NULL; + hmath_status status=hm_value_begin(NULL,&input); + if(status) return status; + status=hm_value_finish(input,hm_linear_clone(argument,&input->stable),&borrowed); + if(status) return status; + status=callback(borrowed,userdata,&result,error); + if(!status) { + if(!result) { error->message="linear callback returned NULL";error->message_length=29;status=HMATH_INVALID_ARGUMENT; } + else status=(hmath_status)hm_linear_clone(hm_value_stable(result),out); + } + hmath_value_release(result);hmath_value_release(borrowed); + return status; +} +hmath_status hmath_linear_export_legacy(hmath_context *context,const hmath_value *value,void **out) { + if(!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL legacy linear export"); + struct hmath_dense_object *result=calloc(1,sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"legacy linear handle allocation failed"); + hmath_status status=hm_enter(context);if(status) {free(result);return status;} + int kind=0;status=(hmath_status)hm_linear_legacy(hm_value_stable(value),&kind,&result->stable); + if(status) {if(result->stable)hm_dense_free(result->stable);free(result);hm_leave();return status;} + atomic_init(&result->refs,1);result->kind=(unsigned)kind;result->precision=64;*out=result; + return HMATH_OK; +} +""" + + +STRUCTURAL_VECTOR_HS = r''' +-- Non-Num vectors retain actual original structural values and their codec. +data StructuralVector where + StructuralVector :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> V.Vector a -> StructuralVector +data StructuralFixed where + StructuralFixed :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> SomeFixed a -> StructuralFixed +encodeStructuralVector :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> V.Vector a -> X.Value +encodeStructuralVector code write readValue force value=opaque "HMath.Vector.Vector" code (StructuralVector code write readValue force value)(mapM_ force(V.vectorValues value))(X.unsupported "original Vector is abstract") +encodeStructuralFixed :: Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> SomeFixed a -> X.Value +encodeStructuralFixed code write readValue force value=opaque "HMath.Vector.FixedVector" code (StructuralFixed code write readValue force value)(case value of SomeFixed fixed -> mapM_ force(V.fixedValues fixed))(X.unsupported "original FixedVector is abstract") +asStructuralVector :: X.Value -> IO StructuralVector +asStructuralVector=unbox "HMath.Vector.Vector" +asStructuralFixed :: X.Value -> IO StructuralFixed +asStructuralFixed=unbox "HMath.Vector.FixedVector" +structuralVectorValue :: X.Value -> Bool +structuralVectorValue(X.Opaque 100 _ _ _ payload)=case cast payload of + Just(Envelope _ dynamic _) -> case(fromDynamic dynamic::Maybe StructuralVector,fromDynamic dynamic::Maybe StructuralFixed)of + (Just _,_) -> True + (_,Just _) -> True + _ -> False + _ -> False +structuralVectorValue(X.List values)=any structuralVectorValue values +structuralVectorValue _=False +structuralVectorInput :: X.Value -> [X.Value] -> Bool +structuralVectorInput prototype args=structuralVectorValue prototype || any structuralVectorValue args || case prototype of + X.Boolean _ -> True + X.Text _ -> True + X.Opaque 294 _ _ _ _ -> True + _ -> False +withStructuralVector :: X.Value -> [X.Value] -> (forall a. Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> IO X.Value) -> IO X.Value +withStructuralVector prototype args action=case filter structuralVectorValue(prototype:concatMap flatten args) of + first:_ -> do + name <- objectName first + if name=="HMath.Vector.Vector" then do + StructuralVector code write readValue force _ <- asStructuralVector first + action code write readValue force + else do + StructuralFixed code write readValue force _ <- asStructuralFixed first + action code write readValue force + [] -> do + TensorCodec.SomeElement kind <- TensorCodec.element prototype + action(TensorCodec.elementCode kind)(pure . TensorCodec.scalar kind)(TensorCodec.asElement kind)(TensorCodec.forceElement kind) + where + flatten(X.List xs)=concatMap flatten xs + flatten value=[value] +structuralVectors :: Int -> X.Value -> [X.Value] -> IO X.Value +structuralVectors operation prototype args=withStructuralVector prototype args $ \code write readValue force -> case(operation,args)of + (OP_vector_,[values]) -> X.asList values >>= mapM readValue >>= pure . encodeStructuralVector code write readValue force . V.vector + (OP_vectorValues_,[value]) -> do + StructuralVector _ _ _ _ raw <- asStructuralVector value + case cast raw of + Just vector -> X.List <$> mapM write(V.vectorValues vector) + Nothing -> X.invalid "structural Vector element types differ" + (OP_vectorDimension_,[value]) -> do StructuralVector _ _ _ _ raw <- asStructuralVector value;pure(X.Index(V.vectorDimension raw)) + (OP_vectorSlice_,[start,count,value]) -> do + s <- X.asIndex start;n <- X.asIndex count + StructuralVector _ _ _ _ raw <- asStructuralVector value + case cast raw of + Just vector -> encodeStructuralVector code write readValue force <$> source(V.vectorSlice s n vector) + Nothing -> X.invalid "structural Vector element types differ" + (OP_vectorConcat_,[values]) -> do + xs <- X.asList values >>= mapM(\value -> do StructuralVector _ _ _ _ raw <- asStructuralVector value;maybe(X.invalid "structural Vector element types differ")pure(cast raw)) + encodeStructuralVector code write readValue force <$> source(V.vectorConcat xs) + (OP_fixedVector_,[count,values]) -> do + n <- X.asIndex count;xs <- X.asList values >>= mapM readValue + structuralFixedFrom code write readValue force n xs + (OP_fixedValues_,[value]) -> do + StructuralFixed _ _ _ _ raw <- asStructuralFixed value + case cast raw of + Just(SomeFixed fixed) -> X.List <$>mapM write(V.fixedValues fixed) + Nothing -> X.invalid "structural FixedVector element types differ" + _ -> X.unsupported "original vector operation requires a numeric instance" +structuralFixedFrom :: forall a. Typeable a => Int -> (a -> IO X.Value) -> (X.Value -> IO a) -> (a -> IO ()) -> Int -> [a] -> IO X.Value +structuralFixedFrom code write readValue force n xs=case someNatVal(toInteger n)of + Nothing -> X.invalid "fixed dimension must be nonnegative" + Just(SomeNat(_::Proxy k)) -> do + result <- source(V.fixedVector xs::Either E.MathError(V.FixedVector k a)) + pure(encodeStructuralFixed code write readValue force(SomeFixed result)) +''' + + +def outputs(): + global _COUNTER + _COUNTER = 0 + entries, types, fields, missing = signatures() + if missing: + raise ValueError("missing linear source symbols: " + repr(missing)) + result = { + "src/HMath/FFI/LinearCodec.hs": codec_haskell(types, fields, entries), + "src/HMath/FFI/LinearAll.hs": dispatch_haskell(entries, types), + "bindings/schema/linear-functions.json": json.dumps( + {"functions": entries, "types": types, "fields": fields}, indent=2 + ) + + "\n", + } + result.update(frontend(entries, types, fields)) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_machinelearning_bindings.py b/tools/generate_machinelearning_bindings.py new file mode 100644 index 0000000..5a186c3 --- /dev/null +++ b/tools/generate_machinelearning_bindings.py @@ -0,0 +1,465 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate original machine-learning models, diagnostics and typed callbacks.""" + +import argparse +import json +import re +from pathlib import Path + +from generate_graph_bindings import snake, source_prose, split_top + +ROOT = Path(__file__).resolve().parent.parent +SPECIAL = { + "fitEncoder", + "labelEncode", + "labelDecode", + "oneHotEncode", + "stratifiedKFold", +} +PROTOTYPES = {"fitEncoder", "stratifiedKFold"} + + +def metadata(): + return json.loads( + (ROOT / "bindings/schema/machinelearning-functions.json").read_text() + ) + + +def normalize(typ): + typ = typ.strip() + if "=>" in typ: + typ = typ.split("=>", 1)[1].strip() + return re.sub(r"\b(?:a|p)\b", "Value", typ) + + +def spec(typ): + typ = normalize(typ) + arrows = split_top(typ, "->") + if len(arrows) > 1: + return ["function", *[spec(x) for x in arrows]] + if typ.startswith("Either MathError "): + return ["either", spec(typ[17:])] + if typ.startswith("Maybe "): + inner = spec(typ[6:]) + if inner[0] == "maybe": + raise ValueError("nested Maybe needs tagged transport") + return ["maybe", inner] + if typ == "Dataset": + return ["list", ["list", ["Double"]]] + if typ.startswith("["): + return ["list", spec(typ[1:-1])] + if typ.startswith("("): + fields = split_top(typ[1:-1], ",") + if len(fields) > 1: + return ["tuple", *[spec(x) for x in fields]] + return ["unit"] if not fields[0] else spec(fields[0]) + if typ.startswith("Fit "): + return ["Fit"] + if typ.startswith("Encoder "): + return ["Encoder"] + known = {e["name"] for e in metadata()["types"]} | { + "Value", + "Word64", + "Double", + "Int", + "Bool", + } + if typ not in known: + raise ValueError(typ) + return [typ] + + +def native_type(typ): + typ = normalize(typ) + if typ.startswith("Either MathError "): + return "(Either E.MathError " + native_type(typ[17:]) + ")" + if typ.startswith("Maybe "): + return "(Maybe " + native_type(typ[6:]) + ")" + if typ.startswith("["): + return "[" + native_type(typ[1:-1]) + "]" + if typ.startswith("("): + inner = typ[1:-1] + arrows = split_top(inner, "->") + return ( + "(" + " -> ".join(native_type(x) for x in arrows) + ")" + if len(arrows) > 1 + else "(" + ",".join(native_type(x) for x in split_top(inner, ",")) + ")" + ) + if typ == "Value": + return "V.Value" + if typ.startswith("Fit "): + return "(M.Fit " + native_type(typ[4:]) + ")" + if typ.startswith("Encoder "): + return "(M.Encoder " + native_type(typ[8:]) + ")" + return "M." + typ if typ in {e["name"] for e in metadata()["types"]} else typ + + +def names(entry): + types = split_top(normalize(entry["signature"]), "->")[:-1] + result = [] + for typ in types: + base = ( + "function" + if "->" in typ + else "dataset" + if typ == "Dataset" + else "values" + if typ.startswith("[") + else { + "Double": "number", + "Int": "count", + "Bool": "flag", + "Word64": "seed", + "a": "value", + "p": "value", + "Value": "value", + }.get(typ, snake(typ.split()[0])) + ) + if base in {"class", "operator", "template", "union"}: + base += "Value" + name = base + index = 2 + while name in result: + name = base + str(index) + index += 1 + result.append(name) + return result + + +def generate(): + data = metadata() + entries = data["functions"] + types = { + e["name"]: (310 + k, e["module"]) + for k, e in enumerate(e for e in data["types"] if e["name"] != "Dataset") + } + assert types["Fit"][0] == 321 and types["Encoder"][0] == 329 + base = [ + "{-# LANGUAGE FlexibleInstances #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated by tools/generate_machinelearning_bindings.py.\nmodule HMath.FFI.MachineLearning.Types where\nimport HMath.FFI.NumericalCodec (From(..),To(..),box,unbox)\nimport qualified HMath.MachineLearning as M\n" + ] + for typ, (tag, _) in types.items(): + if typ in ("Fit", "Encoder"): + continue + getters = [ + e["name"] + for e in entries + if e["signature"].startswith(typ + " -> ") + and len(split_top(e["signature"], "->")) == 2 + and not e["signature"].split("->")[-1].strip().startswith("Either ") + ] + base.append( + "instance From M." + + typ + + " where from = unbox " + + str(tag) + + "\ninstance To M." + + typ + + " where to value = pure (box " + + str(tag) + + " value [" + + ",".join("to (M." + g + " value)" for g in getters) + + "])\n" + ) + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated by tools/generate_machinelearning_bindings.py.\nmodule HMath.FFI.MachineLearning where\nimport Foreign\nimport Foreign.C\nimport qualified HMath.Error as E\nimport qualified HMath.FFI.Boundary as B\nimport qualified HMath.FFI.NumericalCodec as N\nimport qualified HMath.FFI.Value as V\nimport qualified HMath.FFI.MachineLearning.Codec as C\nimport HMath.FFI.MachineLearning.Types ()\nimport qualified HMath.MachineLearning as M\n" + ] + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_machinelearning_bindings.py. */\n#ifndef HMATH_MACHINELEARNING_H\n#define HMATH_MACHINELEARNING_H\n#include "hmath_linear.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original immutable models/configurations; Dataset is a list of Double rows.\n * Inputs are borrowed; each successful output transfers one owned Value. Error\n * outputs remain untouched; release with hmath_value_release. Source fitting\n * methods, seeds, data limits, validation, tie order, convergence diagnostics\n * and MathError/status11 are unchanged. Calls may share immutable inputs with\n * independent references/output addresses. Live owners pin the runtime.\n * Search callbacks use kind101 checked callbacks with tuple(config,Fold) and\n * Double results; retain function/userdata while referenced. Python preserves\n * callback owners and rethrows unexpected exceptions after native cleanup.\n * Encoder/stratified labels use actual native Ord/Eq dictionaries, with no\n * Double/text conversion. Optional prototype is a representative category\n * solely for otherwise uninferrable empty/optional element types. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_machinelearning_bindings.py. */\n#include "hmath_machinelearning.h"\n#include "value_internal.h"\nextern int hm_ml_apply(int,void *const *,size_t,void *,void **);\n' + ] + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_machinelearning_bindings.py; do not edit.\n"""Original immutable estimators, preprocessing, labels and fit diagnostics."""\nfrom ._numerical_base import _invoke\nfrom ._value import Value, register\n\nDataset = list\n' + ] + mappings = [] + symbols = [] + exports = ["Dataset", "parts", "describe"] + source_names = {e["module"] + "." + e["name"] for e in entries} + docs = [ + "# Machine-learning bindings\n\n`from hmath import machinelearning` exposes the original dense CPU estimators. `Dataset` is a list of finite Double observation rows. No estimator, preprocessing rule, seed, stopping rule, feature ordering or class tie order is substituted. Fit preprocessing inside each training fold; successful fitting preserves the source residual, completed iterations and convergence flag rather than implying an optimum was reached.\n\nC includes `hmath_machinelearning.h`; values follow the [owned structured protocol](values.md). All inputs are borrowed for a synchronous call; outputs transfer one reference and stay untouched on failure. Original MathError/status11 retains full constructor/payload. Immutable owners support independent readers holding their own references; final shutdown is BUSY while owners exist. Python supports close()/context managers.\n\n`fitted(result)` returns an independently owned model/payload. `fit_iterations`, `fit_residual`, and `fit_converged` preserve the original diagnostics. Generic Fit payloads retain their structure and native precision. Search callbacks receive `(configuration, Fold)` as two positional arguments and return a Double loss; original mathematical failures remain checked Left errors, while unexpected Python exceptions rethrow after native cleanup. Retained callback owners travel with returned objects.\n\nCategorical encoders retain actual native Ord/Eq dictionaries, including exact integers/rationals, typed FP32/64, bounded integers, Bool/String, recursive collection labels and supported native domain types. No labels become Double approximations or text keys. Explicit `prototype=` is required when collection/optional element types cannot be inferred; it is a type example, never a training label. Empty input failures retain the original source error. Existing encoders retain their learned native label type for every subsequent operation.\n\n" + ] + for typ, (tag, module) in types.items(): + py.append( + "\n\nclass " + + typ + + '(Value):\n """Actual immutable ' + + module + + "." + + typ + + ' owner."""\n\n\nregister(' + + str(tag) + + ", " + + typ + + ")\n" + ) + header.append( + "typedef hmath_value hmath_ml_" + + snake(typ) + + "_object; /* kind" + + str(tag) + + " */\n" + ) + exports.append(typ) + if module + "." + typ not in source_names: + mappings.append( + { + "symbol": module + "." + typ, + "c": ["hmath_ml_" + snake(typ) + "_object"], + "python": "hmath.machinelearning." + typ, + "specializations": [ + "actual native supported category dictionaries" + if typ == "Encoder" + else "original concrete types" + ], + } + ) + header.append( + "typedef hmath_value hmath_ml_dataset_value; /* list of Double rows */\n" + ) + mappings.append( + { + "symbol": "HMath.MachineLearning.Internal.Dataset", + "c": ["hmath_ml_dataset_value"], + "python": "hmath.machinelearning.Dataset", + "specializations": ["original Double rows"], + } + ) + for helper in ("describe", "parts"): + prototype = ( + "hmath_status hmath_ml_" + + helper + + "(hmath_context *context,const hmath_value *value,hmath_value **out)" + ) + header.append("HMATH_API " + prototype + ";\n") + c.append( + "extern int hm_ml_" + + helper + + "(void *,void **);\n" + + prototype + + ' {\n if(!value||!out)return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML helper argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n return hm_value_finish(result,hm_ml_' + + helper + + "(hm_value_stable(value),&result->stable),out);\n}\n" + ) + symbols.append("hmath_ml_" + helper) + py.append( + "\n\ndef " + + helper + + '(value):\n """Inspect original native state without evaluating text as mathematics."""\n return _invoke("hmath_ml_' + + helper + + '", [["Value"]], [value])\n' + ) + hs.append( + 'foreign export ccall "hm_ml_describe" describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\ndescribe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\ndescribe input out = B.boundary $ do\n value <- deRefStablePtr input\n text <- case V.valueInfo value of\n' + ) + for typ, (tag, _) in types.items(): + if typ in ("Fit", "Encoder"): + continue + hs.append( + " (" + + str(tag) + + ",_,_) -> show <$> (N.from value :: IO M." + + typ + + ")\n" + ) + hs.append( + ' _ -> V.unsupported "use original Fit/Encoder getters for generic payloads"\n B.checked (Right (V.Text text)) (`V.publish` out)\n' + ) + hs.append( + 'foreign export ccall "hm_ml_parts" parts :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nparts :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nparts input out = B.boundary $ do\n value <- deRefStablePtr input\n result <- case V.valueInfo value of\n' + ) + for typ, (tag, _) in types.items(): + ctors = [ + e + for e in entries + if e["name"][0].isupper() + and split_top(e["signature"], "->")[-1] in (typ, typ + " a") + ] + if not ctors: + continue + hs.append( + " (" + + str(tag) + + ",_,_) -> do\n original <- N.from value :: IO " + + ("(M.Fit V.Value)" if typ == "Fit" else "M." + typ) + + "\n case original of\n" + ) + for e in ctors: + fields = [ + "field" + str(k) + for k in range(len(split_top(e["signature"], "->")) - 1) + ] + hs.append( + " M." + + e["name"] + + "".join(" " + f for f in fields) + + " -> do\n fields <- sequence [" + + ",".join("N.to " + f for f in fields) + + "]\n pure (V.Tuple [V.Text " + + json.dumps(e["name"]) + + ",V.Tuple fields])\n" + ) + hs.append( + ' _ -> V.unsupported "original model type has no public constructor"\n B.checked (Right result) (`V.publish` out)\n' + ) + hs.append( + 'foreign export ccall "hm_ml_apply" apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\napply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\napply operation inputs arity prototypePointer out = B.boundary $ do\n values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr\n prototype <- if castStablePtrToPtr prototypePointer == nullPtr then pure V.None else deRefStablePtr prototypePointer\n result <- case operation of\n' + ) + for op, e in enumerate(entries): + source = e["module"] + "." + e["name"] + signature = normalize(e["signature"]) + pieces = split_top(signature, "->") + arguments = pieces[:-1] + args = names(e) + symbol = "hmath_ml_" + snake(e["name"]) + proto = e["name"] in PROTOTYPES + prototype = ( + "hmath_status " + + symbol + + "(" + + ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + a for a in args] + + (["const hmath_value *prototype"] if proto else []) + + ["hmath_value **out"] + ) + + ")" + ) + header.append( + "/* " + + source + + " :: " + + e["signature"] + + " */\nHMATH_API " + + prototype + + ";\n" + ) + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + a for a in args) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL ML argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n void *arguments[]={' + + (",".join("hm_value_stable(" + a + ")" for a in args) or "NULL") + + "};\n return hm_value_finish(result,hm_ml_apply(" + + str(op) + + ",arguments," + + str(len(args)) + + "," + + ("prototype?hm_value_stable(prototype):NULL" if proto else "NULL") + + ",&result->stable),out);\n}\n" + ) + if e["name"] in SPECIAL: + variables = ["v" + str(k) for k in range(len(args))] + hs.append( + " " + + str(op) + + " -> case values of\n [" + + ",".join(variables) + + "] -> C." + + e["name"] + + "".join(" " + v for v in variables) + + (" prototype" if proto else "") + + '\n _ -> V.invalid "category operation arity differs"\n' + ) + else: + native = " -> ".join(native_type(x) for x in pieces) + hs.append( + " " + + str(op) + + " -> N.apply (M." + + e["name"] + + " :: " + + native + + ") values\n" + ) + specs = [spec(a) for a in arguments] + publicargs = args + (["*", "prototype=None"] if proto else []) + py.append( + "\n\ndef " + + snake(e["name"]) + + "(" + + ", ".join(publicargs) + + '):\n """' + + source + + " :: " + + e["signature"] + + '."""\n return _invoke(' + + repr(symbol) + + ", " + + repr(specs + ([["Value"]] if proto else [])) + + ", [" + + ", ".join(args + (["prototype"] if proto else [])) + + "])\n" + ) + docs.append( + "## `" + + snake(e["name"]) + + "`\n\n`machinelearning." + + snake(e["name"]) + + "(" + + ", ".join(publicargs) + + ")`\n\n" + + source_prose(e) + + "\n\n```haskell\n" + + e["signature"] + + "\n```\n\n```c\n" + + prototype + + ";\n```\n\n" + ) + mappings.append( + { + "symbol": source, + "c": [symbol], + "python": "hmath.machinelearning." + snake(e["name"]), + "specializations": [ + "actual native supported Ord/Eq dictionary; no arbitrary user-defined instance claim" + if e["name"] in SPECIAL + else "generic record/configuration payload preserved" + if any(v in e["signature"] for v in ("Fit a", "[p]", " p ")) + else "original concrete types" + ], + } + ) + symbols.append(symbol) + exports.append(snake(e["name"])) + hs.append( + ' _ -> V.invalid "ML operation identifier differs"\n B.checked (Right result) (`V.publish` out)\n' + ) + py.append( + "\n\n__all__ = " + + json.dumps(sorted(exports, key=lambda n: (not n.isupper(), n)), indent=4) + + "\n" + ) + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_machinelearning.h": "".join(header), + "cbits/machinelearning.c": "".join(c), + "src/HMath/FFI/MachineLearning.hs": "".join(hs), + "src/HMath/FFI/MachineLearning/Types.hs": "".join(base), + "bindings/python/_hmath_native/machinelearning.py": "".join(py), + "bindings/schema/machinelearning-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "bindings/schema/machinelearning-symbols.txt": "\n".join(symbols) + "\n", + "docs/reference/machinelearning-bindings.md": "".join(docs), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale ML bindings: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_matrix_bindings.py b/tools/generate_matrix_bindings.py new file mode 100644 index 0000000..24d6258 --- /dev/null +++ b/tools/generate_matrix_bindings.py @@ -0,0 +1,693 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate direct Float/Double adapters for the public dense Matrix, LU and QR APIs.""" + +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +# module, source name, argument kinds, result kind, convention, expression +S = [] + + +def add(mod, name, args, out, mode="either", expr=None): + S.append((mod, name, args, out, mode, expr)) + + +for suffix, mode in [("", "maybe"), ("Checked", "either")]: + add("M", "fromList" + suffix, "iiv", "m", mode) + add("M", "zeroMatrix" + suffix, "ii", "m", mode) + add("M", "diagonal" + suffix, "v", "m", mode) + add("M", "at" + suffix, "mii", "f", mode) + add( + "M", + "sliceMatrix" + suffix, + "iiiim", + "m", + mode, + "M.sliceMatrix" + suffix + " (a0,a1) (a2,a3) a4", + ) + add("M", "reshape" + suffix, "iim", "m", mode) + for name in ["addMatrix", "subtractMatrix", "hadamard", "multiply"]: + add("M", name + suffix, "mm", "m", mode) + add("M", "identity" + suffix, "i", "m", mode) +add("M", "scaleMatrix", "fm", "m", "pure") +add("M", "transposeMatrix", "m", "m", "pure") +add("L", "luDecompose", "m", "l") +add("L", "luDecomposeWithTolerance", "fm", "l") +add("L", "luLower", "l", "m", "pure") +add("L", "luUpper", "l", "m", "pure") +add("L", "luPermutation", "l", "p", "pure") +add("L", "solveLU", "lv", "v") +add("L", "solveMatrixLU", "lm", "m") +add("L", "solve", "mv", "v") +add("L", "solveMatrix", "mm", "m") +add("L", "determinantLU", "l", "f") +add("L", "determinant", "m", "f") +add("L", "inverse", "m", "m") +add("Q", "qrDecompose", "m", "q") +add("Q", "qrDecomposeWithTolerance", "fm", "q") +add("Q", "qrQ", "q", "m", "pure") +add("Q", "qrR", "q", "m", "pure") +add("Q", "qrPermutation", "q", "p", "pure") +add("Q", "qrRank", "q", "i", "pure") +for name in ["applyQ", "applyQT", "solveMatrixQR"]: + add("Q", name, "qm", "m") +add("Q", "solveQR", "qv", "v") +add("Q", "leastSquares", "mv", "v") +add("Q", "leastSquaresMatrix", "mm", "m") +add("Q", "ridgeSolve", "fmv", "v") +add("Q", "ridgeSolveMatrix", "fmm", "m") + +import re + + +def snake(name): + # Preserve acronym runs: solveMatrixLU -> solve_matrix_lu. + return re.sub( + r"([a-z0-9])([A-Z])", r"\1_\2", re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + ).lower() + + +def symbol(mod, name, prec): + return ( + "hmath_dense_" + + ({"M": "", "L": "lu_", "Q": "qr_"}[mod]) + + snake(name) + + "_f" + + str(prec) + ) + + +def parameters(module, name, args): + root = name.removesuffix("Checked") + fixed = { + "fromList": ["rows", "columns", "values"], + "zeroMatrix": ["rows", "columns"], + "diagonal": ["values"], + "at": ["matrix", "row", "column"], + "sliceMatrix": ["start_row", "start_column", "rows", "columns", "matrix"], + "reshape": ["rows", "columns", "matrix"], + "identity": ["order"], + "scaleMatrix": ["scalar", "matrix"], + } + if module == "M" and root in fixed: + return fixed[root] + if name.endswith("WithTolerance"): + return ["tolerance", "matrix"] + if name.startswith("ridge"): + return ["lambda_", "matrix", "rhs"] + return [ + ( + "factors" + if t in "lq" + else "matrix" + if i == 0 + else "rhs" + if module in "LQ" + else "right" + ) + if t in "mlq" + else "rhs" + if t == "v" + else "scalar" + for i, t in enumerate(args) + ] + + +def outputs(): + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_bindings.py. */ +#ifndef HMATH_MATRIX_H +#define HMATH_MATRIX_H +#include "hmath.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Immutable Haskell Matrix/LU/QR objects. Each reference pins the runtime; + * release every object before final shutdown. References may be shared across + * threads while each caller holds a reference. Final release concurrent with + * use is invalid. Match _f32/_f64 to the object's dtype; no implicit cast occurs. + * Input buffers are borrowed for the call. Output buffers must be disjoint from + * inputs and each other. All outputs remain untouched on errors. Original + * Maybe failure is OK + NULL object or found=0 (scalar value untouched). + * Original Either failures return HMATH_MATH_ERROR and the original constructor + * and payload in last_error_message. Numerical NaN/Inf policy is unchanged. + * Cancellation is checked before entry, not inside the original algorithm. */ +typedef struct hmath_dense_object hmath_dense_matrix; +typedef struct hmath_dense_object hmath_dense_lu; +typedef struct hmath_dense_object hmath_dense_qr; +typedef struct hmath_dense_object hmath_dense_vector; +typedef struct hmath_dense_object hmath_dense_indices; +HMATH_API void hmath_dense_retain(void *object); +HMATH_API void hmath_dense_release(void *object); +HMATH_API unsigned hmath_dense_precision(const void *object); +/* Metadata/copy helpers represent original shape/toList and list results. */ +HMATH_API hmath_status hmath_dense_shape(hmath_context *context, const hmath_dense_matrix *matrix, ptrdiff_t *rows, ptrdiff_t *columns); +HMATH_API hmath_status hmath_dense_count(hmath_context *context, const void *object, size_t *count); +HMATH_API hmath_status hmath_dense_indices_copy(hmath_context *context, const hmath_dense_indices *indices, ptrdiff_t *out, size_t capacity); +""" + ] + c = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_bindings.py. */ +#include "hmath_matrix.h" +#include "native_internal.h" +#include +#include "matrix_internal.h" +/* kind: 1 Matrix, 2 LU, 3 QR, 4 numeric vector, 5 index list. */ +extern void hm_dense_free(void *object); +extern int hm_dense_metadata(void *object, ptrdiff_t *rows, ptrdiff_t *columns, size_t *count); +extern int hm_dense_indices_copy(void *object, ptrdiff_t *out); +extern int hm_dense_values_f32(void *object, float *out); +extern int hm_dense_values_f64(void *object, double *out); +void hmath_dense_retain(void *object) { + struct hmath_dense_object *value=object; + if(value) atomic_fetch_add_explicit(&value->refs,1,memory_order_relaxed); +} +void hmath_dense_release(void *object) { + struct hmath_dense_object *value=object; + if(value && atomic_fetch_sub_explicit(&value->refs,1,memory_order_acq_rel)==1) { + hm_dense_free(value->stable); free(value); hm_leave(); + } +} +unsigned hmath_dense_precision(const void *object) { + const struct hmath_dense_object *value=object; + return value ? value->precision : 0; +} +static int valid(const struct hmath_dense_object *object,unsigned kind,unsigned precision) { + return object && object->kind==kind && object->precision==precision; +} +hmath_status hmath_dense_shape(hmath_context *context,const hmath_dense_matrix *matrix,ptrdiff_t *rows,ptrdiff_t *columns) { + if(!matrix || matrix->kind!=1 || !rows || !columns) return hm_error(HMATH_INVALID_ARGUMENT,"invalid dense shape arguments"); + hmath_status status=hm_enter(context); if(status) return status; + size_t count; status=(hmath_status)hm_dense_metadata(matrix->stable,rows,columns,&count); hm_leave(); return status; +} +hmath_status hmath_dense_count(hmath_context *context,const void *object,size_t *count) { + const struct hmath_dense_object *value=object; + if(!value || !count || (value->kind!=1 && value->kind!=4 && value->kind!=5)) return hm_error(HMATH_INVALID_ARGUMENT,"count requires matrix or list"); + hmath_status status=hm_enter(context); if(status) return status; + ptrdiff_t rows,columns; status=(hmath_status)hm_dense_metadata(value->stable,&rows,&columns,count); hm_leave(); return status; +} +hmath_status hmath_dense_indices_copy(hmath_context *context,const hmath_dense_indices *indices,ptrdiff_t *out,size_t capacity) { + if(!indices || indices->kind!=5) return hm_error(HMATH_INVALID_ARGUMENT,"expected index list"); + size_t count; hmath_status status=hmath_dense_count(context,indices,&count); if(status) return status; + if(capacitystable,out); hm_leave(); return status; +} +""" + ] + hs = [ + """{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_matrix_bindings.py. +module HMath.FFI.Matrix where +import Control.Exception (bracketOnError, evaluate) +import Data.Coerce (coerce) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.Error (MathError) +import qualified HMath.Matrix as M +import qualified HMath.Matrix.LU as L +import qualified HMath.Matrix.QR as Q + +data Object = M32 (M.Matrix Float) | M64 (M.Matrix Double) + | L32 (L.LU Float) | L64 (L.LU Double) + | Q32 (Q.QR Float) | Q64 (Q.QR Double) + | V32 [Float] | V64 [Double] | Indices [Int] + +forceList :: [a] -> IO () +forceList = mapM_ evaluate +forceObject :: Object -> IO () +forceObject object = case object of + M32 m -> forceList (M.toList m) + M64 m -> forceList (M.toList m) + L32 f -> forceList (M.toList (L.luLower f)) >> forceList (M.toList (L.luUpper f)) >> forceList (L.luPermutation f) + L64 f -> forceList (M.toList (L.luLower f)) >> forceList (M.toList (L.luUpper f)) >> forceList (L.luPermutation f) + Q32 f -> forceList (M.toList (Q.qrQ f)) >> forceList (M.toList (Q.qrR f)) >> forceList (Q.qrPermutation f) >> evaluate (Q.qrRank f) >> pure () + Q64 f -> forceList (M.toList (Q.qrQ f)) >> forceList (M.toList (Q.qrR f)) >> forceList (Q.qrPermutation f) >> evaluate (Q.qrRank f) >> pure () + V32 xs -> forceList xs + V64 xs -> forceList xs + Indices xs -> forceList xs +publish :: Object -> Ptr (StablePtr Object) -> IO () +publish value out = forceObject value >> bracketOnError (newStablePtr value) freeStablePtr (poke out) +publishMaybe :: (a -> Object) -> Maybe a -> Ptr (StablePtr Object) -> IO () +publishMaybe wrap value out = case value of + Nothing -> poke (castPtr out :: Ptr (Ptr ())) nullPtr + Just result -> publish (wrap result) out + +foreign export ccall "hm_dense_free" release :: StablePtr Object -> IO () +release :: StablePtr Object -> IO () +release = freeStablePtr + +foreign export ccall "hm_dense_metadata" metadata :: StablePtr Object -> Ptr CPtrdiff -> Ptr CPtrdiff -> Ptr CSize -> IO CInt +metadata :: StablePtr Object -> Ptr CPtrdiff -> Ptr CPtrdiff -> Ptr CSize -> IO CInt +metadata pointer rows columns count = boundary $ do + value <- deRefStablePtr pointer + let (r,c,n) = case value of + M32 m -> let (a,b)=M.shape m in (a,b,length (M.toList m)) + M64 m -> let (a,b)=M.shape m in (a,b,length (M.toList m)) + V32 xs -> (0,0,length xs) + V64 xs -> (0,0,length xs) + Indices xs -> (0,0,length xs) + _ -> error "dense metadata kind mismatch" + _ <- evaluate r >> evaluate c >> evaluate n + poke rows (fromIntegral r) >> poke columns (fromIntegral c) >> poke count (fromIntegral n) + checked (Right ()) (const (pure ())) +foreign export ccall "hm_dense_indices_copy" indicesCopy :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +indicesCopy :: StablePtr Object -> Ptr CPtrdiff -> IO CInt +indicesCopy pointer out = boundary $ do + value <- deRefStablePtr pointer + case value of + Indices xs -> checked (Right ()) (const (pokeArray out (map fromIntegral xs))) + _ -> error "dense indices kind mismatch" +""" + ] + mapping = [] + kind = {"m": 1, "l": 2, "q": 3, "v": 4, "p": 5} + objtype = { + "m": "hmath_dense_matrix", + "l": "hmath_dense_lu", + "q": "hmath_dense_qr", + "v": "hmath_dense_vector", + "p": "hmath_dense_indices", + } + for precision in [32, 64]: + ct, ht, rt = ( + ("float", "CFloat", "Float") + if precision == 32 + else ("double", "CDouble", "Double") + ) + for k in "mlq": + tag = k.upper() + str(precision) + hs.append(f"""\nget{tag} :: StablePtr Object -> IO ({ {"m": "M.Matrix", "l": "L.LU", "q": "Q.QR"}[k] } {rt}) +get{tag} pointer = do + value <- deRefStablePtr pointer + case value of + {tag} x -> pure x + _ -> fail "dense object kind/precision mismatch" +""") + c.append(f"""hmath_status hmath_dense_values_f{precision}(hmath_context *context,const void *object,{ct} *out,size_t capacity) {{ + const struct hmath_dense_object *value=object; + if(!value || value->precision!={precision} || (value->kind!=1 && value->kind!=4)) return hm_error(HMATH_INVALID_ARGUMENT,"expected matrix/vector of matching dtype"); + size_t count; hmath_status status=hmath_dense_count(context,object,&count); if(status) return status; + if(capacitystable,out); hm_leave(); return status; +}} +""") + h.append( + f"HMATH_API hmath_status hmath_dense_values_f{precision}(hmath_context *context,const void *object,{ct} *out,size_t capacity);\n" + ) + hs.append(f"""\nforeign export ccall "hm_dense_values_f{precision}" values{precision} :: StablePtr Object -> Ptr {ht} -> IO CInt +values{precision} :: StablePtr Object -> Ptr {ht} -> IO CInt +values{precision} pointer out = boundary $ do + object <- deRefStablePtr pointer + let values = case object of + M{precision} m -> M.toList m + V{precision} xs -> xs + _ -> error "dense values kind/precision mismatch" + strict <- mapM evaluate values + checked (Right ()) (const (pokeArray (castPtr out :: Ptr {rt}) strict)) +""") + for mod, name, args, out, mode, expression in S: + sym = symbol(mod, name, precision) + internal = sym.replace("hmath_dense_", "hm_dense_", 1) + hname = "ffi" + "".join(x.title() for x in internal.split("_")) + ca = [] + ha = [] + hn = [] + cn = [] + validate = [] + read = [] + for i, t in enumerate(args): + n = f"a{i}" + hn.append(n) + if t in "mlq": + ca.append(f"const {objtype[t]} *{n}") + ha.append("StablePtr Object") + cn.append(n + "->stable") + validate.append( + f' if(!valid({n},{kind[t]},{precision})) return hm_error(HMATH_INVALID_ARGUMENT,"{n}: object kind/precision mismatch");\n' + ) + read.append(f" {n}Value <- get{t.upper()}{precision} {n}\n") + elif t == "f": + ca.append(ct + " " + n) + ha.append(ht) + cn.append(n) + read.append(f" let {n}Value = (coerce {n} :: {rt})\n") + elif t == "i": + ca.append("ptrdiff_t " + n) + ha.append("CPtrdiff") + cn.append(n) + read.append(f" let {n}Value = fromIntegral {n}\n") + elif t == "v": + ca.extend([f"const {ct} *{n}", f"size_t {n}_count"]) + ha.extend([f"Ptr {ht}", "CSize"]) + hn.append(n + "Count") + cn.extend([n, n + "_count"]) + validate.extend( + [ + f' if({n}_count > (size_t)PTRDIFF_MAX/sizeof({ct})) return hm_error(HMATH_OVERFLOW,"list span exceeds ptrdiff_t");\n', + f' if({n}_count && !{n}) return hm_error(HMATH_INVALID_ARGUMENT,"NULL list input");\n', + ] + ) + read.append( + f" {n}Value <- peekArray (fromIntegral {n}Count) (castPtr {n} :: Ptr {rt})\n" + ) + if out in kind: + ca.append(objtype[out] + " **out") + ha.append("Ptr (StablePtr Object)") + hn.append("out") + cn.append("&result->stable") + else: + ca.append(("ptrdiff_t" if out == "i" else ct) + " *out") + ha.append("Ptr CPtrdiff" if out == "i" else f"Ptr {ht}") + hn.append("out") + cn.append("out") + if mode == "maybe": + ca.append("int *found") + ha.append("Ptr CInt") + hn.append("found") + cn.append("found") + validate.append( + ' if(!found) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Maybe presence output");\n' + ) + validate.append( + ' if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL dense output");\n' + ) + prototype = ( + f"hmath_status {sym}(hmath_context *context, " + ", ".join(ca) + ")" + ) + source = ( + {"M": "HMath.Matrix", "L": "HMath.Matrix.LU", "Q": "HMath.Matrix.QR"}[ + mod + ] + + "." + + name + ) + h.append(f"/* {source}: {mode}; {rt}. */\nHMATH_API {prototype};\n") + internal_ca = [] + for item, n in zip(ha, hn): + typ = ( + "void *" + if item == "StablePtr Object" + else "void **" + if item == "Ptr (StablePtr Object)" + else "ptrdiff_t " + if item == "CPtrdiff" + else ct + " " + if item == ht + else "size_t " + if item == "CSize" + else "ptrdiff_t *" + if item == "Ptr CPtrdiff" + else "int *" + if item == "Ptr CInt" + else ("const " if n != "out" else "") + ct + " *" + ) + internal_ca.append(typ + n) + c.append( + "extern int " + + internal + + "(" + + ", ".join(internal_ca) + + ");\n" + + prototype + + " {\n" + + "".join(validate) + ) + if out in kind: + c.append( + ' struct hmath_dense_object *result=malloc(sizeof *result);\n if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed");\n result->stable=NULL;\n' + ) + c.append( + " hmath_status status=hm_enter(context);\n if(status) { " + + ("free(result); " if out in kind else "") + + "return status; }\n" + ) + c.append(" status=(hmath_status)" + internal + "(" + ", ".join(cn) + ");\n") + if out in kind: + c.append( + " if(status || !result->stable) { free(result); hm_leave(); if(!status) *out=NULL; return status; }\n" + ) + c.append( + f" atomic_init(&result->refs,1); result->kind={kind[out]}; result->precision={precision}; *out=result;\n return status;\n}}\n" + ) + else: + c.append(" hm_leave(); return status;\n}\n") + sig = " -> ".join(ha + ["IO CInt"]) + hs.append( + f'\nforeign export ccall "{internal}" {hname} :: {sig}\n{hname} :: {sig}\n{hname} ' + + " ".join(hn) + + " = boundary $ do\n" + + "".join(read) + ) + if expression: + call = re.sub(r"\ba(\d+)\b", lambda m: "a" + m[1] + "Value", expression) + else: + call = ( + mod + + "." + + name + + " " + + " ".join("a" + str(i) + "Value" for i in range(len(args))) + ) + if out in kind: + wrap = "Indices" if out == "p" else out.upper() + str(precision) + if mode == "maybe": + hs.append( + f" checked (Right ({call}) :: Either MathError (Maybe ({ {'m': 'M.Matrix ' + rt, 'l': 'L.LU ' + rt, 'q': 'Q.QR ' + rt, 'v': '[' + rt + ']', 'p': '[Int]'}[out] }))) $ \\value -> publishMaybe {wrap} value out\n" + ) + else: + wrapped = "Right (" + call + ")" if mode == "pure" else call + hs.append( + f" checked ({wrapped}) $ \\value -> publish ({wrap} value) out\n" + ) + elif mode == "maybe": + hs.append(f""" checked (Right ({call}) :: Either MathError (Maybe {rt})) $ \\result -> case result of + Nothing -> poke found 0 + Just value -> do + strict <- evaluate value + poke out (coerce strict :: {ht}) + poke found 1 +""") + else: + wrapped = "Right (" + call + ")" if mode == "pure" else call + hs.append(f""" checked ({wrapped}) $ \\value -> do + strict <- evaluate value + poke out ({"fromIntegral strict" if out == "i" else "coerce strict :: " + ht}) +""") + mapping.append((source, sym, precision, name, mode, args, out, mod)) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + result = { + "include/hmath_matrix.h": "".join(h), + "cbits/matrix_bindings.c": "".join(c), + "src/HMath/FFI/Matrix.hs": "".join(hs), + } + entries = [ + { + "symbol": source, + "c": [x[1] for x in mapping if x[0] == source], + "python": "hmath.matrix." + snake(name), + "specializations": ["Float", "Double"], + } + for source, name in sorted({(x[0], x[3]) for x in mapping}) + ] + entries += [ + { + "symbol": "HMath.Matrix.shape", + "c": ["hmath_dense_shape"], + "python": "hmath.matrix.shape", + "specializations": ["Float", "Double"], + }, + { + "symbol": "HMath.Matrix.toList", + "c": [ + "hmath_dense_count", + "hmath_dense_values_f32", + "hmath_dense_values_f64", + ], + "python": "hmath.matrix.to_list", + "specializations": ["Float", "Double"], + }, + *[ + { + "symbol": mod + "." + name, + "c": [ctype], + "python": "hmath.matrix." + name, + "specializations": ["Float", "Double"], + } + for mod, name, ctype in [ + ("HMath.Matrix", "Matrix", "hmath_dense_matrix"), + ("HMath.Matrix.LU", "LU", "hmath_dense_lu"), + ("HMath.Matrix.QR", "QR", "hmath_dense_qr"), + ] + ], + ] + result["bindings/schema/matrix-objects.json"] = ( + json.dumps({"schema": 1, "bindings": entries}, indent=2) + "\n" + ) + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_matrix_bindings.py.\n", + "from ._matrix_base import LU, QR, Matrix, _invoke, shape, to_list\n\n", + ] + exports = ["Matrix", "LU", "QR", "shape", "to_list"] + [ + snake(item[1]) for item in S + ] + py.append( + "__all__ = " + + json.dumps( + sorted( + exports, + key=lambda x: (0 if x.isupper() else 1 if x[0].isupper() else 2, x), + ), + indent=4, + ) + + "\n" + ) + docs = [ + "# Dense matrix, LU and QR bindings\n\n", + "These APIs directly call the original `HMath.Matrix`, `HMath.Matrix.LU` and `HMath.Matrix.QR` functions, specialized to Haskell `Float` (binary32) or `Double` (binary64). Other generic Haskell element types are not yet exposed.\n\n", + "Python: `from hmath import matrix`. C/C++: include `hmath_matrix.h`. Original argument order and mathematical validation are retained. Coordinates and extents are flattened into individual arguments; vectors are a typed pointer plus element count in C.\n\n", + "## Results and errors\n\n", + "Original `Maybe` functions return Python `None` on failure; in C, they return `HMATH_OK` and a NULL object, or `found=0` for scalar `at` (leaving the scalar output untouched). Checked `Either MathError` functions raise `HMathError` in Python and return `HMATH_MATH_ERROR` in C; the original constructor and payload remain in the error message. Pure functions add no finite-value validation. Empty dimensions, shape validation order, LU singularity/tolerance policy, QR rank estimation, permutations and ridge regularization retain their original contracts.\n\n", + "## Ownership and precision\n\n", + "Matrix, LU and QR objects are immutable and independently owned. Close every Python object explicitly or use `with`; in C, call `hmath_dense_release` for each returned object. `hmath_dense_retain` adds a reference and both retain/release accept NULL. Each live object keeps the Haskell runtime alive, so final shutdown returns `HMATH_BUSY` until all such objects are released. A derived factor/matrix remains valid after its parent is closed.\n\n", + 'Constructors without an input object accept keyword-only `dtype="float64"` or `dtype="float32"`. Other operations infer dtype from their input objects and reject mixed dtypes. C names end in `_f32` or `_f64` and require the matching object precision; query it with `hmath_dense_precision`. No FP32-to-FP64 intermediate is introduced. The original pure reference algorithms are used, with the original precision-specific default pivot tolerances.\n\n', + "Each caller must hold a live reference for the entire operation. Threads may share immutable inputs but must use independent outputs. Inputs are borrowed for the call; output regions must not overlap inputs or each other. C output pointers/buffers remain untouched on error. Cancellation is checked before the operation, not during the original Haskell algorithm. Haskell dimensions use `ptrdiff_t`, preserving negative-shape errors; checked byte spans and allocation failures are binding-level errors. No legacy tensor element/work cap is added to these dense APIs.\n\n", + "## shape and to_list\n\n", + "`matrix.shape(value)` returns the original `(rows, columns)`, including zero dimensions. `matrix.to_list(value)` returns original row-major storage as a Python list. In C use `hmath_dense_shape`, or `hmath_dense_count` followed by `hmath_dense_values_f32/f64`; capacity is in elements and is checked. Vector solve results use an owned `hmath_dense_vector` with the same count/value-copy helpers. Permutations use `hmath_dense_indices` and `hmath_dense_indices_copy`; they are the original final row/column orders, not swap sequences.\n\n", + ] + for mod, name, args, out, mode, expression in S: + params = parameters(mod, name, args) + extra = ', *, dtype="float64"' if not any(t in "mlq" for t in args) else "" + source = ( + {"M": "HMath.Matrix", "L": "HMath.Matrix.LU", "Q": "HMath.Matrix.QR"}[mod] + + "." + + name + ) + stem = symbol(mod, name, 64).removesuffix("_f64") + py.extend( + [ + "\n\ndef " + snake(name) + "(" + ", ".join(params) + extra + "):\n", + ' """Call ' + + source + + " with its original argument order and " + + mode + + ' convention."""\n', + " return _invoke(\n " + + repr(stem) + + ", " + + repr(args) + + ", " + + repr(out) + + ", " + + repr(mode) + + ",\n [" + + ", ".join(params) + + "], " + + ("dtype" if extra else "None") + + ",\n )\n", + ] + ) + docs.extend( + [ + "## `" + snake(name) + "`\n\n", + "`matrix." + snake(name) + "(" + ", ".join(params) + extra + ")`\n\n", + "Original contract: [`" + + source + + "`](haskell/" + + source.rsplit(".", 1)[0].replace(".", "-") + + ".md#v:" + + name + + "). This defines the computation, boundary conditions, failure order and numerical policy.\n\n", + "| Parameter | Type |\n| --- | --- |\n", + ] + ) + for param, kind in zip(params, args): + docs.append( + "| `" + + param + + "` | " + + { + "m": "Matrix of matching dtype", + "l": "LU factors of matching dtype", + "q": "QR factors of matching dtype", + "v": "finite-length sequence of elements (C: typed pointer + count)", + "f": "scalar of matching dtype", + "i": "Haskell Int (C: ptrdiff_t)", + }[kind] + + " |\n" + ) + if extra: + docs.append("| `dtype` | float32 or float64; default float64 |\n") + docs.append( + "\nReturns " + + { + "m": "an independently owned Matrix", + "l": "independently owned LU factors", + "q": "independently owned QR factors", + "v": "the original list of solution elements", + "p": "the original list of zero-based permutation indices", + "f": "a scalar", + "i": "an integer", + }[out] + + ( + ". A Nothing result becomes None / NULL (or found=0)." + if mode == "maybe" + else ". A Left MathError raises/returns the original error." + if mode == "either" + else "." + ) + + "\n\n" + ) + for prec in [32, 64]: + proto = next( + part.split("HMATH_API ", 1)[1].split(";\n")[0] + for part in h + if "HMATH_API " in part and symbol(mod, name, prec) + "(" in part + ) + docs.append("```c\n" + proto + ";\n```\n\n") + result["bindings/python/_hmath_native/matrix.py"] = "".join(py) + result["docs/reference/matrix-bindings.md"] = "".join(docs) + result["bindings/schema/matrix-functions.json"] = ( + json.dumps( + [ + { + "source": x[0], + "c": x[1], + "precision": x[2], + "name": x[3], + "mode": x[4], + "args": x[5], + "result": x[6], + "module": x[7], + } + for x in mapping + ], + indent=2, + ) + + "\n" + ) + return result + + +if __name__ == "__main__": + import argparse + + p = argparse.ArgumentParser() + p.add_argument("--check", action="store_true") + a = p.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if a.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_matrix_value_bindings.py b/tools/generate_matrix_value_bindings.py new file mode 100644 index 0000000..f506209 --- /dev/null +++ b/tools/generate_matrix_value_bindings.py @@ -0,0 +1,354 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate same-operation Matrix adapters for lossless coefficient values.""" + +import argparse +import json +from pathlib import Path + +from generate_matrix_bindings import S, snake + +ROOT = Path(__file__).resolve().parent.parent +OPS = [entry for entry in S if entry[0] == "M"] + + +def outputs(): + hs = [ + """{-# LANGUAGE GADTs #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_matrix_value_bindings.py. +module HMath.FFI.MatrixValue where +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Matrix as M +import qualified HMath.FFI.Matrix as Legacy +import qualified HMath.FFI.Value as V +import HMath.FFI.Coefficient +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError + +withMatrix :: V.Value -> (forall a. Coefficient a => ScalarType a -> M.Matrix a -> IO V.Value) -> IO V.Value +withMatrix (V.Dense (V.SomeMatrix witness matrix)) action = action witness matrix +withMatrix _ _ = V.invalid "expected Matrix value" +withWitness :: V.Value -> (forall a. Coefficient a => ScalarType a -> IO V.Value) -> IO V.Value +withWitness (V.Scalar witness _) action = action witness +withWitness _ _ = V.invalid "expected scalar coefficient prototype" +asMatrix :: forall a. Coefficient a => V.Value -> IO (M.Matrix a) +asMatrix (V.Dense (V.SomeMatrix _ matrix)) = maybe (V.invalid "Matrix coefficient types differ") pure (cast matrix) +asMatrix _ = V.invalid "expected Matrix value" +scalars :: Coefficient a => V.Value -> IO [a] +scalars value = V.asList value >>= mapM V.asScalar +source :: Either HMath.Error.MathError a -> IO a +source = either (throwIO . CallbackMathError) pure +matrixBoundary :: IO CInt -> IO CInt +matrixBoundary action = B.boundary $ callbackBoundary (\\e -> B.checked (Left e) (const (pure ()))) action +apply :: Int -> [V.Value] -> IO V.Value +apply op args = case (op,args) of +""".replace( + "import HMath.FFI.Coefficient", + "import qualified HMath.Error\nimport HMath.FFI.Coefficient", + ) + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_matrix_value_bindings.py. */\n#include "hmath_matrix_value.h"\n#include "matrix_internal.h"\n#include "value_internal.h"\n#include \nextern int hm_matrix_value_apply(int opcode,void *const *args,size_t count,void **out);\nextern int hm_dense_export_value(void *matrix,void **out);\nextern int hm_dense_import_value(void *value,void **out);\n' + ] + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_matrix_value_bindings.py. */ +#ifndef HMATH_MATRIX_VALUE_H +#define HMATH_MATRIX_VALUE_H +#include "hmath_matrix.h" +#include "hmath_value.h" +/* Structural element types have no invented Num instance. */ +#define HMATH_MATRIX_BOOL 16 +#define HMATH_MATRIX_STRING 17 +#ifdef __cplusplus +extern "C" { +#endif +/* Lossless Matrix core over every supported Num coefficient. Inputs borrow + * immutable Value owners. Successful outputs own independent references; + * release with hmath_value_release. Maybe becomes a successful None Value; + * Either preserves complete MathError and failure leaves out untouched. + * prototype is a typed coefficient scalar, required by constructors even when + * the source list is empty. No dtype coercion or mathematical limits added. + * LU/QR retain their original RealFloat restriction to Float and Double. */ +HMATH_API hmath_status hmath_dense_to_value(hmath_context *context,const hmath_dense_matrix *matrix,hmath_value **out); +/* Import real Float/Double Value Matrix into the pre-existing typed Matrix + * owner. Exact/complex values instead use the generic operations below. */ +HMATH_API hmath_status hmath_dense_from_value(hmath_context *context,const hmath_value *value,hmath_dense_matrix **out); +""" + ] + mapping = [] + for op, (_, name, kinds, result, mode, expr) in enumerate(OPS): + args = ["a" + str(i) for i in range(len(kinds))] + constructor = "m" not in kinds + full = (["prototype"] if constructor else []) + args + pattern = ",".join(full) + prefix = ( + "withWitness prototype $ \\w -> do" + if constructor + else "withMatrix " + args[kinds.index("m")] + " $ \\w m -> do" + ) + hs.append(" (" + str(op) + ",[" + pattern + "]) -> " + prefix + "\n") + for i, kind in enumerate(kinds): + arg = args[i] + if kind == "m" and i == kinds.index("m"): + hs.append(" let " + arg + "Value = m\n") + else: + hs.append( + " " + + arg + + "Value <- " + + { + "m": "asMatrix", + "i": "V.asIndex", + "f": "V.asScalar", + "v": "scalars", + }[kind] + + " " + + arg + + "\n" + ) + expression = expr or "M." + name + " " + " ".join(args) + for arg in reversed(args): + expression = expression.replace(arg, arg + "Value") + wrap = "V.Dense . V.SomeMatrix w" if result == "m" else "V.Scalar w" + if mode == "maybe": + statement = "pure (maybe V.None (" + wrap + ") (" + expression + "))" + elif mode == "either": + statement = "(" + wrap + ") <$> source (" + expression + ")" + else: + statement = "pure ((" + wrap + ") (" + expression + "))" + # Constructor witness must fix result type even if no coefficient list is provided. + hs.append(" " + statement + "\n") + symbol = "hmath_matrix_value_" + snake(name) + proto = ( + "hmath_status " + + symbol + + "(hmath_context *context," + + ",".join("const hmath_value *" + a for a in full) + + ",hmath_value **out)" + ) + h.append("HMATH_API " + proto + ";\n") + c.append( + proto + + " {\n if(!out || " + + " || ".join("!" + a for a in full) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status;\n void *args[]={' + + ",".join("hm_value_stable(" + a + ")" for a in full) + + "};\n return hm_value_finish(result,hm_matrix_value_apply(" + + str(op) + + ",args," + + str(len(full)) + + ",&result->stable),out);\n}\n" + ) + mapping.append( + { + "symbol": "HMath.Matrix." + name, + "c": [symbol], + "python": "hmath.matrix." + snake(name), + "specializations": [ + "Float", + "Double", + "Integer", + "Rational", + "Complex Float", + "Complex Double", + "bounded standard integral Num instances", + "Numeric.Dual/Quaternion Num instances when constructed as typed scalar Values", + *( + ["Bool/String and other captured structural codecs"] + if name + in ( + "fromList", + "fromListChecked", + "at", + "atChecked", + "sliceMatrix", + "sliceMatrixChecked", + "reshape", + "reshapeChecked", + "transposeMatrix", + ) + else [] + ), + ], + } + ) + hs.append(""" (100,[matrix]) -> withMatrix matrix $ \\w m -> pure (V.List (map (V.Scalar w) (M.toList m))) + (101,[matrix]) -> withMatrix matrix $ \\_ m -> let (r,c)=M.shape m in pure (V.Tuple [V.Index r,V.Index c]) + _ -> V.invalid "invalid Matrix Value operation or arity" +foreign export ccall "hm_matrix_value_apply" ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply opcode pointers count out = matrixBoundary $ do + args <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + value <- if any structuralValue args then structuralApply (fromIntegral opcode) args else apply (fromIntegral opcode) args + B.checked (Right ()) (const (V.publish value out)) +foreign export ccall "hm_dense_export_value" exportValue :: StablePtr Legacy.Object -> Ptr (StablePtr V.Value) -> IO CInt +exportValue :: StablePtr Legacy.Object -> Ptr (StablePtr V.Value) -> IO CInt +exportValue pointer out = matrixBoundary $ do + object <- deRefStablePtr pointer + case object of + Legacy.M32 m -> B.checked (Right ()) (const (V.publish (V.Dense (V.SomeMatrix SFloat m)) out)) + Legacy.M64 m -> B.checked (Right ()) (const (V.publish (V.Dense (V.SomeMatrix SDouble m)) out)) + _ -> V.invalid "expected legacy real Matrix owner" +foreign export ccall "hm_dense_import_value" importValue :: StablePtr V.Value -> Ptr (StablePtr Legacy.Object) -> IO CInt +importValue :: StablePtr V.Value -> Ptr (StablePtr Legacy.Object) -> IO CInt +importValue pointer out = matrixBoundary $ do + value <- deRefStablePtr pointer + case value of + V.Dense (V.SomeMatrix SFloat m) -> B.checked (Right ()) (const (Legacy.publish (Legacy.M32 m) out)) + V.Dense (V.SomeMatrix SDouble m) -> B.checked (Right ()) (const (Legacy.publish (Legacy.M64 m) out)) + _ -> V.invalid "legacy typed Matrix import requires Float or Double Matrix" +""") + for name, opcode in [("to_list", 100), ("shape", 101)]: + symbol = "hmath_matrix_value_" + name + proto = ( + "hmath_status " + + symbol + + "(hmath_context *context,const hmath_value *matrix,hmath_value **out)" + ) + h.append("HMATH_API " + proto + ";\n") + c.append( + proto + + ' {\n if(!matrix || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Matrix Value argument");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status;\n void *args[]={hm_value_stable(matrix)};\n return hm_value_finish(result,hm_matrix_value_apply(' + + str(opcode) + + ",args,1,&result->stable),out);\n}\n" + ) + mapping.append( + { + "symbol": "HMath.Matrix." + + ("toList" if name == "to_list" else "shape"), + "c": [symbol], + "python": "hmath.matrix." + name, + "specializations": [ + "same standard coefficients and Bool/String structural elements as Matrix Value" + ], + } + ) + c.append("""hmath_status hmath_dense_to_value(hmath_context *context,const hmath_dense_matrix *matrix,hmath_value **out) { + if(!matrix || matrix->kind!=1 || !out) return hm_error(HMATH_INVALID_ARGUMENT,"expected Matrix owner/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_dense_export_value(matrix->stable,&result->stable),out); +} +hmath_status hmath_dense_from_value(hmath_context *context,const hmath_value *value,hmath_dense_matrix **out) { + if(!value || value->kind!=9 || (value->dtype!=0 && value->dtype!=1) || !out) + return hm_error(HMATH_INVALID_ARGUMENT,"typed Matrix import requires Float or Double Matrix"); + struct hmath_dense_object *result=calloc(1,sizeof *result); + if(!result) return hm_error(HMATH_ALLOCATION_FAILED,"dense handle allocation failed"); + hmath_status status=hm_enter(context); if(status) { free(result); return status; } + status=(hmath_status)hm_dense_import_value(value->stable,&result->stable); + if(status) { free(result); hm_leave(); return status; } + atomic_init(&result->refs,1); result->kind=1; result->precision=value->dtype==1 ? 32 : 64; *out=result; + return HMATH_OK; +} +""") + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "src/HMath/FFI/MatrixValue.hs": "".join(hs) + structural_haskell(), + "include/hmath_matrix_value.h": "".join(h), + "cbits/matrix_value.c": "".join(c), + "bindings/schema/matrix-value-objects.json": json.dumps( + {"schema": 1, "extends": "matrix-objects.json", "bindings": mapping}, + indent=2, + ) + + "\n", + } + + +def structural_haskell(): + lines = [ + "\n-- Original structure-only operations over Bool/String or a captured codec.\n", + "structuralValue :: V.Value -> Bool\nstructuralValue (V.Boolean _) = True\nstructuralValue (V.Text _) = True\nstructuralValue (V.Dense(V.StructuralMatrix _ _ _ _ _)) = True\nstructuralValue _ = False\n", + 'withStructural :: V.Value -> (forall a. Typeable a => Int -> (a -> IO V.Value) -> (V.Value -> IO a) -> (a -> IO ()) -> IO V.Value) -> IO V.Value\nwithStructural (V.Boolean _) action = action 16 (pure . V.Boolean) V.asBoolean (\\x -> evaluate x >> pure ())\nwithStructural (V.Text _) action = action 17 (pure . V.Text) V.asText (mapM_ evaluate)\nwithStructural (V.Dense(V.StructuralMatrix dtype writer reader force _)) action = action dtype writer reader force\nwithStructural _ _ = V.invalid "expected structural element prototype/Matrix"\n', + "structuralApply :: Int -> [V.Value] -> IO V.Value\nstructuralApply op args = case(op,args) of\n", + ] + for opcode, (_mod, name, kinds, result, mode, expression) in enumerate(OPS): + if name not in ( + "fromList", + "fromListChecked", + "at", + "atChecked", + "sliceMatrix", + "sliceMatrixChecked", + "reshape", + "reshapeChecked", + "transposeMatrix", + ): + continue + variables = ["a" + str(i) for i in range(len(kinds))] + constructor = "m" not in kinds + full = (["prototype"] if constructor else []) + variables + owner = "prototype" if constructor else variables[kinds.index("m")] + lines.append( + " (" + + str(opcode) + + ",[" + + ",".join(full) + + "]) -> withStructural " + + owner + + ( + " $ \\dtype writer reader force -> do\n" + if result == "m" + else " $ \\_dtype writer _reader _force -> do\n" + ) + ) + for i, kind in enumerate(kinds): + variable = variables[i] + decoder = { + "m": "V.asMatrix", + "i": "V.asIndex", + "v": "(\\x -> V.asList x >>= mapM reader)", + }[kind] + lines.append( + " " + variable + "Value <- " + decoder + " " + variable + "\n" + ) + call = expression or "M." + name + " " + " ".join(variables) + for variable in reversed(variables): + call = call.replace(variable, variable + "Value") + wrap = ( + "(V.Dense . V.StructuralMatrix dtype writer reader force)" + if result == "m" + else "writer" + ) + if mode == "maybe": + if result == "m": + statement = "pure(maybe V.None " + wrap + " (" + call + "))" + else: + statement = "maybe (pure V.None) writer (" + call + ")" + elif mode == "either": + statement = ( + "source (" + + call + + ") >>= " + + ("pure . " + wrap if result == "m" else "writer") + ) + else: + statement = "pure(" + wrap + " (" + call + "))" + lines.append(" " + statement + "\n") + lines.extend( + [ + " (100,[matrix]) -> withStructural matrix $ \\_ writer _ _ -> do\n values <- V.asMatrix matrix\n V.List <$> mapM writer (M.toList values)\n", + " (101,[matrix]) -> withStructural matrix $ \\_ _ (_reader :: V.Value -> IO a) _ -> do\n values <- (V.asMatrix matrix :: IO(M.Matrix a))\n let (rows,columns)=M.shape values\n pure(V.Tuple[V.Index rows,V.Index columns])\n", + ' _ -> V.unsupported "original structural element type has no Num instance"\n', + ] + ) + return "".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_numeric_bindings.py b/tools/generate_numeric_bindings.py new file mode 100644 index 0000000..4972de3 --- /dev/null +++ b/tools/generate_numeric_bindings.py @@ -0,0 +1,803 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate typed C/Python adapters which call the named Haskell function. + +The manifest records concrete specializations, never a replacement formula. +Run with --check in CI to reject stale generated adapters. +""" + +import argparse +import json +import keyword +import re +from pathlib import Path + +from numeric_specializations import BOUNDED, binding_variants + +ROOT = Path(__file__).resolve().parent.parent +PYTHON_MARKER = "# Generated by tools/generate_numeric_bindings.py; do not edit." + + +def floating(entry): + return any(a["type"] in ("f", "fs", "p", "c") for a in entry["args"]) or entry[ + "result" + ] in ("f", "ff", "fff", "ffff", "c", "fs", "fd", "zf", "sf", "sf2", "sf4", "fsf") + + +def precisions(entry): + return entry.get("precisions", [32, 64] if floating(entry) else [None]) + + +def prefix(entry): + return "hmath_" + namespace(entry) + "_" + entry["python"] + + +def namespace(entry): + """Keep nested module names distinct in both C and Python namespaces.""" + return entry["module"].removeprefix("HMath.").replace(".", "_").lower() + + +def module_alias(module): + return module.removeprefix("HMath.").replace(".", "") + + +def generate(): + entries = json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + # These domains use opaque object/callback adapters owned by separate + # generators. Reject accidental scalar entries instead of overwriting an + # independently maintained Python module such as autodiff.py or matrix.py. + protected = ("HMath.Autodiff", "HMath.Matrix") + for entry in entries: + if any( + entry["module"] == name or entry["module"].startswith(name + ".") + for name in protected + ): + raise ValueError( + f"Object binding domain cannot use numeric generator: {entry['module']}" + ) + header = [ + "/* SPDX-License-Identifier: MPL-2.0 */\n", + "/* Generated by tools/generate_numeric_bindings.py. */\n", + '#ifndef HMATH_NUMERIC_H\n#define HMATH_NUMERIC_H\n#include "hmath.h"\n', + '#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original Haskell semantics, including unchecked NaN/Inf behavior.\n", + " * Each checked MathError is reported as HMATH_MATH_ERROR with its\n", + " * constructor and payload in hmath_last_error_message(). Pure errors\n", + " * return HMATH_HASKELL_EXCEPTION. Output is untouched on failure.\n", + " * Integer arguments are NUL-terminated ASCII decimal strings; results\n", + " * are exact decimal strings allocated by HMath. Free each string with\n", + " * hmath_numeric_string_free, including rational numerator/denominator.\n", + " * Pair/complex arguments and tuple results are flattened in order.\n", + " * List output capacity is checked (prefixSum needs count + 1). Pointers must\n", + " * not overlap one another or inputs. Inputs are borrowed for the call.\n", + " * Concurrent calls use independent outputs; error state is thread-local.\n", + " * Cancellation is checked before entry, not during pure evaluation. */\n", + "HMATH_API void hmath_numeric_string_free(char *value);\n", + "/* Free owned numerical result arrays (and outer exact-string arrays). */\n", + "HMATH_API void hmath_numeric_buffer_free(void *value);\n", + "/* Dynamic results return an owned pointer and logical element count.\n", + " * Free every exact string first, then the outer buffer. Rational\n", + " * arrays contain numerator,denominator pairs (2*count strings).\n", + " * Complex arrays contain real,imaginary pairs (2*count components).\n", + " * Bounded integer suffixes select the original Haskell numeric\n", + " * instance: ordinary arithmetic wraps, checked/saturating functions\n", + " * retain their original checks/clamping. Integer/Rational are exact. */\n", + ] + c = [ + "/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; do not edit. */\n", + '#include "hmath_numeric.h"\n#include "numeric_internal.h"\n#include \n', + "void hmath_numeric_string_free(char *value) { free(value); }\n", + "void hmath_numeric_buffer_free(void *value) { free(value); }\n", + ] + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n", + "-- SPDX-License-Identifier: MPL-2.0\n-- Generated; do not edit.\n", + "module HMath.FFI.Numeric where\n", + "import Control.Exception (bracketOnError, evaluate)\nimport Data.Coerce (coerce)\n", + "import Data.Complex (Complex ((:+)), realPart, imagPart)\n", + "import Data.Ratio (numerator, denominator, (%))\nimport Foreign\nimport Foreign.C\n", + "import HMath.FFI.Boundary\n", + ] + for module in sorted({e["module"] for e in entries}): + hs.append(f"import qualified {module} as {module_alias(module)}\n") + if any(e.get("specializations") for e in entries): + hs.append( + '\ncomplexPairs :: [a] -> [Complex a]\ncomplexPairs [] = []\ncomplexPairs (a : b : rest) = (a :+ b) : complexPairs rest\ncomplexPairs _ = error "invalid complex transport"\n' + ) + hs.append( + '\nrationalPairs :: [Integer] -> [Rational]\nrationalPairs [] = []\nrationalPairs (a : b : rest) = (a % b) : rationalPairs rest\nrationalPairs _ = error "invalid Rational transport"\n' + ) + python = {} + symbols = ["hmath_numeric_string_free", "hmath_numeric_buffer_free"] + docs = [ + "# Numeric bindings\n\n", + ( + "These bindings call the original Haskell functions. They do not replace their algorithms or change domain checks. " + "This is an incremental subset, **not full Haskell API coverage**.\n\n" + ), + ( + "Include `hmath_numeric.h` in C/C++; in Python use `from hmath import scalar, basic, trigonometry, statistics, constants`. " + 'Floating functions accept keyword-only `dtype="float64"` or `dtype="float32"`; these select Haskell `Double` and `Float`, respectively. ' + "Functions whose original signature fixes `Double` accept only `float64`; `float32` is rejected rather than silently promoted. " + "Generic functions may have other Haskell type instances which are not yet bound. " + "Python returns ordinary floats, complex numbers, tuples, lists, arbitrary-precision integers and `fractions.Fraction` values.\n\n" + ), + ( + "Original argument order is preserved. C flattens coordinate pairs and complex values into two real arguments, " + "lists into a pointer and count, and tuple results into separate output pointers. " + "Haskell `Int` uses `ptrdiff_t`; `Integer` uses signed ASCII decimal strings without a fixed precision limit. " + "Rationals use separate exact numerator and denominator strings. Free each returned string with " + "`hmath_numeric_string_free`. Python owns and releases this transport automatically.\n\n" + ), + ( + "Generic Basic, Scalar, Linear and Statistics functions list their supported `dtype` instances below. " + "`integer` uses unbounded Haskell `Integer`; `rational` uses exact `Rational` and Python `fractions.Fraction`. " + "`int8`/`int16`/`int32`/`int64` and unsigned `uint*` select the corresponding bounded Haskell types. " + "`intp`/`uintp` select native-width Haskell `Int`/`Word`. `complex64` and `complex128` select " + "`Complex Float` and `Complex Double`. Only instances permitted by the original constraints are offered. " + "[Typed generic Value adapters](numeric-objects.md) additionally preserve bound Numeric.Dual/Quaternion, " + "original AD.Dual/Expr and supported native Ord labels through their actual dictionaries. " + "These finite instance sets do not claim support for every user-defined Haskell typeclass instance.\n\n" + "Ordinary bounded arithmetic keeps the original wrapping behavior; the dedicated checked and saturating " + "functions keep their original error/clamping behavior. Python rejects values outside the selected bounded " + "input type with `OverflowError`. Use explicit `dtype='integer'`/`'rational'` for exact arithmetic; existing " + "floating defaults remain unchanged. Rational input arrays use alternating decimal numerator/denominator " + "strings; complex arrays use alternating real/imaginary components. Array counts are logical values, " + "not component counts.\n\n" + ), + ( + "A Haskell `Left MathError` becomes `HMATH_MATH_ERROR` (11) in C and `HMathError(status=11)` in Python; " + "the original constructor and payload are retained in the error message. Pure exceptions use status 6. " + "Unchecked functions still allow their original NaN/Inf behavior. No finite-value check is added.\n\n" + ), + ( + "Input buffers live for the call. Output buffers must not overlap inputs or each other, and list outputs " + "must hold the input count (plus one for prefixSum); C output capacity is checked. Outputs remain untouched on failure. Initialize the runtime before numerical calls. " + "Cancellation is checked before the call. Independent calls can run concurrently.\n\n" + ), + ] + for entry in entries: + module = module_alias(entry["module"]) + group = namespace(entry) + python.setdefault( + group, + [ + f"# SPDX-License-Identifier: MPL-2.0\n{PYTHON_MARKER}\nfrom ._numeric import _call\n" + + ( + ( + "from ._numeric_objects import _call_value, _uses_equality_value\n" + if group == "geometry_primitives" + else "from ._numeric_objects import _call_value, _uses_value\n" + ) + if group + in { + "basic", + "scalar", + "linear", + "statistics", + "geometry_primitives", + } + else "" + ) + ], + ) + parameters = [ + a["name"] + "_" if keyword.iskeyword(a["name"]) else a["name"] + for a in entry["args"] + ] + default_dtype = entry.get("default_dtype", "float64") + typed = bool(entry.get("specializations")) + pyargs = parameters + ( + ["*", f"dtype={default_dtype!r}"] if floating(entry) or typed else [] + ) + source = entry["module"] + "." + entry["name"] + signature = f"{group}.{entry['python']}({', '.join(pyargs)})" + if typed: + variant_map = { + v["dtype"]: ( + [a["type"] for a in v["args"]], + v["result"], + f"float{v['precision']}" if v["precision"] else None, + v["suffix"], + ) + for v in binding_variants(entry) + if not v["legacy"] + } + body = ( + f" if _uses_value([{', '.join(parameters)}], dtype, ordered={entry['name'] in {'clamp', 'minimumScalar', 'maximumScalar'}}):\n" + f" return _call_value({prefix(entry)!r}, {[a['type'] for a in entry['args']]!r}, [{', '.join(parameters)}], dtype)\n" + " variants = {\n" + + "".join( + f" {dtype!r}: {spec!r},\n" + for dtype, spec in variant_map.items() + ) + + " }\n" + " if dtype not in variants:\n raise ValueError('unsupported dtype for this Haskell function')\n" + " kinds, result, precision, suffix = variants[dtype]\n" + f" return _call({prefix(entry)!r}, kinds, result, [{', '.join(parameters)}], precision, {entry.get('result_extra', 0)}, symbol_suffix=suffix)\n" + ) + else: + body = ( + ( + ' if dtype != "float64":\n raise ValueError("this Haskell function uses Double; dtype must be \'float64\'")\n' + if precisions(entry) == [64] + else "" + ) + + " return _call(\n" + f" {prefix(entry)!r},\n" + f" {[a['type'] for a in entry['args']]!r},\n" + f" {entry['result']!r},\n" + f" [{', '.join(parameters)}],\n" + f" {'dtype' if floating(entry) else 'None'},\n" + f" {entry.get('result_extra', 0)},\n" + " )\n" + ) + if entry["module"] == "HMath.Geometry.Primitives" and entry["name"] in { + "hammingDistance", + "jaccardDistance", + }: + body = ( + f" if _uses_equality_value([{', '.join(parameters)}], dtype):\n" + f" return _call_value({prefix(entry)!r}, {[a['type'] for a in entry['args']]!r}, [{', '.join(parameters)}], dtype)\n" + ) + body + python[group].append( + f"\n\ndef {entry['python']}({', '.join(pyargs)}):\n" + f' """Call {source}; preserve its argument order, result and errors."""\n' + + body + ) + docs.append(f"## `{group}.{entry['python']}`\n\n`{signature}`\n\n") + docs.append( + f"Original: [`{source}`](haskell/{entry['module'].replace('.', '-')}.md#v:{entry['name']}). " + "The linked contract defines the operation, valid inputs, result and mathematical errors.\n\n" + ) + if typed: + docs.append( + "Supported `dtype`: " + + ", ".join(f"`{name}`" for name in entry["specializations"]) + + ".\n\n" + ) + source_entry = entry + for variant in binding_variants(source_entry): + entry = dict(source_entry, args=variant["args"], result=variant["result"]) + precision = variant["precision"] + ct, ht, native = ( + ("float", "CFloat", "Float") + if precision == 32 + else ("double", "CDouble", "Double") + ) + symbol = prefix(entry) + variant["suffix"] + internal = symbol.replace("hmath_", "hm_numeric_", 1) + hsname = "ffi" + "".join(part.title() for part in symbol.split("_")[1:]) + symbols.append(symbol) + ca, ha, names, reads, arguments, validations = [], [], [], [], [], [] + for arg in entry["args"]: + name, kind = arg["name"], arg["type"] + # Prefix Haskell variables to avoid name clashes with imported APIs. + var = "v" + name[0].upper() + name[1:] + if kind in BOUNDED: + ctype, htype = BOUNDED[kind][:2] + ca.append(f"{ctype} {name}") + ha.append(htype) + names.append(var) + arguments.append(f"({var} :: {htype})") + elif kind.endswith("s") and kind[:-1] in BOUNDED: + ctype, htype = BOUNDED[kind[:-1]][:2] + ca.extend([f"const {ctype} *{name}", f"size_t {name}_count"]) + ha.extend([f"Ptr {htype}", "CSize"]) + names.extend([var, var + "Count"]) + reads.append( + f" {var}Value <- peekArray (fromIntegral {var}Count) {var}\n" + ) + arguments.append(var + "Value") + validations.append( + f' if ({name}_count > (size_t)PTRDIFF_MAX / sizeof({ctype})) return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t");\n' + ) + validations.append( + f' if ({name}_count && !{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input");\n' + ) + elif kind in ("cs", "qs"): + element_c, element_h = ( + (ct, ht) if kind == "cs" else ("const char *", "CString") + ) + ca.extend([f"{element_c} const *{name}", f"size_t {name}_count"]) + ha.extend([f"Ptr {element_h}", "CSize"]) + names.extend([var, var + "Count"]) + validations.append( + f' if ({name}_count > (size_t)PTRDIFF_MAX / (2 * sizeof({element_c}))) return hm_error(HMATH_OVERFLOW, "paired list byte span exceeds ptrdiff_t");\n' + ) + validations.append( + f' if ({name}_count && !{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL paired list input");\n' + ) + if kind == "cs": + reads.append( + f" {var}Raw <- peekArray (2 * fromIntegral {var}Count) (castPtr {var} :: Ptr {native})\n" + ) + reads.append(f" let {var}Value = complexPairs {var}Raw\n") + else: + validations.append( + f" for (size_t i = 0; i < 2 * {name}_count; ++i) {{\n if (!hm_decimal({name}[i])) return hm_error(HMATH_INVALID_ARGUMENT, \"invalid Rational list component\");\n if (i % 2) {{\n const char *digit = {name}[i];\n if (*digit == '-') ++digit;\n while (*digit == '0') ++digit;\n if (!*digit) return hm_error(HMATH_INVALID_ARGUMENT, \"zero Rational list denominator\");\n }}\n }}\n" + ) + reads.append( + f" {var}Raw <- peekArray (2 * fromIntegral {var}Count) {var} >>= mapM readInteger\n" + ) + reads.append(f" let {var}Value = rationalPairs {var}Raw\n") + arguments.append(var + "Value") + elif kind == "f": + ca.append(f"{ct} {name}") + ha.append(ht) + names.append(var) + arguments.append(f"(coerce {var} :: {native})") + elif kind == "i": + ca.append(f"ptrdiff_t {name}") + ha.append("CPtrdiff") + names.append(var) + arguments.append(f"(fromIntegral {var})") + elif kind == "b": + ca.append(f"int {name}") + ha.append("CInt") + names.append(var) + arguments.append(f"({var} /= 0)") + elif kind == "z": + ca.append(f"const char *{name}") + ha.append("CString") + names.append(var) + reads.append(f" {var}Value <- readInteger {var}\n") + arguments.append(var + "Value") + validations.append( + f' if (!hm_decimal({name})) return hm_error(HMATH_INVALID_ARGUMENT, "{name}: expected signed decimal Integer");\n' + ) + elif kind == "q": + ca.extend( + [ + f"const char *{name}_numerator", + f"const char *{name}_denominator", + ] + ) + ha.extend(["CString", "CString"]) + names.extend([var + "Numerator", var + "Denominator"]) + reads.extend( + [ + f" {var}N <- readInteger {var}Numerator\n", + f" {var}D <- readInteger {var}Denominator\n", + ] + ) + arguments.append(f"({var}N % {var}D)") + validations.append( + f' if (!hm_decimal({name}_numerator) || !hm_decimal({name}_denominator)) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Rational decimal components");\n' + ) + validations.append( + f" const char *{name}_digit = {name}_denominator;\n if (*{name}_digit == '-') ++{name}_digit;\n while (*{name}_digit == '0') ++{name}_digit;\n if (!*{name}_digit) return hm_error(HMATH_INVALID_ARGUMENT, \"zero Rational denominator\");\n" + ) + elif kind in ("p", "c"): + ca.extend([f"{ct} {name}_0", f"{ct} {name}_1"]) + ha.extend([ht, ht]) + names.extend([var + "0", var + "1"]) + first, second = ( + f"(coerce {var}0 :: {native})", + f"(coerce {var}1 :: {native})", + ) + arguments.append( + f"({first}, {second})" + if kind == "p" + else f"({first} :+ {second})" + ) + elif kind == "fs": + ca.extend([f"const {ct} *{name}", f"size_t {name}_count"]) + ha.extend([f"Ptr {ht}", "CSize"]) + names.extend([var, var + "Count"]) + reads.append( + f" {var}Value <- peekArray (fromIntegral {var}Count) (castPtr {var} :: Ptr {native})\n" + ) + arguments.append(var + "Value") + validations.append( + f' if ({name}_count > (size_t)PTRDIFF_MAX / sizeof({ct})) return hm_error(HMATH_OVERFLOW, "list byte span exceeds ptrdiff_t");\n' + ) + validations.append( + f' if ({name}_count && !{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input");\n' + ) + elif kind in ("zs", "is"): + element_c, element_h = ( + ("const char *", "CString") + if kind == "zs" + else ("ptrdiff_t", "CPtrdiff") + ) + ca.extend([f"{element_c} const *{name}", f"size_t {name}_count"]) + ha.extend([f"Ptr {element_h}", "CSize"]) + names.extend([var, var + "Count"]) + reads.append( + f" {var}Raw <- peekArray (fromIntegral {var}Count) {var}\n" + ) + reads.append( + f" {var}Value <- mapM readInteger {var}Raw\n" + if kind == "zs" + else f" let {var}Value = map fromIntegral {var}Raw\n" + ) + arguments.append(var + "Value") + validations.append( + f' if ({name}_count > (size_t)PTRDIFF_MAX / sizeof({element_c}) || ({name}_count && !{name})) return hm_error(HMATH_INVALID_ARGUMENT, "invalid list input span");\n' + ) + if kind == "zs": + validations.append( + f' for (size_t i = 0; i < {name}_count; ++i) if (!hm_decimal({name}[i])) return hm_error(HMATH_INVALID_ARGUMENT, "invalid Integer list element");\n' + ) + validations.append( + f' if ({name}_count && !{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL list input");\n' + ) + else: + raise ValueError(kind) + result = entry["result"] + if result in ("fd", "zd", "id", "qd", "cd") or ( + result.endswith("d") and result[:-1] in BOUNDED + ): + result_types = { + "fd": (ct, ht), + "cd": (ct, ht), + "zd": ("char *", "CString"), + "id": ("ptrdiff_t", "CPtrdiff"), + "qd": ("char *", "CString"), + } + result_types.update( + {name + "d": spec[:2] for name, spec in BOUNDED.items()} + ) + element_c, element_h = result_types[result] + ca.extend([f"{element_c} **out_data", "size_t *out_count"]) + ha.extend([f"Ptr (Ptr {element_h})", "Ptr CSize"]) + names.extend(["outData", "outCount"]) + validations.append( + ' if (!out_data || !out_count) return hm_error(HMATH_INVALID_ARGUMENT, "NULL dynamic output");\n' + ) + csig = ( + f"hmath_status {symbol}(\n " + + ",\n ".join(["hmath_context *context"] + ca) + + ")" + ) + header.append( + f"/* {source}; owned array result. */\nHMATH_API {csig};\n" + ) + docs.append(f"```c\n{csig};\n```\n\n") + c.append( + f"extern int {internal}(\n " + + ",\n ".join(ca) + + f");\n{csig} {{\n" + ) + c.extend(validations) + c.append( + " hmath_status status = hm_enter(context);\n if (status) return status;\n" + ) + cnames = [item.rsplit(" ", 1)[-1].lstrip("*") for item in ca] + c.append( + f" status = (hmath_status){internal}({', '.join(cnames)});\n hm_leave();\n return status;\n}}\n" + ) + hsig = "\n " + " ->\n ".join(ha + ["IO CInt"]) + hs.append( + f'\nforeign export ccall "{internal}" {hsname} :: {hsig}\n{hsname} :: {hsig}\n' + ) + hs.append(f"{hsname} {' '.join(names)} = boundary $ do\n") + hs.extend(reads) + call = f"{module}.{entry['name']} " + " ".join(arguments) + wrapped = call if entry["checked"] else f"Right ({call})" + hs.append(f" checked ({wrapped}) $ \\value -> do\n") + if result in ("fd", "id", "cd") or result[:-1] in BOUNDED: + element_native = ( + native + if result in ("fd", "cd") + else "Int" + if result == "id" + else BOUNDED[result[:-1]][1] + ) + expression = ( + "concatMap (\\z -> [realPart z, imagPart z]) value" + if result == "cd" + else "value" + ) + hs.append( + f" strict <- mapM evaluate ({expression} :: [{element_native}])\n" + ) + values = ( + f"map (coerce :: {native} -> {ht}) strict" + if result in ("fd", "cd") + else "map (fromIntegral :: Int -> CPtrdiff) strict" + if result == "id" + else "strict" + ) + hs.append( + f" bracketOnError (newArray ({values})) free $ \\pointer -> do\n poke outData pointer\n poke outCount (fromIntegral (length {'value' if result == 'cd' else 'strict'}))\n" + ) + else: + texts = ( + "map show value" + if result == "zd" + else "concatMap (\\r -> [show (numerator r), show (denominator r)]) value" + ) + hs.append( + f" writeStrings ({texts}) $ \\textPointers ->\n bracketOnError (newArray textPointers) free $ \\pointer -> do\n poke outData pointer\n poke outCount (fromIntegral (length value))\n" + ) + continue + output_kinds = { + "f": ["f"], + "ff": ["f", "f"], + "fff": ["f"] * 3, + "ffff": ["f"] * 4, + "sf": ["f"] * 2, + "sf2": ["f"] * 4, + "sf4": ["f"] * 8, + "fsf": ["f"] * 3, + "c": ["f", "f"], + "b": ["b"], + "z": ["z"], + "zz": ["z", "z"], + "zzz": ["z"] * 3, + "zzzz": ["z"] * 4, + "i": ["i"], + "q": ["z", "z"], + "zf": ["z", "f"], + "fs": ["fs"], + } + output_kinds.update({name: [name] for name in BOUNDED}) + outs = output_kinds[result] + output_values = { + "f": ["value"], + "b": ["value"], + "i": ["value"], + "z": ["value"], + "ff": ["first", "second"], + "zz": ["first", "second"], + "zf": ["first", "second"], + "fff": ["first", "second", "third"], + "ffff": ["first", "second", "third", "fourth"], + "zzz": ["first", "second", "third"], + "sf": ["Special.sfValue value", "Special.sfError value"], + "sf2": [ + "Special.sfValue first", + "Special.sfError first", + "Special.sfValue second", + "Special.sfError second", + ], + "sf4": [ + f"Special.{field} {name}" + for name in ("first", "second", "third", "fourth") + for field in ("sfValue", "sfError") + ], + "fsf": ["first", "Special.sfValue second", "Special.sfError second"], + "zzzz": ["first", "second", "third", "fourth"], + "c": ["realPart value", "imagPart value"], + "q": ["numerator value", "denominator value"], + "fs": ["value"], + } + output_values.update({name: ["value"] for name in BOUNDED}) + values = output_values[result] + pattern = { + "sf2": "(first, second)", + "sf4": "(first, second, third, fourth)", + "fsf": "(first, second)", + }.get(result) or ( + "value" + if result not in ("ff", "fff", "ffff", "zz", "zzz", "zzzz", "zf") + else "(" + ", ".join(values) + ")" + ) + forces, pokes, strings = [], [], [] + for index, (kind, expression) in enumerate(zip(outs, values)): + name = f"out{index}" + ca.append( + { + "f": f"{ct} *", + "b": "int *", + "i": "ptrdiff_t *", + "z": "char **", + "fs": f"{ct} *", + **{key: spec[0] + " *" for key, spec in BOUNDED.items()}, + }[kind] + + name + ) + ha.append( + { + "f": f"Ptr {ht}", + "b": "Ptr CInt", + "i": "Ptr CPtrdiff", + "z": "Ptr CString", + "fs": f"Ptr {ht}", + **{key: f"Ptr {spec[1]}" for key, spec in BOUNDED.items()}, + }[kind] + ) + names.append(name) + if kind == "fs": + length_name = ( + next(a["name"] for a in entry["args"] if a["type"] == "fs") + + "_count" + ) + extra = entry.get("result_extra", 0) + ca.append("size_t out_capacity") + ha.append("CSize") + names.append("_outCapacity") + validations.append( + f' if ({length_name} + {extra} > (size_t)PTRDIFF_MAX / sizeof({ct})) return hm_error(HMATH_OVERFLOW, "output byte span exceeds ptrdiff_t");\n' + ) + validations.append( + f' if (out_capacity < {length_name} + {extra}) return hm_error(HMATH_BOUNDS_ERROR, "insufficient output capacity");\n' + ) + validations.append( + f' if (({length_name} + {extra}) && !{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL list output");\n' + ) + forces.append( + f" strict{index} <- mapM evaluate {expression}\n" + ) + # mapM completes every element before pokeArray starts. + pokes.append( + f" pokeArray (castPtr {name} :: Ptr {native}) strict{index}\n" + ) + else: + validations.append( + f' if (!{name}) return hm_error(HMATH_INVALID_ARGUMENT, "NULL output");\n' + ) + if kind == "z": + strings.append(f"show ({expression})") + pokes.append( + f" poke {name} (textPointers !! {len(strings) - 1})\n" + ) + else: + forces.append( + f" strict{index} <- evaluate ({expression})\n" + ) + val = ( + f"(coerce strict{index} :: {ht})" + if kind == "f" + else f"(coerce strict{index} :: {BOUNDED[kind][1]})" + if kind in BOUNDED + else f"(fromIntegral strict{index})" + if kind == "i" + else f"(if strict{index} then 1 else 0)" + ) + pokes.append(f" poke {name} {val}\n") + csig = ( + f"hmath_status {symbol}(\n " + + ",\n ".join(["hmath_context *context"] + ca) + + ")" + ) + header.append( + f"/* {source}; {variant['dtype'] or 'fixed'} specialization. */\nHMATH_API {csig};\n" + ) + docs.append(f"```c\n{csig};\n```\n\n") + c.append( + f"extern int {internal}(\n " + + ",\n ".join(ca) + + f");\n{csig} {{\n" + ) + c.extend(validations) + c.append( + " hmath_status status = hm_enter(context);\n if (status) return status;\n" + ) + cnames = [item.rsplit(" ", 1)[-1].lstrip("*") for item in ca] + c.append( + f" status = (hmath_status){internal}({', '.join(cnames)});\n hm_leave();\n return status;\n}}\n" + ) + hsig = "\n " + " ->\n ".join(ha + ["IO CInt"]) + hs.append( + f'\nforeign export ccall "{internal}" {hsname} :: {hsig}\n{hsname} :: {hsig}\n' + ) + hs.append(f"{hsname} {' '.join(names)} = boundary $ do\n") + hs.extend(reads) + call = f"{module}.{entry['name']}" + ( + "\n " + "\n ".join(arguments) if arguments else "" + ) + wrapped = call if entry["checked"] else f"Right ({call})" + # Concrete annotation is required for no-argument constants. + if not entry["args"]: + wrapped = f"Right ({call} :: {native})" + hs.append(f" checked ({wrapped}) $ \\{pattern} -> do\n") + hs.extend(forces) + if strings: + hs.append( + f" writeStrings [{', '.join(strings)}] $ \\textPointers -> do\n" + ) + hs.extend(pokes) + else: + hs.extend(line[4:] for line in pokes) + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + outputs = { + "include/hmath_numeric.h": "".join(header), + "cbits/numeric_generated.c": re.sub( + r" if \((.+)\) return (.+);", + r" if (\1)\n return \2;", + "".join(c), + ), + "src/HMath/FFI/Numeric.hs": "".join(hs), + "docs/reference/numeric-bindings.md": "".join(docs), + "bindings/schema/numeric-symbols.txt": "\n".join(symbols) + "\n", + } + outputs.update( + { + f"bindings/python/_hmath_native/{group}.py": "".join(lines) + for group, lines in python.items() + } + ) + outputs["bindings/python/_hmath_native/_numeric_modules.py"] = ( + f"# SPDX-License-Identifier: MPL-2.0\n{PYTHON_MARKER}\n\n" + "NUMERIC_MODULES = (\n" + + "".join(f" {name!r},\n" for name in sorted(python)) + + ")\n" + ) + if "special" in python: + outputs["bindings/python/_hmath_native/special.py"] = outputs[ + "bindings/python/_hmath_native/special.py" + ].replace( + "from ._numeric import _call", "from ._numeric import SFResult, _call" + ) + outputs["bindings/python/_hmath_native/special.py"] += ( + "\n\n__all__ = " + + repr( + sorted( + [e["python"] for e in entries if e["module"] == "HMath.Special"] + + ["SFResult"] + ) + ) + + "\n" + ) + for group, extension in { + "units": "units_values", + "random": "random_values", + "probability": "probability_values", + "statistics_advanced": "statistics_values", + "signal": "signal_values", + "fourier": "fourier_values", + "interpolation": "interpolation_values", + "datastructure": "data_structures", + "discrete": "discrete_values", + "algorithms": "algorithm_values", + "combinatorics": "combinatorics_values", + "tensor": "_tensor_core", + "deeplearning_core": "_neural_core", + "deeplearning_precision": "_neural_precision", + "deeplearning_metrics": "_neural_metrics", + "complex": "complex_extras", + "trigonometry": "trigonometry_extras", + "numbertheory": "numbertheory_extras", + "special": "special_extras", + }.items(): + if group in python: + outputs[f"bindings/python/_hmath_native/{group}.py"] += ( + f"\n\nfrom .{extension} import *\n" + ) + if group == "special": + outputs["bindings/python/_hmath_native/special.py"] += ( + "\n__all__.extend(['sf_error', 'sf_result', 'sf_value'])\n" + ) + return outputs + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + stale = [] + outputs = generate() + protected = {"autodiff.py", "matrix.py", "optimization.py"} + owned_directory = ROOT / "bindings/python/_hmath_native" + for path in owned_directory.glob("*.py"): + if path.name in protected or str(path.relative_to(ROOT)) in outputs: + continue + text = path.read_text() + owned = PYTHON_MARKER in text + legacy_owned = ( + "# Generated; do not edit." in text + and "from ._numeric import _call\n" in text + ) + if owned or legacy_owned: + if args.check: + stale.append(str(path.relative_to(ROOT))) + else: + path.unlink() + for name, text in outputs.items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != text: + stale.append(name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + if stale: + parser.exit(1, "Stale generated bindings: " + ", ".join(stale) + "\n") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_numeric_objects.py b/tools/generate_numeric_objects.py new file mode 100644 index 0000000..4d2291f --- /dev/null +++ b/tools/generate_numeric_objects.py @@ -0,0 +1,136 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Add owned-Value specializations without duplicating original source coverage.""" + +import argparse +import json +from pathlib import Path + +from generate_numeric_bindings import prefix + +ROOT = Path(__file__).resolve().parent.parent + + +def generate(): + entries = [ + entry + for entry in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + if entry.get("specializations") + ] + assert len(entries) == 31 + entries += [ + entry + for entry in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + if entry["name"] in {"hammingDistance", "jaccardDistance"} + and entry["module"] == "HMath.Geometry.Primitives" + ] + assert len(entries) == 33 + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_numeric_objects.py. */\n#ifndef HMATH_NUMERIC_OBJECTS_H\n#define HMATH_NUMERIC_OBJECTS_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Additional type instances of existing source functions; no new source\n * coverage is claimed. Actual Coefficient witnesses retain Float/Double, exact\n * Integer/Rational, bounded/native integers, Complex, nested Numeric.Dual and\n * Num-only Numeric.Quaternion. Original AD.Dual (including nested supported\n * leaves) and AD.Expr use distinct original Num/Fractional/Floating instances.\n * Eq/Ord/Integral/Bounded are required only where the original signature needs\n * them. AD.Expr has no Eq/Ord; Numeric.Dual/Quaternion have no Ord. Unsupported\n * instances return UNSUPPORTED; no ordering or arithmetic instance is invented.\n * clamp/min/max use actual native Ord dictionaries, including supported public\n * labels and recursively typed lists/tuples/Maybe. All inputs are borrowed;\n * outputs own one reference and remain untouched on failure. The prototype\n * selects the actual numeric type (required for empty lists), and all numeric\n * values must have that same actual type. Source exceptions/MathErrors remain\n * unchanged. Arbitrary user-defined Haskell instances need compiled adapters. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_numeric_objects.py. */\n#include "hmath_numeric_objects.h"\n#include "value_internal.h"\nextern int hm_numeric_objects_apply(int,void *,void *const *,size_t,void **);\n' + ] + specializations = [] + docs = [ + "# Typed generic numeric APIs\n\nThese are additional type instances of the same Basic, Scalar, Linear, Statistics and Geometry equality functions, not additional source functions. Existing flat C APIs and Python dtype defaults remain unchanged. C includes `hmath_numeric_objects.h`; each original prefix gains `_value` and an explicit borrowed typed prototype, with owned Value outputs.\n\n", + 'Python automatically selects this path when an argument contains a native numeric owner (recursively through lists), including `Numeric.Dual`, `Numeric.Quaternion`, original `Autodiff.Dual` and symbolic `Autodiff.Expr`. Use `dtype=prototype` for empty vectors, or `dtype="value"` for ordinary values using their exact encoded type, such as unbounded integers or ordered strings/Booleans/tuples/lists. All numeric operands must have the same actual Haskell type; no implicit widening or conversion between the two distinct Dual types occurs.\n\n', + "The actual Coefficient dictionaries preserve all existing standard primitive numeric instances, recursively nested Numeric.Dual and Quaternion where permitted. Original AD.Dual dictionaries preserve its primal-only ordering and full-field equality. Symbolic AD.Expr has Num/Fractional/Floating but no Eq/Ord: normalization and median therefore reject it. Numeric.Quaternion has Num only, so fractional/floating statistics reject it; Numeric.Dual has no Ord. Integral/Bounded operations keep their actual bounded instances and reject nonintegral objects. Ord-only clamp/min/max use the shared resolver for supported native public labels, lists, tuples and optional values, calling the actual original Ord dictionary. Geometry hamming/jaccard Value paths retain the shared native Eq dictionaries: exact coefficients, Numeric.Dual/Quaternion, supported original AD.Dual, structural values and supported domain owners. They do not substitute an ordering comparison for equality. Arbitrary user-defined Haskell instances require a compiled bridge; these finite adapters do not claim universal typeclass coverage.\n\n", + '```python\nfrom hmath import scalar, statistics, numeric_types\n\nwith numeric_types.dual(2.0, 1.0) as x, numeric_types.dual(3.0, 0.0) as y:\n with scalar.add(x, y) as z:\n assert numeric_types.primal(z) == 5.0\n with statistics.mean([x, y]) as mean:\n assert numeric_types.primal(mean) == 2.5\n\nassert scalar.minimum_scalar("alpha", "beta", dtype="value") == "alpha"\n```\n\n', + ] + symbols = [] + for operation, entry in enumerate(entries): + symbol = prefix(entry) + "_value" + params = [ + a["name"] + "_" if a["name"] in ("class", "from", "lambda") else a["name"] + for a in entry["args"] + ] + parameters = ", ".join( + ["hmath_context *context", "const hmath_value *prototype"] + + ["const hmath_value *" + name for name in params] + + ["hmath_value **out"] + ) + header.append( + "/* " + + entry["module"] + + "." + + entry["name"] + + "; original typeclass constraints. */\nHMATH_API hmath_status " + + symbol + + "(" + + parameters + + ");\n" + ) + c.append( + "hmath_status " + + symbol + + "(" + + parameters + + ") {\n if(!out||!prototype" + + "".join("||!" + name for name in params) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL typed numeric argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n void *arguments[]={' + + ",".join("hm_value_stable(" + name + ")" for name in params) + + "};\n return hm_value_finish(result,hm_numeric_objects_apply(" + + str(operation) + + ",hm_value_stable(prototype),arguments," + + str(len(params)) + + ",&result->stable),out);\n}\n" + ) + symbols.append(symbol) + specializations.append( + { + "symbol": entry["module"] + "." + entry["name"], + "additional_c": symbol, + "python": "hmath." + + entry["module"].removeprefix("HMath.").replace(".", "_").lower() + + "." + + entry["python"], + "instances": "actual existing Coefficient/AD dictionaries allowed by original constraints; Ord/Eq-only functions additionally use supported native label dictionaries", + } + ) + docs.append( + "## `" + + specializations[-1]["python"] + + "`\n\nAdditional Value specialization for the [same original function](haskell/" + + entry["module"].replace(".", "-") + + ".md#v:" + + entry["name"] + + ").\n\n```c\nhmath_status " + + symbol + + "(" + + parameters + + ");\n```\n\n" + ) + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_numeric_objects.h": "".join(header), + "cbits/numeric_objects.c": "".join(c), + "bindings/schema/numeric-object-specializations.json": json.dumps( + {"schema": 1, "additional_specializations": specializations}, indent=2 + ) + + "\n", + "bindings/schema/numeric-object-symbols.txt": "\n".join(symbols) + "\n", + "docs/reference/numeric-objects.md": "".join(docs), + } + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--check", action="store_true") + args = p.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + p.exit(1, "Stale typed numeric binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_numeric_types.py b/tools/generate_numeric_types.py new file mode 100644 index 0000000..5a95097 --- /dev/null +++ b/tools/generate_numeric_types.py @@ -0,0 +1,819 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate typed opaque adapters for existing Numeric and Constants APIs.""" + +import argparse +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SPECS = [] + + +def spec(name, args, expression, checked=False, symbol=None, module="Numeric"): + SPECS.append( + { + "name": name, + "args": [{"name": n, "type": t} for n, t in args], + "expression": expression, + "checked": checked, + "symbol": symbol, + "module": module, + } + ) + + +def obj(name): + return (name, "o") + + +def unary(name, subtype, expression, checked=False, symbol=None): + spec(name, [("value", subtype)], expression, checked, symbol or name) + + +def binary(name, subtype, expression, checked=False): + spec(name, [("a", subtype), ("b", subtype)], expression, checked, name) + + +spec("type_name", [obj("value")], "pure (Text (objectType value))") +spec("binary", [("operation", "i32"), obj("a"), obj("b")], "binary operation a b") +spec("unary", [("operation", "i32"), obj("value")], "unary operation value") +spec("literal_integer", [obj("like"), ("value", "z")], "literalInteger like value") +spec("literal_rational", [obj("like"), ("value", "q")], "literalRational like value") +spec("integer_power", [obj("value"), ("power", "z")], "integerPower value power") +spec("equal", [obj("a"), obj("b")], "pure (Boolean (a == b))") +spec("sequence_get", [obj("value"), ("index", "i")], "sequenceItem index value") +spec( + "round_rational", + [("mode", "mode"), ("value", "q")], + "pure (ninteger (N.roundRational mode value))", + symbol="roundRational", +) +unary("classify", "o", "classify value", symbol="classify") +unary("frexp", "o", "frexp value", symbol="frexp") +unary("numeric_limits", "o", "numericLimits value", symbol="numericLimits") +unary("integer_limits", "o", "integerLimits value", symbol="integerLimits") +spec( + "float16_limits", + [], + "pure (limits SDouble N.float16Limits)", + symbol="float16Limits", +) +spec( + "bfloat16_limits", + [], + "pure (limits SDouble N.bfloat16Limits)", + symbol="bfloat16Limits", +) +spec( + "numeric_limits_record", + [ + obj("normal"), + obj("subnormal"), + obj("maximum_value"), + obj("epsilon"), + ("digits", "i"), + ("low", "i"), + ("high", "i"), + ], + "makeLimits normal subnormal maximum_value epsilon digits low high", + symbol="NumericLimits", +) +for index, name in enumerate( + [ + "minimumNormal", + "minimumSubnormal", + "maximumFinite", + "machineEpsilon", + "significandDigits", + "minimumExponent", + "maximumExponent", + ] +): + snake = re.sub(r"(? N.bigFloat (fromIntegral precision) mode value)", + True, + "bigFloat", +) +spec("extended", [("value", "q")], "pure (Big <$> N.extended value)", True, "extended") +unary( + "big_precision", "big", "pure (nint (N.bigPrecision value))", symbol="bigPrecision" +) +unary( + "big_rational", + "big", + "pure (nrational (N.bigRational value))", + symbol="bigRational", +) +unary( + "big_to_double", "big", "pure (ndouble (N.bigToDouble value))", symbol="bigToDouble" +) +for name in ["Add", "Subtract", "Multiply", "Divide"]: + binary("big_" + name.lower(), "big", f"pure (Big <$> N.big{name} a b)", True) + SPECS[-1]["symbol"] = "big" + name +for name in ["Sqrt", "Exp", "Log"]: + unary( + "big_" + name.lower(), + "big", + f"pure (Big <$> N.big{name} value)", + True, + "big" + name, + ) +for name in ["Add", "Multiply"]: + spec( + "mixed_" + name.lower(), + [("a", "big"), ("b", "f64")], + f"pure (Big <$> N.mixed{name} a b)", + True, + "mixed" + name, + ) +for prefix, wrapper, htype in [ + ("fixed", "Fixed", "fixed"), + ("decimal", "Decimal", "decimal"), +]: + spec( + prefix, + [("scale", "i"), ("mode", "mode"), ("value", "q")], + f"pure (rounded {wrapper} <$> N.{prefix} (fromIntegral scale) mode value)", + True, + prefix, + ) + unary( + prefix + "_rational", + htype, + f"pure (nrational (N.{prefix}Rational value))", + False, + prefix + "Rational", + ) + binary( + prefix + "_add", htype, f"pure (rounded {wrapper} <$> N.{prefix}Add a b)", True + ) + SPECS[-1]["symbol"] = prefix + "Add" + for name in ["Multiply", "Divide"]: + spec( + prefix + "_" + name.lower(), + [("mode", "mode"), ("a", htype), ("b", htype)], + f"pure (rounded {wrapper} <$> N.{prefix}{name} mode a b)", + True, + prefix + name, + ) +unary("fixed_scale", "fixed", "pure (nint (N.fixedScale value))", symbol="fixedScale") +unary( + "fixed_coefficient", + "fixed", + "pure (ninteger (N.fixedCoefficient value))", + symbol="fixedCoefficient", +) +spec( + "interval", + [("low", "f64"), ("high", "f64")], + "pure (Interval <$> N.interval low high)", + True, + "interval", +) +unary( + "interval_bounds", + "interval", + 'let (a,b)=N.intervalBounds value in pure (Sequence True "" [ndouble a,ndouble b])', + symbol="intervalBounds", +) +spec( + "interval_contains", + [("value", "interval"), ("point", "f64")], + "pure (Boolean (N.intervalContains value point))", + symbol="intervalContains", +) +for name in ["Add", "Subtract", "Multiply", "Divide"]: + binary( + "interval_" + name.lower(), + "interval", + f"pure (Interval <$> N.interval{name} a b)", + True, + ) + SPECS[-1]["symbol"] = "interval" + name +spec( + "dual", + [obj("primal_value"), obj("tangent_value")], + "makeDual primal_value tangent_value", + symbol="Dual", +) +unary("primal", "o", "primal value", symbol="primal") +unary("tangent", "o", "tangent value", symbol="tangent") +spec( + "derivative", + [("function", "callback"), obj("value")], + "derivative function functionUserdata value", + symbol="derivative", +) +spec( + "quaternion", + [obj("real"), obj("i"), obj("j"), obj("k")], + "makeQuaternion real i j k", + symbol="Quaternion", +) +unary( + "quaternion_conjugate", + "o", + "quaternionConjugate value", + symbol="quaternionConjugate", +) +unary("quaternion_norm", "o", "quaternionNorm value", symbol="quaternionNorm") +unary("quaternion_inverse", "o", "quaternionInverse value", True, "quaternionInverse") +spec( + "quaternion_component", + [obj("value"), ("index", "i")], + "quaternionComponent index value", +) +spec( + "dual_quaternion", + [obj("real"), obj("dual")], + "makeDualQuaternion real dual", + symbol="DualQuaternion", +) +spec( + "dual_quaternion_component", + [obj("value"), ("index", "i")], + "dualQuaternionComponent index value", +) +spec( + "dual_quaternion_multiply", + [obj("a"), obj("b")], + "dualQuaternionMultiply a b", + symbol="dualQuaternionMultiply", +) +unary( + "dual_quaternion_inverse", + "o", + "dualQuaternionInverse value", + True, + "dualQuaternionInverse", +) +for snake, hs in [ + ("rotate_vector", "rotateVector"), + ("rigid_transform", "rigidTransform"), + ("transform_point", "transformPoint"), +]: + spec( + snake, + [obj("value"), obj("x"), obj("y"), obj("z")], + f"{hs} value x y z", + True, + hs, + ) +spec( + "constant", + [ + ("name", "text"), + ("value", "q"), + ("uncertainty", "q"), + ("approximation", "q"), + ("unit", "text"), + ("source", "text"), + ], + "pure (Constant (K.Constant name value uncertainty approximation unit source))", + symbol="Constant", + module="Constants", +) +for index, name in enumerate( + [ + "constantName", + "constantValue", + "standardUncertainty", + "approximationBound", + "constantUnit", + "constantSource", + ] +): + unary( + re.sub(r"(?\n', + """extern int hm_numeric_types_clone(void *stable,void **out); +void hmath_numeric_types_retain(hmath_numeric_value *value) { hmath_value_retain(value); } +void hmath_numeric_types_release(hmath_numeric_value *value) { hmath_value_release(value); } +void hmath_numeric_types_buffer_free(void *value) { free(value); } +int hmath_numeric_types_kind(const hmath_numeric_value *value) { return value ? value->kind : 0; } +int hm_numeric_types_invoke(hmath_numeric_callback callback,void *userdata,void *input_stable,void **out) { + hmath_numeric_value *temporary=NULL,*input=NULL,*output=NULL; + hmath_status status=hm_value_begin(NULL,&temporary); + if(status) { extern void hm_value_free(void *);hm_value_free(input_stable);return status; } + temporary->stable=input_stable; + status=hm_value_finish(temporary,0,&input); + if(status) return status; + status=callback(input,userdata,&output); + if(!status && !output) status=hm_error(HMATH_INVALID_ARGUMENT,"callback returned NULL value"); + if(!status) status=(hmath_status)hm_numeric_types_clone(output->stable,out); + if(output) hmath_value_release(output); + hmath_value_release(input); + return status; +} +""", + ] + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated by tools/generate_numeric_types.py.\nmodule HMath.FFI.NumericTypes where\nimport HMath.FFI.NumericTypes.Core\nimport HMath.FFI.Boundary (checked, readInteger)\nimport HMath.FFI.Coefficient\nimport qualified HMath.Numeric as N\nimport qualified HMath.Constants as K\nimport Data.Coerce (coerce)\nimport Data.Ratio ((%))\nimport Foreign\nimport Foreign.C\n" + ] + symbols = [ + "hmath_numeric_types_" + name + for name in ["retain", "release", "buffer_free", "kind"] + ] + mapping = [] + for item in SPECS: + name = item["name"] + public = "hmath_numeric_types_" + name + internal = "hm_numeric_types_" + name + hsname = "ffi" + "".join(x.title() for x in name.split("_")) + ca = [] + ha = [] + hargs = [] + decode = [] + validation = [] + nativeargs = [] + for arg in item["args"]: + n, k = arg["name"], arg["type"] + h = "raw" + n[0].upper() + n[1:] + if k in OBJECT_TYPES: + ca.append(f"const hmath_numeric_value *{n}") + ha.append("Handle") + hargs.append(h) + decode.append(f" {n}Object <- dereference {h}\n") + decode.append( + f" {n} <- {OBJECT_TYPES[k]} {n}Object\n" + if OBJECT_TYPES[k] + else f" let {n} = {n}Object\n" + ) + validation.append( + f' if(!{n}) return hm_error(HMATH_INVALID_ARGUMENT,"NULL {n}");\n' + ) + nativeargs.append(n + "->stable") + elif k in ("i", "i32", "u16", "f32", "f64"): + ct, ht = { + "i": ("ptrdiff_t", "CPtrdiff"), + "i32": ("int", "CInt"), + "u16": ("uint16_t", "Word16"), + "f32": ("float", "CFloat"), + "f64": ("double", "CDouble"), + }[k] + ca.append(f"{ct} {n}") + ha.append(ht) + hargs.append(h) + nativeargs.append(n) + decode.append( + f" let {n} = coerce {h}\n" + if k in ("f32", "f64") + else f" let {n} = {h}\n" + ) + elif k == "mode": + ca.append(f"int {n}") + ha.append("CInt") + hargs.append(h) + nativeargs.append(n) + decode.append(f" {n} <- roundingMode {h}\n") + elif k in ("z", "q"): + labels = [n] if k == "z" else [n + "_numerator", n + "_denominator"] + parsed = [] + for label in labels: + hh = "raw" + label.replace("_", "X") + vv = label.replace("_", "X") + "Value" + ca.append(f"const char *{label}") + ha.append("CString") + hargs.append(hh) + nativeargs.append(label) + validation.append( + f' if(!hm_decimal({label})) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Integer decimal");\n' + ) + decode.append(f" {vv} <- readInteger {hh}\n") + parsed.append(vv) + if k == "q": + validation.append( + f" const char *{n}Digit={n}_denominator; if(*{n}Digit=='-') ++{n}Digit; while(*{n}Digit=='0') ++{n}Digit; if(!*{n}Digit) return hm_error(HMATH_INVALID_ARGUMENT,\"zero Rational denominator\");\n" + ) + decode.append( + f" let {n} = " + + (parsed[0] if k == "z" else parsed[0] + " % " + parsed[1]) + + "\n" + ) + elif k in ("text", "flags"): + ct, ht = ("uint32_t", "Word32") if k == "text" else ("int", "CInt") + ca.extend([f"const {ct} *{n}", f"size_t {n}_count"]) + ha.extend([f"Ptr {ht}", "CSize"]) + hargs.extend([h, h + "Count"]) + nativeargs.extend([n, n + "_count"]) + validation.append( + f' if({n}_count>(size_t)PTRDIFF_MAX/sizeof({ct}) || ({n}_count && !{n})) return hm_error(HMATH_INVALID_ARGUMENT,"invalid array span");\n' + ) + if k == "text": + validation.append( + f' for(size_t i=0;i<{n}_count;++i) if({n}[i]>0x10ffffu) return hm_error(HMATH_INVALID_ARGUMENT,"invalid Char code point");\n' + ) + decode.append( + f" {n}Object <- readText {h} {h}Count\n {n} <- getText {n}Object\n" + ) + else: + decode.append( + f" {n} <- peekArray (fromIntegral {h}Count) {h} >>= mapM exception\n" + ) + elif k == "callback": + ca.extend([f"hmath_numeric_callback {n}", f"void *{n}_userdata"]) + ha.extend(["FunPtr NumericCallback", "Ptr ()"]) + hargs.extend([n, n + "Userdata"]) + nativeargs.extend([n, n + "_userdata"]) + validation.append( + f' if(!{n}) return hm_error(HMATH_INVALID_ARGUMENT,"NULL callback");\n' + ) + else: + raise ValueError(k) + signature = ( + f"hmath_status {public}(hmath_context *context" + + (", " + ", ".join(ca) if ca else "") + + ", hmath_numeric_value **out)" + ) + header.append("HMATH_API " + signature + ";\n") + ffi_args = [] + for original, arg in zip(ca, nativeargs): + ffi_args.append( + "void *" + arg.split("->")[0] if "->stable" in arg else original + ) + # Native stable pointers replace typed wrapper pointers at this boundary. + ffi_decl = [ + re.sub(r"const hmath_numeric_value \*", "void *", arg) for arg in ca + ] + c.append( + f"extern int {internal}(" + + ", ".join(ffi_decl + ["void **out"]) + + ");\n" + + signature + + " {\n" + ) + c.extend(validation) + c.append( + ' if(!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL value output");\n hmath_numeric_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status) return status;\n' + ) + c.append( + " return hm_value_finish(result, " + + internal + + "(" + + ", ".join(nativeargs + ["&result->stable"]) + + "), out);\n}\n" + ) + hsig = " -> ".join(ha + ["Ptr Handle", "IO CInt"]) + hs.append( + f'\nforeign export ccall "{internal}" {hsname} :: {hsig}\n{hsname} :: {hsig}\n{hsname} ' + + " ".join(hargs + ["out"]) + + " = numericBoundary $ do\n" + ) + hs.extend(decode) + hs.append(f" result <- {item['expression']}\n") + hs.append( + " checked " + + ("(result)" if item["checked"] else "(Right result)") + + " (`publish` out)\n" + ) + symbols.append(public) + if item["symbol"]: + mapping.append( + { + "symbol": "HMath." + item["module"] + "." + item["symbol"], + "c": [public], + "python": "hmath.numeric_types." + name, + "specializations": ["typed opaque representation"], + } + ) + header.append( + "HMATH_API hmath_status hmath_numeric_types_enum_value(hmath_context *context,const hmath_numeric_value *value,int *out);\n" + ) + c.append( + 'extern int hm_numeric_types_enum_value(void *stable,int *out);\nhmath_status hmath_numeric_types_enum_value(hmath_context *context,const hmath_numeric_value *value,int *out) { if(!value||!out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL enum argument"); hmath_status status=hm_enter(context);if(status)return status;status=(hmath_status)hm_numeric_types_enum_value(value->stable,out);hm_leave();return status;}\n' + ) + symbols.append("hmath_numeric_types_enum_value") + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_numeric_types.py; do not edit.\n", + '"""Original HMath.Numeric types and Constants records.\n\n', + "Factories return immutable owned NumericValue objects for structured types.\n", + "Standard scalar results decode to Python numbers; use boxed properties\n", + "on NumericValue when preserving a scalar dtype through callbacks.\n", + '"""\n', + "from ._numeric_types_runtime import (\n IEEEClass,\n NumericException,\n NumericValue,\n RoundingMode,\n _call_named,\n number,\n)\n\n", + ] + signatures = {item["name"]: [a["type"] for a in item["args"]] for item in SPECS} + py.append("_SIGNATURES = " + json.dumps(signatures, indent=4) + "\n\n") + for item in SPECS: + name = item["name"] + names = [a["name"] for a in item["args"]] + parameters = ", ".join(names + ["*", "boxed=False"]) + py.append("def " + name + "(" + parameters + "):\n") + symbol = item["symbol"] + py.append( + ' """' + + ( + "HMath." + + item["module"] + + "." + + symbol + + "; retains the original type/rounding/error contract." + if symbol + else "Typed representation helper; no alternate numerical algorithm." + ) + + '"""\n' + ) + py.append( + " return _call_named(" + repr(name) + ", [" + ", ".join(names) + "], raw=boxed)\n\n" + ) + py.append( + "__all__ = " + + json.dumps( + sorted( + [ + "NumericValue", + "RoundingMode", + "NumericException", + "IEEEClass", + "number", + ] + + [item["name"] for item in SPECS] + ), + indent=4, + ) + + "\n" + ) + type_factories = { + "Float16": "float16_from_bits", + "BFloat16": "bfloat16_from_bits", + "BigFloat": "big_float", + "Fixed": "fixed", + "Decimal": "decimal", + "Interval": "interval", + } + for symbol, factory in type_factories.items(): + mapping.append( + { + "symbol": "HMath.Numeric." + symbol, + "c": ["hmath_numeric_types_" + factory], + "python": "hmath.numeric_types." + factory, + "specializations": ["original opaque Haskell type"], + } + ) + for group, constructors in [ + ( + "RoundingMode", + ["NearestEven", "TowardZero", "TowardPositive", "TowardNegative"], + ), + ( + "NumericException", + [ + "InvalidOperation", + "DivisionByZero", + "NumericOverflow", + "NumericUnderflow", + "Inexact", + ], + ), + ( + "IEEEClass", + [ + "NotANumber", + "PositiveInfinity", + "NegativeInfinity", + "PositiveZero", + "NegativeZero", + "Subnormal", + "Normal", + ], + ), + ]: + for symbol in [group] + constructors: + mapping.append( + { + "symbol": "HMath.Numeric." + symbol, + "c": [ + "hmath_numeric_types_classify" + if group == "IEEEClass" + else "hmath_numeric_types_rounded" + if group == "NumericException" + else "hmath_numeric_types_round_rational" + ], + "python": "hmath.numeric_types." + + group + + ( + "" + if symbol == group + else "." + re.sub(r"(? [Double] -> [Double])", text) + return re.sub(r"\ba\b", "Value", text) + + +def spec(text, known=None): + known = TYPES if known is None else known + text = text.strip() + arrows = split_top(text, "->") + if len(arrows) > 1: + parts = [spec(arrow, known) for arrow in arrows] + if parts[-1][0] == "function": + parts = parts[:-1] + parts[-1][1:] + return ["function", *parts] + if text.startswith("Either MathError "): + return ["either", spec(text[17:], known)] + if text.startswith("Maybe "): + inner = spec(text[6:], known) + if inner[0] == "maybe": + raise ValueError("nested Maybe requires a tagged representation") + return ["maybe", inner] + if text.startswith("[") and text.endswith("]"): + return ["list", spec(text[1:-1], known)] + if text.startswith("(") and text.endswith(")"): + fields = split_top(text[1:-1], ",") + if len(fields) > 1: + return ["tuple", *[spec(field, known) for field in fields]] + if not fields[0]: + return ["unit"] + return spec(text[1:-1], known) + if text in { + *known, + "EstimateDouble", + "Tolerance", + "GaussianState", + "Value", + "Double", + "Int", + "Integer", + "Rational", + "ComplexDouble", + "Bool", + "String", + "MatrixDouble", + "SparseDouble", + "ComplexPolynomial", + "RationalPolynomial", + }: + return [text] + raise ValueError("unsupported numerical representation: " + text) + + +def generate(entries=None, aliases=True): + if entries is None: + entries = json.loads( + (ROOT / "bindings/schema/numerical-functions.json").read_text() + )["functions"] + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_numerical_bindings.py. */\n#ifndef HMATH_NUMERICAL_H\n#define HMATH_NUMERICAL_H\n#include "hmath_linear.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Original checked numerical solvers and diagnostics. All arguments are\n * borrowed Value handles; success transfers one output reference. Outputs\n * remain untouched on failure. Function arguments use kind101 callbacks from\n * hmath_linear_callback, with a tuple of positional arguments. Keep callback\n * function/userdata valid while any object retaining it remains alive.\n * Source formulas, defaults, finite checks, limits and error variants are\n * preserved. Source Left MathError returns status11. Inputs/outputs may share\n * immutable handles; output addresses must be distinct from input storage.\n * Independent readers keep references alive, contexts remain per-call. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; do not edit. */\n#include "hmath_numerical.h"\n#include "value_internal.h"\nextern int hm_numerical_apply(int,void *const *,size_t,void **);\n' + ] + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated representation adapters; numerical functions are the originals.\nmodule HMath.FFI.NumericalAll where\nimport Foreign\nimport Foreign.C\nimport qualified HMath.FFI.Boundary as B\nimport HMath.FFI.NumericalCodec\nimport qualified HMath.FFI.Value as V\nimport qualified HMath.Calculus as C\nimport qualified HMath.Root as R\nimport qualified HMath.ODE as O\nimport qualified HMath.PDE as P\n" + ] + py = { + namespace: [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_numerical_bindings.py.\nfrom ._numerical_base import _invoke\nfrom ._value import Value, register\n" + ] + for namespace in MODULES + } + mappings = [] + source_names = {e["module"] + "." + e["name"] for e in entries} + for name, (namespace, typ, tag, fields) in TYPES.items(): + public = ( + "Estimate" + if name == "EstimateValue" + else "Method" + if name == "ODEMethod" + else name + ) + module = ( + "HMath." + namespace.capitalize() + if namespace not in ("ode", "pde") + else "HMath." + namespace.upper() + ) + py[namespace].append( + f'\n\nclass {public}(Value):\n """Owned immutable original {module}.{public}."""\n\n\nregister({tag}, {public})\n' + ) + symbol = "hmath_" + namespace + "_" + snake(public) + "_object" + header.append(f"typedef hmath_value {symbol}; /* kind{tag} */\n") + if name != "EstimateValue": + qualifier = MODULES[namespace] + hs.append( + f"instance From {typ} where from = unbox {tag}\ninstance To {typ} where\n to value = pure (box {tag} value [" + + ",".join(f"to ({qualifier}.{field} value)" for field in fields) + + "])\n" + ) + if module + "." + public not in source_names: + mappings.append( + { + "symbol": module + "." + public, + "c": [symbol], + "python": "hmath." + namespace + "." + public, + "specializations": ["original concrete type"], + } + ) + # The type alias is represented by an ordinary curried-function callback. + if aliases: + py["ode"].append( + "\n\nfrom typing import Callable as _Callable\nODE = _Callable[[float, list[float]], list[float]]\n" + ) + mappings.append( + { + "symbol": "HMath.ODE.ODE", + "c": ["hmath_linear_callback_fn"], + "python": "hmath.ode.ODE", + "specializations": [ + "Double -> [Double] -> [Double], flat positional callback" + ], + } + ) + hs.append( + 'foreign export ccall "hm_numerical_apply" dispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt\ndispatch :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt\ndispatch operation input arity out = B.boundary $ do\n values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr\n result <- case operation of\n' + ) + docs = [ + "# Numerical solvers\n\nPython exposes `hmath.calculus`, `hmath.root`, `hmath.ode` and `hmath.pde`. C includes `hmath_numerical.h`. Every named operation invokes the original Haskell function with its original argument order, defaults, budgets, diagnostic fields, finite checks and errors.\n\n", + "Inputs are borrowed, successful outputs own a [structured value](values.md), and failure leaves output pointers untouched. Immutable handles can be shared by concurrent readers retaining their own references. Source `Left MathError` returns status11 with its full structured payload. Cancellation is checked before entry; source evaluation/step limits govern the solver.\n\n", + "Function arguments are kind101 objects constructed with `hmath_linear_callback`. Their input is a tuple of the source's curried arguments flattened into positional order; their output transfers one owned value. Callbacks may reenter checked APIs and must not unwind through C. Python accepts normal callables and re-raises their original exceptions after cleanup. An actual source `Either MathError` callback may return a recoverable mathematical error; pure callbacks propagate it to the outer boundary. Callback function/userdata must remain valid for all objects retaining them. Python propagates these owners automatically.\n\n", + "`Estimate` retains an arbitrary structured payload; its value is never implicitly converted to binary64. Numerical estimates produced by these solvers have their original binary64 payload. `Matrix Double`, sparse operators and exact polynomial inputs interoperate with their existing typed binding owners.\n\n", + ] + for operation, entry in enumerate(entries): + namespace = entry["module"].removeprefix("HMath.").lower() + normalized = normalize(entry["signature"], namespace) + parts = split_top(normalized, "->") + arguments = parts[:-1] + specifications = [spec(t) for t in arguments] + spec(parts[-1]) + names = argument_names(entry, len(arguments)) + record = next( + ( + fields + for key, (ns, _, _, fields) in TYPES.items() + if ns == namespace + and ("Estimate" if key == "EstimateValue" else key) == entry["name"] + ), + [], + ) + if record and len(record) == len(arguments): + names = [snake(field) for field in record] + if namespace == "calculus" and entry["name"] == "Estimate": + names = ["value", "error", "evaluations"] + name = snake(entry["name"]) + source = entry["module"] + "." + entry["name"] + symbol = "hmath_" + namespace + "_" + name + prototype = ( + "hmath_status " + + symbol + + "(" + + ", ".join( + [ + "hmath_context *context", + *["const hmath_value *" + n for n in names], + "hmath_value **out", + ] + ) + + ")" + ) + header.append( + f"/* {source} :: {entry['signature']} */\nHMATH_API {prototype};\n" + ) + c.append( + prototype + + " {\n if (!out" + + "".join(" || !" + n for n in names) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL numerical argument");\n hmath_value *temporary=NULL;\n hmath_status status=hm_value_begin(context,&temporary);\n if (status) return status;\n void *arguments[]={' + + (", ".join("hm_value_stable(" + n + ")" for n in names) or "NULL") + + f"}};\n int code=hm_numerical_apply({operation},arguments,{len(names)},&temporary->stable);\n return hm_value_finish(temporary,code,out);\n}}\n" + ) + call = MODULES[namespace] + "." + entry["name"] + if namespace == "calculus" and entry["name"] in ( + "Estimate", + "estimateValue", + "estimateError", + "evaluations", + ): + signature = { + "Estimate": "V.Value -> Double -> Int -> C.Estimate V.Value", + "estimateValue": "C.Estimate V.Value -> V.Value", + "estimateError": "C.Estimate V.Value -> Double", + "evaluations": "C.Estimate V.Value -> Int", + }[entry["name"]] + call = "(" + call + " :: " + signature + ")" + hs.append(f" {operation} -> apply {call} values\n") + py[namespace].append( + f'\n\ndef {name}({", ".join(names)}):\n """{source} :: {entry["signature"]}."""\n return _invoke({symbol!r}, {specifications!r}, [{", ".join(names)}])\n' + ) + mappings.append( + { + "symbol": source, + "c": [symbol], + "python": "hmath." + namespace + "." + name, + "specializations": [ + "original binary64/exact/structured source types; Estimate payload remains generic" + ], + } + ) + docs.append( + f"## `{namespace}.{name}`\n\n`{namespace}.{name}({', '.join(names)})`\n\n{source_prose(entry)}\n\nOriginal: [`{source}`](haskell/{entry['module'].replace('.', '-')}.md#v:{entry['name']}).\n\n```haskell\n{entry['signature']}\n```\n\n```c\n{prototype};\n```\n\n" + ) + hs.append( + ' _ -> V.invalid "unknown numerical operation"\n V.forceValue result\n B.checked (Right ()) (\\_ -> V.publish result out)\n' + ) + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_numerical.h": "".join(header), + "cbits/numerical.c": "".join(c), + "src/HMath/FFI/NumericalAll.hs": "".join(hs), + **{ + "bindings/python/_hmath_native/" + n + ".py": "".join(lines) + for n, lines in py.items() + }, + "bindings/schema/numerical-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "docs/reference/numerical-solvers.md": "".join(docs), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale numerical binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_optimization_bindings.py b/tools/generate_optimization_bindings.py new file mode 100644 index 0000000..e45a225 --- /dev/null +++ b/tools/generate_optimization_bindings.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate the wheel catalog and audit original optimization dispatch coverage.""" + +import argparse +import ast +import json +import pprint +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + entries = json.loads((ROOT / "bindings/schema/optimization.json").read_text())[ + "functions" + ] + names = [entry["name"] for entry in entries] + assert len(names) == len(set(names)), "duplicate source dispatch name" + header = (ROOT / "include/hmath_optimization_all.h").read_text() + native = (ROOT / "cbits/optimization_all.c").read_text() + haskell = (ROOT / "src/HMath/FFI/OptimizationAll.hs").read_text() + python = ast.parse( + (ROOT / "bindings/python/_hmath_native/_optimization_all.py").read_text() + ) + functions = { + node.name: node for node in python.body if isinstance(node, ast.FunctionDef) + } + for entry in entries: + name, symbol = entry["name"], entry["c"] + assert len(entry["parameters"]) == len(entry["arguments"]), name + assert re.search(r"\b" + symbol + r"\s*\(", header), symbol + " header" + assert re.search(r"\b" + symbol + r"\s*\(", native), symbol + " C" + assert 'return invoke(context, "' + name + '"' in native, name + " C dispatch" + assert ( + '"' + name + '" -> apply ' + entry["expression"] + " arguments" in haskell + ), name + " Haskell dispatch" + if name[0].islower() and name not in {"initializeOptimizer", "optimizerStep"}: + assert entry["python"] in functions, name + " Python function" + parameters = [node.arg for node in functions[entry["python"]].args.args] + assert parameters == entry["parameters"], name + " Python parameters" + output = ( + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_optimization_bindings.py; do not edit.\nCATALOG = " + + pprint.pformat(entries, width=88, sort_dicts=False) + + "\n" + ) + path = ROOT / "bindings/python/_hmath_native/_optimization_catalog.py" + if args.check: + existing = ast.literal_eval(ast.parse(path.read_text()).body[0].value) + assert existing == entries, "generated optimization wheel catalog is stale" + else: + path.write_text(output) + print(f"Optimization catalog: {len(entries)} original named dispatches verified.") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_polynomial_bindings.py b/tools/generate_polynomial_bindings.py new file mode 100644 index 0000000..1339186 --- /dev/null +++ b/tools/generate_polynomial_bindings.py @@ -0,0 +1,326 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named adapters; the Haskell module owns source-operation dispatch.""" + +import argparse +import json +import re +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +OPS = json.loads((ROOT / "bindings/schema/polynomial-operations.json").read_text()) + + +def snake(name): + return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower() + + +def source_doc(name): + source = (ROOT / "src/HMath/Polynomial.hs").read_text() + pos = source.find("\n" + name + " ::") + before = source[:pos] + line = before.rfind("\n-- |") + block = before.rfind("\n{- |") + start = max(line, block) + text = before[start:].strip() + if start == block: + text = text.split("-}", 1)[0].replace("{- |", "", 1) + else: + text = text.replace("-- |", "", 1) + return " ".join(text.replace("--", "").replace("@", "`").split()) + + +RETURNS = { + "coefficients": "ascending coefficient list", + "polynomialDegree": "integer degree, or None for the zero polynomial", + "evaluatePolynomial": "coefficient scalar", + "dividePolynomial": "(quotient, remainder)", + "squareFreeFactors": "list of (monic factor, multiplicity)", + "rationalRoots": "list of (exact Rational root, multiplicity)", + "factorRationalPolynomial": "(leading scalar, [(monic factor, multiplicity)])", + "sturmSequence": "list of exact Rational polynomials", + "countRealRoots": "integer number of roots", + "isolateRealRoots": "list of exact Rational endpoint pairs", + "durandKerner": "list of Complex Double roots", + "aberthEhrlich": "list of Complex Double roots", + "companionMatrix": "interoperable Matrix with the same coefficient type", + "seriesCoefficients": "coefficient list, including trailing zeros", + "evaluateRationalFunction": "exact Rational scalar", + "partialFractions": "(polynomial part, [(numerator, denominator, power)])", +} +EXACT = { + "squareFreeFactors", + "rationalRoots", + "factorRationalPolynomial", + "sturmSequence", + "countRealRoots", + "isolateRealRoots", + "rationalFunction", + "rationalNumerator", + "rationalDenominator", + "evaluateRationalFunction", + "addRationalFunction", + "multiplyRationalFunction", + "partialFractions", +} + + +def format_python(source): + result = subprocess.run( + [ + "ruff", + "check", + "--select", + "I,RUF022", + "--fix", + "--stdin-filename", + "polynomial.py", + "-", + ], + input=source, + text=True, + capture_output=True, + check=True, + ) + return subprocess.run( + ["ruff", "format", "--stdin-filename", "polynomial.py", "-"], + input=result.stdout, + text=True, + capture_output=True, + check=True, + ).stdout + + +def outputs(): + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_polynomial_bindings.py. */\n#ifndef HMATH_POLYNOMIAL_H\n#define HMATH_POLYNOMIAL_H\n#include "hmath_value.h"\n#include "hmath_error.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n/* Every successful output is an owned immutable hmath_value. Release it with\n * hmath_value_release. Inputs are borrowed only for the call. Scalar and object\n * coefficient types must match; no implicit numerical conversion occurs.\n * prototype is a typed scalar selecting the coefficient type even for empty\n * input. Lists and tuples use the common Value transport. MathError returns\n * HMATH_MATH_ERROR with full hmath_last_math_error data. Failure leaves the\n * output pointer untouched. Same source budgets/defaults/normalization apply. */\n' + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_polynomial_bindings.py. */\n#include "hmath_polynomial.h"\n#include "value_internal.h"\nextern int hm_polynomial_apply(int opcode,void *const *args,size_t count,void **out);\n' + ] + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_polynomial_bindings.py.\n"""Direct typed bindings to every public HMath.Polynomial operation."""\nfrom ._polynomial_base import (Polynomial,PowerSeries,RationalFunction,_call,_construct,_typed_call,_prototype_call,chebyshev_approximation)\n' + ] + py.append( + "\n__all__ = " + + repr( + ["Polynomial", "PowerSeries", "RationalFunction", "chebyshev_approximation"] + + [snake(entry["name"]) for entry in OPS] + ) + + "\n" + ) + docs = [ + '# Polynomial and power series\n\nThese bindings call the original Haskell functions. Coefficients are ascending: `[a0,a1,...]` represents `a0+a1*x+...`. Polynomial construction removes trailing exact zeros; the zero polynomial has `degree is None`. Power series retain their full finite coefficient sequence, including trailing zeros. They use the source truncation rules. No tolerance, budget or arithmetic algorithm is substituted.\n\nUse `from hmath import polynomial as p`. Constructors accept `dtype="float64"` by default; choose `"float32"`, `"integer"`, `"rational"`, `"complex64"` or `"complex128"` explicitly. Bounded integral types are also available for Num operations. Rational results use `fractions.Fraction` and integers have no FP intermediary. Binary operations require matching coefficient types. A missing original typeclass instance returns `HMATH_UNSUPPORTED`; for example, polynomial division requires Fractional, and logarithmic series require ordered Floating coefficients.\n\n```python\nfrom fractions import Fraction\nfrom hmath import polynomial as p\nf = p.polynomial([1, 0, -2], dtype="rational")\ng = p.differentiate_polynomial(f)\nassert p.evaluate_polynomial(g, Fraction(3, 2)) == -6\nf.close()\ng.close()\n```\n\nC functions borrow inputs for the duration of the call and return independently owned `hmath_value` handles. Construct typed scalar/list/tuple values with `hmath_value.h`; release each owned handle once. `prototype` selects the coefficient type, including for empty lists. Outputs remain untouched on failure. Original `Left MathError` values return status 11 and retain constructor/fields/message through `hmath_last_math_error`. Python raises `HMathError` with `.math_error`. Opaque owners support `close()` and context management. All returned data are immutable; concurrent independent calls may share inputs.\n\n' + ] + mapping = [] + for entry in OPS: + name, args, opcode = entry["name"], entry["arguments"], entry["opcode"] + symbol = "hmath_polynomial_" + snake(name) + proto = ( + "hmath_status " + + symbol + + "(hmath_context *context, " + + ", ".join("const hmath_value *" + a for a in args) + + ", hmath_value **out)" + ) + header.append("HMATH_API " + proto + ";\n") + c.append( + proto + + " {\n if(!out || " + + " || ".join("!" + a for a in args) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL polynomial argument");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status;\n void *args[]={' + + ",".join("hm_value_stable(" + a + ")" for a in args) + + "};\n return hm_value_finish(result,hm_polynomial_apply(" + + str(opcode) + + ",args," + + str(len(args)) + + ",&result->stable),out);\n}\n" + ) + public_args = args[:] + if args[0] == "prototype": + public_args = public_args[1:] + signature = ", ".join(public_args) + if args[0] == "prototype": + signature += ', *, dtype="float64"' + py.append("\ndef " + snake(name) + "(" + signature + "):\n") + desc = ( + source_doc(name) + if opcode < 49 + else "Original derived Eq comparison; coefficient types must match." + ) + result = RETURNS.get( + name, + "Boolean" + if name.endswith("Equal") + else "RationalFunction" + if "RationalFunction" in name or name == "rationalFunction" + else "PowerSeries" + if "Series" in name or name == "powerSeries" + else "Polynomial", + ) + py.append( + " " + + repr( + "HMath.Polynomial." + name + ": " + desc + " Returns " + result + "." + ) + + "\n" + ) + if name in ("polynomial", "powerSeries"): + call = "_construct(" + repr(symbol) + ", coefficients, dtype)" + elif args[0] == "prototype": + call = ( + "_prototype_call(" + + repr(symbol) + + ", dtype, " + + ", ".join(public_args) + + ")" + ) + elif name in ( + "evaluatePolynomial", + "scalePolynomial", + "integratePolynomial", + "integrateSeries", + "evaluateRationalFunction", + "countRealRoots", + "isolateRealRoots", + ): + # Explicit scalar fields inherit the owned polynomial/series coefficient type. + owner = { + "evaluatePolynomial": 0, + "scalePolynomial": 1, + "integratePolynomial": 1, + "integrateSeries": 1, + "evaluateRationalFunction": 0, + "countRealRoots": 0, + "isolateRealRoots": 2, + }[name] + scalar_positions = { + "evaluatePolynomial": [1], + "scalePolynomial": [0], + "integratePolynomial": [0], + "integrateSeries": [0], + "evaluateRationalFunction": [1], + "countRealRoots": [1, 2], + "isolateRealRoots": [1], + }[name] + call = ( + "_typed_call(" + + repr(symbol) + + ", " + + str(owner) + + ", " + + repr(scalar_positions) + + ", " + + ", ".join(args) + + ")" + ) + elif name in ("durandKerner", "aberthEhrlich"): + call = ( + "_call(" + repr(symbol) + ", iterations, float(tolerance), polynomial)" + ) + else: + call = "_call(" + repr(symbol) + ", " + ", ".join(args) + ")" + py.append(" return " + call + "\n") + if opcode < 49: + mapping.append( + { + "symbol": "HMath.Polynomial." + name, + "c": [symbol], + "python": "hmath.polynomial." + snake(name), + "specializations": [ + "original coefficient constraints; standard numeric instances; Rational-only exact and ComplexDouble-only roots as source" + ], + } + ) + docs.append( + "## `" + + snake(name) + + "`\n\n" + + desc + + "\n\n`" + + snake(name) + + "(" + + signature + + ")` returns " + + result + + ". Parameters follow the original source order: " + + ", ".join("`" + a + "`" for a in args) + + "." + + ( + " This operation requires exact Rational coefficients." + if name in EXACT + else "" + ) + + "\n\n```c\n" + + proto + + ";\n```\n\n" + ) + header.append("""/* Callback is synchronous, called exactly according to source sampling. Set + * out only on success. HMATH_MATH_ERROR reads the structured error wire; + * other failure codes abort with its length-delimited message. Userdata/error + * payload storage must remain live until this enclosing call returns. */ +typedef hmath_status (*hmath_polynomial_callback)(double input,double *out,void *userdata,hmath_math_error *error); +HMATH_API hmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context,ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,hmath_value **out); +#ifdef __cplusplus +} +#endif +#endif +""") + c.append("""extern int hm_polynomial_chebyshev_approximation(ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,void **out); +hmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context,ptrdiff_t degree,hmath_polynomial_callback callback,void *userdata,hmath_value **out) { + if(!callback || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL approximation callback/output"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + return hm_value_finish(result,hm_polynomial_chebyshev_approximation(degree,callback,userdata,&result->stable),out); +} +""") + mapping.append( + { + "symbol": "HMath.Polynomial.chebyshevApproximation", + "c": ["hmath_polynomial_chebyshev_approximation"], + "python": "hmath.polynomial.chebyshev_approximation", + "specializations": ["Double callback, synchronous"], + } + ) + for source, kind, owner in [ + ("Polynomial", 6, "Polynomial"), + ("PowerSeries", 7, "PowerSeries"), + ("RationalFunction", 8, "RationalFunction"), + ]: + mapping.append( + { + "symbol": "HMath.Polynomial." + source, + "c": ["hmath_value", "hmath_value_release", "hmath_value_info"], + "python": "hmath.polynomial." + owner, + "specializations": ["owned immutable Value kind" + str(kind)], + } + ) + docs.append( + "## `chebyshev_approximation`\n\n" + + source_doc("chebyshevApproximation") + + "\n\n`chebyshev_approximation(degree, function)` returns a Double Polynomial. The callback is synchronous and sampled only by the original algorithm. It receives one Python float and returns one float. An original MathError raised by the callback is preserved; other Python exceptions are re-raised after native cleanup. No native callback or userdata outlives the call.\n\n```c\nhmath_status hmath_polynomial_chebyshev_approximation(hmath_context *context, ptrdiff_t degree, hmath_polynomial_callback callback, void *userdata, hmath_value **out);\n```\n" + ) + return { + "include/hmath_polynomial.h": "".join(header), + "cbits/polynomial.c": "".join(c), + "bindings/python/_hmath_native/polynomial.py": format_python("".join(py)), + "docs/reference/polynomial.md": "".join(docs), + "bindings/schema/polynomial-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mapping, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_rotation_bindings.py b/tools/generate_rotation_bindings.py new file mode 100644 index 0000000..5543dd9 --- /dev/null +++ b/tools/generate_rotation_bindings.py @@ -0,0 +1,401 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate exact checked Quaternion/SO(3)/SE(3) adapters over shared values.""" + +import argparse +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SPECS = [] + + +def snake(name): + return ( + re.sub(r"(? IO Q.Quaternion +getQuaternion (V.Opaque 72 _ _ _ value) = maybe (V.invalid "Quaternion payload mismatch") pure (cast value) +getQuaternion _ = V.invalid "expected HMath.Quaternion.Quaternion" +getRotation :: V.Value -> IO R.SO3 +getRotation (V.Opaque 73 _ _ _ value) = maybe (V.invalid "SO3 payload mismatch") pure (cast value) +getRotation _ = V.invalid "expected HMath.Rotation.SO3" +getTransform :: V.Value -> IO R.SE3 +getTransform (V.Opaque 74 _ _ _ value) = maybe (V.invalid "SE3 payload mismatch") pure (cast value) +getTransform _ = V.invalid "expected HMath.Rotation.SE3" +getDualQuaternion :: V.Value -> IO R.DualQuaternion +getDualQuaternion (V.Opaque 75 _ _ _ value) = maybe (V.invalid "DualQuaternion payload mismatch") pure (cast value) +getDualQuaternion _ = V.invalid "expected HMath.Rotation.DualQuaternion" +getMatrix :: V.Value -> IO (M.Matrix Double) +getMatrix (V.Dense (V.SomeMatrix _ value)) = maybe (V.invalid "Matrix Double required") pure (cast value) +getMatrix _ = V.invalid "expected dense Matrix Double" +getVector :: V.Value -> IO [Double] +getVector value = V.asList value >>= mapM V.asScalar +getTwist :: V.Value -> IO ([Double],[Double]) +getTwist value = do + values <- V.asTuple 2 value + case values of [a,b] -> (,) <$> getVector a <*> getVector b; _ -> V.invalid "twist tuple arity" +scalar :: Double -> V.Value +scalar = V.Scalar SDouble +vector :: [Double] -> V.Value +vector = V.List . map scalar +quaternion :: Q.Quaternion -> V.Value +quaternion value = V.Opaque 72 0 4 (mapM_ evaluate (Q.components value)) value +rotation :: R.SO3 -> V.Value +rotation value = V.Opaque 73 0 4 (V.forceValue (quaternion (R.rotationQuaternion value))) value +transform :: R.SE3 -> V.Value +transform value = V.Opaque 74 0 7 (V.forceValue (rotation (R.rotationPart value)) >> V.forceValue (vector (R.translationPart value))) value +dualQuaternion :: R.DualQuaternion -> V.Value +dualQuaternion value = let (a,b)=R.dualParts value in V.Opaque 75 0 8 (V.forceValue (quaternion a) >> V.forceValue (quaternion b)) value +matrix :: M.Matrix Double -> V.Value +matrix = V.Dense . V.SomeMatrix SDouble +axisAngle :: ([Double],Double) -> V.Value +axisAngle (axis,angle) = V.Tuple [vector axis,scalar angle] +triple :: (Double,Double,Double) -> V.Value +triple (a,b,c) = V.Tuple [scalar a,scalar b,scalar c] +quaternionPair :: (Q.Quaternion,Q.Quaternion) -> V.Value +quaternionPair (a,b) = V.Tuple [quaternion a,quaternion b] +twist :: ([Double],[Double]) -> V.Value +twist (a,b) = V.Tuple [vector a,vector b] +foreign export ccall "hm_rotations_equal" equal :: Handle -> Handle -> Ptr Handle -> IO CInt +equal :: Handle -> Handle -> Ptr Handle -> IO CInt +equal first second out = boundary $ do + a <- deRefStablePtr first + b <- deRefStablePtr second + result <- case (V.valueInfo a,V.valueInfo b) of + ((72,_,_),(72,_,_)) -> (==) <$> getQuaternion a <*> getQuaternion b + ((73,_,_),(73,_,_)) -> (==) <$> getRotation a <*> getRotation b + ((74,_,_),(74,_,_)) -> (==) <$> getTransform a <*> getTransform b + ((75,_,_),(75,_,_)) -> (==) <$> getDualQuaternion a <*> getDualQuaternion b + _ -> V.invalid "rotation object types differ" + checked (Right (V.Boolean result)) (`V.publish` out) +""" + + +def generate(): + h = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_rotation_bindings.py. */\n#ifndef HMATH_ROTATIONS_H\n#define HMATH_ROTATIONS_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + """/* Actual HMath.Quaternion/HMath.Rotation objects, distinct from Numeric types. + * Owned immutable common Value handles use kinds72 Quaternion,73 SO3,74 SE3, + *75 Rotation.DualQuaternion. Inputs are borrowed for the call; outputs transfer + *one owned reference and remain untouched on failure. Release with + *hmath_value_release. Every live reference pins the runtime. Independent calls + *can share immutable values while retaining a reference per participating thread. + *All scalar/vector/matrix coefficients are original Double. Lists and tuples + *retain their source structure. Vectors are shared list handles; twists are + *tuples of two lists. Matrix conversions consume/return shared Dense handles. + *Original validation, NaN/Inf, normalization, sign, angle, error and interpolation + *policies apply unchanged. Source MathError uses status11 with full payload. + *Active right-handed column-vector rotations use radians. compose(a,b) applies + *b first; Euler angles are intrinsic ZYX, passed as roll,pitch,yaw. + */\n""", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_rotation_bindings.py. */\n#include "hmath_rotations.h"\n#include "value_internal.h"\n' + ] + hs = [HS_PREFIX] + symbols = [] + mappings = [] + pmodules = {} + extra = { + "module": "Rotations", + "name": "equal", + "python": "equal", + "args": [("a", "o"), ("b", "o")], + } + for item in SPECS + [extra]: + module = item["module"].lower() + name = item["python"] + public = "hmath_" + module + "_" + name + internal = "hm_" + module + "_" + name + args = item["args"] + signature = ( + "hmath_status " + + public + + "(hmath_context *context" + + "".join(", const hmath_value *" + arg for arg, _ in args) + + ", hmath_value **out)" + ) + h.append("HMATH_API " + signature + ";\n") + c.append( + "extern int " + + internal + + "(" + + ", ".join(["void *" + arg for arg, _ in args] + ["void **out"]) + + ");\n" + + signature + + " {\n" + ) + c.append( + " if(" + + " || ".join(["!" + arg for arg, _ in args] + ["!out"]) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL rotation argument");\n' + ) + c.append( + " hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status) return status;\n return hm_value_finish(result," + + internal + + "(" + + ", ".join([arg + "->stable" for arg, _ in args] + ["&result->stable"]) + + "),out);\n}\n" + ) + symbols.append(public) + if item is extra: + continue + hsname = "ffi" + item["module"] + item["name"][0].upper() + item["name"][1:] + hsig = " -> ".join(["Handle"] * len(args) + ["Ptr Handle", "IO CInt"]) + hs.append( + '\nforeign export ccall "' + + internal + + '" ' + + hsname + + " :: " + + hsig + + "\n" + + hsname + + " :: " + + hsig + + "\n" + + hsname + + " " + + " ".join(["raw" + arg[0].upper() + arg[1:] for arg, _ in args] + ["out"]) + + " = boundary $ do\n" + ) + getters = { + "q": "getQuaternion", + "r": "getRotation", + "t": "getTransform", + "dq": "getDualQuaternion", + "v": "getVector", + "d": "V.asScalar", + "m": "getMatrix", + "twist": "getTwist", + } + for arg, kind in args: + hs.append( + " arg" + + arg[0].upper() + + arg[1:] + + " <- deRefStablePtr raw" + + arg[0].upper() + + arg[1:] + + " >>= " + + getters[kind] + + "\n" + ) + expr = item["expression"] or ("Q." if module == "quaternion" else "R.") + item[ + "name" + ] + "".join(" arg" + arg[0].upper() + arg[1:] for arg, _ in args) + result = expr if item["checked"] else "Right (" + expr + ")" + wraps = { + "q": "quaternion", + "r": "rotation", + "t": "transform", + "dq": "dualQuaternion", + "v": "vector", + "d": "scalar", + "m": "matrix", + "axis": "axisAngle", + "triple": "triple", + "qq": "quaternionPair", + "twist": "twist", + } + hs.append( + " checked (" + + result + + ") (\\value -> V.publish (" + + wraps[item["result"]] + + " value) out)\n" + ) + pmodules.setdefault(module, []) + pmodules[module].append(item) + mappings.append( + { + "symbol": "HMath." + item["module"] + "." + item["name"], + "c": [public], + "python": "hmath." + module + "." + name, + "specializations": ["original checked Double representation"], + } + ) + typeinfo = [ + ("Quaternion", "Quaternion", "quaternion", "quaternion"), + ("Rotation", "SO3", "rotation", "so3"), + ("Rotation", "SE3", "rotation", "se3"), + ("Rotation", "DualQuaternion", "rotation", "dual_quaternion"), + ] + for source, typ, module, constructor in typeinfo: + mappings.append( + { + "symbol": "HMath." + source + "." + typ, + "c": ["hmath_" + module + "_" + constructor], + "python": "hmath." + module + "." + typ, + "specializations": ["original opaque Haskell type"], + } + ) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + outputs = { + "include/hmath_rotations.h": "".join(h), + "cbits/rotations.c": "".join(c), + "src/HMath/FFI/Rotations.hs": "".join(hs), + "bindings/schema/rotation-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + "bindings/schema/rotation-symbols.txt": "\n".join(symbols) + "\n", + } + for module, items in pmodules.items(): + types = ( + ["Quaternion"] + if module == "quaternion" + else ["SE3", "SO3", "DualQuaternion"] + ) + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_rotation_bindings.py; do not edit.\n", + '"""Original HMath.' + module.title() + ' finite Double operations."""\n', + "from ._rotations_base import " + ", ".join(types + ["_call"]) + "\n\n", + ] + py.append( + "__all__ = " + + json.dumps( + sorted( + types + [i["python"] for i in items], + key=lambda name: (not name.isupper(), name), + ), + indent=4, + ) + + "\n\n" + ) + for item in items: + names = [arg for arg, _ in item["args"]] + py.append( + "\ndef " + + item["python"] + + "(" + + ", ".join(names) + + '):\n """Call HMath.' + + item["module"] + + "." + + item["name"] + + ' with its original validation and result structure."""\n' + ) + py.append( + " return _call(" + + repr("hmath_" + module + "_" + item["python"]) + + ", " + + repr([k for _, k in item["args"]]) + + "".join(", " + a for a in names) + + ")\n" + ) + outputs["bindings/python/_hmath_native/" + module + ".py"] = "".join(py) + return outputs + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + bad = [] + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + bad.append(name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + if bad: + parser.exit(1, "Stale rotation bindings: " + ", ".join(bad) + "\n") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_scalar_extras.py b/tools/generate_scalar_extras.py new file mode 100644 index 0000000..796327a --- /dev/null +++ b/tools/generate_scalar_extras.py @@ -0,0 +1,517 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Complete the remaining Complex, Trigonometry, exact NT and SFResult APIs.""" + +import argparse +import json +import re +from pathlib import Path + +from generate_graph_bindings import snake, source_prose + +ROOT = Path(__file__).resolve().parent.parent +ELEMENTARY = [ + "Exp", + "Log", + "Sqrt", + "Sin", + "Cos", + "Tan", + "Sinh", + "Cosh", + "Tanh", + "Asin", + "Acos", + "Atan", + "Asinh", + "Acosh", + "Atanh", +] +COMPLEX_FUNCTION = [ + "CSin", + "CCos", + "CTan", + "CAsin", + "CAcos", + "CAtan", + "CSinh", + "CCosh", + "CTanh", + "CAsinh", + "CAcosh", + "CAtanh", + "CSec", + "CCsc", + "CCot", + "CSech", + "CCsch", + "CCoth", +] +SPECS = [] + + +def add(namespace, module, name, args, result, expression, signature, checked=True): + SPECS.append( + { + "namespace": namespace, + "module": module, + "name": name, + "args": args, + "result": result, + "expression": expression, + "signature": signature, + "checked": checked, + } + ) + + +for name in ELEMENTARY: + add( + "complex", + "HMath.Complex", + name, + [], + "Elementary", + "pure (elementary C." + name + ")", + "Elementary", + False, + ) +for name in COMPLEX_FUNCTION: + add( + "trigonometry", + "HMath.Trigonometry", + name, + [], + "ComplexFunction", + "pure (complexFunction T." + name + ")", + "ComplexFunction", + False, + ) +add( + "complex", + "HMath.Complex", + "elementary", + [("operation", "Elementary"), ("value", "ComplexDouble")], + "ComplexDouble", + "source (C.elementary operation value) >>= pure . complexDoubleValue", + "Elementary -> Complex Double -> Either MathError (Complex Double)", +) +add( + "complex", + "HMath.Complex", + "complexMatrix", + [("rows", "Int"), ("columns", "Int"), ("values", "[ComplexDouble]")], + "ComplexMatrix", + "source (C.complexMatrix rows columns values) >>= pure . matrix", + "Int -> Int -> [Complex Double] -> Either MathError (Matrix (Complex Double))", +) +add( + "complex", + "HMath.Complex", + "multiplyMatrices", + [("a", "ComplexMatrix"), ("b", "ComplexMatrix")], + "ComplexMatrix", + "source (C.multiplyMatrices a b) >>= pure . matrix", + "Matrix (Complex Double) -> Matrix (Complex Double) -> Either MathError (Matrix (Complex Double))", +) +add( + "complex", + "HMath.Complex", + "conjugateTranspose", + [("value", "ComplexMatrix")], + "ComplexMatrix", + "source (C.conjugateTranspose value) >>= pure . matrix", + "Matrix (Complex Double) -> Either MathError (Matrix (Complex Double))", +) +for name in ["complexFFT", "complexIFFT"]: + add( + "complex", + "HMath.Complex", + name, + [("values", "[ComplexDouble]")], + "[ComplexDouble]", + "source (C." + name + " values) >>= pure . V.List . map complexDoubleValue", + "[Complex Double] -> Either MathError [Complex Double]", + ) +add( + "trigonometry", + "HMath.Trigonometry", + "complexFunction", + [("operation", "ComplexFunction"), ("value", "TypedComplex")], + "TypedComplex", + "trigonometric operation value", + "RealFloat a => ComplexFunction -> Complex a -> Either MathError (Complex a)", +) +for name, args, result, signature in [ + ( + "chineseRemainder", + [("congruences", "[(Integer,Integer)]")], + "(Integer,Integer)", + "[(Integer,Integer)] -> Either MathError (Integer,Integer)", + ), + ( + "linearDiophantine", + [("a", "Integer"), ("b", "Integer"), ("c", "Integer")], + "(Integer,Integer,Integer,Integer)", + "Integer -> Integer -> Integer -> Either MathError (Integer,Integer,Integer,Integer)", + ), + ( + "perfectPower", + [("value", "Integer")], + "Maybe (Integer,Int)", + "Integer -> Maybe (Integer,Int)", + ), + ( + "primeFactorization", + [("budget", "Int"), ("value", "Integer")], + "[(Integer,Int)]", + "Int -> Integer -> Either MathError [(Integer,Int)]", + ), + ("partitions", [("value", "Int")], "[[Int]]", "Int -> Either MathError [[Int]]"), +]: + add( + "numbertheory", + "HMath.NumberTheory", + name, + args, + result, + ( + "source (N." + name + "".join(" " + n for n, t in args) + ")" + if name != "perfectPower" + else "pure (N.perfectPower value)" + ) + + " >>= pure . W.wire", + signature, + name != "perfectPower", + ) +add( + "special", + "HMath.Special", + "SFResult", + [("value", "Double"), ("error", "Double")], + "SFResult", + "pure (sfResult (S.SFResult value error))", + "Double -> Double -> SFResult", + False, +) +add( + "special", + "HMath.Special", + "sfValue", + [("value", "SFResult")], + "Double", + "pure (W.wire (S.sfValue value))", + "SFResult -> Double", + False, +) +add( + "special", + "HMath.Special", + "sfError", + [("value", "SFResult")], + "Double", + "pure (W.wire (S.sfError value))", + "SFResult -> Double", + False, +) + +PREFIX = """{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE ScopedTypeVariables #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_scalar_extras.py; all mathematics is original. +module HMath.FFI.ScalarExtras where +import Control.Exception (evaluate,throwIO) +import Data.Complex (Complex) +import Data.Typeable (cast) +import Foreign +import Foreign.C +import HMath.FFI.Boundary +import HMath.FFI.Coefficient (ScalarType(SComplexDouble,SComplexFloat)) +import HMath.FFI.MathError (CallbackFailure(..)) +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.GraphCodec as W +import qualified HMath.Complex as C +import qualified HMath.Trigonometry as T +import qualified HMath.NumberTheory as N +import qualified HMath.Special as S +import qualified HMath.Matrix as M +source :: Either HMathError a -> IO a +source = either (throwIO . CallbackMathError) pure +""".replace("HMathError", "MathError") +PREFIX = PREFIX.replace( + "import HMath.FFI.Boundary", + "import HMath.Error (MathError)\nimport HMath.FFI.Boundary", +) +PREFIX += """elementary :: C.Elementary -> V.Value +elementary value = V.Opaque 352 (-1) 0 (evaluate value >> pure ()) value +complexFunction :: T.ComplexFunction -> V.Value +complexFunction value = V.Opaque 353 (-1) 0 (evaluate value >> pure ()) value +getElementary :: V.Value -> IO C.Elementary +getElementary = W.unboxed 352 +getComplexFunction :: V.Value -> IO T.ComplexFunction +getComplexFunction = W.unboxed 353 +complexDoubleValue :: Complex Double -> V.Value +complexDoubleValue = V.Scalar SComplexDouble +matrix :: M.Matrix (Complex Double) -> V.Value +matrix = V.Dense . V.SomeMatrix SComplexDouble +getMatrix :: V.Value -> IO (M.Matrix (Complex Double)) +getMatrix (V.Dense (V.SomeMatrix _ value)) = maybe (V.invalid "Complex Double matrix required") pure (cast value) +getMatrix _ = V.invalid "dense complex matrix required" +sfResult :: S.SFResult -> V.Value +sfResult value = V.Tuple [W.wire (S.sfValue value),W.wire (S.sfError value)] +getSFResult :: V.Value -> IO S.SFResult +getSFResult value = do + fields <- V.asTuple 2 value + case fields of [a,b] -> S.SFResult <$> W.unwire a <*> W.unwire b;_ -> V.invalid "SFResult field count differs" +trigonometric :: T.ComplexFunction -> V.Value -> IO V.Value +trigonometric operation value = case value of + V.Scalar SComplexDouble x -> source (T.complexFunction operation x) >>= pure . V.Scalar SComplexDouble + V.Scalar SComplexFloat x -> source (T.complexFunction operation x) >>= pure . V.Scalar SComplexFloat + _ -> V.invalid "complexFunction requires actual Complex Float or Complex Double" +""" + + +def generate(): + hs = [ + PREFIX, + 'foreign export ccall "hm_scalar_extras_apply" apply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt\napply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt\napply operation inputs arity out = boundary $ do\n values <- peekArray (fromIntegral arity) inputs >>= mapM deRefStablePtr\n result <- case (operation,values) of\n', + ] + h = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_scalar_extras.py. */\n#ifndef HMATH_SCALAR_EXTRAS_H\n#define HMATH_SCALAR_EXTRAS_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Borrowed immutable inputs; outputs transfer one Value owner on success and\n * remain untouched on failure. Release with hmath_value_release. Selector\n * objects use actual Elementary(kind352)/ComplexFunction(kind353) payloads.\n * Complex arithmetic/FFT/matrices and SFResult use original Double precision;\n * trigonometric complexFunction retains either actual Complex Float or Double\n * input/output, without intermediate widening. Exact integer transport never\n * uses floating point; nested tuple/list/Maybe results retain source shape.\n * Source bounds, budgets, principal branches, flags and MathError/status11 are\n * unchanged. Independent readers retain references per participating thread. */\n", + "typedef hmath_value hmath_complex_elementary_object;\ntypedef hmath_value hmath_trigonometry_complex_function_object;\ntypedef hmath_value hmath_special_sf_result_value; /* tuple(Double,Double) */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_scalar_extras.py. */\n#include "hmath_scalar_extras.h"\n#include "value_internal.h"\nextern int hm_scalar_extras_apply(int,void *const *,size_t,void **);\n' + ] + mods = {} + mapping = [] + symbols = [] + getters = { + "Elementary": "getElementary", + "ComplexFunction": "getComplexFunction", + "ComplexDouble": "V.asScalar", + "[ComplexDouble]": "(\\value -> V.asList value >>= mapM V.asScalar)", + "ComplexMatrix": "getMatrix", + "SFResult": "getSFResult", + "TypedComplex": "pure", + } + for op, e in enumerate(SPECS): + namespace = e["namespace"] + name = snake(e["name"]) + public = "hmath_" + namespace + "_" + name + params = [n for n, t in e["args"]] + prototype = ( + "hmath_status " + + public + + "(" + + ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + n for n in params] + + ["hmath_value **out"] + ) + + ")" + ) + h.append( + "/* " + + e["module"] + + "." + + e["name"] + + " :: " + + e["signature"] + + " */\nHMATH_API " + + prototype + + ";\n" + ) + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + n for n in params) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL scalar adapter argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n void *arguments[]={' + + (",".join("hm_value_stable(" + n + ")" for n in params) or "NULL") + + "};\n return hm_value_finish(result,hm_scalar_extras_apply(" + + str(op) + + ",arguments," + + str(len(params)) + + ",&result->stable),out);\n}\n" + ) + hs.append( + " (" + + str(op) + + ",[" + + ",".join("v" + n for n in params) + + "]) -> do\n" + ) + expression = e["expression"] + for n, t in e["args"]: + getter = getters.get(t, "W.unwire") + argument = "arg" + n[0].upper() + n[1:] + hs.append(" " + argument + " <- " + getter + " v" + n + "\n") + expression = re.sub(r"\b" + re.escape(n) + r"\b", argument, expression) + hs.append(" " + expression + "\n") + mods.setdefault(namespace, []).append(e) + mapping.append( + { + "symbol": e["module"] + "." + e["name"], + "c": [public], + "python": "hmath." + + namespace + + "." + + ("SFResult" if e["name"] == "SFResult" else name), + "specializations": [ + "actual Complex Float/Double RealFloat instances" + if e["name"] == "complexFunction" + else "original concrete source type/structure" + ], + } + ) + symbols.append(public) + hs.append( + ' _ -> V.invalid "scalar adapter identifier or arity differs"\n checked (Right result) (`V.publish` out)\n' + ) + hs.append( + 'foreign export ccall "hm_scalar_selector_name" selectorName :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nselectorName :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nselectorName input out = boundary $ do\n value <- deRefStablePtr input\n name <- case V.valueInfo value of\n (352,_,_) -> show <$> getElementary value\n (353,_,_) -> show <$> getComplexFunction value\n _ -> V.invalid "expected complex selector"\n checked (Right (V.Text name)) (`V.publish` out)\nforeign export ccall "hm_scalar_selector_equal" selectorEqual :: StablePtr V.Value -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nselectorEqual :: StablePtr V.Value -> StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\nselectorEqual left right out = boundary $ do\n a <- deRefStablePtr left\n b <- deRefStablePtr right\n equal <- case (V.valueInfo a,V.valueInfo b) of\n ((352,_,_),(352,_,_)) -> (==) <$> getElementary a <*> getElementary b\n ((353,_,_),(353,_,_)) -> (==) <$> getComplexFunction a <*> getComplexFunction b\n _ -> pure False\n checked (Right (V.Boolean equal)) (`V.publish` out)\n' + ) + for helper, arity in [("name", 1), ("equal", 2)]: + prototype = ( + "hmath_status hmath_scalar_selector_" + + helper + + "(hmath_context *context" + + "".join(",const hmath_value *value" + str(k) for k in range(arity)) + + ",hmath_value **out)" + ) + h.append("HMATH_API " + prototype + ";\n") + c.append( + "extern int hm_scalar_selector_" + + helper + + "(" + + ",".join(["void *"] * arity + ["void **"]) + + ");\n" + + prototype + + " {\n if(!out" + + "".join(" || !value" + str(k) for k in range(arity)) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL selector argument");\n hmath_value *result=NULL;\n hmath_status status=hm_value_begin(context,&result);\n if(status)return status;\n return hm_value_finish(result,hm_scalar_selector_' + + helper + + "(" + + ",".join("hm_value_stable(value" + str(k) + ")" for k in range(arity)) + + ",&result->stable),out);\n}\n" + ) + symbols.append("hmath_scalar_selector_" + helper) + mapping.append( + { + "symbol": "HMath.Complex.Elementary", + "c": ["hmath_complex_elementary_object"], + "python": "hmath.complex.Elementary", + "specializations": ["actual original selector"], + } + ) + mapping.append( + { + "symbol": "HMath.Trigonometry.ComplexFunction", + "c": ["hmath_trigonometry_complex_function_object"], + "python": "hmath.trigonometry.ComplexFunction", + "specializations": ["actual original selector"], + } + ) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + out = { + "include/hmath_scalar_extras.h": "".join(h), + "cbits/scalar_extras.c": "".join(c), + "src/HMath/FFI/ScalarExtras.hs": "".join(hs), + "bindings/schema/scalar-extras-objects.json": json.dumps( + {"schema": 1, "bindings": mapping}, indent=2 + ) + + "\n", + "bindings/schema/scalar-extras-symbols.txt": "\n".join(symbols) + "\n", + } + docs = [ + '# Complete scalar-domain adapters\n\nThese functions call the original Complex, Trigonometry, NumberTheory and Special APIs. C includes `hmath_scalar_extras.h`; Python namespaces extend existing modules without replacing earlier numerical functions. Complex selectors are owned immutable original objects, constructed with `complex.exp()`/`trigonometry.c_sin()` etc. The `complex_function` adapter accepts `dtype="float32"` or `"float64"`; actual typed Complex Float inputs remain Float through the original RealFloat algorithm. Other complex operations/SFResult retain original Double precision. No principal-branch, pole/nonfinite, error-estimate or integer-budget policy is changed.\n\nValues use the [owned structured protocol](values.md): inputs borrowed, outputs owned/untouched on failure, each reference pins the runtime. Exact integers have no fixed precision or floating conversion. Variable-length/nested lists and tuples keep their original order/shape; Maybe uses None. Checked source errors retain complete MathError/status11. Selectors use kinds352/353. SFResult uses a tuple of two Doubles, interoperable with existing SFResult(value,error) named tuples; its raw constructor does not normalize or certify the error field.\n\n' + ] + for namespace, items in mods.items(): + class_name = ( + "Elementary" + if namespace == "complex" + else "ComplexFunction" + if namespace == "trigonometry" + else None + ) + py = [ + "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_scalar_extras.py; do not edit.\nfrom ._scalar_extras_base import " + + (class_name + ", _invoke" if class_name else "_invoke") + + "\n" + ] + exports = [class_name] if class_name else [] + for e in items: + name = snake(e["name"]) + params = [n for n, t in e["args"]] + extra = ["*", "dtype=None"] if e["name"] == "complexFunction" else [] + py.append( + "\n\ndef " + + name + + "(" + + ", ".join(params + extra) + + '):\n """' + + e["module"] + + "." + + e["name"] + + " :: " + + e["signature"] + + '."""\n return _invoke(' + + repr("hmath_" + namespace + "_" + name) + + ", " + + repr([t for n, t in e["args"]]) + + ", [" + + ", ".join(params) + + "], " + + repr(e["result"]) + + (", dtype=dtype" if extra else "") + + ")\n" + ) + exports.append(name) + docs.append( + "## `" + + namespace + + "." + + name + + "`\n\n" + + source_prose(e) + + "\n\n```haskell\n" + + e["signature"] + + "\n```\n\n```c\n" + + ( + "hmath_status hmath_" + + namespace + + "_" + + name + + "(" + + ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + n for n in params] + + ["hmath_value **out"] + ) + + ");" + ) + + "\n```\n\n" + ) + py.append("\n\n__all__ = " + json.dumps(sorted(exports), indent=4) + "\n") + out["bindings/python/_hmath_native/" + namespace + "_extras.py"] = "".join(py) + out["docs/reference/scalar-extras.md"] = "".join(docs) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale scalar extra binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_shape_bindings.py b/tools/generate_shape_bindings.py new file mode 100644 index 0000000..bb8bbe7 --- /dev/null +++ b/tools/generate_shape_bindings.py @@ -0,0 +1,304 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original shape witnesses backed by real reified Haskell type indices.""" + +import argparse +import json +from pathlib import Path + +from generate_foundation_bindings import format_c +from generate_linear_bindings import snake +from generate_stochastic_bindings import fmt + +ROOT = Path(__file__).resolve().parent.parent +OPERATIONS = [ + ( + "shapeDimensions", + ["shape"], + "asShape shape >>= pure . V.List . map V.Index . S.shapeDimensions", + ), + ("shapeElements", ["shape"], "asShape shape >>= pure . V.Index . S.shapeElements"), + ( + "makeShape", + ["dimensions"], + "do {ds <- V.asList dimensions >>= mapM V.asIndex;Codec.shape <$> source(S.makeShape ds)}", + ), + ( + "ScalarShape", + ["shape"], + "do {s <- asShape shape;pure(V.Boolean(case s of S.ScalarShape -> True;_ -> False))}", + ), + ( + "VectorShape", + ["shape"], + "do {s <- asShape shape;pure(case s of S.VectorShape n -> V.Index n;_ -> V.None)}", + ), + ( + "MatrixShape", + ["shape"], + "do {s <- asShape shape;pure(case s of S.MatrixShape r c -> V.Tuple[V.Index r,V.Index c];_ -> V.None)}", + ), + ( + "staticMatrix", + ["rows", "columns", "matrix"], + "do {r <- V.asScalar rows;c <- V.asScalar columns;staticMatrix r c matrix}", + ), + ("dynamicMatrix", ["matrix"], "dynamicMatrix matrix"), + ("staticMultiply", ["left", "right"], "staticMultiply left right"), + ("staticTranspose", ["matrix"], "staticTranspose matrix"), + ( + "reflectedShape", + ["dimensions"], + "V.asList dimensions >>= mapM V.asScalar >>= reflectedShape", + ), + ( + "staticTensor", + ["dimensions", "tensor"], + "do {ds <- V.asList dimensions >>= mapM V.asScalar;staticTensor ds tensor}", + ), + ("dynamicTensor", ["tensor"], "dynamicTensor tensor"), + ( + "coordinates", + ["prototype", "length", "values"], + "do {n <- V.asScalar count;xs <- V.asList values;coordinatesFrom prototype n xs}", + ), + ("coordinateValues", ["coordinates"], "coordinateValues coordinates"), + ("coordinatesToVector", ["coordinates"], "coordinatesToVector coordinates"), +] +TYPES = ["Shape", "StaticMatrix", "KnownShape", "StaticTensor", "Coordinates"] + + +def outputs(): + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +#ifndef HMATH_SHAPE_H +#define HMATH_SHAPE_H +#include "hmath_foundation.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original runtime and nominal type-indexed shapes. Implicit Haskell Nat + * indices become explicit nonnegative Integer Values; KnownNat/KnownShape + * dictionaries are reified, never coerced. Source Int overflow and dimension + * checks remain. Shape patterns are read-only views. Matrix/Tensor results + * interoperate with their ordinary public APIs. Inputs borrow; outputs own a + * Value; failure leaves *out untouched. */ +""" + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n#include "hmath_shape.h"\n#include "value_internal.h"\nextern int hm_shape_apply(int,void *const *,size_t,void **);\n' + ] + hs = [ + """{-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated calls to original shape APIs and typed representation helpers. +module HMath.FFI.ShapeAll where +import Foreign +import Foreign.C +import qualified HMath.API.Shape as S +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.FoundationCodec(source,foundationBoundary) +import HMath.FFI.ShapeCodec hiding(shape,coordinates) +import qualified HMath.FFI.ShapeCodec as Codec +apply :: Int -> [V.Value] -> IO V.Value +apply operation args=case(operation,args)of +""" + ] + py = [ + '''# SPDX-License-Identifier: MPL-2.0 +"""Original checked shapes and genuine nominal KnownNat/KnownShape witnesses.""" +from ._algebra_base import invoke +from ._foundation_base import FoundationValue,register,_invoke +''' + ] + bindings = [] + docs = [ + """# Runtime and type-indexed shapes + +These APIs call the original `HMath.API.Shape` operations. Haskell type-level +natural dimensions become explicit Python integers/C Integer Values. The adapter +reifies actual `KnownNat` and recursive `KnownShape` dictionaries; it never +coerces a matrix/tensor to an unrelated shape. `reflected_shape` retains exact +Integer dimensions, even above Int. The original constructors decide Int +overflow and dynamic shape errors. Static multiplication also requires equal +nominal inner dimensions and identical element types. + +`scalar_shape`, `vector_shape`, and `matrix_shape` are read-only source pattern +views: Boolean match, optional length, and optional `(rows, columns)`. +`make_shape` performs checked construction. `coordinates(length, values, +dtype=...)` retains the original lazy list element type; numeric, Bool, String +and Exact elements remain lossless. Vector conversion uses the original source +conversion and produces an ordinary interoperable Vector owner. Static wrappers +own independent references. Dynamic conversion retains the original element +type and does not copy or coerce mathematical values. Close each owned result. + +""" + ] + for name in TYPES: + if name == "KnownShape": + py.append( + '\nclass KnownShape:\n """Original recursive type-level natural-list witness interface."""\n @staticmethod\n def reflected_shape(dimensions):\n return reflected_shape(dimensions)\n' + ) + else: + py.append( + "\nclass " + + name + + '(FoundationValue):\n """Original HMath.API.Shape.' + + name + + ' owner."""\n _source_type=' + + repr("HMath.API.Shape." + name) + + "\n" + ) + if name == "Shape": + py.append( + " @property\n def dimensions(self):\n return shape_dimensions(self)\n @property\n def elements(self):\n return shape_elements(self)\n" + ) + if name == "Coordinates": + py.append( + " @property\n def values(self):\n return coordinate_values(self)\n" + ) + py.append( + "register(" + repr("HMath.API.Shape." + name) + "," + name + ")\n" + ) + bindings.append( + { + "symbol": "HMath.API.Shape." + name, + "c": ["hmath_value", "hmath_value_release"], + "python": "hmath.shape." + name, + "specializations": [ + "actual original type-level witness and source checks" + ], + } + ) + for index, (name, parameters, body) in enumerate(OPERATIONS): + arguments = ["count" if a == "length" else a for a in parameters] + symbol = "hmath_shape_" + snake(name) + hs.append( + " (" + str(index) + ",[" + ",".join(arguments) + "]) -> " + body + "\n" + ) + prototype = ( + "hmath_status " + + symbol + + "(" + + ",".join( + ["hmath_context *context"] + + ["const hmath_value *" + a for a in arguments] + + ["hmath_value **out"] + ) + + ")" + ) + h.append("/* HMath.API.Shape." + name + " */\nHMATH_API " + prototype + ";\n") + c.append( + prototype + + " {\n if(!out" + + "".join(" || !" + a for a in arguments) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL shape argument");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n void *args[]={' + + ",".join("hm_value_stable(" + a + ")" for a in arguments) + + "};\n return hm_value_finish(result,hm_shape_apply(" + + str(index) + + ",args," + + str(len(arguments)) + + ",&result->stable),out);\n}\n" + ) + python = snake(name) + if name == "coordinates": + py.append( + '\ndef coordinates(length,values,*,dtype=None):\n """Construct an original Coordinates n a with explicit nominal length."""\n return invoke(' + + repr(symbol) + + ',[["Integer"],["list",["a"]]],[length,values],"typed",dtype)\n' + ) + else: + specs = { + "rows": ["Integer"], + "columns": ["Integer"], + "dimensions": ["list", ["Int"]] + if name == "makeShape" + else ["list", ["Integer"]], + } + py.append( + "\ndef " + + python + + "(" + + ",".join(parameters) + + '):\n """Original HMath.API.Shape.' + + name + + '; borrowed inputs, owned result."""\n return _invoke(' + + repr(symbol) + + "," + + repr([specs.get(p, ["Value"]) for p in parameters]) + + ",[" + + ",".join(parameters) + + "])\n" + ) + bindings.append( + { + "symbol": "HMath.API.Shape." + name, + "c": [symbol], + "python": "hmath.shape." + python, + "specializations": [ + "actual reified source type indices; numeric/Bool/String/Exact structural elements; no numeric coercion" + ], + } + ) + docs.append( + "## `shape." + + python + + "`\n\nCalls `HMath.API.Shape." + + name + + "`. C parameters: `" + + ", ".join(parameters) + + "`, each a borrowed Value; the output owns one reference. " + + ( + "The prototype selects the original element type, including empty coordinates. " + if name == "coordinates" + else "" + ) + + "Failures leave the output pointer untouched.\n\n" + ) + hs.append(""" _ -> V.invalid "invalid shape operation/arity" +foreign export ccall "hm_shape_apply" ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr V.Value) -> CSize -> Ptr(StablePtr V.Value) -> IO CInt +ffiApply operation input count out=foundationBoundary $ do + values <- peekArray(fromIntegral count) input >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(V.publish value out)) +""") + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + py.append( + "\n__all__=" + + repr(sorted(TYPES + [snake(name) for name, *_ in OPERATIONS])) + + "\n" + ) + result = { + "src/HMath/FFI/ShapeAll.hs": "".join(hs), + "include/hmath_shape.h": "".join(h), + "cbits/shape.c": "".join(c), + "bindings/python/_hmath_native/shape_values.py": fmt( + "".join(py), "shape_values.py" + ), + "bindings/schema/shape-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(bindings, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "docs/reference/shapes.md": "".join(docs), + } + return { + name: format_c(data) if name.endswith((".c", ".h")) else data + for name, data in result.items() + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_spectral_bindings.py b/tools/generate_spectral_bindings.py new file mode 100644 index 0000000..1a04443 --- /dev/null +++ b/tools/generate_spectral_bindings.py @@ -0,0 +1,189 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate original Signal, Fourier and Interpolation structured adapters.""" + +import argparse +import json +from pathlib import Path + +import generate_numerical_bindings as engine + +ROOT = Path(__file__).resolve().parent.parent +TYPES = { + "Filter": ("signal", "S.Filter", 360, ["filterCoefficients", "filterState"]), + "FilterFamily": ("signal", "S.FilterFamily", 361, []), + "FilterBand": ("signal", "S.FilterBand", 362, []), + "Window": ("signal", "S.Window", 363, []), + "Peak": ( + "signal", + "S.Peak", + 364, + ["peakIndex", "peakHeight", "peakProminence", "peakWidth"], + ), + "Wavelet": ("signal", "S.Wavelet", 365, []), + "WaveletTree": ( + "signal", + "S.WaveletTree", + 366, + ["waveletApproximation", "waveletDetails"], + ), + "MotherWavelet": ("signal", "S.MotherWavelet", 367, []), + "WaveletPacket": ("signal", "S.WaveletPacket", 368, ["packetBands"]), + "Extrapolation": ("interpolation", "I.Extrapolation", 369, []), + "InterpolationMethod": ("interpolation", "I.InterpolationMethod", 370, []), + "SplineBoundary": ("interpolation", "I.SplineBoundary", 371, []), + "PiecewisePolynomial": ( + "interpolation", + "I.PiecewisePolynomial", + 372, + ["piecewiseKnots"], + ), + "BSpline": ("interpolation", "I.BSpline", 373, []), + "RadialKernel": ("interpolation", "I.RadialKernel", 374, []), + "RBF": ("interpolation", "I.RBF", 375, []), + "Approximation": ( + "interpolation", + "I.Approximation", + 376, + ["approximationCoefficients", "approximationError", "approximationIterations"], + ), + "Direction": ("fourier", "F.Direction", 377, []), + "FFTAlgorithm": ("fourier", "F.FFTAlgorithm", 378, []), + "FFTPlan": ("fourier", "F.FFTPlan", 379, []), + "TransformType": ("fourier", "F.TransformType", 380, []), + "STFT": ("fourier", "F.STFT", 381, ["stftFrames"]), +} + + +def generate(): + entries = json.loads( + (ROOT / "bindings/schema/spectral-functions.json").read_text() + )["functions"] + original_types, original_modules = engine.TYPES, engine.MODULES + try: + engine.TYPES = TYPES + engine.MODULES = {"signal": "S", "interpolation": "I", "fourier": "F"} + outputs = engine.generate( + [e for e in entries if e["name"] != "fftInPlace"], aliases=False + ) + finally: + engine.TYPES, engine.MODULES = original_types, original_modules + result = {} + for name, text in outputs.items(): + for namespace in ("signal", "interpolation", "fourier"): + text = text.replace( + "hmath_" + namespace + "_", "hmath_" + namespace + "_value_" + ) + text = text.replace( + "generate_numerical_bindings.py", "generate_spectral_bindings.py" + ) + text = text.replace("HMATH_NUMERICAL_H", "HMATH_SPECTRAL_H").replace( + "hmath_numerical.h", "hmath_spectral.h" + ) + text = text.replace("hm_numerical_apply", "hm_spectral_apply") + text = text.replace( + "HMath.FFI.NumericalAll where", "HMath.FFI.SpectralAll where" + ) + if name.endswith("NumericalAll.hs"): + text = text.replace( + "import qualified HMath.Calculus as C\nimport qualified HMath.Root as R\nimport qualified HMath.ODE as O\nimport qualified HMath.PDE as P\n", + "import qualified HMath.Signal as S\nimport qualified HMath.Interpolation as I\nimport qualified HMath.Fourier as F\nimport HMath.FFI.NumericalAll ()\nimport Data.Complex (Complex)\n", + ) + text = text.replace( + "apply F.fftShift values", + "apply (F.fftShift :: [V.Value] -> [V.Value]) values", + ) + text = text.replace( + "apply F.ifftShift values", + "apply (F.ifftShift :: [V.Value] -> [V.Value]) values", + ) + text += "\ninstance From S.GaussianState where from = unbox 140\ninstance To S.GaussianState where\n to value = pure (box 140 value [to (S.stateMean value),to (S.stateCovariance value)])\n" + text += '\nforeign export ccall "hm_spectral_fft_in_place" rawFFT :: StablePtr V.Value -> Ptr (Complex Double) -> CPtrdiff -> IO CInt\nrawFFT :: StablePtr V.Value -> Ptr (Complex Double) -> CPtrdiff -> IO CInt\nrawFFT input pointer count = B.boundary $ do\n plan <- deRefStablePtr input >>= from\n outcome <- F.fftInPlace plan pointer (fromIntegral count)\n B.checked outcome (const (pure ()))\n' + text += '\nforeign export ccall "hm_spectral_describe" describe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\ndescribe :: StablePtr V.Value -> Ptr (StablePtr V.Value) -> IO CInt\ndescribe input out = B.boundary $ do\n value <- deRefStablePtr input\n rendered <- case value of\n' + for _ns, typ, tag, _fields in TYPES.values(): + text += f" V.Opaque {tag} _ _ _ _ -> show <$> (from value :: IO {typ})\n" + text += ' V.Opaque 140 _ _ _ _ -> show <$> (from value :: IO S.GaussianState)\n _ -> V.invalid "expected a spectral-domain object"\n B.checked (Right ()) (const (V.publish (V.Text rendered) out))\n' + if name.endswith("numerical.c"): + text += '\nextern int hm_spectral_fft_in_place(void *,void *,ptrdiff_t);\nhmath_status hmath_fourier_value_fft_in_place(hmath_context *context,const hmath_value *plan,double *interleaved,ptrdiff_t count) {\n if (!plan) return hm_error(HMATH_INVALID_ARGUMENT,"NULL FFT plan");\n hmath_status status=hm_enter(context);\n if(status)return status;\n int code=hm_spectral_fft_in_place(hm_value_stable(plan),interleaved,count);\n hm_leave();\n return (hmath_status)code;\n}\n' + text += '\nextern int hm_spectral_describe(void *,void **);\nhmath_status hmath_spectral_describe(hmath_context *context,const hmath_value *value,hmath_value **out) {\n if (!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL spectral description argument");\n hmath_value *temporary=NULL;\n hmath_status status=hm_value_begin(context,&temporary);\n if(status)return status;\n return hm_value_finish(temporary,hm_spectral_describe(hm_value_stable(value),&temporary->stable),out);\n}\n' + if name.endswith("hmath_numerical.h"): + marker = "#ifdef __cplusplus\n}\n#endif\n#endif\n" + addition = "/* Original fftInPlace: borrowed writable interleaved real/imaginary Double\n * storage for count complex values, aligned for Double. The original checks\n * NULL/count/finite values and changes storage only after successful execution.\n * No wrapper copy; caller keeps storage alive and excludes concurrent writers. */\nHMATH_API hmath_status hmath_fourier_value_fft_in_place(hmath_context *context,const hmath_value *plan,double *interleaved,ptrdiff_t count);\n" + addition += "/* Original Show representation as an owned codepoint String value. */\nHMATH_API hmath_status hmath_spectral_describe(hmath_context *context,const hmath_value *value,hmath_value **out);\n" + text = text.replace(marker, addition + marker) + if name.endswith("fourier.py"): + for operation in ("fft_shift", "ifft_shift"): + text = text.replace( + "def " + operation + "(xs):", + "def " + + operation + + '(xs, *, dtype=None):\n if dtype not in (None, "float64"):\n raise ValueError("legacy dtype must be float64; generic elements retain their own types")', + ) + text += "\n\nfrom ._spectral_base import fft_in_place as fft_in_place\n" + if name.endswith("signal.py"): + text += "\n\nfrom .timeseries import GaussianState as GaussianState, gaussian_state as gaussian_state, state_mean as state_mean, state_covariance as state_covariance\n" + if name.endswith(("signal.py", "fourier.py", "interpolation.py")): + text += '\n\ndef describe(value):\n """Return the original Haskell Show representation of a spectral object."""\n return _invoke("hmath_spectral_describe", [["Value"]], [value])\n' + target = ( + name.replace("hmath_numerical.h", "hmath_spectral.h") + .replace("cbits/numerical.c", "cbits/spectral.c") + .replace("FFI/NumericalAll.hs", "FFI/SpectralAll.hs") + .replace("numerical-objects.json", "spectral-objects.json") + .replace("numerical-solvers.md", "spectral-bindings.md") + ) + for namespace in ("signal", "interpolation", "fourier"): + target = target.replace( + "/" + namespace + ".py", "/" + namespace + "_values.py" + ) + result[target] = text + schema = json.loads(result["bindings/schema/spectral-objects.json"]) + generic_symbols = {"HMath.Fourier.fftShift", "HMath.Fourier.ifftShift"} + generic = [item for item in schema["bindings"] if item["symbol"] in generic_symbols] + schema["bindings"] = [ + item for item in schema["bindings"] if item["symbol"] not in generic_symbols + ] + result["bindings/schema/spectral-generic-objects.json"] = ( + json.dumps( + {"schema": 1, "extends": "numeric.json", "bindings": generic}, indent=2 + ) + + "\n" + ) + schema["bindings"].append( + { + "symbol": "HMath.Fourier.fftInPlace", + "c": ["hmath_fourier_value_fft_in_place"], + "python": "hmath.fourier.fft_in_place", + "specializations": [ + "original in-place binary64 complex buffer with borrowed lifetime" + ], + } + ) + result["bindings/schema/spectral-objects.json"] = ( + json.dumps(schema, indent=2) + "\n" + ) + docs = result["docs/reference/spectral-bindings.md"] + docs = ( + "# Signal, Fourier and interpolation bindings\n\nPython uses `hmath.signal`, `hmath.fourier` and `hmath.interpolation`. C includes `hmath_spectral.h` and uses immutable owned [structured values](values.md). Existing scalar entry points remain available. Every operation calls the original implementation.\n\nForward Fourier exponents are negative; inverse transforms divide by N. DCT/DST retain the original orthonormal type I–IV definitions. Plans retain the original bounded reference algorithms and are reusable immutable objects. They do not substitute a different transform provider.\n\nInterpolation preserves strictly increasing unique finite samples, exact extrapolation choices and ascending local polynomial coefficients. Error values remain the source's sampled estimates. Signal filters preserve state continuation, window definitions, boundary conventions, Kalman updates and wavelet coefficient ordering. Source work/shape/iteration limits remain in force.\n\nInputs are borrowed for a synchronous call and successful C outputs own one reference. Output pointers remain untouched on failure. Immutable objects support concurrent readers retaining references and using independent output addresses. Function arguments use kind101 callbacks from `hmath_linear_callback`, with a tuple of flattened positional arguments. Python accepts ordinary callables and retains their owners; exceptions are re-raised after native cleanup. Source MathError returns status11 with a lossless payload. Cancellation is checked before entry.\n\n" + + docs[docs.index("## ") :] + ) + docs += "## `fourier.fft_in_place`\n\n`fourier.fft_in_place(plan, buffer)` mutates a writable, one-dimensional, native-endian, C-contiguous NumPy `complex128` array using the original `fftInPlace`. The wrapper borrows its storage; the original routine stages and validates input before writing the result. Keep the buffer alive and exclude concurrent access during the call. Invalid lengths and nonfinite input follow the original MathError contract; storage is unchanged on failure. C takes a borrowed `double *` with interleaved real/imaginary components and a signed `ptrdiff_t` complex-element count.\n\n```c\nhmath_status hmath_fourier_value_fft_in_place(hmath_context *context, const hmath_value *plan, double *interleaved, ptrdiff_t count);\n```\n" + docs += "\n## `describe`\n\n`signal.describe(value)`, `fourier.describe(value)` and `interpolation.describe(value)` return the original Haskell Show representation of a domain object. C uses `hmath_spectral_describe(context, value, out)` and receives an owned String value.\n" + result["docs/reference/spectral-bindings.md"] = docs + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale spectral binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_stochastic_bindings.py b/tools/generate_stochastic_bindings.py new file mode 100644 index 0000000..d9255b4 --- /dev/null +++ b/tools/generate_stochastic_bindings.py @@ -0,0 +1,714 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Original Random, Probability and remaining advanced-statistics adapters.""" + +import argparse +import json +import subprocess +from pathlib import Path + +import generate_linear_bindings as G + +ROOT = Path(__file__).resolve().parent.parent +MODULES = { + "HMath.Random": ("R", "random_values", "random"), + "HMath.Probability": ("P", "probability_values", "probability"), + "HMath.Statistics.Advanced": ("S", "statistics_values", "statistics_advanced"), +} +TAGS = { + "RNG": 240, + "Generator": 241, + "AliasTable": 242, + "Distribution": 243, + "Markov": 244, + "HMM": 245, + "Streaming": 246, + "TestResult": 247, +} + + +def specification(): + previous_modules, previous_aliases = G.MODULES, G.ALIASES + G.MODULES = {m: (a, n) for m, (a, n, _public) in MODULES.items()} + G.ALIASES = { + **previous_aliases, + "R.RNG": "RNG", + "R.Generator": "Generator", + "P.Distribution": "Distribution", + } + try: + entries, types, fields, missing = G.signatures() + finally: + G.MODULES, G.ALIASES = previous_modules, previous_aliases + numeric = { + x["module"] + "." + x["name"] + for x in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + } + entries = [e for e in entries if e["module"] + "." + e["name"] not in numeric] + if missing: + raise ValueError(missing) + return entries, types, fields + + +def hs_type(spec, types): + return G.hs_type(spec, types).replace("(a)", "(X.Value)") + + +def decode(spec, value, types): + head, *args = spec + if head == "a": + return "pure " + value + if head == "function": + variables = [G.fresh("parameter") for _ in args[:-1]] + encoded = [encode(s, v, types) for s, v in zip(args[:-1], variables)] + arg = "callbackInput" + input_statement = ( + "callbackArgs <- sequence [" + + ",".join(encoded) + + "]; let { callbackInput=X.Tuple callbackArgs }" + ) + call = "LC.callbackValue " + value + " " + arg + result = args[-1] + if result[0] == "Either": + result = result[2] + call = ( + "checkedCallback " + + value + + " " + + arg + + " (\\reply -> " + + decode(result, "reply", types) + + ")" + ) + else: + call += " >>= \\reply -> " + decode(result, "reply", types) + return ( + "pure (\\" + + " ".join(variables) + + " -> unsafePerformIO $ do { " + + input_statement + + "; " + + call + + " })" + ) + if head == "list": + variable = G.fresh("item") + return ( + "X.asList " + + value + + " >>= mapM (\\" + + variable + + " -> " + + decode(args[0], variable, types) + + ")" + ) + if head == "tuple": + variables = [G.fresh("part") for _ in args] + parts = G.fresh("tuple") + return ( + "(X.asTuple " + + str(len(args)) + + " " + + value + + " >>= \\" + + parts + + " -> case " + + parts + + " of { [" + + ",".join(variables) + + "] -> (" + + "," * (len(args) - 1) + + ") <$> " + + " <*> ".join( + "(" + decode(s, v, types) + ")" for s, v in zip(args, variables) + ) + + '; _ -> X.invalid "tuple arity differs" })' + ) + if head == "Matrix": + return "LC.asMatrix " + value + if head in types: + return ("asRNG" if head == "RNG" else "unbox " + str(TAGS[head])) + " " + value + if head == "Int": + return "X.asIndex " + value + if head == "Bool": + return "X.asBoolean " + value + if head == "String": + return "X.asText " + value + if head in ("Double", "Integer", "Word64"): + return "X.asScalar " + value + raise ValueError("unsupported stochastic decode " + repr(spec)) + + +def encode(spec, value, types): + head, *args = spec + if head == "a": + return "pure " + value + if head == "Either": + result = G.fresh("_result") + return ( + "source " + + value + + " >>= \\" + + result + + " -> " + + encode(args[1], result, types) + ) + if head == "IO": + result = G.fresh("_result") + return value + " >>= \\" + result + " -> " + encode(args[0], result, types) + if head == "list": + variable = G.fresh("item") + return ( + "X.List <$> mapM (\\" + + variable + + " -> " + + encode(args[0], variable, types) + + ") " + + value + ) + if head == "tuple": + variables = [G.fresh("part") for _ in args] + return ( + "(\\(" + + ",".join(variables) + + ") -> X.Tuple <$> sequence [" + + ",".join(encode(s, v, types) for s, v in zip(args, variables)) + + "]) " + + value + ) + if head == "Matrix": + return "pure(X.Dense(X.SomeMatrix SDouble " + value + "))" + if head in types: + return "encode" + head + " " + value + if head == "Int": + return "pure(X.Index " + value + ")" + if head == "Bool": + return "pure(X.Boolean " + value + ")" + if head == "String": + return "pure(X.Text " + value + ")" + if head in ("Double", "Integer", "Word64"): + return ( + "pure(X.Scalar " + + {"Double": "SDouble", "Integer": "SInteger", "Word64": "SWord64"}[head] + + " " + + value + + ")" + ) + if head == "unit": + return "pure X.None" + raise ValueError("unsupported stochastic encode " + repr(spec)) + + +def symbol(entry): + return ( + "hmath_stochastic_" + + MODULES[entry["module"]][2] + + "_" + + ("new_" if entry["constructor"] else "") + + G.snake(entry["name"]) + ) + + +def has_callback(spec): + return spec[0] == "function" or any( + has_callback(x) for x in spec[1:] if isinstance(x, list) + ) + + +def native(entries, types, fields): + hs = [ + """{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated; original algorithms and complete immutable continuation states. +module HMath.FFI.Stochastic where +import Control.Exception (catch,evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import System.IO.Unsafe (unsafePerformIO) +import qualified HMath.Error as E +import qualified HMath.Matrix as M +import HMath.FFI.Coefficient +import HMath.FFI.RandomCodec (rng,asRNG) +import qualified HMath.FFI.LinearCodec as LC +import qualified HMath.FFI.Value as X +import qualified HMath.FFI.Boundary as Boundary +import HMath.FFI.MathError +""" + ] + for m, (alias, _ns, _public) in MODULES.items(): + hs.append("import qualified " + m + " as " + alias + "\n") + hs.append(""" +unbox :: forall a. Typeable a => Int -> X.Value -> IO a +unbox kind (X.Opaque actual _ _ _ payload) | kind==actual=maybe(X.invalid "stochastic object payload differs") pure(cast payload) +unbox _ _=X.invalid "stochastic object kind differs" +source :: Either E.MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +forceFields :: [IO X.Value] -> IO () +forceFields fields=sequence fields >>= mapM_ X.forceValue +checkedCallback :: X.Value -> X.Value -> (X.Value -> IO a) -> IO(Either E.MathError a) +checkedCallback function argument decodeResult=(LC.callbackValue function argument >>= decodeResult >>= pure . Right) `catch` relay + where + relay(CallbackMathError errorValue)=pure(Left errorValue) + relay other=throwIO(other::CallbackFailure) +stochasticBoundary :: IO CInt -> IO CInt +stochasticBoundary action=Boundary.boundary $ callbackBoundary (\\e -> Boundary.checked(Left e)(const(pure()))) action +""") + for name, t in types.items(): + qualified = t["alias"] + "." + name + hs.append("\nencode" + name + " :: " + qualified + " -> IO X.Value\n") + if name == "RNG": + hs.append("encodeRNG=pure . rng\n") + continue + hs.append( + "encode" + + name + + " value=pure(X.Opaque " + + str(TAGS[name]) + + " (-1) 0 force value)\n where\n force=" + ) + if fields[name]: + hs.append( + "forceFields [" + + ",".join( + encode(s, "(" + t["alias"] + "." + f + " value)", types) + for f, s in fields[name] + ) + + "]\n" + ) + elif name == "Distribution": + hs.append("case value of\n") + for e in entries: + if e["constructor"] and e["result"][0] == name: + variables = [G.fresh("field") for _ in e["args"]] + hs.append( + " P." + + e["name"] + + " " + + " ".join(variables) + + " -> forceFields [" + + ",".join( + encode(s, v, types) for s, v in zip(e["args"], variables) + ) + + "]\n" + ) + else: + hs.append("evaluate value >> pure()\n") + hs.append( + "\napply :: Int -> [X.Value] -> IO X.Value\napply operation args=case(operation,args) of\n" + ) + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_stochastic_bindings.py. */ +#ifndef HMATH_STOCHASTIC_H +#define HMATH_STOCHASTIC_H +#include "hmath_linear.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Original immutable RNG240,Generator241,AliasTable242,Distribution243, + * Markov244,HMM245,Streaming246,TestResult247. Every output owns one Value; + * retain inputs during the call and release each output. Errors leave out + * untouched and preserve MathError. Seeds/words are exact Word64 scalars. + * Polymorphic sample elements transport arbitrary Values without coercion. + * Callbacks use hmath_linear_callback(kind101). Checked callbacks return true + * source Left on status11; pure callbacks abort. No generator, distribution, + * algorithm, default, proposal/evaluation budget or buffered state is replaced. */ +HMATH_API hmath_status hmath_stochastic_object_parts(hmath_context *context,const hmath_value *value,hmath_value **out); +HMATH_API hmath_status hmath_stochastic_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out); +""" + ] + c = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_stochastic_bindings.py. */ +#include "hmath_stochastic.h" +#include "value_internal.h" +extern int hm_stochastic_apply(int opcode,void *const *args,size_t count,void **out); +""" + ] + for opcode, e in enumerate(entries): + variables = ["a" + str(i) for i in range(len(e["args"]))] + hs.append(" (" + str(opcode) + ",[" + ",".join(variables) + "]) -> do\n") + for variable, spec in zip(variables, e["args"]): + hs.append( + " " + + variable + + "Value <- (" + + decode(spec, variable, types) + + " :: IO " + + hs_type(spec, types) + + ")\n" + ) + expression = ( + "(" + + MODULES[e["module"]][0] + + "." + + e["name"] + + " " + + " ".join(v + "Value" for v in variables) + + " :: " + + hs_type(e["result"], types) + + ")" + ) + hs.append(" " + encode(e["result"], expression, types) + "\n") + proto = ( + "hmath_status " + + symbol(e) + + "(" + + ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + v for v in variables] + + ["hmath_value **out"] + ) + + ")" + ) + h.append( + "/* " + + e["module"] + + "." + + e["name"] + + " :: " + + e["signature"] + + " */\nHMATH_API " + + proto + + ";\n" + ) + c.append( + proto + + " {\n if(!out" + + "".join(" || !" + v for v in variables) + + ') return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic argument");\n hmath_value *result; hmath_status status=hm_value_begin(context,&result);if(status)return status;\n' + ) + ptr = "NULL" + if variables: + c.append( + " void *args[]={" + + ",".join("hm_value_stable(" + v + ")" for v in variables) + + "};\n" + ) + ptr = "args" + c.append( + " return hm_value_finish(result,hm_stochastic_apply(" + + str(opcode) + + "," + + ptr + + "," + + str(len(variables)) + + ",&result->stable),out);\n}\n" + ) + hs.append(" (-1,[value]) -> case X.valueInfo value of\n") + for name, t in types.items(): + constructors = [ + e for e in entries if e["constructor"] and e["result"][0] == name + ] + hs.append(" (" + str(TAGS[name]) + ",_,_) -> do\n") + if not constructors: + hs.append( + ' X.unsupported "original abstract type has no public constructor fields"\n' + ) + continue + hs.append( + " object <- (" + + ( + "asRNG value" + if name == "RNG" + else "unbox " + str(TAGS[name]) + " value" + ) + + " :: IO " + + t["alias"] + + "." + + name + + ")\n case object of\n" + ) + for e in constructors: + variables = [G.fresh("field") for _ in e["args"]] + hs.append( + " " + + t["alias"] + + "." + + e["name"] + + " " + + " ".join(variables) + + " -> do\n values <- sequence [" + + ",".join(encode(s, v, types) for s, v in zip(e["args"], variables)) + + ']\n pure(X.Tuple[X.Text "' + + e["name"] + + '",X.Tuple values])\n' + ) + hs.append( + ' _ -> X.invalid "expected stochastic object"\n (-2,[left,right]) -> case(X.valueInfo left,X.valueInfo right) of\n' + ) + for name, t in types.items(): + tag = TAGS[name] + dec = "asRNG" if name == "RNG" else "unbox " + str(tag) + hs.append( + " ((" + + str(tag) + + ",_,_),(" + + str(tag) + + ",_,_)) -> do\n a <- (" + + dec + + " left :: IO " + + t["alias"] + + "." + + name + + "); b <- " + + dec + + " right\n pure(X.Boolean(a==b))\n" + ) + hs.append(""" _ -> X.invalid "stochastic equality requires matching types" + _ -> X.invalid "invalid stochastic operation/arity" +foreign export ccall "hm_stochastic_apply" ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply :: CInt -> Ptr(StablePtr X.Value) -> CSize -> Ptr(StablePtr X.Value) -> IO CInt +ffiApply operation pointers count out=stochasticBoundary $ do + values <- peekArray(fromIntegral count) pointers >>= mapM deRefStablePtr + value <- apply(fromIntegral operation) values + Boundary.checked(Right())(const(X.publish value out)) +""") + for name, opcode, args in [ + ("object_parts", -1, ["value"]), + ("equal", -2, ["left", "right"]), + ]: + proto = ( + "hmath_status hmath_stochastic_" + + name + + "(" + + ", ".join( + ["hmath_context *context"] + + ["const hmath_value *" + v for v in args] + + ["hmath_value **out"] + ) + + ")" + ) + c.append( + proto + + " {\n if(!out" + + "".join(" || !" + v for v in args) + + ')return hm_error(HMATH_INVALID_ARGUMENT,"NULL stochastic query argument");\n hmath_value *result;hmath_status status=hm_value_begin(context,&result);if(status)return status;\n void *args[]={' + + ",".join("hm_value_stable(" + v + ")" for v in args) + + "};\n return hm_value_finish(result,hm_stochastic_apply(" + + str(opcode) + + ",args," + + str(len(args)) + + ",&result->stable),out);\n}\n" + ) + h.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "src/HMath/FFI/Stochastic.hs": "".join(hs), + "include/hmath_stochastic.h": "".join(h), + "cbits/stochastic.c": "".join(c), + } + + +def fmt(source, name): + source = subprocess.run( + [ + "ruff", + "check", + "--select", + "I,RUF022,F401", + "--fix", + "--stdin-filename", + name, + "-", + ], + input=source, + text=True, + capture_output=True, + check=True, + ).stdout + return subprocess.run( + ["ruff", "format", "--stdin-filename", name, "-"], + input=source, + text=True, + capture_output=True, + check=True, + ).stdout + + +def python_name(entry, entries, types): + if entry["constructor"] and entry["name"] in types: + return entry["name"] + base = G.snake(entry["name"]) + if entry["constructor"] and any( + not e["constructor"] + and e["module"] == entry["module"] + and G.snake(e["name"]) == base + for e in entries + ): + return "new_" + base + return base + + +def frontend(entries, types, fields): + py = { + m: [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_stochastic_bindings.py.\n"""Original ' + + m + + ' remaining public functions and owned immutable records."""\nfrom ._stochastic_base import StochasticValue,_invoke\nfrom ._value import register\n' + ] + for m in MODULES + } + names = {m: [] for m in MODULES} + mapping = [] + docs = [ + "# Random streams, distributions and statistics\n\nEvery function calls the original Haskell implementation. RNG owners retain the complete immutable algorithm state, including buffered outputs. Seeds and generated words use exact Word64 transport. All seven generators, continuation/clone/split/serialization behavior, original distributions, model validation, sample ordering, diagnostics, resource budgets and error recovery are preserved. Values are owned and support `close()`/context management; results survive closing inputs. Generic sample elements preserve arbitrary typed Values rather than coercing through a numeric dtype.\n\nCallbacks use the original argument order. Raising a `MathError` from a checked callback becomes the original source `Left`; the algorithm retains its original recovery behavior. Unexpected Python exceptions rethrow after native cleanup. Pure callbacks abort on failure. Keep C callbacks/userdata alive as long as any owner/derived closure can invoke them. No package import initializes global RNG state or consumes entropy.\n\n" + ] + for name, t in types.items(): + m = t["module"] + names[m].append(name) + py[m].append( + "\nclass " + + name + + '(StochasticValue):\n """Original ' + + m + + "." + + name + + ' immutable owner."""\n' + ) + constructor = next( + (e for e in entries if e["constructor"] and e["name"] == name), None + ) + if name == "RNG": + constructor = next( + e + for e in entries + if e["module"] == "HMath.Random" and e["name"] == "seedRNG" + ) + if constructor: + params = ( + [G.snake(f) for f, _ in fields[name]] + if fields[name] + else ["generator", "seed"] + if name == "RNG" + else ["value" + str(i) for i in range(len(constructor["args"]))] + ) + py[m].append( + " def __init__(self, " + + ", ".join(params) + + "):\n self._initialize(" + + repr(symbol(constructor)) + + ", " + + repr(constructor["args"]) + + ", [" + + ", ".join(params) + + "])\n" + ) + for field, typ in fields[name]: + e = next(e for e in entries if e["module"] == m and e["name"] == field) + py[m].append( + " @property\n def " + + G.snake(field) + + "(self):\n return _invoke(" + + repr(symbol(e)) + + ", " + + repr(e["args"]) + + ", [self])\n" + ) + if name == "RNG": + py[m].append( + ' def serialize(self):\n return _invoke("hmath_stochastic_random_serialize_rng", [["RNG"]], [self])\n' + ) + py[m].append("register(" + str(TAGS[name]) + ", " + name + ")\n") + covered = set() + for e in entries: + m = e["module"] + public = MODULES[m][2] + record = e["constructor"] and e["name"] in types + pname = python_name(e, entries, types) + if not record: + params = ["argument" + str(i + 1) for i in range(len(e["args"]))] + names[m].append(pname) + py[m].append( + "\ndef " + + pname + + "(" + + ", ".join(params) + + "):\n " + + repr(G.source_prose(e)) + + "\n return _invoke(" + + repr(symbol(e)) + + ", " + + repr(e["args"]) + + ", [" + + ", ".join(params) + + "])\n" + ) + src = m + "." + e["name"] + covered.add(src) + mapping.append( + { + "symbol": src, + "c": [symbol(e)], + "python": "hmath." + public + "." + pname, + "specializations": [ + "original concrete types; arbitrary Value element containers without coercion; original checked/pure callbacks" + ], + } + ) + docs.append( + "## `" + + public + + "." + + pname + + "`\n\n" + + G.source_prose(e) + + "\n\nOriginal signature: `" + + e["signature"] + + "`. Each C argument after `context` uses a borrowed Value in original source order; `out` owns one successful result and is untouched on error.\n\n" + ) + for name, t in types.items(): + src = t["module"] + "." + name + if src not in covered: + mapping.append( + { + "symbol": src, + "c": ["hmath_value", "hmath_value_release"], + "python": "hmath." + MODULES[t["module"]][2] + "." + name, + "specializations": [ + "original raw immutable type, Value kind" + str(TAGS[name]) + ], + } + ) + result = { + "bindings/schema/stochastic-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mapping, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "bindings/schema/stochastic-functions.json": json.dumps( + {"functions": entries, "types": types, "fields": fields}, indent=2 + ) + + "\n", + "docs/reference/stochastic.md": "".join(docs), + } + for m, parts in py.items(): + parts.append("\n__all__=" + repr(sorted(set(names[m]))) + "\n") + result["bindings/python/_hmath_native/" + MODULES[m][1] + ".py"] = fmt( + "".join(parts), MODULES[m][1] + ".py" + ) + return result + + +def outputs(): + G._COUNTER = 0 + entries, types, fields = specification() + result = native(entries, types, fields) + result.update(frontend(entries, types, fields)) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/generate_tensor_bindings.py b/tools/generate_tensor_bindings.py new file mode 100644 index 0000000..d9748e9 --- /dev/null +++ b/tools/generate_tensor_bindings.py @@ -0,0 +1,406 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate named C adapters for original generic Tensor and pinned mutable APIs.""" + +import argparse +import ast +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def snake(name): + return re.sub( + r"([a-z0-9])([A-Z])", r"\1_\2", re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + ).lower() + + +def specifications(): + source = (ROOT / "src/HMath/FFI/TensorAll.hs").read_text() + result = [] + mutable = { + "newMutable", + "thawTensor", + "freezeTensor", + "mutableShape", + "readMutable", + "writeMutable", + "modifyMutable", + "sliceMutable", + "transposeMutable", + "mutableAlignment", + "withMutableBuffer", + } + output = { + name: "Tensor" + for name in [ + "tensor", + "tensorColumnMajor", + "contiguous", + "tensorZeros", + "tensorOnes", + "tensorFull", + "tensorArange", + "tensorLinspace", + "tensorLogspace", + "sliceTensor", + "fancyIndex", + "booleanIndex", + "gather", + "scatter", + "scatterAdd", + "reshapeTensor", + "flattenTensor", + "squeeze", + "unsqueeze", + "expand", + "permute", + "transposeTensor", + "moveAxis", + "swapAxes", + "broadcastTo", + "repeatTensor", + "tile", + "concatenate", + "stack", + "padTensor", + "roll", + "flipTensor", + "rotate", + "sortTensor", + "argsort", + "unique", + "nonzero", + "whereTensor", + "maskedFill", + "maskedSelect", + "mapTensor", + "zipTensor", + "tensorAdd", + "tensorSubtract", + "tensorMultiply", + "tensorDivide", + "tensorEqual", + "tensorLess", + "tensorAnd", + "tensorOr", + "tensorNot", + "promoteTensor", + "sumAxes", + "meanAxes", + "productAxes", + "minAxes", + "maxAxes", + "varianceAxes", + "normAxes", + "cumulativeSum", + "cumulativeProduct", + "tensordot", + "einsum", + "batchedMatmul", + "tensorKronecker", + "deserializeTensor", + "evaluateGraph", + "freezeTensor", + ] + } + output.update( + { + "tensorRandom": "(Tensor,Integer)", + "tensorValues": "Elements", + "tensorShape": "[Int]", + "tensorStrides": "[Int]", + "tensorOffset": "Int", + "tensorDType": "String", + "tensorDevice": "Device", + "tensorLayout": "Layout", + "isContiguous": "Bool", + "numel": "Int", + "shapeSize": "Int", + "inferBroadcast": "[Int]", + "indexTensor": "Element", + "splitTensor": "[Tensor]", + "chunkTensor": "[Tensor]", + "topk": "(Tensor,Tensor)", + "argmin": "Int", + "argmax": "Int", + "serializeTensor": "String", + "inputGraph": "TensorGraph", + "mapGraph": "TensorGraph", + "zipGraph": "TensorGraph", + "newMutable": "MutableTensor", + "thawTensor": "MutableTensor", + "mutableShape": "[Int]", + "readMutable": "Element", + "writeMutable": "Unit", + "modifyMutable": "Unit", + "sliceMutable": "MutableTensor", + "transposeMutable": "MutableTensor", + "withMutableBuffer": "Generic", + "mutableAlignment": "Int", + "RowMajor": "Layout", + "ColumnMajor": "Layout", + "Strided": "Layout", + "CPU": "Device", + } + ) + for name, arguments in re.findall(r'\("([^"]+)",\[(.*?)\]\)', source): + if name.startswith("__"): + continue + names = arguments.split(",") if arguments else [] + hints = [] + for param in names: + hint = { + "kind": "Prototype", + "shape": "[Int]", + "axis": "Int", + "start": "Element", + "end": "Element", + "step": "Element", + "base": "Element", + "count": "Int", + "xs": "Elements", + "seed": "Integer", + "index": "[Int]", + "indices": "[Int]", + "axes": "[Int]", + "from": "Int", + "to": "Int", + "counts": "[Int]", + "segments": "[Int]", + "padding": "[(Int,Int)]", + "shift": "Int", + "first": "Int", + "second": "Int", + "turns": "Int", + "keep": "Bool", + "leftAxes": "[Int]", + "rightAxes": "[Int]", + "labels": "[String]", + "outputLabels": "String", + "text": "String", + "mask": "Tensor", + "cb": "Callback", + "fill": "Element", + "input": "Tensor", + "left": "Tensor", + "right": "Tensor", + "a": "Tensor", + "b": "Tensor", + "inputs": "[Tensor]", + }.get(param, "Tensor") + if param in {"start", "step"} and name in {"sliceTensor", "sliceMutable"}: + hint = "Int" + if param == "input" and name in {"mapGraph", "zipGraph", "evaluateGraph"}: + hint = "TensorGraph" + if param in {"left", "right"} and name == "zipGraph": + hint = "TensorGraph" + if param == "input" and name in mutable - {"thawTensor"}: + hint = "MutableTensor" + if param == "cb" and name == "withMutableBuffer": + hint = "BufferCallback" + hints.append(hint) + assert name in output, name + result.append( + { + "module": "HMath.Tensor.Mutable" if name in mutable else "HMath.Tensor", + "name": name, + "python": ("tensor_dtype" if name == "tensorDType" else snake(name)), + "c": "hmath_tensor_object_" + + snake(name) + + ("_create" if name[0].isupper() else ""), + "arguments": list(zip(names, hints)), + "result": output[name], + } + ) + return result + + +def outputs(): + entries = specifications() + outputs = { + ROOT / "bindings/schema/tensor.json": json.dumps( + {"schema": 1, "functions": entries}, indent=2 + ) + + "\n", + ROOT + / "bindings/python/_hmath_native/_tensor_catalog.py": "# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_tensor_bindings.py.\nimport json\nCATALOG = json.loads(" + + repr(json.dumps(entries, separators=(",", ":"))) + + ")\n", + } + declarations = [] + definitions = [] + for item in entries: + names = [arg for arg, _ in item["arguments"]] + cname = { + "from": "from_axis", + "to": "to_axis", + "keep": "keep_dimensions", + "input": "input_tensor", + "kind": "element_type", + "fill": "fill_value", + "leftAxes": "left_axes", + "rightAxes": "right_axes", + "outputLabels": "output_labels", + } + parameters = ( + ["hmath_context *context"] + + ["const hmath_value *" + cname.get(name, name) for name in names] + + ["hmath_value **out"] + ) + signature = ( + "hmath_status " + item["c"] + "(\n " + ",\n ".join(parameters) + ")" + ) + declarations.append( + "/* " + + item["module"] + + "." + + item["name"] + + " -> " + + item["result"] + + ". */\nHMATH_API " + + signature + + ";\n" + ) + definitions.append( + signature + + " {\n" + + ( + " const hmath_value *hm_arguments[] = {" + + ", ".join(cname.get(name, name) for name in names) + + "};\n" + if names + else "" + ) + + ' return invoke(context, "' + + item["name"] + + '", ' + + ("hm_arguments" if names else "NULL") + + ", " + + str(len(names)) + + ", out);\n}\n" + ) + for path, section in [ + (ROOT / "include/hmath_tensor_bindings.h", "\n".join(declarations)), + (ROOT / "cbits/tensor_bindings.c", "\n".join(definitions)), + ]: + text = path.read_text() + a = text.index("/* BEGIN GENERATED */") + len("/* BEGIN GENERATED */") + b = text.index("/* END GENERATED */") + outputs[path] = text[:a] + "\n" + section + text[b:] + manual = { + "tensor", + "tensor_column_major", + "tensor_zeros", + "tensor_ones", + "tensor_full", + "tensor_arange", + "tensor_linspace", + "tensor_logspace", + "concatenate", + "stack", + "einsum", + "promote_tensor", + "deserialize_tensor", + "map_tensor", + "zip_tensor", + "map_graph", + "zip_graph", + "new_mutable", + "modify_mutable", + "mutable_alignment", + "with_mutable_buffer", + } + declarations = [] + public = { + "Tensor", + "TensorDouble", + "TensorGraph", + "MutableTensor", + "BorrowedBuffer", + "element_type", + "Layout", + "Device", + "RowMajor", + "ColumnMajor", + "Strided", + "CPU", + } + parameter_names = { + "input": "tensor", + "inputs": "tensors", + "index": "coordinates", + "cb": "function", + "keep": "keep_dimensions", + "from": "from_axis", + "to": "to_axis", + "leftAxes": "left_axes", + "rightAxes": "right_axes", + "outputLabels": "output_labels", + "xs": "values", + "fill": "value", + } + for item in entries: + if item["name"][0].isupper(): + continue + name = item["python"] + if name not in {"shape_size", "infer_broadcast"}: + public.add(name) + if name in manual: + continue + parameters = [ + parameter_names.get(param, param) for param, _ in item["arguments"] + ] + declarations.append( + "def " + + name + + "(" + + ", ".join(parameters) + + '):\n """' + + item["module"] + + "." + + item["name"] + + ': original dtype and failure conditions."""\n return _invoke(' + + repr(item["name"]) + + (", " + ", ".join(parameters) if parameters else "") + + ")\n" + ) + path = ROOT / "bindings/python/_hmath_native/_tensor_core.py" + text = path.read_text() + a = text.index("# BEGIN GENERATED") + len("# BEGIN GENERATED") + b = text.index("# END GENERATED") + outputs[path] = ( + text[:a] + + "\n" + + "\n".join(declarations) + + "\n__all__ = " + + repr(sorted(public, key=lambda name: (not name.isupper(), name))) + + "\n" + + text[b:] + ) + return outputs + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for path, text in outputs().items(): + if args.check: + same = ( + ast.dump(ast.parse(path.read_text())) == ast.dump(ast.parse(text)) + if path.suffix == ".py" + else path.read_text() == text + ) + if not same: + raise SystemExit(str(path.relative_to(ROOT)) + " is stale") + else: + path.write_text(text) + print( + f"Tensor catalog: {len(specifications())} named original functions/constructors." + ) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_timeseries_bindings.py b/tools/generate_timeseries_bindings.py new file mode 100644 index 0000000..397199f --- /dev/null +++ b/tools/generate_timeseries_bindings.py @@ -0,0 +1,226 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate representation adapters for original time-series functions.""" + +import argparse +import json +from pathlib import Path + +from generate_graph_bindings import ( + argument_names, + snake, + source_prose, + split_top, + type_spec, +) + +ROOT = Path(__file__).resolve().parent.parent +TYPES = { + "Series": ("HMath.TimeSeries.Core", 120), + "Alignment": ("HMath.TimeSeries.Core", 121), + "Fill": ("HMath.TimeSeries.Core", 122), + "Resampling": ("HMath.TimeSeries.Core", 123), + "Rolling": ("HMath.TimeSeries.Core", 124), + "DTWResult": ("HMath.TimeSeries.Diagnostics", 125), + "Deterministic": ("HMath.TimeSeries.Diagnostics", 126), + "ForecastMetric": ("HMath.TimeSeries.Diagnostics", 127), + "Stationarity": ("HMath.TimeSeries.Diagnostics", 128), + "ARIMAModel": ("HMath.TimeSeries.Models", 129), + "ARModel": ("HMath.TimeSeries.Models", 130), + "Decomposition": ("HMath.TimeSeries.Models", 131), + "SARIMAOrder": ("HMath.TimeSeries.Models", 132), + "STLConfig": ("HMath.TimeSeries.Models", 133), + "Smoothing": ("HMath.TimeSeries.Models", 134), + "VARModel": ("HMath.TimeSeries.Models", 135), + "GaussianState": ("HMath.Signal", 140), +} + + +def generate(): + entries = json.loads( + (ROOT / "bindings/schema/timeseries-functions.json").read_text() + )["functions"] + known = {*TYPES, "OptimizeOptions"} + numeric = { + e["module"] + "." + e["name"] + for e in json.loads((ROOT / "bindings/schema/numeric.json").read_text())[ + "functions" + ] + } + header = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated by tools/generate_timeseries_bindings.py. */\n#ifndef HMATH_TIMESERIES_H\n#define HMATH_TIMESERIES_H\n#include "hmath_value.h"\n#ifdef __cplusplus\nextern "C" {\n#endif\n', + "/* Borrowed immutable inputs; successful outputs own one Value reference.\n * Error outputs are untouched. Original binary64 arithmetic, time ordering,\n * missingness, model fitting, diagnostics, budgets and seeds are preserved.\n * OptimizeOptions accepts original kind20 objects from the optimization API.\n * Source MathError returns status11 and hmath_last_math_error payload.\n * Cancellation is checked before entry, source budgets govern evaluation. */\n", + ] + c = [ + '/* SPDX-License-Identifier: MPL-2.0 */\n/* Generated; do not edit. */\n#include "hmath_timeseries.h"\n#include "value_internal.h"\nextern int hm_timeseries_apply(int, void *const *, size_t, void **);\n' + ] + hs = [ + "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n-- SPDX-License-Identifier: MPL-2.0\n-- Generated representation adapters; all mathematics remains in original modules.\nmodule HMath.FFI.TimeSeries where\nimport Foreign\nimport Foreign.C\nimport HMath.FFI.Boundary\nimport HMath.FFI.Value\nimport HMath.FFI.GraphCodec (Wire(..),boxed,unboxed)\nimport qualified HMath.TimeSeries as T\nimport qualified HMath.Signal as S\nimport qualified HMath.Optimization.Common as O\n", + "instance Wire O.OptimizeOptions where\n wire = boxed 20\n unwire = unboxed 20\n", + ] + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_timeseries_bindings.py.\n"""Original timestamped-series, diagnostics and forecasting functions."""\nfrom ._timeseries_base import _invoke\nfrom ._value import Value, register\n', + ] + docs = [ + "# Time-series bindings\n\nC includes `hmath_timeseries.h`; Python uses `from hmath import timeseries`. These functions call the original Haskell time-series implementation. Timestamps retain caller-defined units, ordering and explicit missing values; no calendar interpretation or automatic data cleaning is added. The source observation, work and fitting limits remain in force.\n\n", + "All inputs are borrowed during a synchronous call; every successful C output owns one [structured value](values.md) reference. Outputs are unchanged on error. Checked `Left MathError` returns status11 with the original structured error. Immutable objects support concurrent readers with independent references and output addresses. Python owners have `close()` and context managers. `Maybe Double` observations use `None` for missingness. Forecast models and configuration constructors retain the original argument order and defaults. `OptimizeOptions` comes from `hmath.optimization`.\n\n", + "ARMA/SARIMA use the original local conditional sum-of-squares fit, not a substituted exact likelihood model. Stationarity and interval estimates are not inferred by forecasting calls. Refer to the linked source contract for each model and diagnostic.\n\n", + ] + mappings = [] + for name, (module, tag) in TYPES.items(): + qualifier = "S" if module == "HMath.Signal" else "T" + hs.append( + f"instance Wire {qualifier}.{name} where\n wire = boxed {tag}\n unwire = unboxed {tag}\n" + ) + py.append( + f'\n\nclass {name}(Value):\n """Owned immutable original {module}.{name}."""\n\n\nregister({tag}, {name})\n' + ) + header.append( + f"typedef hmath_value hmath_timeseries_{snake(name)}_object; /* kind{tag} */\n" + ) + # A type/constructor with the same source name is one inventory entry. + if name not in {e["name"] for e in entries}: + mappings.append( + { + "symbol": module + "." + name, + "c": ["hmath_timeseries_" + snake(name) + "_object"], + "python": "hmath.timeseries." + name, + "specializations": ["original concrete type"], + } + ) + header.append( + "/* Return the original Show representation as an owned String Value. */\nHMATH_API hmath_status hmath_timeseries_describe(hmath_context *context, const hmath_value *value, hmath_value **out);\n" + ) + c.append( + 'extern int hm_timeseries_describe(void *,void **);\nhmath_status hmath_timeseries_describe(hmath_context *context,const hmath_value *value,hmath_value **out) {\n if (!value || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series description argument");\n hmath_value *temporary = NULL;\n hmath_status status = hm_value_begin(context,&temporary);\n if (status) return status;\n int code = hm_timeseries_describe(hm_value_stable(value),&temporary->stable);\n return hm_value_finish(temporary,code,out);\n}\n' + ) + hs.append( + 'foreign export ccall "hm_timeseries_describe" describe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\ndescribe :: StablePtr Value -> Ptr (StablePtr Value) -> IO CInt\ndescribe input out = boundary $ do\n value <- deRefStablePtr input\n text <- case value of\n' + ) + for name, (module, tag) in TYPES.items(): + qualifier = "S" if module == "HMath.Signal" else "T" + hs.append( + f" Opaque {tag} _ _ _ _ -> show <$> (unwire value :: IO {qualifier}.{name})\n" + ) + hs.append( + ' _ -> invalid "expected a time-series domain object"\n publish (Text text) out\n pure 0\n' + ) + py.append( + '\n\ndef describe(value):\n """Return the original Haskell Show representation of a domain object."""\n return _invoke("hmath_timeseries_describe", [["SeriesObject"]], [value])\n' + ) + docs.append( + "## `describe`\n\n`timeseries.describe(value)` returns the original Haskell `Show` representation of one time-series object or Gaussian state. It preserves the original constructor and fields as text, including Unicode and embedded NUL. C receives an owned String value through `hmath_timeseries_describe(context, value, out)`. Mathematical operations use the typed object directly.\n\n" + ) + hs += [ + 'foreign export ccall "hm_timeseries_apply" apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt\n', + "apply :: CInt -> Ptr (StablePtr Value) -> CSize -> Ptr (StablePtr Value) -> IO CInt\napply operation input arity out = boundary $ do\n values <- peekArray (fromIntegral arity) input >>= mapM deRefStablePtr\n case (operation,values) of\n", + ] + for operation, entry in enumerate(entries): + signature = split_top(entry["signature"], "->") + arguments, result = signature[:-1], signature[-1] + checked = result.startswith("Either MathError ") + result = result.removeprefix("Either MathError ") + specifications = [type_spec(t, known) for t in arguments] + type_spec(result, known) + args = argument_names(entry, len(arguments)) + constructors = { + "DTWResult": "distance path", + "Stationarity": "statistic critical_values observations null_hypothesis", + "Decomposition": "trend seasonal remainder", + "SARIMAOrder": "ar difference ma seasonal_ar seasonal_difference seasonal_ma period", + "STLConfig": "period seasonal_window trend_window low_pass_window inner_iterations robust_iterations", + "Simple": "alpha", + "Holt": "alpha beta", + "HoltWinters": "period alpha beta gamma", + "MASE": "period training", + } + if entry["name"] in constructors: + args = constructors[entry["name"]].split() + if len(args) != len(arguments): + raise ValueError("time-series constructor fields differ") + name = snake(entry["name"]) + symbol = "hmath_timeseries_" + name + source = entry["module"] + "." + entry["name"] + declaration = [ + "hmath_context *context", + *["const hmath_value *" + arg for arg in args], + "hmath_value **out", + ] + prototype = f"hmath_status {symbol}(" + ", ".join(declaration) + ")" + header.append( + f"/* {source} :: {entry['signature']} */\nHMATH_API {prototype};\n" + ) + c.append( + prototype + + " {\n if (!out" + + "".join(" || !" + a for a in args) + + ')\n return hm_error(HMATH_INVALID_ARGUMENT,"NULL time-series argument");\n hmath_value *temporary = NULL;\n hmath_status status = hm_value_begin(context,&temporary);\n if (status) return status;\n' + ) + c.append( + " void *arguments[] = {" + + (", ".join("hm_value_stable(" + a + ")" for a in args) or "NULL") + + "};\n" + ) + c.append( + f" int code = hm_timeseries_apply({operation},arguments,{len(args)},&temporary->stable);\n return hm_value_finish(temporary,code,out);\n}}\n" + ) + hs.append( + f" ({operation},[" + + ",".join("v" + arg for arg in args) + + "]) -> do\n" + ) + hs += [f" {arg} <- unwire v{arg}\n" for arg in args] + qualifier = "S" if entry["module"] == "HMath.Signal" else "T" + call = qualifier + "." + entry["name"] + (" " + " ".join(args) if args else "") + hs.append( + " checked (" + + (call if checked else "Right (" + call + ")") + + ") (\\result_value -> publish (wire result_value) out)\n" + ) + py.append( + f'\n\ndef {name}({", ".join(args)}):\n """{source} :: {entry["signature"]}."""\n return _invoke({symbol!r}, {specifications!r}, [{", ".join(args)}])\n' + ) + docs.append( + f"## `{name}`\n\n`timeseries.{name}({', '.join(args)})`\n\n{source_prose(entry)}\n\nOriginal: [`{source}`](haskell/{entry['module'].replace('.', '-')}.md#v:{entry['name']}).\n\n```haskell\n{entry['signature']}\n```\n\n```c\n{prototype};\n```\n\n" + ) + if source not in numeric: + mappings.append( + { + "symbol": source, + "c": [symbol], + "python": "hmath.timeseries." + name, + "specializations": ["original concrete types"], + } + ) + hs.append( + ' _ -> invalid "time-series operation identifier or arity differs"\n' + ) + header.append("#ifdef __cplusplus\n}\n#endif\n#endif\n") + return { + "include/hmath_timeseries.h": "".join(header), + "cbits/timeseries.c": "".join(c), + "src/HMath/FFI/TimeSeries.hs": "".join(hs), + "bindings/python/_hmath_native/timeseries.py": "".join(py), + "docs/reference/timeseries-bindings.md": "".join(docs), + "bindings/schema/timeseries-objects.json": json.dumps( + {"schema": 1, "bindings": mappings}, indent=2 + ) + + "\n", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, content in generate().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != content: + parser.exit(1, "Stale time-series binding: " + name + "\n") + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_units_bindings.py b/tools/generate_units_bindings.py new file mode 100644 index 0000000..d087fbd --- /dev/null +++ b/tools/generate_units_bindings.py @@ -0,0 +1,449 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Generate direct exact adapters for all previously-unmapped Units symbols.""" + +import argparse +import json +import re +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TYPES = {"Dimension": 68, "Unit": 69, "Quantity": 70, "SIPrefix": 71} +EXISTING = { + "radiansToDegrees", + "degreesToRadians", + "radiansToGradians", + "gradiansToRadians", +} +# Each entry records source argument order/type, exact result and error convention. +SPECS = { + "dimension": ([("exponents", "[Integer]")], "Dimension", "either"), + "dimensionExponents": ([("dimension", "Dimension")], "[Integer]", "pure"), + "unit": ( + [ + ("name", "String"), + ("dimension", "Dimension"), + ("scale", "Rational"), + ("offset", "Rational"), + ], + "Unit", + "either", + ), + "unitName": ([("unit", "Unit")], "String", "pure"), + "unitDimension": ([("unit", "Unit")], "Dimension", "pure"), + "unitScale": ([("unit", "Unit")], "Rational", "pure"), + "unitOffset": ([("unit", "Unit")], "Rational", "pure"), + "unitProduct": ([("left", "Unit"), ("right", "Unit")], "Unit", "either"), + "unitQuotient": ( + [("numerator", "Unit"), ("denominator", "Unit")], + "Unit", + "either", + ), + "unitPower": ([("unit", "Unit"), ("exponent", "Integer")], "Unit", "either"), + "quantity": ([("unit", "Unit"), ("value", "Rational")], "Quantity", "pure"), + "temperatureDifference": ( + [("unit", "Unit"), ("value", "Rational")], + "Quantity", + "either", + ), + "quantityDimension": ([("quantity", "Quantity")], "Dimension", "pure"), + "siValue": ([("quantity", "Quantity")], "Rational", "pure"), + "inUnit": ([("unit", "Unit"), ("quantity", "Quantity")], "Rational", "either"), + "convert": ( + [("source", "Unit"), ("destination", "Unit"), ("value", "Rational")], + "Rational", + "either", + ), + "addQuantity": ( + [("left", "Quantity"), ("right", "Quantity")], + "Quantity", + "either", + ), + "subtractQuantity": ( + [("left", "Quantity"), ("right", "Quantity")], + "Quantity", + "either", + ), + "multiplyQuantity": ( + [("left", "Quantity"), ("right", "Quantity")], + "Quantity", + "either", + ), + "divideQuantity": ( + [("numerator", "Quantity"), ("denominator", "Quantity")], + "Quantity", + "either", + ), + "prefixName": ([("prefix", "SIPrefix")], "String", "pure"), + "prefixSymbol": ([("prefix", "SIPrefix")], "String", "pure"), + "prefixExponent": ([("prefix", "SIPrefix")], "Int", "pure"), + "siPrefixes": ([], "[SIPrefix]", "pure"), + "prefixed": ([("prefix", "SIPrefix"), ("unit", "Unit")], "Unit", "either"), + "SIPrefix": ( + [("name", "String"), ("symbol", "String"), ("exponent", "Int")], + "SIPrefix", + "pure", + ), +} + + +def snake(name): + return re.sub( + r"([a-z0-9])([A-Z])", r"\1_\2", re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + ).lower() + + +def source_exports(): + text = ( + (ROOT / "src/HMath/Units.hs") + .read_text() + .split(") where", 1)[0] + .split("module HMath.Units (", 1)[1] + ) + return re.findall(r"^ (\w+)", text, re.MULTILINE) + ["prefixName", "prefixSymbol", "prefixExponent"] + + +def ops(): + result = [] + for name in source_exports(): + if name in EXISTING or (name in TYPES and name != "SIPrefix"): + continue + spec = SPECS.get( + name, + ( + [], + "Dimension" + if name.endswith("Dimension") or name == "dimensionless" + else "Unit", + "pure", + ), + ) + result.append((name, *spec)) + return result + + +def source_doc(name): + source = (ROOT / "src/HMath/Units.hs").read_text() + match = re.search(r"\n" + re.escape(name) + r"(?:\s+::|\s*=|\s+\w)", source) + if not match: + return "Original public HMath.Units constructor or field." + before = source[: match.start()] + start = max(before.rfind("\n{- |"), before.rfind("\n-- |")) + text = before[start:].strip() + if text.startswith("{- |"): + text = text[4:].split("-}", 1)[0] + elif text.startswith("-- |"): + text = text[4:] + else: + return "Original public HMath.Units value." + return " ".join(text.replace("--", "").replace("@", "`").split()) + + +def python_format(source): + checked = subprocess.run( + [ + "ruff", + "check", + "--select", + "I,RUF022", + "--fix", + "--stdin-filename", + "units_values.py", + "-", + ], + input=source, + text=True, + capture_output=True, + check=True, + ).stdout + return subprocess.run( + ["ruff", "format", "--stdin-filename", "units_values.py", "-"], + input=checked, + text=True, + capture_output=True, + check=True, + ).stdout + + +def outputs(): + entries = ops() + h = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_units_bindings.py. */ +#ifndef HMATH_UNITS_H +#define HMATH_UNITS_H +#include "hmath_value.h" +#ifdef __cplusplus +extern "C" { +#endif +/* Exact original Units API. Unit/Quantity scalar inputs must be Rational + * Values; dimension and power exponents use arbitrary Integer Values. + * Prefix exponents use Haskell Int. Objects are immutable and independently + * owned; release every result with hmath_value_release. Inputs are borrowed + * for this call only. All errors preserve the original MathError; output + * pointers remain untouched on failure. Catalog getters return owned handles. */ +""" + ] + c = [ + """/* SPDX-License-Identifier: MPL-2.0 */ +/* Generated by tools/generate_units_bindings.py. */ +#include "hmath_units.h" +#include "value_internal.h" +extern int hm_units_apply(int opcode,void *const *args,size_t count,void **out); +""" + ] + hs = [ + """{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ForeignFunctionInterface #-} +-- SPDX-License-Identifier: MPL-2.0 +-- Generated by tools/generate_units_bindings.py. No numerical reimplementation. +module HMath.FFI.Units where +import Control.Exception (evaluate,throwIO) +import Data.Typeable (Typeable,cast) +import Foreign +import Foreign.C +import qualified HMath.Units as U +import HMath.Error (MathError) +import HMath.FFI.Coefficient +import qualified HMath.FFI.Value as V +import qualified HMath.FFI.Boundary as B +import HMath.FFI.MathError + +dimension :: U.Dimension -> V.Value +dimension x=V.Opaque 68 (-1) 9 (mapM_ forceCoefficient (U.dimensionExponents x)) x +unit :: U.Unit -> V.Value +unit x=V.Opaque 69 (-1) 0 (V.forceValue(V.Text(U.unitName x)) >> V.forceValue(dimension(U.unitDimension x)) >> forceCoefficient(U.unitScale x) >> forceCoefficient(U.unitOffset x)) x +quantity :: U.Quantity -> V.Value +quantity x=V.Opaque 70 (-1) 0 (V.forceValue(dimension(U.quantityDimension x)) >> forceCoefficient(U.siValue x) >> evaluate x >> pure ()) x +siPrefix :: U.SIPrefix -> V.Value +siPrefix x=V.Opaque 71 (-1) 0 (V.forceValue(V.Text(U.prefixName x)) >> V.forceValue(V.Text(U.prefixSymbol x)) >> evaluate(U.prefixExponent x) >> pure ()) x +asObject :: Typeable a => Int -> V.Value -> IO a +asObject kind (V.Opaque actual _ _ _ payload) | kind==actual=maybe (V.invalid "Units object payload/type mismatch") pure (cast payload) +asObject _ _=V.invalid "Units object kind mismatch" +source :: Either MathError a -> IO a +source=either (throwIO . CallbackMathError) pure +unitsBoundary :: IO CInt -> IO CInt +unitsBoundary action=B.boundary $ callbackBoundary (\\e -> B.checked (Left e) (const(pure ()))) action +apply :: Int -> [V.Value] -> IO V.Value +apply opcode args=case (opcode,args) of +""" + ] + py = [ + '# SPDX-License-Identifier: MPL-2.0\n# Generated by tools/generate_units_bindings.py.\n"""Exact original HMath.Units operations and owned catalog values."""\nfrom ._units_base import Dimension,Unit,Quantity,SIPrefix,_call\n' + ] + py.append( + "__all__=" + + repr(list(TYPES) + [snake(x[0]) for x in entries]) + + "\n" + ) + docs = [ + """# Exact units and quantities + +Unit conversion and quantity arithmetic call the original `HMath.Units` implementation. Values are exact `fractions.Fraction` objects, including affine offsets; exponents are arbitrary integers. Nine dimensions distinguish seven SI base dimensions, data, and plane angle. Invalid conversions preserve original `MathError` constructors and messages. + +```python +from fractions import Fraction +from hmath import units as u + +with u.kilometre() as km, u.metre() as metre: + assert u.convert(km, metre, Fraction(3, 2)) == 1500 +with u.celsius() as c, u.fahrenheit() as f: + assert u.convert(c, f, 100) == 212 +``` + +Catalog names are zero-argument functions returning independently owned immutable Unit/Dimension handles. Use `close()` or a context manager; releasing an input cannot invalidate a returned quantity or derived unit. Constants are not initialized at import time. `Dimension`, `Unit`, `Quantity`, and `SIPrefix` constructors follow their original source constructors; named functions provide equivalent access. Their equality uses original derived Haskell `Eq`. + +Absolute temperatures and differences retain their original hidden distinction: absolute plus absolute fails, absolute minus absolute yields a difference, difference minus absolute fails, and multiplying/dividing an absolute temperature fails. `temperature_difference` ignores the unit's affine offset. `in_unit` subtracts an affine offset only for absolute quantities. Zero divisor, incompatible dimensions, invalid scale, affine unit products/prefixes, and prefix resource limits retain original errors. The SI prefix catalog includes exactly the source ordering and spellings. + +Python integer inputs to Rational fields are converted exactly, and `Fraction` values never pass through FP64. A Python float is converted to the exact fraction representing that already-rounded float; use `Fraction("0.1")` when decimal 0.1 is intended. Prefix exponents must fit Haskell `Int`; unit powers and dimension exponents use unbounded `Integer`. The existing four angle-conversion numeric functions retain their Float/Double interfaces. + +Include `hmath_units.h` plus `hmath_value.h` in C. Unit/quantity scalar inputs use Rational Values, dimensional/power exponents use Integer Values, and prefix exponents use Index or an exact Int-range integral Value. Text uses length-delimited codepoints, preserving Unicode, embedded NUL and Haskell Char surrogates. Every result is owned and must be released once. Errors leave `out` untouched. Inputs are immutable and borrowed for the call only; independent calls may share them. + +""" + ] + mapping = [] + decoder = { + "String": "V.asText", + "Rational": "V.asScalar", + "Integer": "V.asScalar", + "Int": "V.asIndex", + "[Integer]": "(\\v -> V.asList v >>= mapM V.asScalar)", + } + encoder = { + "String": "V.Text", + "Rational": "V.Scalar SRational", + "Integer": "V.Scalar SInteger", + "Int": "V.Index", + "[Integer]": "V.List . map (V.Scalar SInteger)", + "[SIPrefix]": "V.List . map siPrefix", + } + for typ, tag in TYPES.items(): + decoder[typ] = "asObject " + str(tag) + encoder[typ] = "siPrefix" if typ == "SIPrefix" else typ[0].lower() + typ[1:] + for opcode, (name, args, result, mode) in enumerate(entries): + variables = ["a" + str(i) for i in range(len(args))] + hs.append(" (" + str(opcode) + ",[" + ",".join(variables) + "]) -> do\n") + for variable, (_parameter, typ) in zip(variables, args): + hs.append( + " " + + variable + + "Value <- " + + decoder[typ] + + " " + + variable + + "\n" + ) + expression = "U." + name + " " + " ".join(v + "Value" for v in variables) + if mode == "either": + hs.append( + " (" + encoder[result] + ") <$> source (" + expression + ")\n" + ) + else: + hs.append(" pure ((" + encoder[result] + ") (" + expression + "))\n") + symbol = "hmath_units_value_" + snake(name) + params = ( + ["hmath_context *context"] + + ["const hmath_value *" + a for a, _ in args] + + ["hmath_value **out"] + ) + proto = "hmath_status " + symbol + "(" + ", ".join(params) + ")" + h.append("HMATH_API " + proto + ";\n") + checks = ["!out"] + ["!" + a for a, _ in args] + c.append( + proto + + " {\n if (" + + " || ".join(checks) + + ')\n return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units argument");\n hmath_value *result;\n hmath_status status=hm_value_begin(context,&result);\n if(status) return status;\n' + ) + cargs = "NULL" + if args: + c.append( + " void *args[]={" + + ",".join("hm_value_stable(" + a + ")" for a, _ in args) + + "};\n" + ) + cargs = "args" + c.append( + " return hm_value_finish(result,hm_units_apply(" + + str(opcode) + + "," + + cargs + + "," + + str(len(args)) + + ",&result->stable),out);\n}\n" + ) + pname = "si_prefix" if name == "SIPrefix" else snake(name) + signature = ", ".join(a for a, _ in args) + doc = source_doc(name) + py.append( + "\ndef " + + pname + + "(" + + signature + + "):\n " + + repr("HMath.Units." + name + ": " + doc) + + "\n return _call(" + + repr(symbol) + + ", " + + repr([typ for _, typ in args]) + + (", " + signature if args else "") + + ")\n" + ) + docs.append( + "## `" + + pname + + "`\n\n" + + doc + + "\n\n`" + + pname + + "(" + + signature + + ")` returns `" + + result + + "`" + + (" or raises the original checked error." if mode == "either" else ".") + + " Parameters: " + + ( + ", ".join("`" + a + "`: `" + typ + "`" for a, typ in args) + if args + else "none; returns a new owned reference to the source catalog value." + ) + + "\n\n```c\n" + + proto + + ";\n```\n\n" + ) + if name not in TYPES: + mapping.append( + { + "symbol": "HMath.Units." + name, + "c": [symbol], + "python": "hmath.units." + pname, + "specializations": [ + "original concrete Integer/Rational/Int/String/record types; exact conversion" + ], + } + ) + for typ, tag in TYPES.items(): + mapping.append( + { + "symbol": "HMath.Units." + typ, + "c": [ + "hmath_value", + "hmath_units_value_" + + snake(typ if typ == "SIPrefix" else typ[0].lower() + typ[1:]), + ], + "python": "hmath.units." + typ, + "specializations": ["immutable exact Units Value kind" + str(tag)], + } + ) + # Private dispatch opcode100 compares original Eq of matching owner families. + hs.append(""" (100,[a,b]) -> case (V.valueInfo a,V.valueInfo b) of + ((68,_,_),(68,_,_)) -> do x <- asObject 68 a; y <- asObject 68 b; pure(V.Boolean((x::U.Dimension)==y)) + ((69,_,_),(69,_,_)) -> do x <- asObject 69 a; y <- asObject 69 b; pure(V.Boolean((x::U.Unit)==y)) + ((70,_,_),(70,_,_)) -> do x <- asObject 70 a; y <- asObject 70 b; pure(V.Boolean((x::U.Quantity)==y)) + ((71,_,_),(71,_,_)) -> do x <- asObject 71 a; y <- asObject 71 b; pure(V.Boolean((x::U.SIPrefix)==y)) + _ -> V.invalid "Units equality requires matching types" + _ -> V.invalid "invalid Units operation/arity" +foreign export ccall "hm_units_apply" ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply :: CInt -> Ptr (StablePtr V.Value) -> CSize -> Ptr (StablePtr V.Value) -> IO CInt +ffiApply opcode pointers count out=unitsBoundary $ do + args <- peekArray (fromIntegral count) pointers >>= mapM deRefStablePtr + value <- apply (fromIntegral opcode) args + B.checked (Right ()) (const (V.publish value out)) +""") + h.append( + "HMATH_API hmath_status hmath_units_value_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out);\n#ifdef __cplusplus\n}\n#endif\n#endif\n" + ) + c.append("""hmath_status hmath_units_value_equal(hmath_context *context,const hmath_value *left,const hmath_value *right,hmath_value **out) { + if(!left || !right || !out) return hm_error(HMATH_INVALID_ARGUMENT,"NULL Units equality argument"); + hmath_value *result; hmath_status status=hm_value_begin(context,&result); if(status) return status; + void *args[]={hm_value_stable(left),hm_value_stable(right)}; + return hm_value_finish(result,hm_units_apply(100,args,2,&result->stable),out); +} +""") + return { + "src/HMath/FFI/Units.hs": "".join(hs), + "include/hmath_units.h": "".join(h), + "cbits/units.c": "".join(c), + "bindings/python/_hmath_native/units_values.py": python_format("".join(py)), + "bindings/schema/units-values-objects.json": json.dumps( + {"schema": 1, "bindings": sorted(mapping, key=lambda x: x["symbol"])}, + indent=2, + ) + + "\n", + "docs/reference/units-values.md": "".join(docs), + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = ROOT / name + if args.check: + if not path.exists() or path.read_text() != data: + raise SystemExit("Stale: " + name) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data) diff --git a/tools/numeric_specializations.py b/tools/numeric_specializations.py new file mode 100644 index 0000000..1b8c252 --- /dev/null +++ b/tools/numeric_specializations.py @@ -0,0 +1,149 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Concrete standard numeric instances for polymorphic Haskell adapters. + +This is a binding/type description, not an implementation of numeric operations. +The source function remains the unit of coverage; its type instances are tracked +individually. Open Haskell classes can have user-defined instances beyond this +finite set, so no entry is labelled universally type-complete. +""" + +from copy import deepcopy + +BOUNDED = { + "int8": ("int8_t", "Int8", 8, True, "_i8"), + "int16": ("int16_t", "Int16", 16, True, "_i16"), + "int32": ("int32_t", "Int32", 32, True, "_i32"), + "int64": ("int64_t", "Int64", 64, True, "_i64"), + "uint8": ("uint8_t", "Word8", 8, False, "_u8"), + "uint16": ("uint16_t", "Word16", 16, False, "_u16"), + "uint32": ("uint32_t", "Word32", 32, False, "_u32"), + "uint64": ("uint64_t", "Word64", 64, False, "_u64"), + "intp": ("ptrdiff_t", "Int", None, True, "_int"), + "uintp": ("size_t", "Word", None, False, "_word"), +} +INTEGRAL = ["integer", *BOUNDED] +REAL = ["float32", "float64", "rational", *INTEGRAL] +COMPLEX = ["complex64", "complex128"] +NUM = [*REAL, *COMPLEX] +FRACTIONAL = ["float32", "float64", "rational", *COMPLEX] +FLOATING = ["float32", "float64", *COMPLEX] + + +def generic_types(module, name): + """Only instances permitted by the original function's constraints.""" + if module == "HMath.Basic": + return {"clamp": REAL, "lerp": FRACTIONAL}.get(name) + if module == "HMath.Scalar": + if name in { + "add", + "subtractScalar", + "multiply", + "absolute", + "sign", + "cumulativeSum", + "prefixSum", + "cumulativeProduct", + }: + return NUM + if name in {"minimumScalar", "maximumScalar"}: + return REAL + if name == "positiveModulo": + return INTEGRAL + if name in { + "saturatingAdd", + "saturatingSubtract", + "saturatingMultiply", + "checkedAdd", + "checkedSubtract", + "checkedMultiply", + }: + return list(BOUNDED) + if module == "HMath.Linear": + return FLOATING if name in {"magnitude", "normalize"} else NUM + if module == "HMath.Statistics": + return { + "mean": FRACTIONAL, + "variance": FRACTIONAL, + "standardDeviation": FLOATING, + "median": ["float32", "float64", "rational"], + }.get(name) + return None + + +def dtype_wire(dtype): + if dtype in ("float32", "float64"): + return "f", "fs", "f", "fd", int(dtype[-2:]), "_f" + dtype[-2:] + if dtype == "integer": + return "z", "zs", "z", "zd", None, "_integer" + if dtype == "rational": + return "q", "qs", "q", "qd", None, "_rational" + if dtype in COMPLEX: + bits = 32 if dtype == "complex64" else 64 + return "c", "cs", "c", "cd", bits, "_c" + dtype[-2:] if bits == 32 else "_c128" + if dtype in BOUNDED: + return dtype, dtype + "s", dtype, dtype + "d", None, BOUNDED[dtype][4] + raise ValueError(dtype) + + +def binding_variants(entry): + """Return explicit wire instances while retaining one source symbol.""" + types = entry.get("specializations") + if not types: + # Legacy entries remain byte-for-byte compatible with existing ABI. + floating = any( + a["type"] in ("f", "fs", "p", "c") for a in entry["args"] + ) or entry["result"] in ( + "f", + "ff", + "fff", + "ffff", + "c", + "fs", + "fd", + "zf", + "sf", + "sf2", + "sf4", + "fsf", + ) + return [ + { + "dtype": f"float{bits}" if bits else None, + "precision": bits, + "suffix": f"_f{bits}" if bits else "", + "args": entry["args"], + "result": entry["result"], + "legacy": True, + } + for bits in entry.get("precisions", [32, 64] if floating else [None]) + ] + variants = [] + generic_arguments = entry.get("generic_arguments", [True] * len(entry["args"])) + for dtype in types: + scalar_in, list_in, scalar_out, list_out, precision, suffix = dtype_wire(dtype) + args = deepcopy(entry["args"]) + for generic, argument in zip(generic_arguments, args): + if generic: + argument["type"] = ( + list_in if argument["type"] in ("fs", "zs") else scalar_in + ) + result = entry["result"] + if entry.get("generic_result", True): + result = list_out if result in ("fs", "fd", "zd") else scalar_out + # Existing Float buffer-output entry points retain their public form. + if dtype in ("float32", "float64"): + result = entry["result"] + variants.append( + { + "dtype": dtype, + "precision": precision, + "suffix": suffix, + "args": args, + "result": result, + "legacy": False, + } + ) + for legacy in entry.get("legacy_variants", []): + variant = next(v for v in variants if v["dtype"] == legacy["dtype"]) + variants.append(dict(variant, suffix=legacy["suffix"], legacy=True)) + return variants diff --git a/tools/publish_github_release.py b/tools/publish_github_release.py new file mode 100644 index 0000000..157486b --- /dev/null +++ b/tools/publish_github_release.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Stage a verified immutable candidate, then publish it after index uploads.""" + +import argparse +import hashlib +import json +import re +import subprocess +import tempfile +from pathlib import Path + +from verify_release_candidate import verify_candidate + + +def gh(*arguments): + return subprocess.check_output(["gh", *arguments], text=True) + + +def tag_target(repository, tag): + result = subprocess.run( + ["gh", "api", f"repos/{repository}/commits/{tag}", "--jq", ".sha"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode: + if "(HTTP 404)" in result.stderr or "(HTTP 422)" in result.stderr: + return None + raise RuntimeError(result.stderr) + return result.stdout.strip() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--repository", required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--stage-only", action="store_true") + args = parser.parse_args() + manifest = verify_candidate(args.directory, args.commit) + version = manifest["version"] + paths = [args.directory / "release.json", args.directory / "SHA256SUMS"] + paths += [args.directory / item["path"] for item in manifest["artifacts"]] + tag = "v" + version + target = tag_target(args.repository, tag) + if target is not None and target != args.commit: + raise ValueError("existing tag points to another source commit") + pages = json.loads( + gh( + "api", + "--paginate", + "--slurp", + f"repos/{args.repository}/releases?per_page=100", + ) + ) + existing = next((r for page in pages for r in page if r["tag_name"] == tag), None) + assets = {} + draft_target = None + if existing: + if existing["draft"]: + draft_target = gh( + "api", + f"repos/{args.repository}/commits/{existing['target_commitish']}", + "--jq", + ".sha", + ).strip() + assets = {a["name"]: a for a in existing["assets"]} + if set(assets) - {p.name for p in paths}: + raise ValueError("existing release contains assets outside this candidate") + # Validate every existing asset before creating/updating anything. + missing = [] + for path in paths: + expected = hashlib.sha256(path.read_bytes()).hexdigest() + if path.name not in assets: + missing.append(path) + continue + digest = assets[path.name].get("digest") + if not digest: + with tempfile.TemporaryDirectory( + prefix="hmath-release-asset-" + ) as directory: + gh( + "release", + "download", + tag, + "--repo", + args.repository, + "--pattern", + path.name, + "--dir", + directory, + ) + digest = ( + "sha256:" + + hashlib.sha256( + (Path(directory) / path.name).read_bytes() + ).hexdigest() + ) + if digest != "sha256:" + expected: + raise ValueError(f"existing GitHub release asset differs: {path.name}") + # A moving branch can advance after staging. Only an already validated + # receipt permits recovery of that original immutable candidate. + if ( + draft_target is not None + and draft_target != args.commit + and ( + "release.json" not in assets + or re.fullmatch(r"[0-9a-fA-F]{40}", existing["target_commitish"]) + ) + ): + raise ValueError("existing draft targets another source commit") + if not existing: + gh( + "release", + "create", + tag, + "--repo", + args.repository, + "--target", + args.commit, + "--title", + "HMath " + version, + "--generate-notes", + "--draft", + ) + elif existing["draft"] and existing["target_commitish"] != args.commit: + gh( + "release", + "edit", + tag, + "--repo", + args.repository, + "--target", + args.commit, + ) + # Persist candidate_run_id first, so a later dispatch selects this same run. + for path in missing: + gh("release", "upload", tag, str(path), "--repo", args.repository) + if not args.stage_only: + stable = [] + for page in pages: + for release in page: + match = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", release["tag_name"]) + if match and not release["draft"] and not release["prerelease"]: + stable.append(tuple(map(int, match.groups()))) + newest = not stable or tuple(map(int, version.split("."))) >= max(stable) + gh( + "release", + "edit", + tag, + "--repo", + args.repository, + "--draft=false", + "--latest=" + str(newest).lower(), + ) + + +if __name__ == "__main__": + main() diff --git a/tools/release_manifest.py b/tools/release_manifest.py new file mode 100644 index 0000000..08a8fdf --- /dev/null +++ b/tools/release_manifest.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Record checksums and source identity for all prepared language artifacts.""" + +import argparse +import hashlib +import json +import re +from pathlib import Path + +from release_version import release_version +from verify_release_candidate import validate_artifacts + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--commit", required=True) + parser.add_argument("--run-id", required=True, type=int) + args = parser.parse_args() + if not re.fullmatch(r"[0-9a-f]{40}", args.commit): + parser.error("--commit must be an exact Git commit SHA") + if args.run_id < 1: + parser.error("--run-id must be a positive workflow run ID") + version = release_version() + paths = validate_artifacts(args.directory, version) + records = [ + { + "path": str(path.relative_to(args.directory)), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "bytes": path.stat().st_size, + } + for path in paths + ] + (args.directory / "release.json").write_text( + json.dumps( + { + "version": version, + "commit": args.commit, + "candidate_run_id": args.run_id, + "abi": 1, + "artifacts": records, + }, + indent=2, + ) + + "\n" + ) + (args.directory / "SHA256SUMS").write_text( + "".join(record["sha256"] + " " + record["path"] + "\n" for record in records) + + hashlib.sha256((args.directory / "release.json").read_bytes()).hexdigest() + + " release.json\n" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/release_version.py b/tools/release_version.py new file mode 100644 index 0000000..99a9f5c --- /dev/null +++ b/tools/release_version.py @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Read the project version once and reject inconsistent release metadata.""" + +import re +from pathlib import Path + +import tomllib + +ROOT = Path(__file__).resolve().parent.parent + + +def release_version(): + version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + if not re.fullmatch(r"\d+\.\d+\.\d+", version): + raise ValueError("release version must have major.minor.patch components") + checks = { + "hmath.cabal": r"^version:\s*([\d.]+)\s*$", + "meson.build": r"project\('hmath', 'c', version: '([^']+)'", + "cbits/native.c": r'hmath_library_version\(void\)\s*\{\s*return "([^\"]+)";', + } + for name, pattern in checks.items(): + match = re.search(pattern, (ROOT / name).read_text(), re.MULTILINE) + if not match or match[1] != version: + raise ValueError(f"{name}: version differs from pyproject.toml ({version})") + return version + + +if __name__ == "__main__": + print(release_version()) diff --git a/tools/select_release_candidate.py b/tools/select_release_candidate.py new file mode 100644 index 0000000..beb0dd4 --- /dev/null +++ b/tools/select_release_candidate.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Select a previously verified Prepare run; never rebuild on publication retry. + +Only read-only GitHub REST requests are used. An existing release receipt wins +so a retry keeps the exact immutable artifacts already staged/published. +""" + +import argparse +import base64 +import json +import os +import re +import subprocess + +import tomllib +from release_version import release_version +from verify_release_candidate import _json, _run_id, _sha, _version + +WORKFLOW = ".github/workflows/prepare-release.yml" + + +def gh_read(path, *, paginate=False, raw=False, missing=False): + arguments = ["gh", "api", "--method", "GET"] + if paginate: + arguments += ["--paginate", "--slurp"] + if raw: + arguments += ["--header", "Accept: application/octet-stream"] + result = subprocess.run( + [*arguments, path], capture_output=True, text=True, check=False + ) + if result.returncode: + if missing and re.search(r"\bHTTP 404\b", result.stderr): + return None + raise RuntimeError(f"GitHub read failed for {path}: {result.stderr.strip()}") + return result.stdout if raw else _json(result.stdout) + + +def validate_run(run, repository, commit, run_id): + """Validate the authoritative workflow-run metadata before artifact download.""" + expected = _run_id(run_id) + if not isinstance(run, dict) or _run_id(run.get("id")) != expected: + raise ValueError("GitHub returned a different workflow run") + repository_info = run.get("repository") + actual_repository = ( + repository_info.get("full_name", "") + if isinstance(repository_info, dict) + else "" + ) + if ( + not isinstance(actual_repository, str) + or actual_repository.casefold() != repository.casefold() + ): + raise ValueError("candidate workflow belongs to another repository") + actual_sha = _sha(run.get("head_sha")) + if commit is not None and actual_sha != commit: + raise ValueError( + "candidate workflow head_sha differs from the recorded preparation source" + ) + checks = { + "path": WORKFLOW, + "head_branch": "master", + "event": "workflow_dispatch", + "status": "completed", + "conclusion": "success", + } + for field, expected_value in checks.items(): + if run.get(field) != expected_value: + raise ValueError( + f"candidate workflow {field} differs from the required preparation run" + ) + return expected + + +def _receipt_run(repository, version): + # Listing also covers drafts whose tag has not yet been created. + pages = gh_read(f"repos/{repository}/releases?per_page=100", paginate=True) + if not isinstance(pages, list) or any(not isinstance(page, list) for page in pages): + raise ValueError("invalid GitHub release listing") + matches = [ + release + for page in pages + for release in page + if release.get("tag_name") == "v" + version + ] + if len(matches) > 1: + raise ValueError("multiple release/draft records claim this version") + if not matches: + return None + assets = [ + asset + for asset in matches[0].get("assets", []) + if asset.get("name") == "release.json" + ] + if len(assets) > 1: + raise ValueError("multiple release receipts claim this version") + if not assets: + return None + asset = assets[0] + asset_id = _run_id(asset.get("id")) + body = gh_read(f"repos/{repository}/releases/assets/{asset_id}", raw=True) + if not isinstance(body, str): + raise TypeError("release receipt is unreadable") + receipt = _json(body) + if not isinstance(receipt, dict) or receipt.get("version") != version: + raise ValueError("existing release receipt belongs to another version") + # Its source may precede this controller workflow, but the authoritative run + # must still match the recorded SHA. Never substitute newly rebuilt bytes. + return { + "candidate_run_id": _run_id(receipt.get("candidate_run_id")), + "candidate_sha": _sha(receipt.get("commit")), + "version": _version(version), + } + + +def source_version(repository, commit): + """Read immutable source metadata, independently of the controller checkout.""" + metadata = gh_read(f"repos/{repository}/contents/pyproject.toml?ref={commit}") + if ( + not isinstance(metadata, dict) + or metadata.get("encoding") != "base64" + or not isinstance(metadata.get("content"), str) + ): + raise ValueError( + "candidate source pyproject.toml is not a readable base64 file" + ) + data = base64.b64decode("".join(metadata["content"].split()), validate=True) + project = tomllib.loads(data.decode()).get("project", {}) + if not isinstance(project, dict) or project.get("name") != "hmath-python": + raise ValueError("candidate source does not describe hmath-python") + return _version(project.get("version")) + + +def select_candidate(repository, commit, run_id=None): + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository): + raise ValueError("--repository must be owner/repository") + _sha(commit) + receipt = None + expected_sha = None + if run_id is not None and run_id != "": + chosen = _run_id(run_id) + else: + receipt = _receipt_run(repository, release_version()) + chosen = receipt["candidate_run_id"] if receipt else None + expected_sha = receipt["candidate_sha"] if receipt else commit + if chosen is None: + pages = gh_read( + f"repos/{repository}/actions/workflows/prepare-release.yml/runs?branch=master&event=workflow_dispatch&status=success&per_page=100", + paginate=True, + ) + if not isinstance(pages, list) or any( + not isinstance(page, dict) + or not isinstance(page.get("workflow_runs"), list) + for page in pages + ): + raise ValueError("invalid GitHub preparation-run listing") + runs = [ + run + for page in pages + for run in page["workflow_runs"] + if run.get("head_sha") == commit + ] + if not runs: + raise ValueError( + "no successful Prepare HMath release dispatch exists for this exact commit on master" + ) + runs.sort( + key=lambda run: (run.get("created_at", ""), int(_run_id(run.get("id")))), + reverse=True, + ) + chosen = _run_id(runs[0]["id"]) + run = gh_read(f"repos/{repository}/actions/runs/{chosen}") + validate_run(run, repository, expected_sha, chosen) + candidate_sha = _sha(run["head_sha"]) + version = source_version(repository, candidate_sha) + if receipt and version != receipt["version"]: + raise ValueError( + "staged release receipt version differs from its preparation source" + ) + return { + "candidate_run_id": chosen, + "candidate_sha": candidate_sha, + "version": version, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repository", required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--run-id") + args = parser.parse_args() + selected = select_candidate(args.repository, args.commit, args.run_id) + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + for name, value in selected.items(): + print(f"{name}={value}", file=output) + print(json.dumps(selected)) + + +if __name__ == "__main__": + main() diff --git a/tools/verify_release_candidate.py b/tools/verify_release_candidate.py new file mode 100644 index 0000000..f46208c --- /dev/null +++ b/tools/verify_release_candidate.py @@ -0,0 +1,367 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Validate the complete, immutable C/Python/Haskell release candidate. + +Artifact validation is usable before receipt creation. Candidate verification +also checks its source/run identity, manifest and SHA256SUMS. No network or +publication operation is performed by this module. +""" + +import argparse +import hashlib +import json +import re +import tarfile +import zipfile +from email.parser import BytesParser +from pathlib import Path, PurePosixPath + +import tomllib + +_VERSION = r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)" +_PLATFORM = r"manylinux_(?:2_\d+|2014)_x86_64" +_RECEIPTS = {"release.json", "SHA256SUMS"} + + +def _version(value): + if not isinstance(value, str) or not re.fullmatch(_VERSION, value): + raise ValueError("release version must be canonical major.minor.patch") + return value + + +def _sha(value): + if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value): + raise ValueError("source identity must be an exact lowercase Git commit SHA") + return value + + +def _run_id(value): + if type(value) not in (int, str) or not re.fullmatch(r"[1-9]\d*", str(value)): + raise ValueError("candidate_run_id must be a positive decimal workflow run ID") + return str(value) + + +def _hash(data): + return hashlib.sha256(data).hexdigest() + + +def _json(data): + def pairs(items): + result = {} + for key, value in items: + if key in result: + raise ValueError(f"duplicate JSON field: {key}") + result[key] = value + return result + + return json.loads(data, object_pairs_hook=pairs) + + +def _member_path(name): + # PurePosixPath normalizes '.' and empty components; inspect the original + # spelling too so normalization cannot hide traversal/duplicate members. + path = PurePosixPath(name) + if ( + path.is_absolute() + or "\\" in name + or any(p in ("", ".", "..") for p in name.rstrip("/").split("/")) + ): + raise ValueError(f"unsafe artifact member path: {name}") + return path + + +def _tar(path, prefix, *, sdk=False): + files, links = {}, {} + seen = set() + with tarfile.open(path, "r:gz") as archive: + for member in archive: + name = str(_member_path(member.name)) + if name in seen: + raise ValueError(f"duplicate tar member: {name}") + seen.add(name) + parts = PurePosixPath(name).parts + if not parts or parts[0] != prefix: + raise ValueError( + f"archive prefix differs from filename/version: {name}" + ) + relative = str(PurePosixPath(*parts[1:])) + if member.isdir(): + continue + if ( + member.issym() + and sdk + and relative == "lib/libhmath.so" + and member.linkname == "libhmath.so.1" + ): + links[relative] = member.linkname + continue + if not member.isfile() or len(parts) < 2: + raise ValueError(f"unsupported artifact member type: {name}") + stream = archive.extractfile(member) + if stream is None: + raise ValueError(f"unreadable artifact member: {name}") + files[relative] = stream.read() + return files, links + + +def _metadata(data, package, version): + metadata = BytesParser().parsebytes(data) + for field, expected in (("Name", package), ("Version", version)): + values = metadata.get_all(field, []) + if len(values) != 1 or values[0] != expected: + raise ValueError(f"package {field} differs from the candidate: {values}") + return metadata + + +def _elf(data): + if ( + len(data) < 64 + or data[:6] != b"\x7fELF\x02\x01" + or int.from_bytes(data[16:18], "little") != 3 + or int.from_bytes(data[18:20], "little") != 62 + ): + raise ValueError( + "native payload must be an ELF64 little-endian x86-64 shared library" + ) + + +def _wheel(path, version): + pattern = rf"hmath_python-{re.escape(version)}-py3-none-({_PLATFORM}(?:\.{_PLATFORM})*)\.whl" + match = re.fullmatch(pattern, path.name) + if not match: + raise ValueError("unexpected wheel filename/version/platform") + platforms = match[1].split(".") + if len(set(platforms)) != len(platforms): + raise ValueError("duplicate wheel platform tag") + files = {} + with zipfile.ZipFile(path) as archive: + seen = set() + for item in archive.infolist(): + name = str(_member_path(item.filename)) + if name in seen: + raise ValueError(f"duplicate wheel member: {name}") + seen.add(name) + if item.is_dir(): + continue + files[name] = archive.read(item) + dist = f"hmath_python-{version}.dist-info/" + metadata_names = [name for name in files if name.endswith(".dist-info/METADATA")] + if metadata_names != [dist + "METADATA"]: + raise ValueError("wheel must contain exactly its own name/version METADATA") + _metadata(files[dist + "METADATA"], "hmath-python", version) + if dist + "WHEEL" not in files: + raise ValueError("wheel has no WHEEL metadata") + metadata = BytesParser().parsebytes(files[dist + "WHEEL"]) + if metadata.get_all("Wheel-Version") != ["1.0"] or metadata.get_all( + "Root-Is-Purelib" + ) != ["false"]: + raise ValueError( + "wheel must declare the supported non-pure Wheel-Version 1.0 format" + ) + tags = metadata.get_all("Tag", []) + if len(tags) != len(platforms) or set(tags) != { + "py3-none-" + platform for platform in platforms + }: + raise ValueError("WHEEL tags differ from the filename") + native = files.get("_hmath_native/libhmath.so") + if native is None: + raise ValueError("wheel is missing the bundled HMath native library") + _elf(native) + libraries = { + name: value + for name, value in files.items() + if name.startswith("hmath_python.libs/") + } + if not libraries or any(len(PurePosixPath(name).parts) != 2 for name in libraries): + raise ValueError("wheel must include its repaired auditwheel dependencies") + return native, libraries + + +def _python_source(path, version): + files, _ = _tar(path, f"hmath_python-{version}") + if "pyproject.toml" not in files or "PKG-INFO" not in files: + raise ValueError("Python source archive lacks pyproject.toml/PKG-INFO") + project = tomllib.loads(files["pyproject.toml"].decode())["project"] + if project.get("name") != "hmath-python" or project.get("version") != version: + raise ValueError( + "Python source project name/version differs from the candidate" + ) + _metadata(files["PKG-INFO"], "hmath-python", version) + + +def _haskell_source(path, version): + files, _ = _tar(path, f"hmath-{version}") + if "hmath.cabal" not in files: + raise ValueError("Haskell archive lacks hmath.cabal") + text = files["hmath.cabal"].decode() + for field, expected in (("name", "hmath"), ("version", version)): + values = re.findall( + rf"^{field}:\s*([^\r\n]+)", text, re.MULTILINE | re.IGNORECASE + ) + if len(values) != 1 or values[0].split("--", 1)[0].strip() != expected: + raise ValueError(f"Haskell source {field} differs from the candidate") + + +def _sdk(path, version, wheel, native, libraries): + files, links = _tar(path, f"hmath-{version}-linux-x86_64", sdk=True) + if links != {"lib/libhmath.so": "libhmath.so.1"}: + raise ValueError("SDK must contain its relative libhmath.so SONAME alias") + if "manifest.json" not in files: + raise ValueError("SDK lacks its manifest") + metadata = _json(files["manifest.json"]) + expected = { + "version": version, + "abi": 1, + "platform": "linux-x86_64", + "wheel": wheel.name, + "wheel_sha256": _hash(wheel.read_bytes()), + } + if type(metadata.get("abi")) is not int or any( + metadata.get(key) != value for key, value in expected.items() + ): + raise ValueError( + "SDK version/platform/ABI/wheel identity differs from the candidate" + ) + if files.get("lib/libhmath.so.1") != native: + raise ValueError("SDK native library differs from the exact candidate wheel") + sdk_libraries = { + name: value + for name, value in files.items() + if name.startswith("hmath_python.libs/") + } + if sdk_libraries != libraries: + raise ValueError( + "SDK bundled dependencies differ from the exact candidate wheel" + ) + for name in ( + "include/hmath.h", + "lib/pkgconfig/hmath.pc", + "lib/cmake/HMath/HMathConfig.cmake", + "lib/cmake/HMath/HMathConfigVersion.cmake", + "share/licenses/hmath/LICENSE", + ): + if name not in files: + raise ValueError(f"SDK lacks required installed file: {name}") + + +def validate_artifacts(directory, version): + """Validate flat, exact current-version artifacts; return their sorted Paths. + + Existing receipt filenames are allowed for idempotent receipt generation, + but are only trusted after verify_candidate validates them. + """ + directory = Path(directory) + version = _version(version) + if not directory.is_dir(): + raise ValueError("candidate directory does not exist") + paths = [] + for path in directory.iterdir(): + if path.is_symlink() or not path.is_file(): + raise ValueError("candidate must contain flat regular files only") + if path.name not in _RECEIPTS: + paths.append(path) + wheels = [path for path in paths if path.suffix == ".whl"] + if len(wheels) != 1: + raise ValueError( + "candidate must contain exactly one repaired Linux x86-64 wheel" + ) + wheel = wheels[0] + expected = { + wheel.name, + f"hmath_python-{version}.tar.gz", + f"hmath-{version}.tar.gz", + f"hmath-{version}-linux-x86_64.tar.gz", + } + if {path.name for path in paths} != expected: + raise ValueError("candidate has missing, unexpected or other-version artifacts") + native, libraries = _wheel(wheel, version) + _python_source(directory / f"hmath_python-{version}.tar.gz", version) + _haskell_source(directory / f"hmath-{version}.tar.gz", version) + _sdk( + directory / f"hmath-{version}-linux-x86_64.tar.gz", + version, + wheel, + native, + libraries, + ) + return sorted(paths) + + +def verify_candidate(directory, commit, version=None): + """Verify exact artifact bytes and receipt/source/run identity; return manifest.""" + directory = Path(directory) + _sha(commit) + for receipt in _RECEIPTS: + if not (directory / receipt).is_file() or (directory / receipt).is_symlink(): + raise ValueError(f"candidate lacks a regular {receipt} receipt") + manifest = _json((directory / "release.json").read_bytes()) + manifest_version = _version(manifest.get("version")) + if version is not None and manifest_version != _version(version): + raise ValueError("candidate version differs from the selected preparation run") + version = manifest_version + if ( + manifest.get("commit") != commit + or type(manifest.get("abi")) is not int + or manifest.get("abi") != 1 + ): + raise ValueError( + "candidate source commit/ABI differs from the selected preparation" + ) + _run_id(manifest.get("candidate_run_id")) + paths = validate_artifacts(directory, version) + expected = {path.name: path for path in paths} + records = manifest.get("artifacts") + if not isinstance(records, list): + raise TypeError("manifest artifacts must be a list") + declared = {} + for record in records: + if not isinstance(record, dict) or set(record) != {"path", "sha256", "bytes"}: + raise ValueError("invalid artifact receipt record") + name, digest, count = record["path"], record["sha256"], record["bytes"] + if not isinstance(name, str) or name not in expected or name in declared: + raise ValueError("manifest has unexpected/duplicate artifact paths") + if ( + not isinstance(digest, str) + or not re.fullmatch(r"[0-9a-f]{64}", digest) + or type(count) is not int + or count < 0 + ): + raise ValueError("invalid artifact digest/byte count") + if count != expected[name].stat().st_size or digest != _hash( + expected[name].read_bytes() + ): + raise ValueError(f"candidate artifact checksum/size mismatch: {name}") + declared[name] = digest + if set(declared) != set(expected): + raise ValueError("manifest does not list exactly the allowed artifacts") + checksums = {} + for line in (directory / "SHA256SUMS").read_text().splitlines(): + match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) + if not match or match[2] in checksums: + raise ValueError("invalid/duplicate SHA256SUMS entry") + checksums[match[2]] = match[1] + expected_checksums = { + **declared, + "release.json": _hash((directory / "release.json").read_bytes()), + } + if checksums != expected_checksums: + raise ValueError("SHA256SUMS differs from the manifest") + return manifest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--commit", required=True) + parser.add_argument("--version") + parser.add_argument("--run-id") + args = parser.parse_args() + manifest = verify_candidate(args.directory, args.commit, args.version) + if args.run_id is not None and _run_id(manifest["candidate_run_id"]) != _run_id( + args.run_id + ): + raise ValueError("candidate receipt belongs to another preparation run") + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() From e785a1a571d5aa2681b9b9f4f3aba3fce4f4ddea Mon Sep 17 00:00:00 2001 From: LunaStev Date: Mon, 2 Nov 2026 23:11:30 +0900 Subject: [PATCH 2/3] fix: install pinned codegen tools in CI and prepare 1.1.0 --- .github/workflows/docs.yml | 4 +++- .github/workflows/prepare-release.yml | 2 +- .github/workflows/validate.yml | 2 +- MANIFEST.in | 2 +- cbits/native.c | 2 +- hmath.cabal | 3 ++- meson.build | 2 +- pyproject.toml | 2 +- requirements-codegen.txt | 2 ++ requirements-docs.txt | 1 + 10 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 requirements-codegen.txt diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 8589918..a55da79 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,7 +23,9 @@ jobs: with: python-version: '3.12' cache: pip - cache-dependency-path: requirements-docs.txt + cache-dependency-path: | + requirements-docs.txt + requirements-codegen.txt - uses: ./.github/actions/setup-haskell with: ghc-version: '9.10.3' diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index c8e1a80..d5d81a5 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -32,9 +32,9 @@ jobs: restore-keys: docs-haddock- - name: Check every public API before preparing a complete release run: | + python -m pip install -r requirements-docs.txt python tools/generate_numeric_bindings.py --check python tools/generate_matrix_bindings.py --check - python -m pip install -r requirements-docs.txt python tools/build_docs.py interface=$(python - <<'PY' import json, pathlib diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 84f0f73..1a546d7 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -59,7 +59,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y liblapacke-dev libopenblas-dev zlib1g-dev cmake ninja-build clang - python -m pip install meson==1.8.5 numpy cffi + python -m pip install -r requirements-codegen.txt meson==1.8.5 numpy cffi - name: Wave compiler if: matrix.primary env: diff --git a/MANIFEST.in b/MANIFEST.in index b946f33..cef05a7 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,5 @@ include LICENSE README.md CHANGELOG.md ROADMAP.md hmath.cabal cabal.project meson-build.py -include meson.build meson_options.txt mkdocs.yml requirements-docs.txt fourmolu.yaml .clang-format +include meson.build meson_options.txt mkdocs.yml requirements-docs.txt requirements-codegen.txt fourmolu.yaml .clang-format recursive-include src *.hs recursive-include cbits *.c *.h recursive-include include *.h diff --git a/cbits/native.c b/cbits/native.c index f4614ab..5f62dd5 100644 --- a/cbits/native.c +++ b/cbits/native.c @@ -35,7 +35,7 @@ const char *hmath_status_string(hmath_status s) { return (unsigned)s < sizeof names / sizeof names[0] ? names[s] : "unknown status"; } uint32_t hmath_abi_version(void) { return HMATH_ABI_VERSION; } -const char *hmath_library_version(void) { return "1.0.2"; } +const char *hmath_library_version(void) { return "1.1.0"; } const char *hmath_build_info(void) { return "HMath ABI 1; C11; GHC threaded RTS; scalar binary32/64; tensor binary64; max-rank=8"; } diff --git a/hmath.cabal b/hmath.cabal index fae3a30..ba41cf8 100644 --- a/hmath.cabal +++ b/hmath.cabal @@ -2,7 +2,7 @@ cabal-version: 3.0 -- SPDX-License-Identifier: MPL-2.0 name: hmath -version: 1.0.2 +version: 1.1.0 synopsis: General-purpose mathematics library written in Haskell description: HMath is a general-purpose mathematics library written in Haskell. @@ -25,6 +25,7 @@ extra-source-files: setup.py mkdocs.yml requirements-docs.txt + requirements-codegen.txt docs/**/*.md README.md ROADMAP.md diff --git a/meson.build b/meson.build index a2a6abb..265bd2f 100644 --- a/meson.build +++ b/meson.build @@ -1,5 +1,5 @@ # SPDX-License-Identifier: MPL-2.0 -project('hmath', 'c', version: '1.0.2', meson_version: '>=1.3.0', +project('hmath', 'c', version: '1.1.0', meson_version: '>=1.3.0', default_options: ['c_std=c11', 'warning_level=2', 'buildtype=release']) cabal = find_program('cabal') python = import('python').find_installation('python3') diff --git a/pyproject.toml b/pyproject.toml index 6a5fc73..3f4c722 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "hmath-python" -version = "1.0.2" +version = "1.1.0" description = "Python bindings for the Haskell HMath numerical library" readme = "README.md" requires-python = ">=3.9" diff --git a/requirements-codegen.txt b/requirements-codegen.txt new file mode 100644 index 0000000..587d954 --- /dev/null +++ b/requirements-codegen.txt @@ -0,0 +1,2 @@ +ruff==0.16.10 +clang-format==21.1.8 diff --git a/requirements-docs.txt b/requirements-docs.txt index 4168f66..ae9ddb0 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,2 +1,3 @@ +-r requirements-codegen.txt mkdocs==1.6.1 mkdocs-material==9.8.0 From 91f70a3ba23b8cae5286b8dca54b310efc82450e Mon Sep 17 00:00:00 2001 From: LunaStev Date: Mon, 2 Nov 2026 23:20:53 +0900 Subject: [PATCH 3/3] fix: link structured error state into native fuzz harness --- tools/run_fuzz.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/run_fuzz.py b/tools/run_fuzz.py index 99b89d9..8865484 100644 --- a/tools/run_fuzz.py +++ b/tools/run_fuzz.py @@ -43,8 +43,10 @@ def main(): "-Icbits", "test/fuzz_native.c", "cbits/native.c", + "cbits/error_wire.c", "cbits/native_dlpack.c", "-lm", + "-pthread", "-o", str(binary), ],